MainComponent.cpp 486 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390
  1. #include "ui/ControllerBridge.h"
  2. #include "ui/ExternalDrag.h"
  3. #include "ui/AudioClipboard.h"
  4. #include "ui/MidiClipboard.h"
  5. #include "ui/VideoTracks.h"
  6. #include "ui/AdrWindow.h"
  7. #include "ui/FirstSongTour.h" // (round 190fq: the support note waits for the Welcome screen)
  8. #include "ui/GamepadInput.h"
  9. #include "ui/ThemeSettings.h"
  10. #include "ui/ColourPicker.h"
  11. #include "core/AutoScanPolicy.h"
  12. #include "core/RenderAhead.h"
  13. #include "core/DrawMode.h"
  14. #include "core/SessionKeys.h"
  15. #include "core/EditorLimit.h"
  16. #include "core/FirstSongTour.h"
  17. #include "core/SessionKeys.h"
  18. #include "core/FlSettings.h"
  19. #include "core/PlaylistOps.h"
  20. #include "core/ClipOps.h"
  21. #include "core/OneClickRec.h"
  22. #include "core/CountIn.h"
  23. #include "core/MixerOps.h"
  24. #include "core/NoteNames.h"
  25. #include "core/KeyGuess.h"
  26. #include "core/ProjectKey.h"
  27. #include "core/ScaleKeys.h"
  28. #include "core/SimplePads.h"
  29. #include "core/SamplerPage.h"
  30. #include "core/SessionOps.h"
  31. #include "ui/FileChoosers.h"
  32. #include "ui/ProjectLoading.h"
  33. #include "ui/UiTrace.h"
  34. #include "core/LoadTrace.h"
  35. #include "ui/MainComponent.h"
  36. #include "ui/RemoteControlSettings.h"
  37. #include "ui/NativeChild.h"
  38. #include "core/PlaylistOps.h"
  39. #include "core/Performance.h"
  40. #include "core/TransportEdit.h"
  41. #include "ui/CrashReporter.h"
  42. #include "ui/DanceView.h"
  43. #include "engine/AudioLogger.h"
  44. #include "ui/PluginSkin.h"
  45. #include "platform/Paths.h"
  46. #include "ui/SetupWizard.h"
  47. #include "core/FlPluginDb.h"
  48. #include "core/Preferences.h"
  49. #include "core/EditorPolish.h"
  50. #include "ui/HistoryPanel.h"
  51. #include "ui/LyricsPanel.h"
  52. #include "ui/ReferenceMatchPanel.h"
  53. #include "ui/VersionsPanel.h"
  54. #include "ui/PluginsOffPanel.h"
  55. #include "ui/MissingFilesDialog.h"
  56. #include "ui/SettingsDialog.h"
  57. #include "ui/SimpleDock.h"
  58. #include "ui/PluginManager.h"
  59. #include "ui/ShortcutManager.h"
  60. #include "ui/WaveformView.h"
  61. #include "ui/QuickAddPalette.h"
  62. #include "ui/QuickPick.h"
  63. #include "core/FolderWatcher.h"
  64. #include "ui/PluginPickerView.h"
  65. #include "ui/PatcherEditor.h"
  66. #include "ui/ToolWindow.h"
  67. #include "ui/RackEditor.h"
  68. #include "ui/LoopStarterWindow.h"
  69. #include "ui/WindowOwner.h"
  70. #include "engine/PluginSandbox.h"
  71. #include "platform/FileTypes.h"
  72. #include "platform/CrashGuard.h"
  73. #include "platform/LinuxRealtime.h"
  74. #include "platform/Package.h"
  75. #include "engine/Text.h"
  76. #include "core/MetronomeVoice.h"
  77. #include "core/RackOps.h"
  78. #include "core/Templates.h"
  79. #include "ui/NewProjectDialog.h"
  80. #include "ui/PluginMonitorWindow.h"
  81. #include "ui/TouchKeyboard.h"
  82. #include "engine/MidiFileIo.h"
  83. #include "engine/ProjectFile.h"
  84. #include "engine/ProjectPackage.h"
  85. #include "engine/SessionPack.h"
  86. #include "ui/SessionDialogs.h"
  87. #include "engine/LiveSessions.h"
  88. #include "ui/LiveChat.h"
  89. #include "ui/LiveRemoteUi.h"
  90. #include "core/ProjectSafety.h"
  91. #include "core/MissingFiles.h"
  92. #include "ui/AutomationUi.h"
  93. #include "ui/RemoteControl.h"
  94. #include "ui/ChannelSettings.h"
  95. #include "core/ClipLauncher.h"
  96. #include "ui/ClipGridComponent.h"
  97. #include "ui/Dialogs.h"
  98. #include "ui/EventEditor.h"
  99. #include "ui/EditorTools.h"
  100. #include "ui/AudioEditor.h"
  101. #include "ui/TempoTapper.h"
  102. #include "ui/ExportDialog.h"
  103. #include "ui/AudioCheck.h"
  104. #include "ui/AlsExportDialog.h"
  105. #include "ui/OtherAppsExport.h"
  106. #include "ui/FlStudioExportDialog.h"
  107. #include "ui/FruitySlicerEditor.h"
  108. #include "ui/SlicexEditor.h"
  109. #include "core/NativeEngines.h"
  110. #include "ui/ParametricEqEditor.h"
  111. #include "ui/PluginWindow.h"
  112. #include "ui/I18n.h"
  113. #include "ui/Theme.h"
  114. #include "ui/TypeAhead.h"
  115. #include "ui/WaveformView.h"
  116. #include "core/HintMarkup.h"
  117. #include "core/SongStats.h"
  118. #if JUCE_PLUGINHOST_VST3
  119. namespace juce
  120. {
  121. // cmake/LynxPatchJuce.cmake fix 20 (round 177b): LYNX's items at the top of a VST3 plugin's parameter context menu
  122. extern void (*lynxVst3ParamMenuHook) (AudioPluginInstance&, int, PopupMenu&);
  123. } // namespace juce
  124. #endif
  125. namespace lynx
  126. {
  127. // round 177b: the engine LYNX's VST3 parameter-menu hook uses (set while the main window lives)
  128. static AudioEngine*& vst3MenuEngine()
  129. {
  130. static AudioEngine* engine = nullptr;
  131. return engine;
  132. }
  133. namespace
  134. {
  135. using workspace::Panel;
  136. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  137. const char* panelAction (Panel p)
  138. {
  139. switch (p)
  140. {
  141. case Panel::playlist: return "panel.playlist";
  142. case Panel::channelRack: return "panel.channelRack";
  143. case Panel::pianoRoll: return "panel.pianoRoll";
  144. case Panel::mixer: return "panel.mixer";
  145. case Panel::browser: return "panel.browser";
  146. }
  147. return "";
  148. }
  149. juce::String panelName (Panel p)
  150. {
  151. switch (p)
  152. {
  153. case Panel::playlist: return "Playlist";
  154. case Panel::channelRack: return "Channel Rack";
  155. case Panel::pianoRoll: return "Piano Roll";
  156. case Panel::mixer: return "Mixer";
  157. case Panel::browser: return "Browser";
  158. }
  159. return {};
  160. }
  161. } // namespace
  162. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  163. : persistent (restoreUserSettings),
  164. engine (e),
  165. rack (e),
  166. pianoRoll (e),
  167. playlist (e),
  168. mixer (e),
  169. browser (e)
  170. {
  171. if (startupMark != nullptr) startupMark ("main window: panels constructed (rack, piano roll, playlist, mixer, browser)"); // (round 190gd)
  172. rackcards::install(); // (round 183c: racks show as their own card in the Device View)
  173. heldKeys.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on, true); });
  174. connectBrowser (browser);
  175. if (restoreUserSettings) // (issue #104: the Plugin database folder on disk; changes made in LYNX are written to it)
  176. {
  177. quickpick::installPluginDatabase (engine);
  178. // round 190bf: and a change made to it in the file manager shows in the Browser by itself, about a second
  179. // later, as in FL (fl190be Q2); the menus and the picker read it when they next open
  180. const auto root = quickpick::pluginDatabaseFolder();
  181. auto safe = juce::Component::SafePointer<MainComponent> (this);
  182. pluginDatabaseWatcher = std::make_unique<folderwatch::Watcher> (
  183. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  184. [safe] {
  185. juce::MessageManager::callAsync ([safe] {
  186. if (safe != nullptr)
  187. safe->readPluginDatabaseAgain();
  188. });
  189. });
  190. }
  191. addChildComponent (updateBar);
  192. addChildComponent (remoteControlBar);
  193. remoteControlBar.setFont (theme::font (theme::type::small, true));
  194. remoteControlBar.setColour (juce::Label::backgroundColourId, theme::colour::accent.withAlpha (0.16f));
  195. remoteControlBar.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  196. remoteControlBar.setJustificationType (juce::Justification::centredLeft);
  197. updateBar.onVisibilityChanged = [this] { resized(); };
  198. if (restoreUserSettings) // (the real window: Update saves the project as on quit and reopens it)
  199. updater::setHost ({ [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  200. if (safe != nullptr)
  201. safe->confirmDiscard (std::move (then));
  202. },
  203. [safe = juce::Component::SafePointer<MainComponent> (this)] {
  204. return safe != nullptr ? safe->currentFile : juce::File();
  205. } });
  206. mixeroptions::changed = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  207. if (safe != nullptr)
  208. {
  209. safe->saveUiSettings();
  210. safe->playlist.repaint();
  211. }
  212. };
  213. mixeroptions::setShowUsedOnly = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  214. if (safe != nullptr)
  215. safe->mixer.getStripsForSnapshot().setShowUsedOnly (on);
  216. };
  217. mixeroptions::setShowLoudness = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  218. if (safe != nullptr)
  219. safe->mixer.getStripsForSnapshot().setShowLoudness (on);
  220. };
  221. mixeroptions::selectPlaylistTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks) {
  222. if (safe != nullptr)
  223. safe->playlist.selectTracks (tracks);
  224. };
  225. mixeroptions::renderTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks,
  226. std::function<void (const std::vector<juce::File>&)> done) {
  227. if (safe != nullptr)
  228. showExportDialogForTracks (safe->engine, safe->currentFile.getParentDirectory(), safe->projectName, tracks, std::move (done));
  229. };
  230. if (persistent)
  231. {
  232. engine.getRollingLog().setEnabled (true); // on by default, as in FL (Tools › Audio logger)
  233. loadUiSettings();
  234. // the start-up song follows Options › Mixer too (round 163) and the automatic crossfades of new projects (166e)
  235. engine.setSong (makeNewProject());
  236. skin::onStyleSettingsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // an editor's own style was picked
  237. if (safe != nullptr) safe->saveUiSettings();
  238. };
  239. messages::onChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // "Remember my choice" / Manage messages
  240. if (safe != nullptr) safe->saveUiSettings();
  241. };
  242. loadKeyMap();
  243. startSession();
  244. if (BrowserComponent::sampleBrowserWasOpen()) // it was open when LYNX closed (round 163)
  245. juce::Timer::callAfterDelay (800, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  246. if (safe != nullptr && findToolWindow ("sampleBrowser") == nullptr)
  247. safe->openSampleBrowser();
  248. });
  249. EditorGlobals::get().onOptionsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // Follow on/off
  250. if (safe != nullptr) safe->saveUiSettings();
  251. };
  252. }
  253. if (startupMark != nullptr) startupMark ("main window: settings, key map, start-up song, session");
  254. PianoRollComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  255. PlaylistComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  256. pianoRoll.onNoteNamesChanged = [this] { saveUiSettings(); };
  257. // FL's EEPlayBtnClick (FLEngine 0xe4bd40, REA round 169f): Pattern mode first (also while the song plays), then the
  258. // play / pause of the transport. EEPlayBtnMouseDown (0xe4bda0), right button: FL's Stop (FUN_011ca520 (0, 0), the very
  259. // call of the toolbar's StopBtnClick), which in FL goes back to where playback started, pressed again to the start
  260. // (measured in FL 2026, round 169f, Pattern mode after a ruler click)
  261. pianoRoll.onPlayPause = [this] {
  262. if (engine.getSong().mode != PlayMode::pattern)
  263. toggleMode();
  264. playPause();
  265. };
  266. pianoRoll.onPlayRightClick = [this] { stopAndRewind (false); }; // FL's Stop (FUN_011ca520 (0, 0)), issue #169
  267. pianoRoll.onBrowseScores = [this] { // (round 168g: the Piano roll's File › Browse scores)
  268. showPanel (Panel::browser);
  269. browser.showScores();
  270. };
  271. EventEditorHooks::onBrowseAutomations = [this] { // (the Event editor's File › Browse automations: FL's Scores\\Automation)
  272. showPanel (Panel::browser);
  273. browser.showScores ("Automation");
  274. };
  275. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  276. newButton.onClick = [this] { newProject(); };
  277. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  278. openButton.onClick = [this] { chooseFileToOpen(); };
  279. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  280. saveButton.onClick = [this] { save (false); };
  281. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  282. exportButton.onClick = [this] { exportAudio(); };
  283. auto withKey = [this] (const juce::String& text, const char* id) {
  284. const auto key = shortcutText (id).trim();
  285. return key.isEmpty() ? text : text + " (" + key + ")";
  286. };
  287. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  288. undoButton.onClick = [this] { flUndo(); }; // FL's toolbar Undo is its Edit › Undo (UndoAction)
  289. undoButton.onRightClick = [this] { showHistory(); };
  290. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  291. redoButton.onClick = [this] { undoRedo (true); };
  292. redoButton.onRightClick = [this] { showHistory(); };
  293. // FL's toolbar picker button (round 171c): a click opens the Plugin picker (F8); a right-click LYNX's quick-add palette
  294. pluginPickerButton.setTooltip (withKey (tr ("Plugin picker: every plugin as a picture; drag one onto the Channel Rack or the Mixer (right-click: quick-add palette)"),
  295. "view.pluginPicker"));
  296. pluginPickerButton.onClick = [this] { togglePluginPicker(); };
  297. pluginPickerButton.onRightClick = [this] { showQuickAdd(); };
  298. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  299. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  300. playButton.onClick = [this] { playStop(); };
  301. stopButton.setTooltip (tr ("Stop and return to the start (double-click: back to the start and all notes off)"));
  302. stopButton.onClick = [this] { stopAndRewind(); };
  303. stopButton.onDoubleClick = [this] { // FL-like: a double Stop goes back to the very start (and silences hanging notes)
  304. engine.panic();
  305. stopAndRewind (true);
  306. };
  307. stopButton.onRightClick = [this] { showStopMenu(); };
  308. output.onModeChanged = [this] { saveUiSettings(); };
  309. recordButton.setOnColour (theme::colour::record);
  310. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  311. recordButton.onClick = [this] { toggleRecording(); };
  312. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  313. recordMenuButton.onClick = [this] { showRecordMenu(); };
  314. recordButton.onRightClick = [this] { showRecordMenu(); };
  315. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  316. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  317. patternModeButton.setText (tr ("Pattern"));
  318. songModeButton.setText (tr ("Song"));
  319. for (auto* b : { &patternModeButton, &songModeButton })
  320. {
  321. b->setOnColour (theme::colour::bg6);
  322. b->setIconColourWhenOn (theme::colour::textPrimary);
  323. }
  324. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  325. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  326. patternModeButton.onClick = [this] {
  327. if (engine.getSong().mode != PlayMode::pattern)
  328. toggleMode();
  329. };
  330. songModeButton.onClick = [this] {
  331. if (engine.getSong().mode != PlayMode::song)
  332. toggleMode();
  333. };
  334. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  335. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  336. metronomeButton.setClickingTogglesState (true);
  337. metronomeButton.setOnColour (theme::colour::bg6);
  338. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  339. metronomeButton.setTooltip (tr ("Metronome"));
  340. metronomeButton.onClick = [this] {
  341. engine.getTransport().metronome.store (metronomeButton.getToggleState());
  342. saveUiSettings(); // FL keeps it (ToolbarForm "MetronomeBtn", issue #152)
  343. };
  344. midiLight.onReconnect = [this] {
  345. engine.reconnectMidiInputs();
  346. midiInputTicks = 0; // shows the reopened inputs at the next tick
  347. };
  348. metronomeButton.onRightClick = [this] { showMetronomeMenu(); };
  349. // FL's MultiLinkBtn (round 177b-4): lit while "Multilink to controllers" is on; [RMB] FL's MLWheelMenu (round 190df)
  350. multilinkButton.setFlat (true);
  351. multilinkButton.setWantsKeyboardFocus (false);
  352. multilinkButton.onClick = [this] { runAction ("options.multilink"); };
  353. multilinkButton.onRightClick = [this] {
  354. auto menu = getMultilinkMenuForSnapshot();
  355. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&multilinkButton));
  356. };
  357. typingPianoButton.setOnColour (theme::colour::bg6);
  358. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  359. typingPianoButton.onClick = [this] { toggleTypingPiano(); };
  360. typingPianoButton.onRightClick = [this] { showTypingPianoMenu(); };
  361. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  362. for (auto* b : { &countInButton, &waitInputButton })
  363. {
  364. b->setOnColour (theme::colour::bg6);
  365. b->setIconColourWhenOn (theme::colour::accent);
  366. }
  367. countInButton.onClick = [this] { runAction ("record.countIn"); };
  368. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  369. // round 170e2: FL's "Blend recorded notes" switch (on = overdub, off = replace) and its tempo tapper button
  370. blendButton.setOnColour (theme::colour::bg6);
  371. blendButton.setIconColourWhenOn (theme::colour::accent);
  372. blendButton.onClick = [this] { runAction ("record.blend"); };
  373. tapTempoButton.onClick = [this] { openTempoTapper (engine); };
  374. // round 170e3: loop record, step edit and punch in/out as switches beside them
  375. for (auto* b : { &loopRecordButton, &stepEditButton, &punchButton })
  376. {
  377. b->setOnColour (theme::colour::bg6);
  378. b->setIconColourWhenOn (theme::colour::accent);
  379. }
  380. loopRecordButton.onClick = [this] { runAction ("record.loop"); };
  381. stepEditButton.onClick = [this] { runAction ("record.stepEdit"); };
  382. punchButton.onClick = [this] { runAction ("record.punch"); };
  383. for (int i = 0; i < workspace::panelCount; ++i)
  384. {
  385. const auto panel = (Panel) i;
  386. auto& b = panelButtons[(std::size_t) i];
  387. b.setFlat (true);
  388. b.setOnColour (theme::colour::bg5);
  389. b.setIconColourWhenOn (theme::colour::textPrimary);
  390. b.setTooltip (panelName (panel) + " (" + keys::displayString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  391. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  392. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  393. b.onClick = [this, panel] { togglePanel (panel); };
  394. b.onRightClick = [this, panel] {
  395. showPanel (panel);
  396. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  397. workspace.toggleMaximised (panel);
  398. refreshPanelButtons();
  399. };
  400. }
  401. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  402. patternBox.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  403. gridBox.setScrollWheelEnabled (true);
  404. patternBox.onChange = [this]
  405. {
  406. const auto index = patternBox.getSelectedItemIndex();
  407. if (index >= 0 && index != engine.getSong().currentPattern)
  408. selectPattern (index);
  409. };
  410. newPatternButton.setTooltip (tr ("New pattern"));
  411. newPatternButton.onClick = [this]
  412. {
  413. engine.editSong ([] (Song& s) {
  414. Pattern p;
  415. p.name = newPatternName (s);
  416. s.patterns.push_back (std::move (p));
  417. s.currentPattern = (int) s.patterns.size() - 1;
  418. });
  419. };
  420. swingSlider.setRange (0.0, 1.0, 0.01);
  421. swingSlider.setDoubleClickReturnValue (true, 0.0);
  422. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  423. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  424. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  425. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  426. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  427. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  428. swingSlider.setWantsKeyboardFocus (false);
  429. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  430. patternMenuButton.onClick = [this] { showPatternMenu(); };
  431. // the workspace panels
  432. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  433. mixerinput::openAudioSettings = [this] { openSettings ((int) SettingsPage::audio); };
  434. PatcherWindows::onBrowsePluginDatabase = [this] (bool) {
  435. showPanel (Panel::browser);
  436. browser.showPluginDatabaseForSnapshot(); // (its Generators and Effects folders open)
  437. if (auto* w = getTopLevelComponent())
  438. w->toFront (true);
  439. };
  440. rack.onOpenMixerInsert = [this] (int insert) { // double-click on a channel's route box
  441. showPanel (Panel::mixer);
  442. mixer.selectTrack (insert);
  443. };
  444. playlist.onLinkedMixerTrack = [this] (int insert) { // round 190ft (FL FUN_012e3aa0): only while the mixer shows
  445. if (mixer.isShowing())
  446. mixer.selectTrack (insert);
  447. };
  448. openMixerInsertHandler() = rack.onOpenMixerInsert; // and on the channel window's TRACK box (round 168s)
  449. locateInBrowserHandler() = [this] (const juce::File& file) { // (the sampler's File row, round 190df)
  450. showPanel (Panel::browser);
  451. browser.locateFile (file);
  452. };
  453. // the Sampler waveform menu's "Open in new sampler channel" / "... Fruity Granulizer channel" (round 190ey): the file in
  454. // a new channel of that kind (as the audio clip menu's Open in a new Sampler channel), its editor open
  455. openInNewChannelHandler() = [this] (const juce::File& file, InstrumentKind kind) {
  456. if (! file.existsAsFile())
  457. return;
  458. // round 190gk: "... Fruity Slicer channel" / "... Slicex channel": FL loads the plugin's template channel, then
  459. // the sample into it (SBONewMenuClick 0x11f8330, REA 190fl); LYNX's new channel of that kind, and its editor
  460. // loads the file as its own Load does (slices / regions as on a load)
  461. if (kind == InstrumentKind::fruityslicer || kind == InstrumentKind::slicex)
  462. {
  463. auto made = natives::makeChannel (kind, flStudioAccess());
  464. if (! made)
  465. return;
  466. // round 190gw (live check 190gu B3): the channel takes the sample's name, " #n" when taken
  467. made->name = samplerpage::openInNewChannelName (engine.getSong(), file.getFileNameWithoutExtension().toStdString());
  468. const auto added = rack.addChannel (*made, false);
  469. if (kind == InstrumentKind::slicex)
  470. loadSlicexSampleWhenOpened (added, file.getFullPathName());
  471. else
  472. loadSampleWhenOpened (added, file.getFullPathName());
  473. showPanel (Panel::channelRack);
  474. rack.toggleEditor (added, false);
  475. loadSlicexSampleWhenOpened (-1, {}); // (an editor that did not open forgets it)
  476. loadSampleWhenOpened (-1, {});
  477. return;
  478. }
  479. ChannelDef c;
  480. c.instrument = kind;
  481. audioclips::loadSampleInto (c, file.getFullPathName().toStdString(), file.getFileNameWithoutExtension().toStdString());
  482. c.instrument = kind; // (loadSampleInto keeps the Granulizer; a sampler stays one)
  483. c.name = samplerpage::openInNewChannelName (engine.getSong(), file.getFileNameWithoutExtension().toStdString()); // (round 190gw)
  484. const auto added = rack.addChannel (c, false);
  485. showPanel (Panel::channelRack);
  486. rack.toggleEditor (added, false);
  487. };
  488. mixer.onInstrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); };
  489. rackViewport.setViewedComponent (&rack, false);
  490. rackViewport.setScrollBarsShown (true, true);
  491. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  492. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  493. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  494. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  495. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  496. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  497. // FL keeps the channel filter, the global swing and the graph editor switch in the rack's title bar
  498. rackFilterBox.text = rack.filterName();
  499. rackFilterBox.onClick = [this] { rack.showFilterMenu (&rackFilterBox); };
  500. rack.onFilterChanged = [this] {
  501. rackFilterBox.text = rack.filterName();
  502. rackFilterBox.repaint();
  503. rackGraphButton.setToggleState (rack.areGraphLanesShown(), juce::dontSendNotification);
  504. rackPianoRollButton.setToggleState (rack.isPianoRollView(), juce::dontSendNotification);
  505. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  506. };
  507. rackGraphButton.setClickingTogglesState (false);
  508. rackGraphButton.onClick = [this] { rack.toggleGraphLanes(); };
  509. // the step sequencer / piano-roll view switch (FL keeps it in the rack's title bar too)
  510. rackPianoRollButton.setClickingTogglesState (false);
  511. rackPianoRollButton.setOnColour (theme::colour::bg6);
  512. rackPianoRollButton.setIconColourWhenOn (theme::colour::accent);
  513. rackPianoRollButton.onClick = [this] { runAction ("rack.pianoRollView"); };
  514. ui::setHint (rackPianoRollButton, tr ("Piano-roll view: every channel shows its notes as a miniature piano roll (click one to edit it) "
  515. "instead of the step buttons; click again for the steps"));
  516. rackTitleTools.addAndMakeVisible (rackPianoRollButton);
  517. // Follow (issue #12): a long pattern pages along with the playing step
  518. rackFollowButton.setClickingTogglesState (false);
  519. rackFollowButton.setOnColour (theme::colour::bg6);
  520. rackFollowButton.setIconColourWhenOn (theme::colour::accent);
  521. rackFollowButton.setWantsKeyboardFocus (false);
  522. rackFollowButton.setMouseClickGrabsKeyboardFocus (false);
  523. rackFollowButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  524. rackFollowButton.setTooltip (tr ("Follow: a pattern longer than the Channel Rack pages along with the playing step; off, it stays where you scrolled"));
  525. ui::setQuickTip (rackFollowButton, tr ("Follow the playhead"));
  526. rackFollowButton.onClick = [this] { runAction ("rack.follow"); };
  527. rackTitleTools.addAndMakeVisible (rackFollowButton);
  528. // FL's Loop button (round 165f-rack): click switches the pattern's channel looping, right-click its loop type and burns
  529. rackLoopButton.setClickingTogglesState (false);
  530. rackLoopButton.setOnColour (theme::colour::bg6);
  531. rackLoopButton.setIconColourWhenOn (theme::colour::accent);
  532. rackLoopButton.onClick = [this] { rack.toggleLooping(); };
  533. rackLoopButton.onRightClick = [this] { rack.showLoopMenu (&rackLoopButton); };
  534. ui::setHint (rackLoopButton, tr ("Channel looping: channels shorter than the pattern repeat to its end (polyrhythms) [LMB] on / off "
  535. "[RMB] loop type (step channels, all channels, advanced) and Burn to pattern"));
  536. rackTitleTools.addAndMakeVisible (rackLoopButton);
  537. // Loop Starter (round 168b; FL 25's dice in the Channel Rack): a drum loop of the genre's kit, re-rolled with dice
  538. rackLoopStarterButton.setWantsKeyboardFocus (false);
  539. rackLoopStarterButton.onClick = [this] { loopstarterui::open (engine); };
  540. ui::setHint (rackLoopStarterButton, tr ("Loop Starter: pick a genre and get a drum loop (kit channels with steps) to re-roll and send to the Playlist"));
  541. rackTitleTools.addAndMakeVisible (rackLoopStarterButton);
  542. // the pattern selector (issue #9): change the pattern the rack edits right from its title bar
  543. rackPatternSelector.onStep = [this] (int delta) { stepPatternFromSelector (delta); };
  544. rackPatternSelector.onMenu = [this] { showRackPatternList(); };
  545. ui::setHint (rackPatternSelector, tr ("Pattern the Channel Rack edits: [LMB] on the name: the list of patterns, on the arrows: previous / next [Wheel] step") + " " + tr ("[LMB] drag up / down: step through the patterns"));
  546. rackTitleTools.addAndMakeVisible (rackPatternSelector);
  547. rackTitleTools.addAndMakeVisible (rackFilterBox);
  548. rackTitleTools.addAndMakeVisible (swingSlider);
  549. // the pattern length in bars (issue #12)
  550. rackLengthBox.onSet = [this] (int bars) {
  551. const auto index = engine.getSong().currentPattern;
  552. const auto ticks = (std::int64_t) juce::jlimit (0, 999, bars) * engine.getSong().barTicks();
  553. if (index >= 0 && index < (int) engine.getSong().patterns.size() && engine.getSong().patterns[(std::size_t) index].lengthTicks != ticks)
  554. engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; });
  555. refreshRackLengthBox();
  556. };
  557. rackLengthBox.onMenu = [this] { showPatternLengthMenu(); };
  558. ui::setHint (rackLengthBox, tr ("Pattern length in bars: [LMB] drag or [Wheel] change it [2xLMB] automatic (from the notes) [RMB] menu"));
  559. ui::setQuickTip (rackLengthBox, tr ("Pattern length (bars)"));
  560. rackTitleTools.addAndMakeVisible (rackLengthBox);
  561. rackTitleTools.addAndMakeVisible (rackGraphButton);
  562. rackTitleTools.layout = [this] {
  563. auto r = rackTitleTools.getLocalBounds();
  564. rackPatternSelector.setBounds (r.removeFromLeft (rackPatternSelectorWidth).reduced (0, 3));
  565. r.removeFromLeft (6);
  566. rackFilterBox.setBounds (r.removeFromLeft (rackFilterBoxWidth).reduced (0, 3));
  567. r.removeFromLeft (4);
  568. swingSlider.setBounds (r.removeFromLeft (26));
  569. r.removeFromLeft (4);
  570. rackLengthBox.setBounds (r.removeFromLeft (rackLengthBoxWidth).reduced (0, 3));
  571. r.removeFromLeft (4);
  572. rackGraphButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  573. r.removeFromLeft (4);
  574. rackPianoRollButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  575. r.removeFromLeft (4);
  576. rackFollowButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  577. r.removeFromLeft (4);
  578. rackLoopButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  579. r.removeFromLeft (4);
  580. rackLoopStarterButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  581. };
  582. workspace.setTitleAccessory (Panel::channelRack, &rackTitleTools, rackTitleToolsWidth);
  583. workspace.setTitleAccessory (Panel::mixer, &mixer.getLayoutBox(), MixerLayoutBox::width); // FL's "Mixer layout" (issue #52)
  584. mixer.getStripsForSnapshot().onLayoutChanged = [this] {
  585. mixer.getLayoutBox().repaint();
  586. mixer.selectTrack (mixer.getStripsForSnapshot().getSelectedTrack()); // keep the selected strip in view
  587. saveUiSettings();
  588. };
  589. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  590. workspace.onFocusChanged = [this] (Panel panel) {
  591. refreshPanelButtons();
  592. // another panel took over (a click, F5..F9): the Browser's search box gives the keys back (issue #9)
  593. if (panel != Panel::browser)
  594. browser.leaveSearchBox();
  595. };
  596. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  597. PluginWindows::setDockWorkspace (&workspace); // FL's docked plugin windows float there (issue #116, developer switch)
  598. setEditorDock (&workspace); // and LYNX's own editor windows (round 190ev)
  599. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  600. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  601. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  602. };
  603. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  604. if (panel == Panel::channelRack)
  605. showPatternMenu();
  606. };
  607. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  608. workspace.setPersistent (persistent);
  609. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  610. playlist.onOpenPianoRoll = [this] {
  611. // edit a channel that plays in this pattern
  612. const auto& song = engine.getSong();
  613. const auto& notes = song.activePattern().notes;
  614. const auto channel = engine.getSelectedChannel();
  615. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  616. engine.setSelectedChannel (notes.front().channel);
  617. openPianoRoll();
  618. };
  619. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  620. picker.onPatternMenu = [this] { makePatternMenu (picker.pickedPatterns()).showMenuAsync (juce::PopupMenu::Options().withMousePosition()); };
  621. picker.onNewPattern = [this] { newPatternButton.onClick(); };
  622. playlist.onRenamePattern = [this] (int p) { showRenamePattern (p); };
  623. playlist.onGeneratorAdded = [this] (int channel, InstrumentKind kind) { rack.openGeneratorWindow (channel, kind); }; // round 190dx
  624. playlist.onViewOptionChanged = [this] { saveUiSettings(); };
  625. playlist.onOpenInSampler = [this] (int channel) {
  626. // the audio clip's file in a new Sampler channel (to play it from notes), its settings open
  627. const auto& song = engine.getSong();
  628. if (channel < 0 || channel >= (int) song.channels.size())
  629. return;
  630. ChannelDef c;
  631. c.name = song.channels[(std::size_t) channel].name;
  632. c.instrument = InstrumentKind::sampler;
  633. c.samplePath = song.channels[(std::size_t) channel].samplePath;
  634. c.colour = song.channels[(std::size_t) channel].colour;
  635. const auto added = rack.addChannel (c, false);
  636. showPanel (Panel::channelRack);
  637. rack.toggleEditor (added, false);
  638. };
  639. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  640. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  641. // recent files (stored in %APPDATA%\LYNX)
  642. recent.setMaxNumberOfItems (12);
  643. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  644. addAndMakeVisible (menuBar);
  645. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  646. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  647. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  648. &songPosition, &masterVolume, &masterPitch, &perfMeter, &chordPanel, &keyPanel, &output, &hintBar, &tweakReadout, &workspace, &midiLight,
  649. &multilinkButton, &linkToggle })
  650. {
  651. addAndMakeVisible (c);
  652. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  653. }
  654. // the dancers of the project's dance channels (FL's Fruity Dance) over the workspace (round 165e)
  655. danceStage = std::make_unique<DanceStage> (engine);
  656. danceStage->setMouseClickGrabsKeyboardFocus (false);
  657. addAndMakeVisible (*danceStage);
  658. for (auto& b : panelButtons)
  659. {
  660. addAndMakeVisible (b);
  661. b.setMouseClickGrabsKeyboardFocus (false);
  662. b.setWantsKeyboardFocus (false);
  663. }
  664. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  665. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  666. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton, &newPatternButton, &patternMenuButton, &pluginPickerButton })
  667. b->setWantsKeyboardFocus (false);
  668. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  669. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  670. b->setFlat (true);
  671. // a light header: every toolbar button is flat; "on" is a faint wash, in the accent for the states that
  672. // matter while working (playing, recording, metronome, recording options)
  673. {
  674. using namespace theme;
  675. const auto onWash = colour::accent.withAlpha (0.24f), onIcon = colour::accentHover; // (round 170e3: a clearer "on")
  676. for (auto* b : { &playButton, &stopButton, &recordButton, &patternModeButton, &songModeButton })
  677. b->setFlat (true);
  678. playButton.setOnColour (onWash);
  679. playButton.setIconColourWhenOn (onIcon);
  680. recordButton.setOnColour (colour::record.withAlpha (0.2f));
  681. recordButton.setIconColourWhenOn (colour::record);
  682. for (auto* b : { &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton,
  683. &patternModeButton, &songModeButton, &multilinkButton })
  684. {
  685. b->setOnColour (onWash);
  686. b->setIconColourWhenOn (onIcon);
  687. }
  688. for (auto& b : panelButtons)
  689. {
  690. b.setOnColour (colour::textPrimary.withAlpha (0.08f));
  691. b.setIconColourWhenOn (colour::textPrimary);
  692. }
  693. }
  694. quickTips = std::make_unique<ui::QuickTipWindow>();
  695. ui::installSliderContract();
  696. // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
  697. ui::onTweak = [this] (const AutomationTarget& t) { engine.noteTweaked (t); };
  698. // Options › Theme › Startup sound: its Play button (issue #12)
  699. themeui::previewStartupSound = [this] (const juce::String& path) {
  700. std::shared_ptr<const SampleData> sound;
  701. if (path.isNotEmpty() && juce::File (path).existsAsFile())
  702. sound = engine.getSampleLibrary().load (path);
  703. engine.previewSample (sound != nullptr ? sound : makeStartupSample());
  704. };
  705. // the toolbar's last-tweaked read-out opens the parameter's own menu (FL's Tools › Last tweaked; round 162d)
  706. tweakReadout.onClick = [this] {
  707. makeLastTweakedMenu (0).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tweakReadout));
  708. };
  709. // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
  710. onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
  711. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  712. || t.kind == AutomationTargetKind::channelParam || t.kind == AutomationTargetKind::channelAdjust;
  713. if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
  714. engine.setSelectedChannel (t.index);
  715. openPianoRoll();
  716. pianoRoll.showEventLane (t);
  717. };
  718. PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
  719. if (const auto t = engine.targetOfPlugin (plugin, param))
  720. {
  721. if (starting)
  722. engine.noteTweaked (*t, true);
  723. else
  724. engine.tweakReleased (*t);
  725. }
  726. };
  727. engine.nameAutomation = [this] (const AutomationTarget& t) { return describeAutomationTarget (engine, t).toStdString(); };
  728. externaldrag::install(); // issue #174: drags onto a hosted plugin's own editor become the system's file drag
  729. ui::installTypeAhead(); // issue #182: type-to-jump in menus, dropdowns and lists (JUCE fix 37)
  730. #if JUCE_PLUGINHOST_VST3
  731. // round 177b: a right-click on a VST3 plugin's knob (when the plugin asks the host for the parameter's menu) offers
  732. // LYNX's parameter items first: Create automation clip, Edit events, Link to MIDI / internal controller...
  733. vst3MenuEngine() = &engine;
  734. juce::lynxVst3ParamMenuHook = [] (juce::AudioPluginInstance& plugin, int param, juce::PopupMenu& menu) {
  735. if (auto* e = vst3MenuEngine())
  736. if (const auto t = e->targetOfPlugin (plugin, param))
  737. {
  738. menu.addSectionHeader ("LYNX SHARE - " + describeAutomationTarget (*e, *t));
  739. addAutomationItem (menu, *e, *t, true);
  740. }
  741. };
  742. #endif
  743. addAndMakeVisible (gridBox); // global grid (editors)
  744. snapToggleButton.setFlat (true);
  745. snapToggleButton.setOnColour (juce::Colours::transparentBlack);
  746. snapToggleButton.setIconColourWhenOn (theme::colour::accent);
  747. snapToggleButton.setWantsKeyboardFocus (false);
  748. snapToggleButton.setMouseClickGrabsKeyboardFocus (false);
  749. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  750. snapToggleButton.onClick = [this] {
  751. EditorGlobals::get().toggleGrid();
  752. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  753. };
  754. addAndMakeVisible (snapToggleButton);
  755. engine.addChangeListener (this);
  756. // MIDI controller profiles (round 190aw): LYNX as the controllers see it
  757. controllerBridge = std::make_unique<ControllerBridge> (engine, ControllerBridge::Window {
  758. [this] (const std::string& action) { return runAction (action); },
  759. [this] { return mixer.getSelectedTrack(); },
  760. [this] (int track) { mixer.selectTrack (track); } });
  761. engine.setControllerSurface (controllerBridge.get());
  762. // "Omni" links of mixer-slot controls follow the selected mixer track (round 190bt)
  763. engine.selectedMixerTrackForLinks = [this] { return mixer.getSelectedTrack(); };
  764. // round 190ef: the MIDI mappings of slots, scenes and transport switches act here; the transport is mappable
  765. engine.onRemoteFire = [this] (const remotemap::Fire& f) { fireRemote (f); };
  766. mapmode::tag (playButton, remotemap::Target::of (RemoteAction::play));
  767. mapmode::tag (stopButton, remotemap::Target::of (RemoteAction::stop));
  768. mapmode::tag (recordButton, remotemap::Target::of (RemoteAction::record));
  769. mapmode::tag (metronomeButton, remotemap::Target::of (RemoteAction::metronome));
  770. mapmode::tag (tempoDisplay, remotemap::Target::parameter ({ AutomationTargetKind::tempo, 0, 0, 0 }));
  771. setTypingPiano (typingPiano);
  772. setKeyboardSettingsListener ([this] { saveUiSettings(); }); // round 190ds: the keyboards' modes are UI settings
  773. setTypingKeyLetters ([this] (int key) -> std::string {
  774. // the letter of the typing key that plays `key` (FL's layout; the first key of the layout that does), Keys mode
  775. if (! typingPiano)
  776. return {};
  777. for (const char letter : std::string ("ZSXDCVGBHNJMQ2W3ER5T6Y7UI9O0P,L.;/")) // (the Q row before its duplicates , . /)
  778. if (const auto notes = keys::typingPianoKey (letter, typingOctave, typingRoot, typingLayout).notes; ! notes.empty() && notes.front() == key)
  779. return std::string (1, letter);
  780. return {};
  781. });
  782. refreshRecordOptionButtons();
  783. refreshToolbar();
  784. refreshPanelButtons();
  785. setToolbarLayout (toolbarLayout, false); // icon sizes and row height (loaded with the UI options)
  786. if (persistent && toolbarLayout.uiScale != 100)
  787. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  788. addChildComponent (chordNearHint);
  789. chordPanel.onMenu = [this] { showChordPanelMenu(); };
  790. keyPanel.onClick = [this] { showKeyMenu(); };
  791. linkToggle.setComponentID ("toolbar.link");
  792. linkToggle.onConfigure = [this] { openSettings ((int) SettingsPage::link); };
  793. keyPanel.setComponentID ("toolbar.key"); // (round 190dv: the first-song tour's ring)
  794. refreshKeyPanel();
  795. PianoRollComponent::onSelectedKeys = [this] (const std::vector<int>& keys) {
  796. if (! chordPanel.isVisible())
  797. return;
  798. refreshChordOptions();
  799. chordReadout.selection (keys, juce::Time::getMillisecondCounter());
  800. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  801. chordPanel.setText (chordReadout.lastWasNovelty() ? tr (text) : text);
  802. };
  803. setControlHints();
  804. fittedChannelCount = (int) engine.getSong().channels.size();
  805. hintBar.setHint ({ idleHint(), {}, false, false });
  806. setWantsKeyboardFocus (true);
  807. installDialogTextFocus(); // dialogs open with their text field focused (round 165q)
  808. if (startupMark != nullptr) startupMark ("main window: toolbar, menus, controllers");
  809. setSize (1180, 642);
  810. startTimerHz (30);
  811. uiTraceMonitor.start ([this, last = std::make_shared<RtStats::Snapshot>()] {
  812. // the audio side of the second (the watchdog thread: atomics only)
  813. const auto rt = engine.getRtStats().snapshot();
  814. const auto calls = rt.callbacks - last->callbacks;
  815. juce::String text;
  816. text << "audio: callbacks " << juce::String ((juce::int64) calls) << ", over deadline " << juce::String ((juce::int64) (rt.overBudget - last->overBudget))
  817. << ", late " << juce::String ((juce::int64) (rt.lateCalls - last->lateCalls)) << ", max load since start " << juce::String (rt.maxLoad * 100.0, 0)
  818. << "%, cpu " << juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) << "%";
  819. *last = rt;
  820. return text;
  821. });
  822. // new or updated plugins since the last run: an incremental scan in the background (unchanged files are
  823. // skipped), a few seconds after start so it doesn't compete with loading; the first run asks in the wizard
  824. if (autoscan::atStartup (persistent, setupWizardDone(), backgroundScanAtStart()) && platform::testMode())
  825. platform::testModeLog ("background plugin scan at start");
  826. else if (autoscan::atStartup (persistent, setupWizardDone(), backgroundScanAtStart()))
  827. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  828. if (safe != nullptr)
  829. safe->engine.getPluginHost().startBackgroundScan();
  830. });
  831. // round 168t (the YouTube review, 168d #9: "How do we get back to the playlist? Where is the playlist?"): the first
  832. // three starts name the window buttons and their keys in the hint bar for a while
  833. if (persistent)
  834. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  835. if (safe != nullptr)
  836. safe->showWindowsTip();
  837. });
  838. // Online Sessions P2 (round 169b): live sessions
  839. live = std::make_unique<LiveSessionManager> (engine);
  840. liveui::attach (*live);
  841. liveui::setRemoteSession (live.get(), &engine); // (P5-A1: the shared plugins in the menus, the guest's editor)
  842. live->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  843. if (safe != nullptr)
  844. {
  845. safe->repaint (safe->titleArea);
  846. safe->menuItemsChanged();
  847. safe->updateTitle(); // (the session's state is in the window title too: narrow layouts hide the badge)
  848. }
  849. };
  850. live->onJoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  851. if (safe == nullptr)
  852. return;
  853. const auto* host = song.session.find (session::hostTag);
  854. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  855. safe->startNewProject (std::move (song), {});
  856. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  857. safe->updateTitle();
  858. };
  859. // round 169j: the host's LYNX SHARE restarted during a session: its journal's song becomes the open project again
  860. live->onResumed = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  861. if (safe == nullptr)
  862. return;
  863. const auto journal = LiveSessionManager::readJournal (LiveSessionManager::defaultJournal());
  864. safe->startNewProject (std::move (song), {});
  865. if (journal && journal->projectFile.existsAsFile())
  866. {
  867. safe->currentFile = journal->projectFile;
  868. safe->projectName = journal->projectFile.getFileNameWithoutExtension();
  869. }
  870. safe->updateTitle();
  871. };
  872. // round 190ah: a guest's LYNX SHARE restarted during a session: the project it had is open again
  873. live->onRejoined = [safe = juce::Component::SafePointer<MainComponent> (this)] (Song song) {
  874. if (safe == nullptr)
  875. return;
  876. const auto* host = song.session.find (session::hostTag);
  877. const auto hostName = host != nullptr ? juce::String::fromUTF8 (host->name.c_str()) : juce::String();
  878. safe->startNewProject (std::move (song), {});
  879. safe->projectName = hostName.isNotEmpty() ? tr ("Live session with {0}", { hostName }) : tr ("Live session");
  880. safe->updateTitle();
  881. };
  882. engine.onSessionUndoSkipped = [] (const juce::StringArray& skipped) {
  883. ui::postHint ({ tr ("Undo left alone what someone else changed since: {0}", { skipped.joinIntoString (", ") }), {} }, 4000);
  884. };
  885. // round 190gh (B8): a MIDI device plugged in or out while LYNX SHARE runs (FL: "New MIDI device detected")
  886. engine.onMidiDevicesChanged = [] (const juce::StringArray& added, const juce::StringArray& removed) {
  887. juce::StringArray lines;
  888. if (! added.isEmpty())
  889. lines.add (tr ("MIDI device connected: {0}", { added.joinIntoString (", ") }));
  890. if (! removed.isEmpty())
  891. lines.add (tr ("MIDI device disconnected: {0}", { removed.joinIntoString (", ") }));
  892. ui::postNotice ({ lines.joinIntoString (" · "), {} }, 5000);
  893. };
  894. if (startStyle.style != layoutstyle::Style::pattern)
  895. setLayoutStyle (startStyle.style, false); // (the saved workspace layout is already this style's)
  896. updateGamepad(); // (round 184a, S16: only when the option is on)
  897. juce::Timer::callAfterDelay (1500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  898. if (safe != nullptr)
  899. safe->startLiveFromCommandLine();
  900. });
  901. // the keys a secondary window (tool, plugin, channel window) leaves unused run the global shortcuts, as in FL
  902. // FL's Auto select linked modules [DECOMP FUN_00f5c340] (round 187a): a focused channel / plugin window selects its
  903. // channel and that channel's mixer track; a mixer effect's window selects its track
  904. setLinkedWindowFocusHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (int channel, int insert) {
  905. if (safe == nullptr || ! ChannelRackComponent::autoSelectLinked)
  906. return;
  907. const auto& song = safe->engine.getSong();
  908. if (channel >= 0 && channel < (int) song.channels.size())
  909. {
  910. if (safe->engine.getSelectedChannel() != channel || safe->engine.getSelectedChannels().size() != 1)
  911. safe->engine.setSelectedChannel (channel);
  912. insert = song.channels[(std::size_t) channel].mixerTrack;
  913. }
  914. if (insert >= 0 && insert < (int) song.mixer.size())
  915. safe->mixer.selectTrack (insert);
  916. });
  917. simpleClickKeys.up = [this] (juce::Component* clicked) { simpleClickEnded (clicked); };
  918. setSecondaryWindowKeyHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  919. return safe != nullptr && safe->keyFromSecondaryWindow (key);
  920. });
  921. // keys over a focused plugin (rounds 181c/187a, issue #96): what it passes back plays, and with its "Typing keyboard priority" off LYNX goes first
  922. setPluginViewPlainKeyHandler ([] (juce::Component& window) { return PluginWindows::letsHostProcessKeys (window); },
  923. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  924. return safe != nullptr && safe->keyFromPluginView (key, true);
  925. },
  926. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  927. return safe != nullptr && safe->keyFromPluginView (key, false);
  928. });
  929. if (startupMark != nullptr) startupMark ("main window: live sessions, the rest of the constructor");
  930. }
  931. MainComponent::~MainComponent()
  932. {
  933. EffectsPanel::onHotSwapSlot = nullptr; // (round 190ce: it calls this window)
  934. engine.setControllerSurface (nullptr); // (the controllers get their closing messages)
  935. engine.selectedMixerTrackForLinks = nullptr;
  936. engine.onRemoteFire = nullptr;
  937. engine.setMapMode (remotemap::Mode::off);
  938. closeRemoteControlSettings();
  939. gamepadInput.reset();
  940. if (detailView != nullptr) // (round 183a: a docked Piano roll goes home while the workspace still exists)
  941. detailView->releaseEditor();
  942. if (simpleWorkflow != nullptr) // (round 190ds: the same for the Simple dock's Editor tab)
  943. simpleWorkflow->releaseEditor();
  944. setKeyboardSettingsListener (nullptr);
  945. setTypingKeyLetters (nullptr);
  946. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  947. juce::Desktop::getInstance().removeGlobalMouseListener (&simpleClickKeys);
  948. workspace.onWillShow = nullptr;
  949. engine.onSessionUndoSkipped = nullptr;
  950. engine.onMidiDevicesChanged = nullptr;
  951. PianoRollComponent::onSelectedKeys = nullptr;
  952. liveui::closeChat();
  953. liveui::setRemoteSession (nullptr, nullptr);
  954. live.reset(); // (a session still on ends: the others are told)
  955. setPluginViewPlainKeyHandler (nullptr, nullptr, nullptr);
  956. setSecondaryWindowKeyHandler (nullptr);
  957. setLinkedWindowFocusHandler (nullptr);
  958. cancelProjectLoad(); // an open in progress uses the engine from its thread
  959. if (sessionLock != nullptr) // a clean exit: no "LYNX did not close properly" next time
  960. sessionMarker.deleteFile();
  961. mixerinput::openAudioSettings = nullptr;
  962. openMixerInsertHandler() = nullptr;
  963. locateInBrowserHandler() = nullptr;
  964. openInNewChannelHandler() = nullptr;
  965. PatcherWindows::onBrowsePluginDatabase = nullptr;
  966. EditorGlobals::get().onOptionsChanged = nullptr;
  967. PianoRollComponent::shortcutText = nullptr;
  968. PlaylistComponent::shortcutText = nullptr;
  969. saveUiSettings();
  970. workspace.saveState();
  971. // Round 190fc (0.1.27 RC blocker B1): the Simple workflow goes while everything its Host reaches still exists. As a
  972. // member it was destroyed after `workspace` (declared later, destroyed first), and its destructor leaves the style
  973. // (SimpleWorkflow::left): Host::setTitleAccessory then reached the destroyed Workspace's panel frames — an access
  974. // violation in PanelFrame::setAccessory on every close (and the setup wizard's "Restart now") in the Simple layout.
  975. if (simpleWorkflow != nullptr)
  976. {
  977. playlist.onTrackEffects = nullptr;
  978. playlist.onSimpleTrackSelected = nullptr;
  979. playlist.onSimpleFilesDropped = nullptr;
  980. playlist.onExportTrack = nullptr;
  981. simpleWorkflow.reset();
  982. }
  983. simpleWorkflowAliveAfterTeardown = SimpleWorkflow::alive.load();
  984. ui::uninstallSliderContract();
  985. ui::onTweak = nullptr;
  986. themeui::previewStartupSound = nullptr;
  987. onEditEventsInPianoRoll = nullptr;
  988. PluginWindows::onGesture = nullptr;
  989. #if JUCE_PLUGINHOST_VST3
  990. juce::lynxVst3ParamMenuHook = nullptr;
  991. vst3MenuEngine() = nullptr;
  992. #endif
  993. removeDialogTextFocus();
  994. engine.nameAutomation = nullptr;
  995. PluginWindows::closeAll(); // plugin UIs before the engine
  996. PluginWindows::setDockWorkspace (nullptr); // (issue #116: the docked ones were in the workspace)
  997. setEditorDock (nullptr);
  998. ParametricEqWindows::closeAll();
  999. closeAutomationEditors();
  1000. closeChannelSettings();
  1001. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  1002. engine.removeChangeListener (this);
  1003. stopTimer();
  1004. }
  1005. void MainComponent::paint (juce::Graphics& g)
  1006. {
  1007. const uitrace::Scope trace ("MainComponent paint", true, g.getClipBounds());
  1008. using namespace theme;
  1009. g.fillAll (colour::bg1);
  1010. // the toolbar: one band, its panels separated by hairlines
  1011. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  1012. g.setColour (colour::bg3);
  1013. g.fillRect (bar);
  1014. g.setColour (colour::border);
  1015. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  1016. // round 170e3: each panel sits in its own quiet well (transport, master, recording, snap and pattern, windows,
  1017. // file, meters), so the groups read at a glance; with "Separators" off, only hairlines between them
  1018. if (toolbarLayout.separators) // (the toolbar menu's "Separators")
  1019. {
  1020. for (const auto& r : panelBounds)
  1021. if (! r.isEmpty())
  1022. {
  1023. const auto well = r.toFloat().reduced (1.0f, 2.0f);
  1024. g.setColour (colour::bg1.withAlpha (0.55f));
  1025. g.fillRoundedRectangle (well, radius::lg);
  1026. g.setColour (colour::border);
  1027. g.drawRoundedRectangle (well.reduced (0.5f), radius::lg, 1.0f);
  1028. }
  1029. }
  1030. else
  1031. {
  1032. g.setColour (colour::border.brighter (0.08f));
  1033. for (auto x : dividers)
  1034. g.fillRect (x, bar.getY() + 12, 1, bar.getHeight() - 24);
  1035. }
  1036. // Pattern / Song: one switch of two halves (round 170e3), the playing mode lit
  1037. if (! modeArea.isEmpty())
  1038. {
  1039. g.setColour (colour::bg2);
  1040. g.fillRoundedRectangle (modeArea.toFloat(), radius::lg);
  1041. g.setColour (colour::borderStrong);
  1042. g.drawRoundedRectangle (modeArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  1043. }
  1044. // play, stop and record share one quiet well
  1045. if (! transportArea.isEmpty())
  1046. {
  1047. g.setColour (colour::bg2);
  1048. g.fillRoundedRectangle (transportArea.toFloat(), radius::lg);
  1049. g.setColour (colour::border);
  1050. g.drawRoundedRectangle (transportArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  1051. }
  1052. // the hint bar sits in an inset well under the menu
  1053. if (! hintBar.getBounds().isEmpty())
  1054. {
  1055. g.setColour (colour::bg1);
  1056. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  1057. }
  1058. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  1059. if (! titleArea.isEmpty())
  1060. {
  1061. // the people of a live session first (round 169b), the project's name after them
  1062. const auto people = live != nullptr ? liveui::paintPresence (g, titleArea, *live) : 0;
  1063. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  1064. g.setFont (font (type::small, true));
  1065. g.setColour (colour::textSecondary);
  1066. if (const auto rest = titleArea.withTrimmedLeft (people > 0 ? people + 10 : 0); rest.getWidth() >= 50)
  1067. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name
  1068. + (engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String()), // round 190ap
  1069. rest, juce::Justification::centredRight, 1, 0.8f);
  1070. }
  1071. // captions that name the snap and pattern selectors, after their icons (the magnet is a button)
  1072. g.setFont (font (type::caption - 1.0f, true));
  1073. g.setColour (colour::textDisabled);
  1074. if (! snapLabelArea.isEmpty())
  1075. if (snapLabelArea.getWidth() > rowHeight + 20) // (the narrowest toolbar keeps only the magnet)
  1076. g.drawText (tr ("SNAP"), snapLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  1077. if (! patternLabelArea.isEmpty())
  1078. {
  1079. const auto iconBox = patternLabelArea.withWidth (rowHeight).toFloat();
  1080. icons::draw (g, Icon::pattern, iconBox.withSizeKeepingCentre (14.0f, 14.0f), colour::textDisabled);
  1081. if (patternLabelArea.getWidth() > rowHeight + 20)
  1082. g.drawText (tr ("PATTERN"), patternLabelArea.withTrimmedLeft (rowHeight + 1), juce::Justification::centredLeft, true);
  1083. }
  1084. }
  1085. void MainComponent::resized()
  1086. {
  1087. using toolbarlayout::Group;
  1088. if (const auto size = toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()); size != appliedIconSize)
  1089. applyIconSizing (size);
  1090. dividers.clear();
  1091. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  1092. auto toolbar = bar.reduced (8, toolbarLayout.visible ? 5 : 3);
  1093. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  1094. auto big = h + 14; // transport buttons: big, centred on both rows (round 170e3)
  1095. auto bigWidth = h + 14;
  1096. int gap = 17; // a divider and the space around it (13 when compact)
  1097. const auto grow = h - toolbarlayout::rowHeight (toolbarlayout::IconSize::medium); // wider panels for bigger rows
  1098. // panel widths
  1099. auto& lf = getLookAndFeel();
  1100. auto measureMenu = [&] {
  1101. int w = 0;
  1102. for (const auto& name : getMenuBarNames())
  1103. w += lf.getMenuBarItemWidth (menuBar, 0, name);
  1104. return w;
  1105. };
  1106. menuBar.getProperties().set ("lynxTightMenuBar", false);
  1107. int menuWidth = measureMenu();
  1108. if (menuWidth > 390) // translated menu titles (German, Russian...): English stays as it was
  1109. {
  1110. menuBar.getProperties().set ("lynxTightMenuBar", true);
  1111. menuWidth = measureMenu();
  1112. }
  1113. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  1114. int tempoWidth = 96 + grow, timeWidth = 140 + grow;
  1115. const int gridWidth = 148;
  1116. // the snap and pattern captions: an icon (the magnet button / the pattern icon) and the longer of the two names
  1117. const juce::Font captionFont (theme::font (theme::type::caption - 1.0f, true));
  1118. int captionWidth = h + 3 + juce::jlimit (30, 80, juce::roundToInt (juce::jmax (juce::GlyphArrangement::getStringWidth (captionFont, tr ("SNAP")),
  1119. juce::GlyphArrangement::getStringWidth (captionFont, tr ("PATTERN"))))) + 6;
  1120. std::array<int, toolbarlayout::groupCount> widths {};
  1121. const int tapWidth = juce::roundToInt (h * 0.8f); // the tempo tapper, right of the tempo (round 170e3)
  1122. widths[(std::size_t) Group::transport] = modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 2 + tapWidth + 4 + timeWidth;
  1123. widths[(std::size_t) Group::master] = 2 * (h + 26) + 4; // two big knobs side by side (round 170e3)
  1124. widths[(std::size_t) Group::record] = 5 * h + 8; // five per row (round 170e3)
  1125. widths[(std::size_t) Group::snap] = captionWidth + gridWidth;
  1126. widths[(std::size_t) Group::windows] = 3 * h + 4;
  1127. widths[(std::size_t) Group::file] = 3 * h + 4;
  1128. widths[(std::size_t) Group::meters] = 118;
  1129. widths[(std::size_t) Group::output] = 116 + grow * 2;
  1130. widths[(std::size_t) Group::chord] = 96; // (FL's panel: 96 px)
  1131. widths[(std::size_t) Group::multilink] = h; // one button (FL's MultiLinkBtn)
  1132. widths[(std::size_t) Group::key] = 112; // "Key" over "C# harmonic minor" (round 184a S11; the name shrinks to fit)
  1133. widths[(std::size_t) Group::link] = toolbar::LinkToggle::idealWidth (h); // "Link" / "2 Links" and its arrow (round 190gl)
  1134. const auto room = toolbar.getWidth();
  1135. // room for most hints on two lines; on a very wide window the hint bar takes more (round 170e3)
  1136. auto minHint = juce::jmax (menuWidth + 8, 320);
  1137. const auto maxHint = room >= 3000 ? 1000 : 620;
  1138. auto visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1139. // round 181b: the Chord detection panel is on the default toolbar, as in FL. At 1920 px it misses by about 90 px:
  1140. // tighter displays and gaps make the room (they get wider again when there is more); all the panels stay
  1141. if (toolbarLayout.visible && toolbarLayout.isShown (Group::chord) && ! visible[(std::size_t) Group::chord] && visible[(std::size_t) Group::record])
  1142. {
  1143. auto tighter = widths;
  1144. tighter[(std::size_t) Group::transport] -= 12 + 36; // the tempo and the song position, as narrow as the compact ones
  1145. tighter[(std::size_t) Group::snap] -= 16;
  1146. tighter[(std::size_t) Group::chord] = 88;
  1147. if (const auto fits = toolbarlayout::fit (toolbarLayout, tighter, 13, room, minHint); fits[(std::size_t) Group::chord])
  1148. {
  1149. widths = tighter;
  1150. tempoWidth -= 12;
  1151. timeWidth -= 36;
  1152. gap = 13;
  1153. visible = fits;
  1154. }
  1155. }
  1156. // round 170e3: rather than dropping the recording switches on a narrow window (1280-1440 px), the panels get
  1157. // tighter: four switches per row (the typing piano and the MIDI light go; Ctrl+T and the View menu keep the piano),
  1158. // a narrower snap box and displays
  1159. compactRecord = false;
  1160. narrowSnap = false;
  1161. if (toolbarLayout.visible && toolbarLayout.isShown (Group::record) && ! visible[(std::size_t) Group::record])
  1162. {
  1163. compactRecord = true;
  1164. const auto before = 3 * (bigWidth + 4) + tempoWidth + timeWidth;
  1165. big = h + 6;
  1166. bigWidth = h + 4;
  1167. tempoWidth = 84 + grow;
  1168. timeWidth = 104 + grow;
  1169. widths[(std::size_t) Group::transport] -= before - (3 * (bigWidth + 4) + tempoWidth + timeWidth);
  1170. widths[(std::size_t) Group::master] = 92; // the knobs over each other, as before
  1171. widths[(std::size_t) Group::record] = 4 * h + 6;
  1172. widths[(std::size_t) Group::snap] -= 16;
  1173. gap = 13;
  1174. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1175. // round 170e5: still too narrow (1280 px): the snap and pattern captions keep only their icons, the hint
  1176. // column only the menu's width, tighter displays and gaps; the recording switches stay
  1177. if (! visible[(std::size_t) Group::record])
  1178. {
  1179. const auto icons = h + 4;
  1180. widths[(std::size_t) Group::snap] -= captionWidth - icons;
  1181. captionWidth = icons;
  1182. tempoWidth -= 6;
  1183. timeWidth -= 8;
  1184. widths[(std::size_t) Group::transport] -= 14;
  1185. minHint = menuWidth + 8;
  1186. gap = 11;
  1187. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1188. }
  1189. // and still (1280 px, measured: the switches missed it by a few px): a narrower snap box, tight gaps; then
  1190. // the window buttons go before the recording switches (F5-F9 and the View menu open the same windows)
  1191. if (! visible[(std::size_t) Group::record])
  1192. {
  1193. widths[(std::size_t) Group::snap] -= 24;
  1194. narrowSnap = true;
  1195. gap = 8;
  1196. visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  1197. }
  1198. if (! visible[(std::size_t) Group::record])
  1199. {
  1200. auto narrow = toolbarLayout;
  1201. for (auto& e : narrow.entries)
  1202. if (e.group == Group::windows)
  1203. e.shown = false;
  1204. visible = toolbarlayout::fit (narrow, widths, gap, room, minHint);
  1205. }
  1206. }
  1207. if (! toolbarLayout.visible) // Ctrl+F11: only the menu and the hint bar, on one row
  1208. visible.fill (false);
  1209. panelBounds = {};
  1210. int used = 0;
  1211. for (int i = 0; i < toolbarlayout::groupCount; ++i)
  1212. used += visible[(std::size_t) i] ? widths[(std::size_t) i] + gap : 0;
  1213. auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used)), maxHint, room - used);
  1214. // round 170e3: the spare room goes to useful things first (a wider output monitor, snap and pattern boxes, song
  1215. // position and hint bar), then a little air between the panels, so no dead zone opens anywhere on a wide window
  1216. auto spare = juce::jmax (0, room - used - hintWidth);
  1217. auto grant = [&spare] (int share, int most) {
  1218. const auto g = juce::jmax (0, juce::jmin (most, spare * share / 100));
  1219. spare -= g;
  1220. return g;
  1221. };
  1222. if (visible[(std::size_t) Group::output])
  1223. widths[(std::size_t) Group::output] += grant (40, 900);
  1224. if (visible[(std::size_t) Group::snap])
  1225. widths[(std::size_t) Group::snap] += grant (20, 220);
  1226. if (const auto more = grant (15, 120); more > 0)
  1227. {
  1228. timeWidth += more;
  1229. widths[(std::size_t) Group::transport] += more;
  1230. }
  1231. hintWidth += grant (25, 500);
  1232. const auto shownGroups = (int) std::count (visible.begin(), visible.end(), true);
  1233. // at most twice the normal gap between the panels; what is still left goes to the output monitor and the hint bar
  1234. const auto extra = toolbarlayout::extraGap (spare, shownGroups, gap);
  1235. spare -= extra * shownGroups;
  1236. if (spare > 0)
  1237. {
  1238. const auto toOutput = visible[(std::size_t) Group::output] ? spare / 2 : 0;
  1239. widths[(std::size_t) Group::output] += toOutput;
  1240. hintWidth += spare - toOutput;
  1241. spare = 0;
  1242. }
  1243. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  1244. auto divide = [&] {
  1245. take (gap / 2 + extra / 2);
  1246. dividers.push_back (toolbar.getX());
  1247. take (gap - gap / 2 + extra - extra / 2);
  1248. };
  1249. auto hide = [] (std::initializer_list<juce::Component*> components) {
  1250. for (auto* c : components)
  1251. {
  1252. c->setVisible (false);
  1253. c->setBounds ({});
  1254. }
  1255. };
  1256. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  1257. c.setVisible (true);
  1258. c.setBounds (r);
  1259. };
  1260. // a block of icon buttons, three per row on both rows
  1261. auto grid = [&] (juce::Rectangle<int> panel, std::initializer_list<juce::Component*> buttons, int columns = 3) {
  1262. int i = 0;
  1263. for (auto* b : buttons)
  1264. {
  1265. const auto x = panel.getX() + (i % columns) * (h + 2);
  1266. put (*b, juce::Rectangle<int> (x, i < columns ? row1 : row2, h, h));
  1267. ++i;
  1268. }
  1269. };
  1270. // 1. the menu (and the project name beside it) over the hint bar; always first
  1271. if (! toolbarLayout.visible)
  1272. {
  1273. const auto row = toolbar.withHeight (h);
  1274. const auto menu = row.withWidth (juce::jmin (menuWidth + 8, row.getWidth()));
  1275. put (menuBar, menu);
  1276. titleArea = {};
  1277. placeHintBar (row.withTrimmedLeft (menu.getWidth() + 12).withWidth (juce::jmin (900, row.getWidth() - menu.getWidth() - 12)).reduced (0, 1));
  1278. fixedToolbarArea = bar;
  1279. }
  1280. else
  1281. {
  1282. auto column = take (hintWidth);
  1283. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  1284. put (menuBar, menu);
  1285. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  1286. if (titleArea.getWidth() < 60)
  1287. titleArea = {};
  1288. placeHintBar (column.withY (row2).withHeight (h).reduced (0, 1));
  1289. fixedToolbarArea = juce::Rectangle<int> (column.getX() - 4, 0, column.getWidth() + 8, toolbarHeight);
  1290. }
  1291. snapLabelArea = patternLabelArea = transportArea = modeArea = {};
  1292. for (const auto& entry : toolbarLayout.entries)
  1293. {
  1294. const auto group = entry.group;
  1295. if (! visible[(std::size_t) group])
  1296. {
  1297. switch (group)
  1298. {
  1299. case Group::transport:
  1300. hide ({ &patternModeButton, &songModeButton, &playButton, &stopButton, &recordButton, &tempoDisplay, &tapTempoButton, &timeDisplay, &songPosition });
  1301. break;
  1302. case Group::master: hide ({ &masterVolume, &masterPitch }); break;
  1303. case Group::record: hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton, &blendButton, &loopRecordButton, &stepEditButton, &punchButton, &midiLight }); break;
  1304. case Group::snap: hide ({ &gridBox, &snapToggleButton, &patternBox, &newPatternButton, &patternMenuButton }); break;
  1305. case Group::windows:
  1306. for (auto& b : panelButtons)
  1307. hide ({ &b });
  1308. hide ({ &pluginPickerButton });
  1309. break;
  1310. case Group::file: hide ({ &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton }); break;
  1311. case Group::meters: hide ({ &perfMeter }); break;
  1312. case Group::output: hide ({ &output }); break;
  1313. case Group::chord: hide ({ &chordPanel }); break;
  1314. case Group::multilink: hide ({ &multilinkButton }); break;
  1315. case Group::key: hide ({ &keyPanel }); break;
  1316. case Group::link: hide ({ &linkToggle }); break;
  1317. case Group::count_: break;
  1318. }
  1319. continue;
  1320. }
  1321. if (toolbarlayout::rightAligned (group) && spare > 0)
  1322. {
  1323. take (spare);
  1324. spare = 0;
  1325. }
  1326. divide();
  1327. auto panel = take (widths[(std::size_t) group]);
  1328. panelBounds[(std::size_t) group] = juce::Rectangle<int> (panel.getX() - 5, 0, panel.getWidth() + 10, toolbarHeight);
  1329. switch (group)
  1330. {
  1331. case Group::transport: // Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  1332. {
  1333. auto mode = panel.removeFromLeft (modeWidth);
  1334. modeArea = mode.withY (row1).withHeight (2 * h + 2).expanded (3, 2);
  1335. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  1336. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  1337. panel.removeFromLeft (8);
  1338. const auto y = panel.getCentreY() - big / 2;
  1339. transportArea = juce::Rectangle<int> (panel.getX(), y, 3 * bigWidth + 2 * 4, big);
  1340. for (auto* b : { &playButton, &stopButton, &recordButton })
  1341. {
  1342. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big).reduced (0, 3));
  1343. panel.removeFromLeft (bigWidth + 4);
  1344. }
  1345. panel.removeFromLeft (4);
  1346. const auto displays = juce::Rectangle<int> (panel.getX(), row1 + 3, panel.getWidth(), 2 * h - 6);
  1347. const auto displayHeight = displays.getHeight() - 10;
  1348. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  1349. put (tapTempoButton, displays.withTrimmedLeft (tempoWidth + 2).withWidth (tapWidth).withHeight (displayHeight));
  1350. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 2 + tapWidth + 4).withWidth (timeWidth).withHeight (displayHeight));
  1351. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 2 + tapWidth + 4 + timeWidth));
  1352. break;
  1353. }
  1354. case Group::master: // master volume beside master pitch, each a big knob with its name and value under it
  1355. {
  1356. if (compactRecord)
  1357. {
  1358. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  1359. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  1360. break;
  1361. }
  1362. const auto both = panel.withY (row1).withHeight (2 * h + 2);
  1363. put (masterVolume, both.withWidth (both.getWidth() / 2 - 2));
  1364. put (masterPitch, both.withTrimmedLeft (both.getWidth() / 2 + 2));
  1365. break;
  1366. }
  1367. case Group::record: // the recording switches (round 170e3, as FL's recording panel): metronome, wait for input, count-in,
  1368. // blend and the typing piano over loop record, step edit, punch, the recording options menu and the MIDI light
  1369. if (compactRecord)
  1370. {
  1371. hide ({ &typingPianoButton, &midiLight });
  1372. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton,
  1373. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton }, 4);
  1374. }
  1375. else
  1376. grid (panel, { &metronomeButton, &waitInputButton, &countInButton, &blendButton, &typingPianoButton,
  1377. &loopRecordButton, &stepEditButton, &punchButton, &recordMenuButton, &midiLight }, 5);
  1378. break;
  1379. case Group::snap: // global snap over the pattern selector, each with its name
  1380. {
  1381. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  1382. snapLabelArea = first.removeFromLeft (captionWidth);
  1383. put (snapToggleButton, snapLabelArea.withWidth (h));
  1384. put (gridBox, first.reduced (0, 1));
  1385. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  1386. patternLabelArea = second.removeFromLeft (captionWidth);
  1387. put (patternMenuButton, second.removeFromRight (h));
  1388. if (narrowSnap) // (the pattern box keeps room for a name)
  1389. {
  1390. put (newPatternButton, patternLabelArea.withWidth (h));
  1391. patternLabelArea = {};
  1392. }
  1393. else
  1394. {
  1395. put (newPatternButton, second.removeFromRight (h));
  1396. second.removeFromRight (2);
  1397. }
  1398. put (patternBox, second.reduced (0, 1));
  1399. break;
  1400. }
  1401. case Group::windows: // the windows and the plugin picker
  1402. grid (panel, { &panelButtons[(std::size_t) Panel::playlist], &panelButtons[(std::size_t) Panel::channelRack],
  1403. &panelButtons[(std::size_t) Panel::pianoRoll], &panelButtons[(std::size_t) Panel::mixer],
  1404. &panelButtons[(std::size_t) Panel::browser], &pluginPickerButton });
  1405. break;
  1406. case Group::file: // new, open, save over export, undo, redo
  1407. grid (panel, { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  1408. break;
  1409. case Group::meters: put (perfMeter, panel.withY (row1).withHeight (2 * h + 2)); break;
  1410. case Group::output: put (output, panel.withY (row1).withHeight (2 * h + 2)); break;
  1411. case Group::chord: put (chordPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1412. case Group::multilink: put (multilinkButton, panel.withY (row1).withHeight (h)); break;
  1413. case Group::key: put (keyPanel, panel.withY (row1).withHeight (2 * h + 2)); break;
  1414. case Group::link: put (linkToggle, panel.withY (row1 + h / 2 + 1).withHeight (h).reduced (0, 1)); break; // (centred on the two rows)
  1415. case Group::count_: break;
  1416. }
  1417. }
  1418. // the toolbar's edit mode: its overlay over the toolbar, and its tray between the toolbar and the windows
  1419. const auto tray = toolbarEditor != nullptr ? toolbar::EditOverlay::trayHeight : 0;
  1420. if (toolbarEditor != nullptr)
  1421. {
  1422. toolbarEditor->setBounds (0, 0, getWidth(), toolbarHeight + tray);
  1423. toolbarEditor->setToolbarHeight (toolbarHeight);
  1424. toolbarEditor->toFront (false);
  1425. }
  1426. auto below = getLocalBounds().withTrimmedTop (toolbarHeight + tray);
  1427. if (updateBar.isVisible())
  1428. updateBar.setBounds (below.removeFromTop (updater::UpdateBar::height));
  1429. if (remoteControlBar.isVisible())
  1430. remoteControlBar.setBounds (below.removeFromTop (24));
  1431. workspace.setBounds (below);
  1432. if (danceStage != nullptr)
  1433. {
  1434. danceStage->setBounds (getLocalBounds());
  1435. danceStage->toFront (false);
  1436. }
  1437. if (setupOverlay != nullptr)
  1438. {
  1439. hostSetupOverlayNatively();
  1440. nativechild::place (*setupOverlay, *this, getLocalBounds());
  1441. setupOverlay->toFront (false);
  1442. }
  1443. layoutMapMode(); // (round 190ef)
  1444. }
  1445. void MainComponent::hostSetupOverlayNatively()
  1446. {
  1447. // issue #116: in front of the native panels and docked plugin windows too (a native child window of its own, showing
  1448. // what is under it); without a native window yet, a plain overlay until there is one
  1449. if (setupOverlay == nullptr || ! nativechild::dockingEnabled() || nativechild::isAttached (*setupOverlay) || getPeer() == nullptr)
  1450. return;
  1451. removeChildComponent (setupOverlay.get());
  1452. if (auto host = nativechild::makeOverlayHost (setupOverlay, *this))
  1453. {
  1454. nativechild::forwardUnusedKeys (*host);
  1455. setupOverlay = std::move (host);
  1456. return;
  1457. }
  1458. addAndMakeVisible (*setupOverlay);
  1459. }
  1460. // --- toolbar layout ------------------------------------------------------------------------------
  1461. // The toolbar's rows and icons, and the editors' tool strips, for one icon size (round 170e3: the size in effect can be
  1462. // one step above the chosen one on a very wide window, toolbarlayout::effectiveIconSize).
  1463. void MainComponent::applyIconSizing (toolbarlayout::IconSize size)
  1464. {
  1465. appliedIconSize = size;
  1466. rowHeight = toolbarlayout::rowHeight (size);
  1467. toolbarHeight = toolbarLayout.visible ? 2 * rowHeight + 12 : rowHeight + 6; // (round 170e3: room for the panel wells)
  1468. const auto fraction = toolbarlayout::iconFraction (size), maxPx = toolbarlayout::iconMaxPx (size);
  1469. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton,
  1470. &patternMenuButton, &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &snapToggleButton,
  1471. &blendButton, &tapTempoButton, &loopRecordButton, &stepEditButton, &punchButton })
  1472. b->setIconSizing (fraction, maxPx);
  1473. for (auto& b : panelButtons)
  1474. b.setIconSizing (fraction, maxPx);
  1475. for (auto* b : { &playButton, &stopButton, &recordButton }) // solid transport glyphs on big buttons (round 170e3)
  1476. b->setIconSizing (0.42f, maxPx + 2.0f);
  1477. ToolStrip::iconSize = size;
  1478. pianoRoll.resized();
  1479. playlist.resized();
  1480. }
  1481. void MainComponent::setToolbarLayout (const toolbarlayout::Layout& layout, bool save)
  1482. {
  1483. const auto scaleChanged = layout.uiScale != toolbarLayout.uiScale;
  1484. if (save && layout.isShown (toolbarlayout::Group::key) != toolbarLayout.isShown (toolbarlayout::Group::key))
  1485. keyPanelFollowsStyle = false; // shown or hidden by hand (round 184a S11): the layout decides from now on
  1486. if (save && layout.isShown (toolbarlayout::Group::link) != toolbarLayout.isShown (toolbarlayout::Group::link))
  1487. linkToggleFollowsStyle = false; // (round 190gl, the same for the Link toggle)
  1488. toolbarLayout = layout;
  1489. applyIconSizing (toolbarlayout::effectiveIconSize (toolbarLayout.iconSize, getWidth()));
  1490. if (save && scaleChanged)
  1491. {
  1492. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  1493. // the windows grow with the zoom: keep their title bars and close buttons on the screen (round 163)
  1494. juce::Timer::callAfterDelay (200, [] { fitAllWindowsOnScreen(); });
  1495. }
  1496. resized();
  1497. repaint();
  1498. if (toolbarEditor != nullptr)
  1499. toolbarEditor->layoutChanged();
  1500. if (save)
  1501. saveUiSettings();
  1502. }
  1503. void MainComponent::showLinkToggle (bool on)
  1504. {
  1505. if (toolbarLayout.isShown (toolbarlayout::Group::link) == on)
  1506. return;
  1507. auto layout = toolbarLayout;
  1508. layout.setShown (toolbarlayout::Group::link, on);
  1509. setToolbarLayout (layout, true); // (by hand: the layout style stops deciding)
  1510. }
  1511. juce::PopupMenu MainComponent::makeToolbarMenu()
  1512. {
  1513. using toolbarlayout::Group;
  1514. juce::PopupMenu menu;
  1515. // FL's toolbar menu (Edit, Separators, Hide, Presets), then LYNX's direct switches per panel
  1516. menu.addSectionHeader (tr ("Toolbar"));
  1517. menu.addItem (tr ("Edit toolbar (drag panels to move, add or remove them)"), true, toolbarEditor != nullptr,
  1518. [this] { setToolbarEditing (toolbarEditor == nullptr); });
  1519. menu.addItem (tr ("Separators"), true, toolbarLayout.separators, [this] {
  1520. auto layout = toolbarLayout;
  1521. layout.separators = ! layout.separators;
  1522. setToolbarLayout (layout);
  1523. });
  1524. menu.addItem (tr ("Hide the toolbar panels") + shortcutText ("view.toolbar"), true, ! toolbarLayout.visible, [this] {
  1525. auto layout = toolbarLayout;
  1526. layout.visible = ! layout.visible;
  1527. setToolbarLayout (layout);
  1528. });
  1529. juce::PopupMenu presets;
  1530. const auto current = toolbarlayout::matchingPreset (toolbarLayout);
  1531. for (int p = 0; p < toolbarlayout::presetCount; ++p)
  1532. presets.addItem (tr (toolbarlayout::presetName ((toolbarlayout::Preset) p)), true, current == p, [this, p] {
  1533. auto layout = toolbarlayout::applyPreset (toolbarLayout, (toolbarlayout::Preset) p);
  1534. layout.visible = true;
  1535. setToolbarLayout (layout);
  1536. });
  1537. menu.addSubMenu (tr ("Presets"), presets);
  1538. menu.addSectionHeader (tr ("Panels"));
  1539. for (const auto& entry : toolbarLayout.entries)
  1540. {
  1541. const auto group = entry.group;
  1542. menu.addItem (tr (toolbarlayout::groupName (group)), true, entry.shown, [this, group] {
  1543. auto layout = toolbarLayout;
  1544. layout.setShown (group, ! layout.isShown (group));
  1545. layout.visible = true;
  1546. setToolbarLayout (layout);
  1547. });
  1548. }
  1549. menu.addSeparator();
  1550. menu.addItem (tr ("Show detected MIDI chords near the hint bar"), true, chordShowNearHint, [this] {
  1551. chordShowNearHint = ! chordShowNearHint;
  1552. chordNearHint.setVisible (false);
  1553. saveUiSettings();
  1554. });
  1555. menu.addSeparator();
  1556. juce::PopupMenu sizes;
  1557. const char* sizeNames[] = { TR_NOOP ("Small icons"), TR_NOOP ("Medium icons"), TR_NOOP ("Large icons") };
  1558. for (int i = 0; i < 3; ++i)
  1559. sizes.addItem (tr (sizeNames[i]), true, (int) toolbarLayout.iconSize == i, [this, i] {
  1560. auto layout = toolbarLayout;
  1561. layout.iconSize = (toolbarlayout::IconSize) i;
  1562. setToolbarLayout (layout);
  1563. });
  1564. menu.addSubMenu (tr ("Icon size"), sizes);
  1565. juce::PopupMenu scales;
  1566. for (auto percent : toolbarlayout::uiScales)
  1567. scales.addItem (juce::String (percent) + "%", true, toolbarLayout.uiScale == percent, [this, percent] {
  1568. auto layout = toolbarLayout;
  1569. layout.uiScale = percent;
  1570. setToolbarLayout (layout);
  1571. });
  1572. menu.addSubMenu (tr ("UI scale"), scales);
  1573. menu.addSeparator();
  1574. menu.addItem (tr ("Customize toolbar..."), [this] { showCustomizeToolbar(); });
  1575. menu.addItem (tr ("Reset toolbar to default"), ! toolbarLayout.isDefault(), false, [this] {
  1576. setToolbarLayout (toolbarlayout::Layout::makeDefault());
  1577. });
  1578. return menu;
  1579. }
  1580. void MainComponent::setToolbarEditing (bool editing)
  1581. {
  1582. if (editing == (toolbarEditor != nullptr))
  1583. return;
  1584. if (! editing)
  1585. {
  1586. removeChildComponent (toolbarEditor.get());
  1587. toolbarEditor.reset();
  1588. resized();
  1589. repaint();
  1590. return;
  1591. }
  1592. if (! toolbarLayout.visible) // editing shows the panels
  1593. {
  1594. auto layout = toolbarLayout;
  1595. layout.visible = true;
  1596. setToolbarLayout (layout);
  1597. }
  1598. toolbar::EditOverlay::Host host;
  1599. host.layout = [this] { return toolbarLayout; };
  1600. host.setLayout = [this] (const toolbarlayout::Layout& layout) { setToolbarLayout (layout); };
  1601. host.panels = [this] { return panelBounds; };
  1602. host.fixedArea = [this] { return fixedToolbarArea; };
  1603. host.snapshot = [this] (juce::Rectangle<int> area) {
  1604. // the panel as it looks, without the edit overlay on it
  1605. if (toolbarEditor != nullptr)
  1606. toolbarEditor->setVisible (false);
  1607. auto image = createComponentSnapshot (area, true);
  1608. if (toolbarEditor != nullptr)
  1609. toolbarEditor->setVisible (true);
  1610. return image;
  1611. };
  1612. host.done = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  1613. // after the click that asked for it
  1614. juce::MessageManager::callAsync ([safe] {
  1615. if (safe != nullptr)
  1616. safe->setToolbarEditing (false);
  1617. });
  1618. };
  1619. toolbarEditor = std::make_unique<toolbar::EditOverlay> (std::move (host), toolbarHeight);
  1620. addAndMakeVisible (*toolbarEditor);
  1621. resized();
  1622. repaint();
  1623. if (isShowing())
  1624. toolbarEditor->grabKeyboardFocus();
  1625. }
  1626. void MainComponent::runUndoStep (undokeys::Step step)
  1627. {
  1628. if (step != undokeys::Step::none)
  1629. undoRedo (step == undokeys::Step::redo);
  1630. }
  1631. void MainComponent::flUndo()
  1632. {
  1633. // FL's default: undo, or redo when something is undone ("undo/redo on the same shortcut"); "Alternate undo mode":
  1634. // every press one more step back (core/UndoKeys.h)
  1635. runUndoStep (undokeys::undoKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1636. }
  1637. void MainComponent::flUndoBackwards()
  1638. {
  1639. // FL's Undo backwards: one more step back; "Alternate undo mode" swaps the two shortcuts, so there it is the
  1640. // undo/redo key (round 190b)
  1641. runUndoStep (undokeys::backwardsKey (alternateUndo, engine.canUndo(), engine.canRedo()));
  1642. }
  1643. void MainComponent::undoRedo (bool redo)
  1644. {
  1645. // FL says in the hint bar what was undone and the undo level ("Undone: ... Level 2/3")
  1646. if (redo ? ! engine.canRedo() : ! engine.canUndo())
  1647. return;
  1648. const auto label = engine.getHistoryLabel (engine.getHistoryPosition() + (redo ? 1 : 0));
  1649. if (redo)
  1650. engine.redo();
  1651. else
  1652. engine.undo();
  1653. ui::Hint h;
  1654. h.text = (redo ? tr ("Redone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) })
  1655. : tr ("Undone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) }));
  1656. h.value = tr ("Level {0}/{1}", { juce::String (engine.getHistoryPosition() + 1), juce::String (engine.getHistorySize()) });
  1657. ui::postHint (h, 2500);
  1658. }
  1659. ui::Hint MainComponent::hintAt (juce::Point<int> p)
  1660. {
  1661. ui::Hint h;
  1662. if (p.y < toolbarHeight)
  1663. {
  1664. h.text = tr ("Toolbar: [RMB] toolbar menu (edit the panels: move, add, remove; presets; hide with Ctrl+F11)");
  1665. h.hasMenu = true;
  1666. }
  1667. return h;
  1668. }
  1669. void MainComponent::showToolbarMenu()
  1670. {
  1671. makeToolbarMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1672. }
  1673. void MainComponent::showCustomizeToolbar()
  1674. {
  1675. auto panel = std::make_unique<toolbar::CustomizePanel> (toolbarLayout);
  1676. panel->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] (const toolbarlayout::Layout& layout) {
  1677. if (safe != nullptr)
  1678. safe->setToolbarLayout (layout);
  1679. };
  1680. juce::DialogWindow::LaunchOptions options;
  1681. options.content.setOwned (fitContentToScreen (std::move (panel)).release());
  1682. options.dialogTitle = tr ("Customize toolbar");
  1683. options.dialogBackgroundColour = theme::colour::bg2;
  1684. options.useNativeTitleBar = true;
  1685. options.resizable = false;
  1686. options.escapeKeyTriggersCloseButton = true;
  1687. if (auto* dialog = options.launchAsync())
  1688. keepAboveMainWindow (*dialog);
  1689. }
  1690. void MainComponent::mouseDown (const juce::MouseEvent& e)
  1691. {
  1692. // a right-click on the toolbar's background (between the panels): show / hide groups, icon size, customize
  1693. if (e.mods.isPopupMenu() && e.y < toolbarHeight)
  1694. showToolbarMenu();
  1695. }
  1696. juce::Rectangle<int> MainComponent::getToolStripAreaForSnapshot (bool playlistStrip)
  1697. {
  1698. auto& editor = playlistStrip ? (juce::Component&) playlist : (juce::Component&) pianoRoll;
  1699. if (! editor.isVisible() || editor.getParentComponent() == nullptr || ! isParentOf (&editor))
  1700. return {};
  1701. const auto area = getLocalArea (&editor, editor.getLocalBounds());
  1702. return area.withHeight (40).withWidth (juce::jmin (area.getWidth(), 900)).getIntersection (getLocalBounds());
  1703. }
  1704. // --- keys --------------------------------------------------------------------------------------
  1705. keys::Context MainComponent::focusContext() const
  1706. {
  1707. if (pianoRollKeysHere()) // (round 183a: docked in the Clip-launch workflow's detail view)
  1708. return keys::Context::pianoRoll;
  1709. switch (workspace.getFocused())
  1710. {
  1711. case Panel::playlist: return keys::Context::playlist;
  1712. case Panel::channelRack: return keys::Context::channelRack;
  1713. case Panel::pianoRoll: return keys::Context::pianoRoll;
  1714. case Panel::mixer: return keys::Context::mixer;
  1715. case Panel::browser: return keys::Context::browser;
  1716. }
  1717. return keys::Context::global;
  1718. }
  1719. void MainComponent::dragOperationStarted (const juce::DragAndDropTarget::SourceDetails&)
  1720. {
  1721. // a drop on a window above this one (the Sampler's waveform, a plugin...) lands there, not on the panel under it
  1722. matchWindowOrderToScreen();
  1723. }
  1724. bool MainComponent::shouldDropFilesWhenDraggedExternally (const juce::DragAndDropTarget::SourceDetails& details, juce::StringArray& files,
  1725. bool& canMoveFiles)
  1726. {
  1727. return externaldrag::shouldDropFiles (details, &engine.getSong(), files, canMoveFiles);
  1728. }
  1729. bool MainComponent::keyPressed (const juce::KeyPress& key)
  1730. {
  1731. if (mapKeyPressed (key)) // round 190ef: the map modes' keys and the key mappings (Clip-launch layout only)
  1732. return true;
  1733. // round 190fo: while the Simple dock shows a Sampler track's pads, V B N M / F G H J / R T Y U / 4 5 6 7 play them
  1734. if (simpleWorkflow != nullptr && ! key.getModifiers().isAnyModifierKeyDown())
  1735. if (const auto padChannel = simpleWorkflow->padChannelForKey (key.getKeyCode()); padChannel >= 0)
  1736. {
  1737. if (! heldKeys.hasTag (key.getKeyCode()))
  1738. heldKeys.press (padChannel, simplepads::padKey, 0.8f, key.getKeyCode());
  1739. return true;
  1740. }
  1741. const auto chord = chordFromKeyPress (key);
  1742. // 1. the typing piano: the keys its layout takes (notes, FL's LOCK) win over the shortcuts; FL's FREE keys don't
  1743. const auto typed = typingKey (key);
  1744. if (typed.taken)
  1745. {
  1746. const auto code = key.getKeyCode();
  1747. if (! heldKeys.hasTag (code) && typingLaunches.count (code) == 0) // key repeat: the notes are already sounding
  1748. {
  1749. // FL sends the typing keyboard's notes as MIDI channel 1 (FUN_011828c0 -> FUN_01181620 channel 0): with
  1750. // "MIDI channel used for playlist live mode" = 1 and Performance mode on, they launch the Playlist's clips
  1751. // (what "Layout Performance mode" is for), else they play the selected channels
  1752. if (engine.typingNotesLaunchClips())
  1753. {
  1754. for (auto note : typed.notes)
  1755. if (perf::Command c; typingPerformance.note (note, true, c))
  1756. engine.performanceCommand (c);
  1757. typingLaunches[code] = typed.notes;
  1758. }
  1759. else
  1760. {
  1761. // round 190ds: Scale keys / Chord pad / Lock to key (core/ScaleKeys.h): the white keys play the project
  1762. // key's degrees or chords; nothing changes in Keys mode without the lock, or with no project key
  1763. auto notes = typed.notes;
  1764. const auto& mode = scalekeys::current();
  1765. if (mode.mode != scalekeys::Mode::keys || mode.lockToKey)
  1766. {
  1767. const auto zRow = keys::typingPianoKey ('Z', typingOctave, 0, 0).notes; // (FL's own layout: Z = C)
  1768. const auto baseC = zRow.empty() ? 60 : zRow.front();
  1769. std::vector<int> mapped;
  1770. for (auto note : typed.notes)
  1771. for (auto n : scalekeys::typedNotes (engine.getSong(), mode, mode.mode == scalekeys::Mode::keys ? note : note - typingRoot, baseC))
  1772. if (std::find (mapped.begin(), mapped.end(), n) == mapped.end())
  1773. mapped.push_back (n);
  1774. notes = std::move (mapped);
  1775. }
  1776. for (auto c : engine.getSelectedChannels())
  1777. for (auto note : notes) // (a chord layout's key plays several)
  1778. heldKeys.press (c, note, 0.8f, code);
  1779. }
  1780. }
  1781. return true;
  1782. }
  1783. const auto pianoKeys = typingPiano && ! isPlainKey (chord); // (a FREE plain key is a shortcut as with the piano off)
  1784. // round 190ce: Esc ends hot-swap (the reference's key for it) before it means anything else
  1785. if (key.isKeyCode (juce::KeyPress::escapeKey) && ! key.getModifiers().isAnyModifierKeyDown() && browser.isHotSwapping())
  1786. {
  1787. browser.endHotSwap();
  1788. return true;
  1789. }
  1790. // 2. a key the user gave an action himself (Options › Shortcuts) wins over the panels' built-in keys
  1791. // (issue #12: Metronome on 'C' did nothing while the Playlist, whose Knife is 'C', had the focus)
  1792. if (const auto own = keyMap.findUserBound (chord, focusContext(), pianoKeys); ! own.empty() && runAction (own))
  1793. return true;
  1794. // round 190ef: B is the reference's Draw Mode switch in the Clip-launch layout (core/SessionKeys.h); in the other
  1795. // layouts it stays the Playlist's and Piano roll's brush tool
  1796. if (key.getKeyCode() == 'B' || key.getKeyCode() == 'b')
  1797. if (isPlainKey (chord) && sessionkeys::defaultKeyActs (sessionkeys::Command::drawMode)
  1798. && dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) == nullptr)
  1799. {
  1800. drawmode::toggle();
  1801. return true;
  1802. }
  1803. // 3. the focused panel's own keys
  1804. const auto focused = workspace.getFocused();
  1805. const auto panelShown = workspace.isPanelVisible (focused);
  1806. if (((panelShown && focused == Panel::pianoRoll) || pianoRollKeysHere()) && pianoRoll.handleKey (key))
  1807. return true;
  1808. if (panelShown && focused == Panel::playlist && ! pianoRollKeysHere() && playlist.handleKey (key))
  1809. return true;
  1810. // 4. the key map
  1811. if (const auto action = keyMap.find (chord, focusContext(), pianoKeys); ! action.empty() && runAction (action))
  1812. return true;
  1813. // 5. issue #182: in the Browser, a typed character no key above took jumps to the row that starts with it (the
  1814. // typing piano, FL's L / R and the hot-swap Q keep their keys)
  1815. return panelShown && focused == Panel::browser && browser.typeToJump (key);
  1816. }
  1817. bool MainComponent::isPlainKey (const keys::Chord& chord) noexcept
  1818. {
  1819. return (chord.mods & (keys::ctrl | keys::alt | keys::shift)) == 0;
  1820. }
  1821. keys::TypingKey MainComponent::typingKey (const juce::KeyPress& key) const
  1822. {
  1823. if (! typingPiano || ! isPlainKey (chordFromKeyPress (key)))
  1824. return {};
  1825. // the key's place (FL's table goes by scan code): a German keyboard's Y, left of X, is the Z row's first key
  1826. const auto place = keys::typingpiano::physicalKey (key.getKeyCode(), [] (int code) { return scanCodeOfKeyCode (code); });
  1827. return keys::typingPianoKey (keys::letterOfKeyCode (place), typingOctave, typingRoot, typingLayout);
  1828. }
  1829. void MainComponent::releaseTypingLaunches (bool all)
  1830. {
  1831. for (auto it = typingLaunches.begin(); it != typingLaunches.end();)
  1832. if (all || ! juce::KeyPress::isKeyCurrentlyDown (it->first))
  1833. {
  1834. for (auto note : it->second)
  1835. if (perf::Command c; typingPerformance.note (note, false, c))
  1836. engine.performanceCommand (c);
  1837. it = typingLaunches.erase (it);
  1838. }
  1839. else
  1840. ++it;
  1841. }
  1842. bool MainComponent::keyFromSecondaryWindow (const juce::KeyPress& key)
  1843. {
  1844. // (round 165q / issue #12) a text field keeps its typing keys; the rest runs the global actions
  1845. const auto typingIntoText = dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr;
  1846. const auto chord = chordFromKeyPress (key);
  1847. // issue #117: the typing piano plays from Sytrus's window (any LYNX window) too; its release is polled (timer)
  1848. if (keys::KeyMap::secondaryWindowPlaysNote (typingKey (key).taken, typingIntoText))
  1849. return keyPressed (key);
  1850. const auto action = keyMap.findFromSecondaryWindow (chord, typingIntoText, typingPiano && (! isPlainKey (chord) || typingKey (key).taken));
  1851. return ! action.empty() && runAction (action);
  1852. }
  1853. bool MainComponent::keyFromPluginView (const juce::KeyPress& key, bool optionOn)
  1854. {
  1855. // the typing piano as over the main window (its release is polled, MainComponent::keyStateChanged). With the
  1856. // plugin's "Typing keyboard priority" off (LYNX first) the shortcuts run too; keys that do nothing here stay the plugin's.
  1857. if (typingKey (key).taken)
  1858. return keyPressed (key);
  1859. return optionOn && keyFromSecondaryWindow (key);
  1860. }
  1861. bool MainComponent::runAction (const std::string& id)
  1862. {
  1863. auto is = [&id] (const char* name) { return id == name; };
  1864. if (id.rfind ("view.detail", 0) == 0) // round 183a: Clip-launch workflow only (false: the chord falls through as before)
  1865. return runDetailAction (id);
  1866. // Round 190ce: the Browser's collections (the number keys on its selected row), hot-swap, the Device View's 0 key
  1867. if (id.rfind ("browser.collection", 0) == 0 && id.size() == 19 && id.back() >= '1' && id.back() <= '7')
  1868. {
  1869. browser.toggleCollectionOnSelection (id.back() - '1');
  1870. return true;
  1871. }
  1872. if (id == "browser.clearCollections")
  1873. {
  1874. browser.clearCollectionsOnSelection();
  1875. return true;
  1876. }
  1877. if (id == "view.hotSwap")
  1878. {
  1879. // (round 190ck: the default Q only in the Ableton-style layout, core/HotSwap.h keyActsInLayout)
  1880. if (! hotswap::keyActsInLayout (layoutStyle, keyMap.isDefault ("view.hotSwap")))
  1881. return false;
  1882. if (browser.isHotSwapping())
  1883. {
  1884. browser.endHotSwap();
  1885. return true;
  1886. }
  1887. // the Device View's selected device when it shows one, else the selected channel
  1888. auto target = detailView != nullptr ? detailView->selectedDeviceTarget() : hotswap::Target();
  1889. if (! target.active())
  1890. target = hotswap::targetOfChannel (engine.getSong(), engine.getSelectedChannel());
  1891. if (! target.active())
  1892. return false;
  1893. toggleHotSwap (target);
  1894. return true;
  1895. }
  1896. if (id == "rack.follow")
  1897. {
  1898. auto& g = EditorGlobals::get();
  1899. g.setFollowingView (EditorGlobals::FollowView::channelRack, ! g.isFollowingView (EditorGlobals::FollowView::channelRack));
  1900. rackFollowButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  1901. return true;
  1902. }
  1903. if (id.rfind ("pianoRoll.", 0) == 0 && pianoRoll.runKeyAction (id)) return true; // tools, slide, channel keys
  1904. if (id.rfind ("playlist.tool.", 0) == 0 && playlist.runKeyAction (id)) return true;
  1905. if (is ("transport.playStop")) playStop();
  1906. else if (is ("transport.pause")) playPause();
  1907. else if (is ("transport.playFromStart")) playFromStart();
  1908. else if (is ("transport.toggleMode")) toggleMode();
  1909. else if (is ("transport.nextMarker")) engine.jumpToNextMarker (true);
  1910. else if (is ("transport.previousMarker")) engine.jumpToNextMarker (false);
  1911. else if (is ("view.typingPiano")) toggleTypingPiano();
  1912. else if (is ("options.multilink")) engine.setMultilink (! engine.isMultilinkOn());
  1913. else if (is ("view.toolbar"))
  1914. {
  1915. auto layout = toolbarLayout;
  1916. layout.visible = ! layout.visible;
  1917. setToolbarLayout (layout);
  1918. }
  1919. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  1920. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  1921. else if (is ("panel.pianoRoll"))
  1922. {
  1923. togglePanel (Panel::pianoRoll);
  1924. if (workspace.isPanelVisible (Panel::pianoRoll))
  1925. pianoRoll.scrollToNotes();
  1926. }
  1927. else if (is ("panel.browser")) togglePanel (Panel::browser);
  1928. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  1929. else if (is ("panel.maximisePlaylist"))
  1930. {
  1931. workspace.toggleMaximised (Panel::playlist);
  1932. refreshPanelButtons();
  1933. }
  1934. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  1935. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  1936. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  1937. else if (is ("pattern.firstEmpty")) { engine.editSong ([] (Song& s) { gotoFirstEmptyPattern (s); }); showRenamePattern (engine.getSong().currentPattern); }
  1938. else if (is ("pattern.nextEmptyNoName")) engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1939. else if (is ("pattern.delete")) deleteCurrentPattern();
  1940. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  1941. else if (is ("pattern.insert")) insertPatternHere();
  1942. else if (is ("pattern.clone")) clonePatternNow();
  1943. else if (is ("pattern.moveUp")) movePatternNow (-1);
  1944. else if (is ("pattern.moveDown")) movePatternNow (1);
  1945. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  1946. else if (is ("view.pluginPicker")) togglePluginPicker();
  1947. else if (is ("panel.quickAdd"))
  1948. {
  1949. // FL's F8 opens the plugin picker or closes it (FLEngine 0xebf510, round 167o)
  1950. if (auto* open = findToolWindow ("quickadd"))
  1951. closeToolWindowOf (*open->getContentComponent());
  1952. else
  1953. showQuickAdd();
  1954. }
  1955. else if (is ("edit.history")) showHistory();
  1956. else if (is ("tools.stopSound")) engine.stopSound();
  1957. else if (is ("browser.search"))
  1958. {
  1959. showPanel (Panel::browser);
  1960. browser.focusSearch();
  1961. }
  1962. else if (is ("transport.record")) toggleRecording();
  1963. else if (is ("record.quickAudio")) quickRecordAudio();
  1964. else if (is ("transport.metronome"))
  1965. {
  1966. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  1967. refreshModeButton();
  1968. saveUiSettings(); // FL keeps it (ToolbarForm "MetronomeBtn", issue #152)
  1969. }
  1970. else if (is ("record.countIn"))
  1971. {
  1972. // FL's Ctrl+P (issue #152): off <-> on at the length chosen last (it was always 1 bar), kept between sessions
  1973. auto o = engine.getRecordOptions();
  1974. o.countInBars = countin::toggled (o.countInBars, o.countInLength);
  1975. engine.setRecordOptions (o);
  1976. refreshRecordOptionButtons();
  1977. saveUiSettings();
  1978. }
  1979. else if (is ("record.captureMidi")) // round 170d (Ableton's Capture MIDI, Logic's Capture as Recording)
  1980. {
  1981. // round 190ef / 190em: in the Clip-launch layout with the clip grid on screen, the phrase goes to the ARMED track
  1982. // (Live 12.4.16, live check 190ei; no armed track: the grid's selected track), in the selected scene's slot as a
  1983. // new clip that is launched at once, or into the clip that track plays
  1984. if (isClipLaunchWorkflow() && clipGridView != nullptr && clipGridView->isShowing())
  1985. {
  1986. auto [track, scene] = clipGridSelection (*clipGridView);
  1987. for (int t = 0; t < launcher::maxTracks; ++t)
  1988. if (engine.isGridTrackArmed (t))
  1989. {
  1990. track = t;
  1991. break;
  1992. }
  1993. int placed = -1;
  1994. bool into = false;
  1995. const auto r = engine.captureMidiToSlot (track, scene, placed, into);
  1996. if (r.notes > 0 && placed >= 0)
  1997. ui::postHint ({ into ? tr ("Capture MIDI: {0} notes put in the playing clip", { juce::String (r.notes) })
  1998. : tr ("Capture MIDI: {0} notes put in a new clip", { juce::String (r.notes) }), {}, false, false }, 4000);
  1999. else
  2000. ui::postHint ({ tr ("Capture MIDI: nothing to capture (play some notes first, without recording)"), {}, false, false }, 4000);
  2001. return true;
  2002. }
  2003. const auto r = engine.captureMidi();
  2004. if (r.notes > 0)
  2005. ui::postHint ({ tr ("Capture MIDI: {0} notes put in the pattern", { juce::String (r.notes) }), {}, false, false }, 4000);
  2006. else
  2007. ui::postHint ({ tr ("Capture MIDI: nothing to capture (play some notes first, without recording)"), {}, false, false }, 4000);
  2008. }
  2009. else if (is ("record.waitForInput"))
  2010. {
  2011. auto o = engine.getRecordOptions();
  2012. o.waitForInput = ! o.waitForInput;
  2013. engine.setRecordOptions (o);
  2014. refreshRecordOptionButtons();
  2015. }
  2016. else if (is ("record.blend") || is ("record.loop") || is ("record.punch"))
  2017. {
  2018. auto o = engine.getRecordOptions();
  2019. if (is ("record.blend"))
  2020. o.mode = o.mode == RecordMode::overdub ? RecordMode::replace : RecordMode::overdub;
  2021. else if (is ("record.loop"))
  2022. o.loopRecord = ! o.loopRecord;
  2023. else
  2024. o.punchLoopRegion = ! o.punchLoopRegion;
  2025. engine.setRecordOptions (o);
  2026. refreshRecordOptionButtons();
  2027. saveUiSettings();
  2028. }
  2029. else if (is ("record.stepEdit"))
  2030. {
  2031. engine.setStepEdit (! engine.isStepEdit());
  2032. stepSeekTick = stepPrevTick = -1.0; // starts at the position shown now
  2033. refreshRecordOptionButtons();
  2034. }
  2035. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  2036. else if (is ("rack.pianoRollView"))
  2037. {
  2038. rack.setPianoRollView (! rack.isPianoRollView());
  2039. saveUiSettings();
  2040. }
  2041. else if (is ("view.audioEditor")) openAudioEditorForSelection();
  2042. else if (is ("channel.soloSelected")) rack.solo (engine.getSelectedChannel());
  2043. else if (is ("automation.lastTweaked"))
  2044. {
  2045. // FL's Add › Automation for last tweaked parameter (round 143) from a key (round 190an): LYNX's own controls
  2046. // and a hosted plugin's parameters alike (AudioEngine::noteTweaked keeps the last moved one)
  2047. if (const auto t = engine.getLastTweaked (0))
  2048. createAutomationClip (engine, *t);
  2049. else
  2050. ui::postHint ({ tr ("Automation for last tweaked parameter"), tr ("Last tweaked: none") }, 3000);
  2051. }
  2052. else if (is ("view.tempoTapper")) openTempoTapper (engine);
  2053. else if (is ("view.sampleBrowser")) toggleSampleBrowser();
  2054. else if (is ("view.pluginDatabase"))
  2055. {
  2056. showPanel (Panel::browser);
  2057. browser.showPluginDatabase();
  2058. }
  2059. else if (is ("view.midiSettings") || is ("view.projectInfo"))
  2060. {
  2061. // FL's F10 / F11 (round 167o, issue #23): the same key closes Settings showing that page; on another page it
  2062. // switches in place
  2063. const auto page = is ("view.midiSettings") ? SettingsPage::midi : SettingsPage::info;
  2064. const auto shown = shownSettingsPage();
  2065. switch (keys::settingsKeyPress (shown >= 0, shown, (int) page))
  2066. {
  2067. case keys::SettingsKey::close: closeSettings(); break;
  2068. case keys::SettingsKey::switchPage: switchSettingsPage (page); break;
  2069. case keys::SettingsKey::open: openSettings ((int) page); break;
  2070. }
  2071. }
  2072. else if (is ("view.settings"))
  2073. {
  2074. // issue #181: Ctrl+, / Cmd+, opens Settings where it was left (General at first), and closes it when open
  2075. if (shownSettingsPage() >= 0)
  2076. closeSettings();
  2077. else
  2078. openSettings (lastSettingsPage);
  2079. }
  2080. else if (is ("view.closeUnfocusedWindows")) closeUnfocusedWindows();
  2081. else if (is ("view.alignChannelEditors")) alignAllChannelEditors (engine.getSelectedChannel());
  2082. else if (is ("view.touchKeyboard")) toggleTouchKeyboard (engine);
  2083. else if (is ("view.closePluginWindows") || is ("view.closeWindows"))
  2084. {
  2085. PluginWindows::closeAll();
  2086. ParametricEqWindows::closeAll(); // every native effect / controller editor
  2087. if (is ("view.closeWindows")) // FL's F12: the editors and tool windows too (LYNX's docked panels stay)
  2088. {
  2089. closeAutomationEditors();
  2090. closeChannelSettings();
  2091. closeAllToolWindows();
  2092. closeHelp();
  2093. }
  2094. }
  2095. else if (is ("rack.groupSelected")) rack.groupSelected();
  2096. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  2097. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  2098. else if (is ("browser.previous")) browser.step (-1, false);
  2099. else if (is ("browser.next")) browser.step (1, false);
  2100. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  2101. else if (is ("browser.swapNext")) browser.step (1, true);
  2102. else if (is ("browser.load")) browser.loadSelected();
  2103. else if (is ("browser.closeFolder")) browser.openFolder (false);
  2104. else if (is ("browser.openFolder")) browser.openFolder (true);
  2105. else if (is ("browser.rename"))
  2106. {
  2107. if (! browser.renameSelectedPlugin()) // not a plugin: F2's global action (rename the pattern)
  2108. showRenamePattern (engine.getSong().currentPattern);
  2109. }
  2110. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  2111. else if (is ("playlist.pickerPanel")) setPickerPanelOn (! pickerPanelOn);
  2112. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  2113. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  2114. else if (is ("file.new")) newProject();
  2115. else if (is ("file.open")) chooseFileToOpen();
  2116. else if (is ("file.save")) save (false);
  2117. else if (is ("file.saveAs")) save (true);
  2118. else if (is ("file.saveNewVersion")) saveNewVersion();
  2119. else if (is ("file.export")) exportAudio();
  2120. else if (is ("file.exportMaster")) showMasterDialog (engine, currentFile.getParentDirectory(), projectName);
  2121. else if (is ("file.exportMp3")) exportAudio (1);
  2122. else if (is ("file.exportMidi")) exportMidiFile();
  2123. else if (is ("tools.consolidateSelection")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), false);
  2124. else if (is ("tools.consolidateSelectionSongStart")) consolidatePlaylistSelection (engine, playlist.getSelectedClips(), true);
  2125. else if (is ("edit.undo")) flUndo();
  2126. else if (is ("edit.undoBackwards")) flUndoBackwards();
  2127. else if (is ("edit.redo")) undoRedo (true);
  2128. else if (is ("help.shortcuts"))
  2129. {
  2130. if (helpWindow != nullptr) // F1 again closes the sheet (issue #23)
  2131. closeHelp();
  2132. else
  2133. showHelp();
  2134. }
  2135. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  2136. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  2137. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  2138. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  2139. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  2140. else if (is ("rack.moveDown")) rack.moveSelected (1);
  2141. else if (is ("rack.selectAll")) rack.selectAll();
  2142. else if (is ("rack.clone")) rack.cloneSelected();
  2143. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  2144. else if (is ("rack.cut")) rack.cutSelected();
  2145. else if (is ("rack.copy")) rack.copySelected();
  2146. else if (is ("rack.paste")) rack.pasteSelected();
  2147. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  2148. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  2149. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  2150. else
  2151. return false;
  2152. return true;
  2153. }
  2154. bool MainComponent::keyStateChanged (bool)
  2155. {
  2156. // JUCE has no per-key "keyReleased"; check which held keys were released (each held note remembers its
  2157. // channel and key, so the selection changing meanwhile can't leave one sounding)
  2158. std::vector<int> released;
  2159. heldKeys.forEachTag ([&released] (int code) {
  2160. if (! juce::KeyPress::isKeyCurrentlyDown (code))
  2161. released.push_back (code);
  2162. });
  2163. for (auto code : released)
  2164. heldKeys.releaseTag (code);
  2165. releaseTypingLaunches (false);
  2166. // round 190ef: a mapped computer key let go: its mappings get the release (a clip in Gate mode stops)
  2167. for (auto it = heldMappedKeys.begin(); it != heldMappedKeys.end();)
  2168. if (! juce::KeyPress::isKeyCurrentlyDown (*it))
  2169. {
  2170. for (const auto& f : remotemap::keyFires (engine.getSong(), *it, false))
  2171. fireRemote (f);
  2172. it = heldMappedKeys.erase (it);
  2173. }
  2174. else
  2175. ++it;
  2176. return false;
  2177. }
  2178. // --- round 190ef: MIDI Map Mode / Key Map Mode (ui/MapMode.h, core/RemoteMap.h) ------------------------------------------
  2179. void MainComponent::setMapMode (remotemap::Mode mode)
  2180. {
  2181. if (layoutStyle != layoutstyle::Style::clipLaunch)
  2182. mode = remotemap::Mode::off;
  2183. if (mode != remotemap::Mode::off && mapOverlay == nullptr)
  2184. {
  2185. mapOverlay = std::make_unique<mapmode::Overlay> (engine, *this);
  2186. mapOverlay->onMessage = [] (const juce::String& text) { ui::postHint ({ text, {}, false, false }, 5000); };
  2187. addChildComponent (*mapOverlay);
  2188. mappingBrowser = std::make_unique<mapmode::MappingBrowser> (engine);
  2189. addChildComponent (*mappingBrowser);
  2190. }
  2191. if (mapOverlay == nullptr)
  2192. return;
  2193. const auto was = mapOverlay->getMode();
  2194. engine.setMapMode (mode);
  2195. mapOverlay->setMode (mode);
  2196. mapOverlay->setVisible (mode != remotemap::Mode::off);
  2197. mappingBrowser->setMode (mode);
  2198. mappingBrowser->setVisible (mode != remotemap::Mode::off);
  2199. layoutMapMode();
  2200. syncClipLaunchSwitches();
  2201. if (mode != was)
  2202. ui::postHint ({ mode == remotemap::Mode::midi ? tr ("MIDI Map Mode: click an element, then move a control on your MIDI device (Ctrl+M ends it)")
  2203. : mode == remotemap::Mode::key ? tr ("Key Map Mode: click an element, then press a computer key (Ctrl+K ends it)")
  2204. : tr ("Map mode off: the mappings act"),
  2205. {}, false, false },
  2206. 5000);
  2207. }
  2208. void MainComponent::layoutMapMode()
  2209. {
  2210. if (mapOverlay == nullptr || ! mapOverlay->isVisible())
  2211. return;
  2212. mapOverlay->setBounds (getLocalBounds());
  2213. mapOverlay->toFront (false);
  2214. // the Mapping Browser takes the Browser's place (the reference: "available while a map mode is on"); with the Browser
  2215. // hidden, a strip at the left of the workspace
  2216. auto browserShown = browser.getWidth() > 0;
  2217. for (const juce::Component* c = &browser; c != nullptr && c != this; c = c->getParentComponent())
  2218. browserShown = browserShown && c->isVisible();
  2219. auto area = browserShown ? getLocalArea (&browser, browser.getLocalBounds())
  2220. : getLocalArea (&workspace, workspace.getLocalBounds()).removeFromLeft (juce::jmin (320, getWidth() / 3));
  2221. mappingBrowser->setBounds (area);
  2222. mappingBrowser->toFront (false);
  2223. }
  2224. bool MainComponent::mapKeyPressed (const juce::KeyPress& key)
  2225. {
  2226. if (layoutStyle != layoutstyle::Style::clipLaunch)
  2227. return false;
  2228. const auto mods = key.getModifiers();
  2229. auto code = key.getKeyCode();
  2230. if (code >= 'a' && code <= 'z')
  2231. code -= 'a' - 'A';
  2232. const auto command = mods.isCommandDown() && ! mods.isAltDown() && ! mods.isShiftDown();
  2233. if (command && code == 'M' && sessionkeys::defaultKeyActs (sessionkeys::Command::midiMapMode))
  2234. {
  2235. setMapMode (getMapMode() == remotemap::Mode::midi ? remotemap::Mode::off : remotemap::Mode::midi);
  2236. return true;
  2237. }
  2238. if (command && code == 'K' && sessionkeys::defaultKeyActs (sessionkeys::Command::keyMapMode))
  2239. {
  2240. setMapMode (getMapMode() == remotemap::Mode::key ? remotemap::Mode::off : remotemap::Mode::key);
  2241. return true;
  2242. }
  2243. const auto plain = ! mods.isCommandDown() && ! mods.isAltDown() && ! mods.isCtrlDown();
  2244. if (getMapMode() != remotemap::Mode::off && mapOverlay->selection().has_value())
  2245. {
  2246. if (plain && (code == juce::KeyPress::deleteKey || code == juce::KeyPress::backspaceKey))
  2247. {
  2248. mapOverlay->unmapSelected();
  2249. return true;
  2250. }
  2251. if (getMapMode() == remotemap::Mode::key && plain && ! mods.isShiftDown() && code != juce::KeyPress::escapeKey)
  2252. {
  2253. mapOverlay->assignKey (code);
  2254. return true;
  2255. }
  2256. }
  2257. // the key mappings act while no map mode is on; a mapped key wins over the typing keyboard and the shortcuts
  2258. if (getMapMode() == remotemap::Mode::off && plain && ! mods.isShiftDown() && ! engine.getSong().remoteMappings.empty())
  2259. {
  2260. const auto fires = remotemap::keyFires (engine.getSong(), code, true);
  2261. if (fires.empty())
  2262. return false;
  2263. if (std::find (heldMappedKeys.begin(), heldMappedKeys.end(), code) == heldMappedKeys.end()) // (not the key's repeat)
  2264. {
  2265. heldMappedKeys.push_back (code);
  2266. for (const auto& f : fires)
  2267. fireRemote (f);
  2268. }
  2269. return true;
  2270. }
  2271. return false;
  2272. }
  2273. void MainComponent::fireRemote (const remotemap::Fire& f)
  2274. {
  2275. const auto press = f.edge == remotemap::Edge::press;
  2276. const auto& t = f.target;
  2277. switch (t.action)
  2278. {
  2279. case RemoteAction::parameter:
  2280. if (press) // (a key toggles the parameter between Min and Max)
  2281. if (const auto now = engine.currentTargetValue (t.param); now >= 0.0f)
  2282. engine.applyTargetValues ({ { t.param, remotemap::keyToggle (now, f.min, f.max) } });
  2283. break;
  2284. case RemoteAction::clipSlot:
  2285. engine.launcherCommand ({ press ? launcher::Command::Type::launch : launcher::Command::Type::release, t.track, t.scene });
  2286. break;
  2287. case RemoteAction::sceneLaunch:
  2288. if (press)
  2289. engine.launcherCommand ({ launcher::Command::Type::launchScene, 0, t.scene });
  2290. break;
  2291. case RemoteAction::trackStop:
  2292. if (press)
  2293. engine.launcherCommand ({ launcher::Command::Type::stopTrack, t.track });
  2294. break;
  2295. case RemoteAction::stopAllClips:
  2296. if (press)
  2297. engine.launcherCommand ({ launcher::Command::Type::stopAll });
  2298. break;
  2299. case RemoteAction::play:
  2300. if (press && ! engine.getTransport().playing.load())
  2301. playStop();
  2302. break;
  2303. case RemoteAction::stop:
  2304. if (press && engine.getTransport().playing.load())
  2305. playStop();
  2306. break;
  2307. case RemoteAction::record:
  2308. if (press)
  2309. runAction ("transport.record");
  2310. break;
  2311. case RemoteAction::sessionRecord:
  2312. if (press && clipGridView != nullptr)
  2313. engine.toggleSessionRecord (clipGridSelection (*clipGridView).second);
  2314. break;
  2315. case RemoteAction::metronome:
  2316. if (press)
  2317. runAction ("transport.metronome");
  2318. break;
  2319. }
  2320. }
  2321. juce::String MainComponent::shortcutText (const char* actionId) const
  2322. {
  2323. const auto& chords = keyMap.chordsFor (actionId);
  2324. return chords.empty() ? juce::String() : "\t" + juce::String (keys::displayString (chords.front()));
  2325. }
  2326. void MainComponent::toggleTypingPiano()
  2327. {
  2328. setTypingPiano (! typingPiano);
  2329. // say what changed in the hint bar (issue #34: people did not find the typing piano; Ctrl+T gave no feedback)
  2330. ui::Hint hint;
  2331. hint.text = typingPiano ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  2332. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)");
  2333. ui::postHint (hint, 2500);
  2334. }
  2335. void MainComponent::setTypingPiano (bool on)
  2336. {
  2337. typingPiano = on;
  2338. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  2339. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  2340. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard to piano: on (Z..M and Q..P play the selected channels)")
  2341. : tr ("Typing keyboard to piano: off (letter and number keys are shortcuts)"))
  2342. + juce::String (" (") + juce::String (keys::displayString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  2343. : keyMap.chordsFor ("view.typingPiano").front()))
  2344. + ")");
  2345. // release anything still sounding from the keyboard
  2346. heldKeys.releaseAll();
  2347. releaseTypingLaunches (true);
  2348. }
  2349. void MainComponent::loadKeyMap()
  2350. {
  2351. keyMap.resetToDefaults();
  2352. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  2353. if (file.existsAsFile())
  2354. {
  2355. std::vector<std::string> errors;
  2356. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  2357. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  2358. for (const auto& e : errors)
  2359. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  2360. }
  2361. auto keyOf = [this] (const std::string& id) {
  2362. const auto& chords = keyMap.chordsFor (id);
  2363. return chords.empty() ? juce::String() : juce::String (keys::displayString (chords.front()));
  2364. };
  2365. pianoRoll.refreshToolKeys (keyOf);
  2366. playlist.refreshToolKeys (keyOf);
  2367. }
  2368. // --- Browsers ------------------------------------------------------------------------------------
  2369. // The main Browser and the separate Sample browser window (round 163) act on the project the same way.
  2370. void MainComponent::connectBrowser (BrowserComponent& b)
  2371. {
  2372. b.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  2373. b.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  2374. b.onOpenMixerPreset = [this] (const juce::File& file) {
  2375. if (! mixerpresets::isMixerPreset (file))
  2376. return false;
  2377. if (! mixer.loadPresetOnSelection (file))
  2378. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  2379. tr ("This file is not a mixer track state LYNX SHARE can read."));
  2380. return true;
  2381. };
  2382. // the Browser's "Current project" items (REA_rodada115)
  2383. b.onOpenPattern = [this] (int pattern) {
  2384. selectPattern (pattern);
  2385. openPianoRoll();
  2386. };
  2387. b.onPatternMenu = [this] (int pattern) {
  2388. selectPattern (pattern);
  2389. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  2390. };
  2391. b.onOpenChannel = [this] (int channel) {
  2392. engine.setSelectedChannel (channel);
  2393. rack.toggleEditor (channel, true);
  2394. };
  2395. b.onOpenEffect = [this] (int track, int slot) {
  2396. showPanel (Panel::mixer);
  2397. mixer.openSlotEditor (track, slot);
  2398. };
  2399. b.onShowInsert = [this] (int track) {
  2400. showPanel (Panel::mixer);
  2401. mixer.selectTrack (track);
  2402. };
  2403. b.onOpenAutomation = [this] (int automation) { openAutomationEditor (engine, automation); };
  2404. // the Browser's Plugin database (round 142): the same targets as the quick-add palette
  2405. b.onAddInstrument = [this] (ChannelDef c) {
  2406. if (PatcherWindows::takeInstrumentFromBrowser (c)) // a Patcher's Add plugin › Browse plugin database (round 162)
  2407. return;
  2408. rack.addChannel (std::move (c), true);
  2409. showPanel (Panel::channelRack);
  2410. };
  2411. b.onAddEffect = [this] (EffectSlot slot) {
  2412. if (PatcherWindows::takeEffectFromBrowser (slot))
  2413. return;
  2414. if (! mixer.addEffectToSelected (std::move (slot)))
  2415. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  2416. tr ("The selected insert has no free effect slot."));
  2417. else
  2418. showPanel (Panel::mixer);
  2419. };
  2420. b.onPreviewVolumeChanged = [this] { saveUiSettings(); };
  2421. // round 190ce: hot-swap (the main Browser only: it is the one the device buttons and the key link)
  2422. b.onHotSwapChanged = [this] {
  2423. if (detailView != nullptr)
  2424. detailView->hotSwapChanged();
  2425. };
  2426. b.onHotSwapWillReplaceInstrument = [this] (int channel) { rack.closeEditorForHotSwap (channel); };
  2427. if (b.getRole() == BrowserComponent::Role::main)
  2428. EffectsPanel::onHotSwapSlot = [this] (int track, int slot) { toggleHotSwap (hotswap::targetOfEffect (engine.getSong(), track, slot)); };
  2429. b.onHotSwapSample = [this] (int channel, const juce::File& file) { rack.assignSampleForHotSwap (channel, file); };
  2430. b.onSendToPlaylist = [this] (const juce::File& file) {
  2431. playlist.addAudioClipAtPlayhead (file);
  2432. showPanel (Panel::playlist);
  2433. };
  2434. b.onToggleSampleBrowser = [this] { toggleSampleBrowser(); };
  2435. }
  2436. void MainComponent::toggleSampleBrowser()
  2437. {
  2438. if (auto* w = findToolWindow ("sampleBrowser"))
  2439. {
  2440. w->closeButtonPressed(); // (hidden, then deleted: remembered as closed)
  2441. return;
  2442. }
  2443. openSampleBrowser();
  2444. }
  2445. void MainComponent::openSampleBrowser()
  2446. {
  2447. auto* window = openToolWindow (BrowserComponent::makeSampleBrowserContent (engine, [this] (BrowserComponent& b) { connectBrowser (b); }),
  2448. tr ("Sample browser"), "sampleBrowser");
  2449. if (window == nullptr)
  2450. return;
  2451. window->setResizable (true, false);
  2452. window->setResizeLimits (240, 260, 4000, 4000);
  2453. const auto saved = BrowserComponent::sampleBrowserBounds();
  2454. const auto area = juce::Desktop::getInstance().getDisplays().getTotalBounds (true);
  2455. if (saved.getWidth() >= 240 && saved.getHeight() >= 260 && area.intersects (saved))
  2456. window->setBounds (saved);
  2457. else if (auto* top = getTopLevelComponent())
  2458. window->setBounds (top->getScreenBounds().getRight() - 360, top->getScreenY() + 80, 340, juce::jmax (400, top->getHeight() - 160));
  2459. }
  2460. // --- UI options ----------------------------------------------------------------------------------
  2461. juce::File MainComponent::uiSettingsFile() const
  2462. {
  2463. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  2464. }
  2465. void MainComponent::loadUiSettings()
  2466. {
  2467. juce::StringArray lines;
  2468. lines.addLines (uiSettingsFile().loadFileAsString());
  2469. // the sound in FL's order (0.1.20) wins over the old key, wherever each line is
  2470. const auto flMetronomeSound = std::any_of (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("metronomeSoundFl"); });
  2471. // "Blend recorded notes" (round 177c): see startingRecordMode() for who starts with what
  2472. {
  2473. const auto saved = std::find_if (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("recordBlend="); });
  2474. auto o = engine.getRecordOptions();
  2475. o.mode = startingRecordMode (uiSettingsFile().existsAsFile(), saved != lines.end(),
  2476. saved != lines.end() && saved->fromFirstOccurrenceOf ("=", false, false).trim() == "1");
  2477. o.countInBars = countin::startingBars (uiSettingsFile().existsAsFile()); // (issue #152; saved keys below win)
  2478. engine.setRecordOptions (o);
  2479. }
  2480. for (const auto& line : lines)
  2481. {
  2482. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  2483. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  2484. if (key == "typingPiano")
  2485. typingPiano = on;
  2486. else if (key == "typingOctave")
  2487. typingOctave = keys::typingpiano::clampOctave (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2488. else if (key == "typingRoot")
  2489. typingRoot = keys::typingpiano::clampRoot (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2490. else if (key == "typingLayout") // FL's layout name, so the list can grow
  2491. typingLayout = keys::typingpiano::layoutIndex (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2492. else if (key == "keepEditorsOpen")
  2493. ChannelRackComponent::keepEditorsOpen = on;
  2494. else if (key == "selFirstChanPatChanges")
  2495. ChannelRackComponent::selectFirstChannelWithNotes = on;
  2496. else if (key == "prPaintMode") // FL's PRPaintMode (round 189o)
  2497. PianoRollComponent::monophonicPainting = on;
  2498. else if (key == "prPreviewPlaying") // issue #183: the Piano roll's "Preview notes while playing" (off)
  2499. PianoRollComponent::previewWhilePlaying = on;
  2500. else if (key == "limitEditors") // FL's LimitEditors (round 189o; on unless saved off)
  2501. editorlimit::enabled() = on;
  2502. else if (key == "detachNewPlugins") // FL's General › "Detach all new plugins" (issue #116)
  2503. {
  2504. engine.setDetachNewPlugins (on);
  2505. setEditorsDetached (on); // (round 190ev: LYNX's own editor windows follow FL's option too)
  2506. }
  2507. else if (key == "autoSelectLinked")
  2508. ChannelRackComponent::autoSelectLinked = on;
  2509. else if (key == "muteRemovedSteps")
  2510. ChannelRackComponent::muteRemovedSteps = on;
  2511. else if (key == "audioTrackControls") // round 190w: Playlist › View › Track headers
  2512. PlaylistComponent::showAudioTrackControls = on;
  2513. else if (key == "audioTrackLevels")
  2514. PlaylistComponent::showAudioTrackLevels = on;
  2515. else if (key == "instrumentTrackLevels")
  2516. PlaylistComponent::showInstrumentTrackLevels = on;
  2517. else if (key == "automationLanes") // round 177b: Playlist › Automation lanes
  2518. autolanes::setShown (on);
  2519. else if (key == "pickerPanel") // issue #175: FL's Playlist menu › Picker panel › Enable
  2520. {
  2521. pickerPanelOn = on;
  2522. playlistArea.setPickerHidden (layoutStyle == layoutstyle::Style::simple || ! pickerPanelOn);
  2523. }
  2524. else if (key == "alternateUndo")
  2525. alternateUndo = on;
  2526. else if (key == "waveSpectral") // ("waveColours", the old spectral-by-default key, is ignored)
  2527. ui::WaveformCache::spectral = on;
  2528. else if (key == "pluginStyle") // "Automatic" or a style forced on every plugin
  2529. {
  2530. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim();
  2531. skin::setForcedStyle (v.equalsIgnoreCase ("Automatic") || v.isEmpty() ? -1 : (int) skin::styleFromName (v));
  2532. }
  2533. else if (key == "pluginStyleOverrides")
  2534. skin::overridesFromString (line.fromFirstOccurrenceOf ("=", false, false).trim());
  2535. else if (key == "reducedEffects")
  2536. skin::setReducedEffects (on);
  2537. else if (key == "animationRate") // round 174e2: 0 = the display's refresh, else 60 / 30
  2538. {
  2539. const auto hz = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2540. ui::FrameTicker::rateLimit() = hz == 30 || hz == 60 ? hz : 0;
  2541. }
  2542. else if (key == "uiAnimations") // round 179a (ui/Motion.h)
  2543. ui::motion::enabled() = on;
  2544. else if (key == "artMotion")
  2545. skin::setArtMotion (on);
  2546. else if (key == "waveStereo")
  2547. ui::WaveformCache::stereo = on;
  2548. else if (key == "samplerSpectrumView") // round 190gw: the Sampler waveform menu's view switches
  2549. samplerpage::waveViews().spectrum = on;
  2550. else if (key == "samplerMultichannelView")
  2551. samplerpage::waveViews().multichannel = on;
  2552. else if (key == "noteNames")
  2553. notenames::currentStyle.store (juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2554. else if (key == "noteFlats")
  2555. notenames::currentFlats.store (on);
  2556. else if (key == "noteNamesEveryKey")
  2557. notenames::everyKey.store (on);
  2558. else if (key == "rackPlayheadColumn")
  2559. ChannelRackComponent::playheadColumn.store (on);
  2560. else if (key == "rackStepsChannelColour")
  2561. ChannelRackComponent::stepsChannelColour.store (on);
  2562. else if (key == "rackCompletePreview")
  2563. ChannelRackComponent::completePreview.store (on);
  2564. else if (key == "rememberSeekTime") // (issue #169: the old "rememberSeek" key held LYNX's old default, off; FL's is on)
  2565. EditorGlobals::get().rememberSeek = on;
  2566. else if (key == "createVariants")
  2567. EditorGlobals::get().createVariants = on;
  2568. else if (key == "plLeftResizing") // round 189g: FL's Playlist Edit / Select options
  2569. EditorGlobals::get().leftResizing = on;
  2570. else if (key == "plWheelNudging")
  2571. EditorGlobals::get().wheelNudging = on;
  2572. else if (key == "plManualFades")
  2573. EditorGlobals::get().manualFades = on;
  2574. else if (key == "plSnapFadeHandles")
  2575. EditorGlobals::get().snapFadeHandles = on;
  2576. else if (key == "plAutomationFollowsClips") // round 190cg (absent = as the layout)
  2577. EditorGlobals::get().automationFollowsClips = on ? 1 : 0;
  2578. else if (key == "plMagicLasso")
  2579. EditorGlobals::get().magicLasso = on;
  2580. else if (key == "dropAudioOnHeaders") // round 189e: FL's Edit › Drop audio on track headers (DropAudioToPLMode)
  2581. {
  2582. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2583. trackmodes::headerDropOptions().mode = v == 256 || v == 257 || v == 258 ? (trackmodes::HeaderDrop) v : trackmodes::HeaderDrop::ask;
  2584. }
  2585. else if (key == "dropLocksToContent")
  2586. trackmodes::headerDropOptions().lockToContent = on;
  2587. else if (key == "selectTracksOnDrop")
  2588. trackmodes::headerDropOptions().selectTracks = on;
  2589. else if (key == "prGridHighlights") // (round 168g: the Piano roll's View items)
  2590. PianoRollComponent::gridHighlights = on;
  2591. else if (key == "prShowChordName")
  2592. PianoRollComponent::showChordName = on;
  2593. else if (key == "prSongBars")
  2594. PianoRollComponent::songBarsRuler = on;
  2595. else if (key == "prKeyStyle") // (round 190j: 0 = flat, FL's; 1 = piano keys)
  2596. PianoRollComponent::keyStyle = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue() == 1 ? pianokeys::Style::piano
  2597. : pianokeys::Style::flat;
  2598. else if (key == "audioLogEnabled")
  2599. engine.getRollingLog().setEnabled (on);
  2600. else if (key == "audioLogSeconds")
  2601. {
  2602. const auto seconds = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2603. if (seconds == 60 || seconds == 120 || seconds == 300 || seconds == 600)
  2604. engine.getRollingLog().setLengthSeconds (seconds);
  2605. }
  2606. else if (key == "audioLogPreEffects")
  2607. engine.getRollingLog().setPosition (on ? RollingAudioLog::Position::preEffects : RollingAudioLog::Position::postEffects);
  2608. else if (key == "chordDelayMs")
  2609. chordReadout.setDelayMs ((std::uint32_t) line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue());
  2610. else if (key == "chordRoman")
  2611. {
  2612. auto o = chordReadout.getOptions();
  2613. o.roman = on;
  2614. chordReadout.setOptions (o);
  2615. }
  2616. else if (key == "chordNearHint")
  2617. chordShowNearHint = on;
  2618. else if (key == "keyPanelFollowsStyle")
  2619. keyPanelFollowsStyle = on;
  2620. else if (key == "linkToggleFollowsStyle")
  2621. linkToggleFollowsStyle = on;
  2622. else if (key == "stretchedClipsLoop")
  2623. setStretchedClipsLoop (on);
  2624. else if (key == "autoClipsAtPlayback")
  2625. autoclipplace::setAtPlayback (on);
  2626. else if (key == "disableTypingPriority")
  2627. pluginkeys::newPluginsHostFirst() = on;
  2628. else if (key == "clipLaunchWorkflow") // (round 181a; applied when the window is ready; "layoutStyle" wins)
  2629. startStyle.legacyFlag (on);
  2630. else if (key == "layoutStyle") // (round 184a)
  2631. startStyle.styleId (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2632. else if (key == "lanesBeforeClipLaunch")
  2633. lanesBeforeClipLaunch = on;
  2634. else if (key == "detailHeight") // round 183a: the Clip-launch workflow's detail view
  2635. DetailView::preferredHeight = juce::jlimit (DetailView::minHeight, 2000, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2636. else if (key == "detailShown")
  2637. DetailView::shownSetting = on;
  2638. else if (key == "sceneTempoShown") // round 190ef: the clip grid's scene tempo / time signature fields
  2639. clipGridSceneTempoShown() = on;
  2640. else if (key == "simpleDockHeight") // round 190bu: the Simple workflow's track dock
  2641. SimpleDock::preferredHeight = juce::jlimit (SimpleDock::minHeight, 2000, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2642. else if (key == "simpleDockShown")
  2643. SimpleDock::shownSetting = on;
  2644. else if (key == "keyboardMode") // round 190ds: the keyboards' modes (core/ScaleKeys.h)
  2645. scalekeys::current().mode = (scalekeys::Mode) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2646. else if (key == "keyboardLock")
  2647. scalekeys::current().lockToKey = on;
  2648. else if (key == "chordComplexity")
  2649. scalekeys::current().complexity = (scalekeys::Complexity) juce::jlimit (0, scalekeys::complexityCount - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2650. else if (key == "chordSpread")
  2651. scalekeys::current().spread = (scalekeys::Spread) juce::jlimit (0, scalekeys::spreadCount - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2652. else if (key == "chordStrum")
  2653. scalekeys::current().strumMs = juce::jlimit (0, scalekeys::maxStrumMs, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2654. else if (key == "chordStrumDown")
  2655. scalekeys::current().strumDown = on;
  2656. else if (key == "chordProjectSet")
  2657. scalekeys::current().projectChords = on;
  2658. else if (key == "detailDevices")
  2659. DetailView::devicesPage = on;
  2660. else if (key == "detailExtraWindowKey")
  2661. DetailView::extraWindowKey = on;
  2662. else if (key == "detailExtraSelectInMixer")
  2663. DetailView::extraSelectInMixer = on;
  2664. else if (key == "alsSessionOnPlaylist")
  2665. AudioEngine::alsSessionOnPlaylist = on;
  2666. else if (key == "followPlaylist" || key == "followPianoRoll")
  2667. EditorGlobals::get().setFollowing (key == "followPianoRoll", on, false);
  2668. else if (key == "followChannelRack" || key == "followAudioEditor")
  2669. EditorGlobals::get().setFollowingView (key == "followChannelRack" ? EditorGlobals::FollowView::channelRack
  2670. : EditorGlobals::FollowView::audioEditor, on, false);
  2671. else if (key == "scopeMode")
  2672. toolbar::OutputMonitor::mode = juce::jlimit (0, toolbar::OutputMonitor::modeCount - 1,
  2673. line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2674. else if (key == "toolbarGroups")
  2675. toolbarLayout.orderFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2676. else if (key == "toolbarIcons")
  2677. toolbarLayout.iconSize = toolbarlayout::Layout::iconSizeFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2678. else if (key == "toolbarSeparators")
  2679. toolbarLayout.separators = on;
  2680. else if (key == "toolbarVisible")
  2681. toolbarLayout.visible = on;
  2682. else if (key == "menuDensity")
  2683. theme::menus::setCompact (line.fromFirstOccurrenceOf ("=", false, false).trim() != "comfortable");
  2684. else if (key == "uiScale")
  2685. toolbarLayout.uiScale = toolbarlayout::clampScale (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2686. else if (key == "editPatternsIn")
  2687. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2688. else if (key == "autosaveMinutes")
  2689. autosaveMinutes = prefs::clampAutosaveMinutes (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2690. else if (key == "askUnusedRecordings")
  2691. askUnusedRecordings = on;
  2692. else if (key == "messagesHidden") // FL's "Manage messages" (round 186c)
  2693. messages::setHiddenList (line.fromFirstOccurrenceOf ("=", false, false).trim());
  2694. else if (key == "backupWaitsForQuiet")
  2695. backupWaitsForQuiet = on;
  2696. else if (key == "backupLongestWait")
  2697. backupLongestWaitMinutes = prefs::clampBackupLongestWait (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2698. else if (key == "hoverValues")
  2699. hoverValues = on;
  2700. else if (key == "autosaveKeep")
  2701. autosaveKeep = prefs::clampAutosaveKeep (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2702. else if (key == "metronomeSound" && ! flMetronomeSound) // (before 0.1.20: 0 LYNX click, 1..5 hi-hat..pulse)
  2703. engine.getTransport().metronomeSound.store (metronome::soundFromLegacy (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2704. else if (key == "metronomeSoundFl") // FL's order: 0 Hi-hat, 1 Tick, 2 Beep, 3 Cowbell, 4 Pulse
  2705. engine.getTransport().metronomeSound.store (metronome::clampSound (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2706. // FL's Settings options of round 190bx (core/FlSettings.h: resampling quality, CPU switches, auto close...)
  2707. else if (flsettings::parse (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString()))
  2708. {
  2709. }
  2710. else if (key == "renderAhead") // (round 190gq: Options › Audio settings › "Render ahead", on by default)
  2711. renderAheadOption().store (line.fromFirstOccurrenceOf ("=", false, false).trim() != "0");
  2712. else if (key == "metronomeTrack")
  2713. engine.getTransport().metronomeTrack.store (juce::jlimit (0, maxMixerTracks - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2714. else if (key == "playTruncatedOnTransport")
  2715. engine.getTransport().playTruncatedOnTransport.store (on);
  2716. else if (key == "resetPluginsOnTransport")
  2717. engine.getTransport().resetPluginsOnTransport.store (on);
  2718. else if (key == "metronomeVolume")
  2719. engine.getTransport().metronomeVolume.store ((float) controls::clampUtilityVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue()));
  2720. else if (key == "previewVolume")
  2721. engine.setPreviewVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  2722. else if (key == "previewInTime") // the Browser's "Preview in time" (round 190aq)
  2723. engine.setPreviewInTime (on);
  2724. else if (key == "browserAutoPreview") // the Browser's "Preview files when they are selected" (round 190ce)
  2725. BrowserComponent::autoPreview = on;
  2726. else if (key == "editorVolume")
  2727. engine.setEditorVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  2728. else if (key == "rackPianoRollView")
  2729. rack.setPianoRollView (on);
  2730. else if (key == "undoLevels")
  2731. engine.setUndoLevels (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2732. else if (key == "askWhatToRecord" || key == "recordNotes" || key == "recordAudio" || key == "recordStartsPlayback" || key == "disarmOnStop"
  2733. || key == "recordOffOnStop" || key == "unarmAfterRender" || key == "renderAutoClip" || key == "lowLatencyRecording"
  2734. || key == "recLatencyCompensation")
  2735. {
  2736. auto o = engine.getRecordOptions();
  2737. (key == "askWhatToRecord" ? o.askWhatToRecord : key == "recordNotes" ? o.recordNotes : key == "recordAudio" ? o.recordAudio
  2738. : key == "lowLatencyRecording" ? o.lowLatencyRecording : key == "recLatencyCompensation" ? o.latencyCompensation
  2739. : key == "disarmOnStop" ? o.disarmOnStop : key == "recordOffOnStop" ? o.recordOffOnStop : key == "unarmAfterRender" ? o.unarmAfterRender
  2740. : key == "renderAutoClip" ? o.autoCreateClip
  2741. : o.startsPlayback) = on;
  2742. engine.setRecordOptions (o);
  2743. }
  2744. else if (key == "recordAutomation" || key == "recordQuantiseAutomation" || key == "recordClips")
  2745. {
  2746. auto o = engine.getRecordOptions();
  2747. (key == "recordAutomation" ? o.recordAutomation : key == "recordClips" ? o.recordClips : o.quantiseAutomation) = on;
  2748. engine.setRecordOptions (o);
  2749. }
  2750. else if (key == "recordToStepSequencer" || key == "recordingMarkers" || key == "recordNoteEnd")
  2751. {
  2752. auto o = engine.getRecordOptions();
  2753. if (key == "recordNoteEnd")
  2754. o.noteEnd = (NoteEnd) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  2755. else
  2756. (key == "recordToStepSequencer" ? o.toStepSequencer : o.recordingMarkers) = on;
  2757. engine.setRecordOptions (o);
  2758. }
  2759. else if (key == "recordCatchWindow" || key == "recordCompensateOutput") // (round 170d)
  2760. {
  2761. auto o = engine.getRecordOptions();
  2762. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getLargeIntValue();
  2763. if (key == "recordCatchWindow")
  2764. o.catchWindow = juce::jlimit<std::int64_t> (0, ppq, v);
  2765. else
  2766. o.compensateOutput = v != 0;
  2767. engine.setRecordOptions (o);
  2768. }
  2769. else if (key == "recordPunchLoop" || key == "recordPreRoll" || key == "recordPostRoll" || key == "recordLoop" || key == "recordLastPassPlays")
  2770. {
  2771. auto o = engine.getRecordOptions();
  2772. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  2773. if (key == "recordPunchLoop")
  2774. o.punchLoopRegion = v != 0;
  2775. else if (key == "recordLoop")
  2776. o.loopRecord = v != 0;
  2777. else if (key == "recordLastPassPlays")
  2778. o.lastLoopPassPlays = v != 0;
  2779. else
  2780. (key == "recordPreRoll" ? o.preRollBars : o.postRollBars) = juce::jlimit (0, 8, v);
  2781. engine.setRecordOptions (o);
  2782. }
  2783. else if (key == juce::String (countin::onKey.data()) || key == juce::String (countin::lengthKey.data())) // (issue #152)
  2784. {
  2785. auto o = engine.getRecordOptions();
  2786. countin::readSetting (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue(), o.countInBars, o.countInLength);
  2787. engine.setRecordOptions (o);
  2788. refreshRecordOptionButtons();
  2789. }
  2790. else if (key == "metronomeOn") // (issue #152)
  2791. {
  2792. engine.getTransport().metronome.store (on);
  2793. refreshModeButton();
  2794. }
  2795. else if (key == "recordQuantiseStarts")
  2796. {
  2797. recordQuantiseOn = on;
  2798. updateRecordQuantise();
  2799. }
  2800. else if (NewProjectDefaults::ownsKey (key.toStdString())) // (issue #170: newLinkTracks was missing from this list)
  2801. newProjectDefaults().readKey (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2802. else if (key == "mixerUsedOnly")
  2803. MixerStrips::showUsedOnly = on;
  2804. else if (key == "mixerLoudness") // round 190am (also starts the measurement)
  2805. mixer.getStripsForSnapshot().setShowLoudness (on);
  2806. else if (key == "mixerKeepLostLinks")
  2807. MixerStrips::keepLostLinks = on;
  2808. else if (key == "mixerFollowPlaylist")
  2809. MixerStrips::followPlaylist = on;
  2810. else if (key == "mixerLayout") // FL's FXViewMode numbering (issue #52)
  2811. {
  2812. MixerStrips::layout = mixerlayout::parse (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  2813. mixer.getStripsForSnapshot().updateSize();
  2814. }
  2815. else if (key == "quantizeSongJumps")
  2816. engine.quantizeSongJumps.store (juce::jlimit (0, 5, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  2817. }
  2818. startup = StartupOptions::load();
  2819. browser.refreshPreviewVolume();
  2820. }
  2821. void MainComponent::saveUiSettings()
  2822. {
  2823. if (! persistent)
  2824. return;
  2825. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\ntypingOctave=" + juce::String (typingOctave)
  2826. + "\ntypingRoot=" + juce::String (typingRoot)
  2827. + "\ntypingLayout=" + juce::String (keys::typingpiano::layoutName (typingLayout)) + "\nkeepEditorsOpen="
  2828. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0)
  2829. + "\nselFirstChanPatChanges=" + juce::String (ChannelRackComponent::selectFirstChannelWithNotes ? 1 : 0)
  2830. + "\nprPaintMode=" + juce::String (PianoRollComponent::monophonicPainting ? 1 : 0)
  2831. + "\nprPreviewPlaying=" + juce::String (PianoRollComponent::previewWhilePlaying ? 1 : 0)
  2832. + "\nlimitEditors=" + juce::String (editorlimit::enabled() ? 1 : 0)
  2833. + "\ndetachNewPlugins=" + juce::String (engine.detachesNewPlugins() ? 1 : 0)
  2834. + "\nautoSelectLinked=" + juce::String (ChannelRackComponent::autoSelectLinked ? 1 : 0)
  2835. + "\nmuteRemovedSteps=" + juce::String (ChannelRackComponent::muteRemovedSteps ? 1 : 0)
  2836. + "\naudioTrackControls=" + juce::String (PlaylistComponent::showAudioTrackControls ? 1 : 0)
  2837. + "\naudioTrackLevels=" + juce::String (PlaylistComponent::showAudioTrackLevels ? 1 : 0)
  2838. + "\ninstrumentTrackLevels=" + juce::String (PlaylistComponent::showInstrumentTrackLevels ? 1 : 0)
  2839. + "\nautomationLanes=" + juce::String (autolanes::shown() ? 1 : 0)
  2840. + "\npickerPanel=" + juce::String (pickerPanelOn ? 1 : 0)
  2841. + "\nalternateUndo=" + juce::String (alternateUndo ? 1 : 0)
  2842. + "\neditPatternsIn="
  2843. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  2844. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0)
  2845. + "\nwaveSpectral=" + juce::String (ui::WaveformCache::spectral ? 1 : 0)
  2846. + "\nwaveStereo=" + juce::String (ui::WaveformCache::stereo ? 1 : 0)
  2847. + "\nsamplerSpectrumView=" + juce::String (samplerpage::waveViews().spectrum ? 1 : 0)
  2848. + "\nsamplerMultichannelView=" + juce::String (samplerpage::waveViews().multichannel ? 1 : 0)
  2849. + "\nnoteNames=" + juce::String (notenames::currentStyle.load())
  2850. + "\nnoteFlats=" + juce::String (notenames::currentFlats.load() ? 1 : 0)
  2851. + "\nnoteNamesEveryKey=" + juce::String (notenames::everyKey.load() ? 1 : 0)
  2852. + "\nrackPlayheadColumn=" + juce::String (ChannelRackComponent::playheadColumn.load() ? 1 : 0)
  2853. + "\nrackStepsChannelColour=" + juce::String (ChannelRackComponent::stepsChannelColour.load() ? 1 : 0)
  2854. + "\nrackCompletePreview=" + juce::String (ChannelRackComponent::completePreview.load() ? 1 : 0)
  2855. + "\nreducedEffects=" + juce::String (skin::reducedEffects() ? 1 : 0)
  2856. + "\nanimationRate=" + juce::String (ui::FrameTicker::rateLimit())
  2857. + "\nuiAnimations=" + juce::String (ui::motion::enabled() ? 1 : 0)
  2858. + "\nartMotion=" + juce::String (skin::artMotion() ? 1 : 0)
  2859. + "\npluginStyle=" + juce::String (skin::forcedStyle() < 0 ? "Automatic" : skin::styleName ((skin::Style) skin::forcedStyle()))
  2860. + "\npluginStyleOverrides=" + skin::overridesToString()
  2861. + "\nrememberSeekTime=" + juce::String (EditorGlobals::get().rememberSeek ? 1 : 0)
  2862. + "\ncreateVariants=" + juce::String (EditorGlobals::get().createVariants ? 1 : 0)
  2863. + "\nplLeftResizing=" + juce::String (EditorGlobals::get().leftResizing ? 1 : 0)
  2864. + "\nplWheelNudging=" + juce::String (EditorGlobals::get().wheelNudging ? 1 : 0)
  2865. + "\nplManualFades=" + juce::String (EditorGlobals::get().manualFades ? 1 : 0)
  2866. + "\nplSnapFadeHandles=" + juce::String (EditorGlobals::get().snapFadeHandles ? 1 : 0)
  2867. + (EditorGlobals::get().automationFollowsClips < 0 ? juce::String()
  2868. : "\nplAutomationFollowsClips=" + juce::String (EditorGlobals::get().automationFollowsClips))
  2869. + "\nplMagicLasso=" + juce::String (EditorGlobals::get().magicLasso ? 1 : 0)
  2870. + "\ndropAudioOnHeaders=" + juce::String ((int) trackmodes::headerDropOptions().mode)
  2871. + "\ndropLocksToContent=" + juce::String (trackmodes::headerDropOptions().lockToContent ? 1 : 0)
  2872. + "\nselectTracksOnDrop=" + juce::String (trackmodes::headerDropOptions().selectTracks ? 1 : 0)
  2873. + "\nprGridHighlights=" + juce::String (PianoRollComponent::gridHighlights ? 1 : 0)
  2874. + "\nprShowChordName=" + juce::String (PianoRollComponent::showChordName ? 1 : 0)
  2875. + "\nprSongBars=" + juce::String (PianoRollComponent::songBarsRuler ? 1 : 0)
  2876. + "\nprKeyStyle=" + juce::String ((int) PianoRollComponent::keyStyle)
  2877. + "\naudioLogEnabled=" + juce::String (engine.getRollingLog().isEnabled() ? 1 : 0)
  2878. + "\naudioLogSeconds=" + juce::String (engine.getRollingLog().lengthSeconds())
  2879. + "\naudioLogPreEffects=" + juce::String (engine.getRollingLog().getPosition() == RollingAudioLog::Position::preEffects ? 1 : 0)
  2880. + "\nchordDelayMs=" + juce::String ((std::int64_t) chordReadout.getDelayMs())
  2881. + "\nchordRoman=" + juce::String (chordReadout.getOptions().roman ? 1 : 0)
  2882. + "\nchordNearHint=" + juce::String (chordShowNearHint ? 1 : 0)
  2883. + "\nkeyPanelFollowsStyle=" + juce::String (keyPanelFollowsStyle ? 1 : 0)
  2884. + "\nlinkToggleFollowsStyle=" + juce::String (linkToggleFollowsStyle ? 1 : 0)
  2885. + "\nstretchedClipsLoop=" + juce::String (stretchedClipsLoop() ? 1 : 0)
  2886. + "\nautoClipsAtPlayback=" + juce::String (autoclipplace::atPlayback() ? 1 : 0)
  2887. + "\ndisableTypingPriority=" + juce::String (pluginkeys::newPluginsHostFirst().load() ? 1 : 0)
  2888. + "\nclipLaunchWorkflow=" + juce::String (layoutstyle::legacyClipLaunchFlag (layoutStyle) ? 1 : 0)
  2889. + "\nlayoutStyle=" + layoutstyle::id (layoutStyle)
  2890. + "\nlanesBeforeClipLaunch=" + juce::String (lanesBeforeClipLaunch ? 1 : 0)
  2891. + "\ndetailHeight=" + juce::String (DetailView::preferredHeight)
  2892. + "\ndetailShown=" + juce::String (DetailView::shownSetting ? 1 : 0)
  2893. + "\nsceneTempoShown=" + juce::String (clipGridSceneTempoShown() ? 1 : 0)
  2894. + "\nsimpleDockHeight=" + juce::String (SimpleDock::preferredHeight)
  2895. + "\nsimpleDockShown=" + juce::String (SimpleDock::shownSetting ? 1 : 0)
  2896. + "\nkeyboardMode=" + juce::String ((int) scalekeys::current().mode)
  2897. + "\nkeyboardLock=" + juce::String (scalekeys::current().lockToKey ? 1 : 0)
  2898. + "\nchordComplexity=" + juce::String ((int) scalekeys::current().complexity)
  2899. + "\nchordSpread=" + juce::String ((int) scalekeys::current().spread)
  2900. + "\nchordStrum=" + juce::String (scalekeys::current().strumMs)
  2901. + "\nchordStrumDown=" + juce::String (scalekeys::current().strumDown ? 1 : 0)
  2902. + "\nchordProjectSet=" + juce::String (scalekeys::current().projectChords ? 1 : 0)
  2903. + "\ndetailDevices=" + juce::String (DetailView::devicesPage ? 1 : 0)
  2904. + "\ndetailExtraWindowKey=" + juce::String (DetailView::extraWindowKey ? 1 : 0)
  2905. + "\ndetailExtraSelectInMixer=" + juce::String (DetailView::extraSelectInMixer ? 1 : 0)
  2906. + "\nalsSessionOnPlaylist=" + juce::String (AudioEngine::alsSessionOnPlaylist.load() ? 1 : 0)
  2907. + "\nfollowPlaylist=" + juce::String (EditorGlobals::get().isFollowing (false) ? 1 : 0)
  2908. + "\nfollowPianoRoll=" + juce::String (EditorGlobals::get().isFollowing (true) ? 1 : 0)
  2909. + "\nfollowChannelRack=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack) ? 1 : 0)
  2910. + "\nfollowAudioEditor=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor) ? 1 : 0)
  2911. + "\nscopeMode=" + juce::String (toolbar::OutputMonitor::mode)
  2912. + "\ntoolbarGroups=" + juce::String (toolbarLayout.orderToString())
  2913. + "\ntoolbarIcons=" + toolbarlayout::Layout::iconSizeId (toolbarLayout.iconSize)
  2914. + "\nuiScale=" + juce::String (toolbarLayout.uiScale)
  2915. + "\nmenuDensity=" + juce::String (theme::menus::compact() ? "compact" : "comfortable")
  2916. + "\ntoolbarSeparators=" + juce::String (toolbarLayout.separators ? 1 : 0)
  2917. + "\ntoolbarVisible=" + juce::String (toolbarLayout.visible ? 1 : 0)
  2918. + "\nautosaveMinutes=" + juce::String (autosaveMinutes) + "\nautosaveKeep=" + juce::String (autosaveKeep)
  2919. + "\naskUnusedRecordings=" + juce::String (askUnusedRecordings ? 1 : 0)
  2920. + "\nmessagesHidden=" + messages::hiddenList()
  2921. + "\nbackupWaitsForQuiet=" + juce::String (backupWaitsForQuiet ? 1 : 0)
  2922. + "\nbackupLongestWait=" + juce::String (backupLongestWaitMinutes)
  2923. + "\nhoverValues=" + juce::String (hoverValues ? 1 : 0)
  2924. + "\nundoLevels=" + juce::String (engine.getUndoLevels())
  2925. + "\nmetronomeVolume=" + juce::String (engine.getTransport().metronomeVolume.load(), 2)
  2926. + "\nmetronomeSoundFl=" + juce::String (metronome::clampSound (engine.getTransport().metronomeSound.load()))
  2927. + "\nmetronomeTrack=" + juce::String (engine.getTransport().metronomeTrack.load())
  2928. + "\nplayTruncatedOnTransport=" + juce::String (engine.getTransport().playTruncatedOnTransport.load() ? 1 : 0)
  2929. + "\nresetPluginsOnTransport=" + juce::String (engine.getTransport().resetPluginsOnTransport.load() ? 1 : 0)
  2930. + juce::String (flsettings::serialise())
  2931. + "\nrenderAhead=" + juce::String (renderAheadOption().load() ? 1 : 0)
  2932. + "\npreviewVolume=" + juce::String (engine.getPreviewVolume(), 2)
  2933. + "\npreviewInTime=" + juce::String (engine.isPreviewInTime() ? 1 : 0)
  2934. + "\nbrowserAutoPreview=" + juce::String (BrowserComponent::autoPreview ? 1 : 0)
  2935. + "\neditorVolume=" + juce::String (engine.getEditorVolume(), 2)
  2936. + "\nrackPianoRollView=" + juce::String (rack.isPianoRollView() ? 1 : 0)
  2937. + "\naskWhatToRecord=" + juce::String (engine.getRecordOptions().askWhatToRecord ? 1 : 0)
  2938. + "\nrecordNotes=" + juce::String (engine.getRecordOptions().recordNotes ? 1 : 0)
  2939. + "\nrecordAudio=" + juce::String (engine.getRecordOptions().recordAudio ? 1 : 0)
  2940. + "\nrecordStartsPlayback=" + juce::String (engine.getRecordOptions().startsPlayback ? 1 : 0)
  2941. + "\ndisarmOnStop=" + juce::String (engine.getRecordOptions().disarmOnStop ? 1 : 0)
  2942. + "\nlowLatencyRecording=" + juce::String (engine.getRecordOptions().lowLatencyRecording ? 1 : 0)
  2943. + "\nrecordOffOnStop=" + juce::String (engine.getRecordOptions().recordOffOnStop ? 1 : 0)
  2944. + "\nunarmAfterRender=" + juce::String (engine.getRecordOptions().unarmAfterRender ? 1 : 0)
  2945. + "\nrenderAutoClip=" + juce::String (engine.getRecordOptions().autoCreateClip ? 1 : 0)
  2946. + "\nrecLatencyCompensation=" + juce::String (engine.getRecordOptions().latencyCompensation ? 1 : 0)
  2947. + "\nrecordQuantiseStarts=" + juce::String (recordQuantiseOn ? 1 : 0)
  2948. + "\nrecordNoteEnd=" + juce::String ((int) engine.getRecordOptions().noteEnd)
  2949. + "\nrecordToStepSequencer=" + juce::String (engine.getRecordOptions().toStepSequencer ? 1 : 0)
  2950. + "\nrecordingMarkers=" + juce::String (engine.getRecordOptions().recordingMarkers ? 1 : 0)
  2951. + "\nrecordAutomation=" + juce::String (engine.getRecordOptions().recordAutomation ? 1 : 0)
  2952. + "\nrecordClips=" + juce::String (engine.getRecordOptions().recordClips ? 1 : 0)
  2953. + "\nrecordQuantiseAutomation=" + juce::String (engine.getRecordOptions().quantiseAutomation ? 1 : 0)
  2954. + "\nrecordPunchLoop=" + juce::String (engine.getRecordOptions().punchLoopRegion ? 1 : 0)
  2955. + "\nrecordLoop=" + juce::String (engine.getRecordOptions().loopRecord ? 1 : 0)
  2956. + "\nrecordLastPassPlays=" + juce::String (engine.getRecordOptions().lastLoopPassPlays ? 1 : 0)
  2957. + "\nrecordBlend=" + juce::String (engine.getRecordOptions().mode == RecordMode::overdub ? 1 : 0)
  2958. + "\nrecordPreRoll=" + juce::String (engine.getRecordOptions().preRollBars)
  2959. // FL's precount switch and duration, and the metronome switch (issue #152)
  2960. + "\n" + juce::String (countin::onKey.data()) + "=" + juce::String (engine.getRecordOptions().countInBars > 0 ? 1 : 0)
  2961. + "\n" + juce::String (countin::lengthKey.data()) + "=" + juce::String (engine.getRecordOptions().countInLength)
  2962. + "\nmetronomeOn=" + juce::String (engine.getTransport().metronome.load() ? 1 : 0)
  2963. + "\nrecordCatchWindow=" + juce::String (engine.getRecordOptions().catchWindow)
  2964. + "\nrecordCompensateOutput=" + juce::String (engine.getRecordOptions().compensateOutput ? 1 : 0)
  2965. + "\nrecordPostRoll=" + juce::String (engine.getRecordOptions().postRollBars) + "\nmixerUsedOnly=" + juce::String (MixerStrips::showUsedOnly ? 1 : 0) + "\nmixerLoudness=" + juce::String (MixerStrips::showLoudness ? 1 : 0) + "\nmixerKeepLostLinks=" + juce::String (MixerStrips::keepLostLinks ? 1 : 0) + "\nmixerFollowPlaylist=" + juce::String (MixerStrips::followPlaylist ? 1 : 0) + "\nmixerLayout=" + juce::String ((int) MixerStrips::layout)
  2966. + "\nquantizeSongJumps=" + juce::String (engine.quantizeSongJumps.load()) + "\n"
  2967. + juce::String (newProjectDefaults().toText()));
  2968. }
  2969. // --- transport -----------------------------------------------------------------------------------
  2970. void MainComponent::playStop()
  2971. {
  2972. auto& transport = engine.getTransport();
  2973. if (engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting()) // pressed again: cancel
  2974. {
  2975. engine.stop();
  2976. return;
  2977. }
  2978. if (transport.playing.load())
  2979. {
  2980. // back to the remembered position: the last ruler click, else where playback started (FL, issue #169)
  2981. const auto back = stopReturn (false, true);
  2982. engine.stop();
  2983. engine.seek ((double) back);
  2984. playStartTicks = (double) back;
  2985. transportPaused = false;
  2986. }
  2987. else
  2988. {
  2989. notePlayStart (transportPaused);
  2990. transportPaused = false;
  2991. engine.startPlayback();
  2992. }
  2993. }
  2994. void MainComponent::playPause()
  2995. {
  2996. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting())
  2997. {
  2998. engine.stop();
  2999. transportPaused = true; // (FL's pause keeps the position and the mark)
  3000. }
  3001. else
  3002. {
  3003. notePlayStart (transportPaused);
  3004. transportPaused = false;
  3005. engine.startPlayback();
  3006. }
  3007. }
  3008. double MainComponent::positionToStartFrom() const
  3009. {
  3010. const auto& transport = engine.getTransport();
  3011. if (const auto pending = transport.seekRequest.load(); pending >= 0.0)
  3012. return pending; // a ruler click a moment ago: the audio thread hasn't moved there yet
  3013. return transport.positionTicks.load();
  3014. }
  3015. void MainComponent::notePlayStart (bool resume)
  3016. {
  3017. playStartTicks = positionToStartFrom();
  3018. if (resume && returnTicks >= 0.0)
  3019. return; // a resume after a pause: the mark stays (FL)
  3020. returnTicks = playStartTicks;
  3021. returnSongMode = engine.getSong().mode == PlayMode::song;
  3022. seekClicksSeen = EditorGlobals::get().seekMarkSerial; // (the click that put the position here is this start)
  3023. }
  3024. void MainComponent::forgetSeekMark()
  3025. {
  3026. auto& globals = EditorGlobals::get();
  3027. globals.seekMark = -1;
  3028. seekClicksSeen = globals.seekMarkSerial;
  3029. returnTicks = -1.0;
  3030. transportPaused = false;
  3031. }
  3032. std::int64_t MainComponent::stopReturn (bool alreadyStopped, bool spaceKey)
  3033. {
  3034. auto& globals = EditorGlobals::get();
  3035. if (globals.seekMarkSerial != seekClicksSeen && globals.seekMark >= 0) // a ruler click, also one made while playing
  3036. {
  3037. seekClicksSeen = globals.seekMarkSerial;
  3038. returnTicks = (double) globals.seekMark;
  3039. returnSongMode = globals.seekMarkSongMode;
  3040. }
  3041. const auto songMode = engine.getSong().mode == PlayMode::song;
  3042. const auto mark = returnTicks >= 0.0 && returnSongMode == songMode ? (std::int64_t) std::llround (returnTicks) : (std::int64_t) -1;
  3043. const auto start = returnSongMode == songMode ? (std::int64_t) std::llround (playStartTicks) : (std::int64_t) 0;
  3044. const auto target = transportedit::stopReturnTarget (alreadyStopped, globals.rememberSeek, spaceKey, mark, start);
  3045. if (alreadyStopped) // FL's second Stop: the start, and the mark is forgotten
  3046. {
  3047. returnTicks = -1.0;
  3048. globals.seekMark = -1;
  3049. seekClicksSeen = globals.seekMarkSerial;
  3050. }
  3051. return target;
  3052. }
  3053. void MainComponent::playFromStart()
  3054. {
  3055. // FL 2026's Shift+Space (measured in FL, issue #11): playing, recording, waiting or counting in -> stop at the start
  3056. // of the time selection (Song mode) or else of the song / pattern; stopped -> play from the current position, as
  3057. // Space does (a later Space goes back there).
  3058. const auto wasPlaying = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting();
  3059. if (! wasPlaying)
  3060. {
  3061. playStop();
  3062. return;
  3063. }
  3064. engine.stop();
  3065. transportPaused = false;
  3066. const auto& song = engine.getSong();
  3067. const auto target = transportedit::shiftSpaceStopTarget (song.mode == PlayMode::song, song.hasLoop(), song.loopStart);
  3068. if (target > 0)
  3069. engine.seek ((double) target);
  3070. else
  3071. engine.rewind();
  3072. playStartTicks = (double) target;
  3073. }
  3074. void MainComponent::stopAndRewind (bool toStart)
  3075. {
  3076. // Stop while nothing plays (the second press, or a double click) goes back to the very start even when
  3077. // "Remember seek time" sends the first Stop to the ruler mark (round 162, issue #9)
  3078. // (paused is not stopped: FL's Stop after a pause (transport state 2) still goes back to the seek mark, issue #169)
  3079. const auto alreadyStopped = toStart || ! (transportPaused || engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting());
  3080. const auto back = stopReturn (alreadyStopped, false); // (issue #169: FL's seek mark, Pattern mode too)
  3081. engine.stop();
  3082. transportPaused = false;
  3083. // FL: the transport's Stop also ends a Browser sample preview (issue #11)
  3084. browser.stopPreview(); // (the engine's one preview voice: the Sample browser window's preview stops too)
  3085. if (back > 0) // "Remember seek time": back to the position clicked on a ruler, or where playback started
  3086. engine.seek ((double) back);
  3087. else
  3088. engine.rewind();
  3089. playStartTicks = (double) back;
  3090. }
  3091. void MainComponent::showStopMenu()
  3092. {
  3093. auto& globals = EditorGlobals::get();
  3094. juce::PopupMenu menu;
  3095. menu.addSectionHeader (tr ("Stop"));
  3096. menu.addItem (tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), true, globals.rememberSeek, [this] {
  3097. EditorGlobals::get().rememberSeek = ! EditorGlobals::get().rememberSeek;
  3098. saveUiSettings();
  3099. });
  3100. menu.addSeparator();
  3101. menu.addItem (tr ("All notes off (panic)") + "\t" + tr ("double-click"), [this] { engine.panic(); });
  3102. menu.addItem (tr ("Back to the start"), [this] { stopAndRewind (true); });
  3103. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stopButton));
  3104. }
  3105. void MainComponent::toggleMode()
  3106. {
  3107. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  3108. }
  3109. // --- panels --------------------------------------------------------------------------------------
  3110. void MainComponent::togglePanel (Panel panel)
  3111. {
  3112. workspace.toggle (panel);
  3113. refreshPanelButtons();
  3114. }
  3115. void MainComponent::fitChannelRack (bool width)
  3116. {
  3117. rack.updateSize();
  3118. const auto scrollbar = rackViewport.getScrollBarThickness();
  3119. // compact like FL's rack: at most two bars of steps are shown, longer patterns scroll sideways, so the
  3120. // rack does not cover the Playlist after a project with long patterns is opened
  3121. // and never past the desktop's right edge from where the rack is (the default layout keeps the Playlist's track
  3122. // names uncovered on a small desktop, round 167v)
  3123. const auto maxWidth = juce::jmin (juce::jmax (300, workspace.getWidth() - 16 - workspace.getPanelBounds (Panel::channelRack).getX() - scrollbar - 8), rack.widthForSteps (32));
  3124. const auto contentWidth = juce::jmin (rack.naturalWidth(), maxWidth); // the ghost steps only fill a wider rack
  3125. const auto needsHorizontal = rack.naturalWidth() > contentWidth;
  3126. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  3127. fittedChannelCount = (int) engine.getSong().channels.size();
  3128. }
  3129. void MainComponent::showPanel (Panel panel)
  3130. {
  3131. workspace.show (panel);
  3132. refreshPanelButtons();
  3133. }
  3134. void MainComponent::showWindowsTip()
  3135. {
  3136. const auto counter = PluginHost::settingsFolder().getChildFile ("windows-tip.txt");
  3137. const auto shown = counter.existsAsFile() ? counter.loadFileAsString().trim().getIntValue() : 0;
  3138. if (shown >= 3)
  3139. return;
  3140. counter.replaceWithText (juce::String (shown + 1));
  3141. auto key = [this] (Panel p) {
  3142. const auto chords = keyMap.chordsFor (panelAction (p));
  3143. return chords.empty() ? juce::String() : "[" + juce::String (keys::toString (chords.front())) + "] ";
  3144. };
  3145. ui::Hint hint;
  3146. hint.text = tr ("Windows: {0}Playlist {1}Channel Rack {2}Piano Roll {3}Mixer {4}Browser (or the window buttons in the toolbar; again: hide)",
  3147. { key (Panel::playlist), key (Panel::channelRack), key (Panel::pianoRoll), key (Panel::mixer), key (Panel::browser) });
  3148. ui::postHint (hint, 15000);
  3149. }
  3150. void MainComponent::refreshPanelButtons()
  3151. {
  3152. for (int i = 0; i < workspace::panelCount; ++i)
  3153. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  3154. }
  3155. void MainComponent::openPianoRoll()
  3156. {
  3157. showPanel (Panel::pianoRoll);
  3158. pianoRoll.scrollToNotes();
  3159. }
  3160. void MainComponent::saveLayoutAs()
  3161. {
  3162. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  3163. window->addTextEditor ("name", tr ("My layout"));
  3164. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3165. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3166. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  3167. const auto name = window->getTextEditorContents ("name").trim();
  3168. if (result == 1 && name.isNotEmpty())
  3169. workspace.saveLayoutAs (name);
  3170. }),
  3171. true);
  3172. keepAboveMainWindow (*window);
  3173. }
  3174. juce::PopupMenu MainComponent::layoutsMenu()
  3175. {
  3176. juce::PopupMenu menu;
  3177. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  3178. files.sort();
  3179. for (const auto& file : files)
  3180. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  3181. workspace.loadLayout (file);
  3182. refreshPanelButtons();
  3183. });
  3184. if (files.isEmpty())
  3185. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  3186. menu.addSeparator();
  3187. menu.addItem (tr ("Open layouts folder"), [] {
  3188. Workspace::layoutsFolder().createDirectory();
  3189. Workspace::layoutsFolder().startAsProcess();
  3190. });
  3191. return menu;
  3192. }
  3193. namespace
  3194. {
  3195. // Both | Grid | Song, in the Playlist's title bar while Clip-launch workflow is on (round 181a). Round 190ef: then the
  3196. // reference's control-bar switches Draw Mode (pencil), Key and MIDI (Key / MIDI Map Mode), in its order.
  3197. class ClipGridSwitch final : public juce::Component
  3198. {
  3199. public:
  3200. static constexpr int width = 132 + 8 + 26 + 4 + 40 + 4 + 44;
  3201. std::function<void()> onDraw, onKey, onMidi;
  3202. void setStates (bool drawOn, remotemap::Mode mode)
  3203. {
  3204. draw.setToggleState (drawOn, juce::dontSendNotification);
  3205. key.setToggleState (mode == remotemap::Mode::key, juce::dontSendNotification);
  3206. midi.setToggleState (mode == remotemap::Mode::midi, juce::dontSendNotification);
  3207. }
  3208. explicit ClipGridSwitch (std::function<void (PlaylistArea::GridView)> pick)
  3209. {
  3210. addAndMakeVisible (draw);
  3211. draw.setTooltip (tr ("Draw Mode") + juce::String (sessionkeys::menuKey (sessionkeys::Command::drawMode, layoutstyle::Style::clipLaunch)).replace ("\t", " "));
  3212. draw.onClick = [this] { if (onDraw != nullptr) onDraw(); };
  3213. for (auto* b : { &key, &midi })
  3214. {
  3215. addAndMakeVisible (*b);
  3216. b->setColour (juce::TextButton::buttonOnColourId, b == &key ? theme::colour::warning : theme::colour::info);
  3217. b->setColour (juce::TextButton::textColourOnId, theme::colour::bg0);
  3218. }
  3219. key.setButtonText (trc ("@computer key: Key")); // (round 190em: a computer key, not the musical key)
  3220. key.setTooltip (tr ("Key Map Mode: map computer keys to clips, scenes, buttons and controls (Ctrl+K)"));
  3221. key.onClick = [this] { if (onKey != nullptr) onKey(); };
  3222. midi.setButtonText ("MIDI");
  3223. midi.setTooltip (tr ("MIDI Map Mode: map MIDI controls to clips, scenes, buttons and controls (Ctrl+M)"));
  3224. midi.onClick = [this] { if (onMidi != nullptr) onMidi(); };
  3225. const std::pair<juce::TextButton*, PlaylistArea::GridView> buttons[] { { &both, PlaylistArea::GridView::beside },
  3226. { &grid, PlaylistArea::GridView::grid },
  3227. { &song, PlaylistArea::GridView::song } };
  3228. both.setButtonText (tr ("Both"));
  3229. grid.setButtonText (tr ("Grid"));
  3230. song.setButtonText (tr ("Song"));
  3231. both.setToggleState (true, juce::dontSendNotification);
  3232. for (const auto& [button, view] : buttons)
  3233. {
  3234. addAndMakeVisible (*button);
  3235. button->setRadioGroupId (1181);
  3236. button->setClickingTogglesState (true);
  3237. // (the radio group also "clicks" the button it turns off)
  3238. button->onClick = [pick, view = view, button = button] {
  3239. if (button->getToggleState())
  3240. pick (view);
  3241. };
  3242. }
  3243. }
  3244. void show (PlaylistArea::GridView view)
  3245. {
  3246. (view == PlaylistArea::GridView::beside ? both : view == PlaylistArea::GridView::grid ? grid : song).setToggleState (true, juce::dontSendNotification);
  3247. }
  3248. void resized() override
  3249. {
  3250. auto r = getLocalBounds().reduced (0, 4);
  3251. auto switches = r.removeFromRight (26 + 4 + 40 + 4 + 44);
  3252. r.removeFromRight (8);
  3253. const auto w = r.getWidth() / 3;
  3254. both.setBounds (r.removeFromLeft (w));
  3255. grid.setBounds (r.removeFromLeft (w));
  3256. song.setBounds (r);
  3257. draw.setBounds (switches.removeFromLeft (26));
  3258. switches.removeFromLeft (4);
  3259. key.setBounds (switches.removeFromLeft (40));
  3260. switches.removeFromLeft (4);
  3261. midi.setBounds (switches);
  3262. }
  3263. private:
  3264. juce::TextButton both, grid, song;
  3265. IconButton draw { "drawMode", Icon::draw };
  3266. juce::TextButton key, midi;
  3267. };
  3268. } // namespace
  3269. void MainComponent::syncClipLaunchSwitches()
  3270. {
  3271. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  3272. flip->setStates (drawmode::isOn(), getMapMode());
  3273. }
  3274. void MainComponent::setLayoutStyle (layoutstyle::Style style, bool swapLayout)
  3275. {
  3276. using layoutstyle::Style;
  3277. const auto from = layoutStyle;
  3278. const auto partsReady = [this] (Style s) {
  3279. return s == Style::pattern || (s == Style::clipLaunch && clipGridView != nullptr) || (s == Style::simple && simpleWorkflow != nullptr);
  3280. };
  3281. if (style == from && partsReady (style))
  3282. return;
  3283. // each style's own parts are made the first time it is chosen (nothing of them exists in Pattern workflow)
  3284. if (style == Style::clipLaunch && clipGridView == nullptr)
  3285. {
  3286. clipGridView = makeClipGrid (engine);
  3287. clipGridSwitch = std::make_unique<ClipGridSwitch> ([this] (PlaylistArea::GridView view) { setClipGridView (view); });
  3288. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get())) // (round 190ef)
  3289. {
  3290. flip->onDraw = [] { drawmode::toggle(); };
  3291. drawmode::addListener ([safe = juce::Component::SafePointer<MainComponent> (this)] (bool) {
  3292. if (safe != nullptr)
  3293. safe->syncClipLaunchSwitches();
  3294. });
  3295. flip->onKey = [this] { setMapMode (getMapMode() == remotemap::Mode::key ? remotemap::Mode::off : remotemap::Mode::key); };
  3296. flip->onMidi = [this] { setMapMode (getMapMode() == remotemap::Mode::midi ? remotemap::Mode::off : remotemap::Mode::midi); };
  3297. }
  3298. makeDetailView();
  3299. }
  3300. if (style == Style::simple && simpleWorkflow == nullptr)
  3301. {
  3302. SimpleWorkflow::Host host;
  3303. host.setOverlay = [this] (juce::Component* c) {
  3304. // round 190fc (0.1.27 RC H2): an overlay that had the keys (Welcome, Start from, the chooser) gives them back
  3305. // to the main window when it goes; JUCE would hand them to the first child that takes keys (the dock's
  3306. // search box, the Lyrics text...), where Space typed instead of playing
  3307. auto* old = playlistArea.getOverlay();
  3308. const auto hadKeys = old != nullptr && old != c && old->hasKeyboardFocus (true);
  3309. playlistArea.setOverlay (c);
  3310. if (hadKeys && c == nullptr && isShowing())
  3311. grabKeyboardFocus();
  3312. };
  3313. host.showKeys = [this] {
  3314. if (! isTouchKeyboardOpen()) // (round 190p: a new instrument can be played at once, with the mouse too)
  3315. toggleTouchKeyboard (engine);
  3316. };
  3317. host.setTitleAccessory = [this] (juce::Component* c, int width) { workspace.setTitleAccessory (Panel::playlist, c, width); };
  3318. host.showLoops = [this] {
  3319. if (findToolWindow ("sampleBrowser") == nullptr)
  3320. toggleSampleBrowser();
  3321. };
  3322. // round 190ch: Lyrics / Notes, Reference match and a new project from the "Start from" list
  3323. host.toggleLyrics = [this] { toggleLyrics(); };
  3324. host.showReferenceMatch = [this] { showReferenceMatch(); };
  3325. host.startFrom = [this] (Song song) {
  3326. auto shared = std::make_shared<Song> (std::move (song));
  3327. confirmDiscard ([this, shared] { startNewProject (std::move (*shared), {}); });
  3328. };
  3329. host.trackAdded = [this] (int track) { playlist.selectTrack (track); };
  3330. host.setSideDock = [this] (juce::Component* c, int width) { playlistArea.setSideDock (c, width); };
  3331. // round 190t: the Sampler tile's start folder, the Finish dock's "Save the song as a file", the backup status
  3332. host.sampleFolder = [this] { return browser.firstSampleFolder(); };
  3333. host.exportAudio = [this] (int format) { exportAudio (format); };
  3334. host.exportOtherApps = [this] { exportForOtherApps(); };
  3335. host.saveStatus = [this] { return simpleSaveStatus(); };
  3336. // round 190bu: the dock for the selected track sits where Clip-launch's detail view does (never both)
  3337. host.setBottomDock = [this] (juce::Component* c, std::function<int (int)> heightFor) { playlistArea.setDetailView (c, std::move (heightFor)); };
  3338. host.toggleChannelWindow = [this] (int channel) { rack.toggleEditor (channel, true); };
  3339. host.selectedTrack = [this] { return playlist.getCurrentTrack(); };
  3340. host.settingsChanged = [this] { saveUiSettings(); };
  3341. // round 190ds: the dock's Editor tab docks the Piano roll (as the Clip-launch detail view does; never both)
  3342. host.dockPianoRoll = [this] (int pattern) { return dockPianoRoll (pattern); };
  3343. host.undockPianoRoll = [this] { undockPianoRoll(); };
  3344. host.setFoldToKey = [this] (bool on) {
  3345. if (const auto key = projectkey::get (engine.getSong()); on && key) // (the rows show the project key, then fold)
  3346. pianoRoll.setScale (key->root, projectkey::lynxScale (*key));
  3347. pianoRoll.setFoldToScale (on);
  3348. };
  3349. host.foldedToKey = [this] { return pianoRoll.isFoldedToScale(); };
  3350. host.openPianoRollPanel = [this] { showPanel (Panel::pianoRoll); };
  3351. workspace.onWillShow = [this] (Panel panel) { pianoRollPanelWillShow (panel); };
  3352. // round 190dv: the Welcome screen (by itself only in a real session) and the first-song tour
  3353. host.window = [this] { return static_cast<juce::Component*> (this); };
  3354. host.offerWelcome = persistent;
  3355. host.newProjectForTour = [this] (std::function<void()> then) {
  3356. auto go = [this, then] {
  3357. confirmDiscard ([this, then] {
  3358. startNewProject (makeDefaultTemplateProject (nullptr), {});
  3359. if (then)
  3360. then();
  3361. });
  3362. };
  3363. juce::AlertWindow::showYesNoCancelBox (juce::MessageBoxIconType::QuestionIcon, tr ("First-song tour"),
  3364. tr ("The tour builds a song from the start. Start it in a new project?"), tr ("New project"),
  3365. tr ("This project"), tr ("Cancel"), nullptr,
  3366. juce::ModalCallbackFunction::create ([go, then] (int result) {
  3367. if (result == 1)
  3368. go();
  3369. else if (result == 2 && then)
  3370. then();
  3371. }));
  3372. };
  3373. simpleWorkflow = std::make_unique<SimpleWorkflow> (engine, std::move (host));
  3374. // the Simple headers' "+FX": the dock's Effects tab on that track (round 190bu; the Mixer shows the same slots)
  3375. playlist.onTrackEffects = [this] (int insert) {
  3376. if (simpleWorkflow != nullptr)
  3377. simpleWorkflow->showEffectsOfInsert (insert);
  3378. };
  3379. playlist.onSimpleTrackSelected = [this] (int track) {
  3380. if (simpleWorkflow != nullptr && layoutStyle == layoutstyle::Style::simple)
  3381. simpleWorkflow->trackSelected (track);
  3382. };
  3383. playlist.onSimpleFilesDropped = [this] (const juce::StringArray& files, std::int64_t tick) {
  3384. if (simpleWorkflow != nullptr)
  3385. simpleWorkflow->dropFiles (files, tick);
  3386. };
  3387. // round 190fo: "Export this track" in the Simple track menu
  3388. playlist.onExportTrack = [this] (int track, bool asMidi) {
  3389. engine.capturePluginStates();
  3390. exportOneTrack (engine, track, asMidi,
  3391. currentFile != juce::File() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  3392. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled"));
  3393. };
  3394. }
  3395. if (from == Style::simple && style != Style::simple && simpleWorkflow != nullptr)
  3396. simpleWorkflow->left();
  3397. // round 190fc (H2): every click in the Simple window leaves the keys with the main window (text fields excepted)
  3398. if (style == Style::simple)
  3399. juce::Desktop::getInstance().addGlobalMouseListener (&simpleClickKeys);
  3400. else
  3401. juce::Desktop::getInstance().removeGlobalMouseListener (&simpleClickKeys);
  3402. // the workspace layout is kept per style, so going back restores the Pattern layout exactly
  3403. const auto layoutFile = [] (Style s) { return platform::settingsFile (layoutstyle::workspaceFile (s)); };
  3404. if (persistent && swapLayout && style != from)
  3405. {
  3406. layoutFile (from).replaceWithText (workspace.getLayoutText());
  3407. if (const auto saved = layoutFile (style); saved.existsAsFile())
  3408. workspace.applyLayoutText (saved.loadFileAsString());
  3409. else if (style == Style::clipLaunch)
  3410. {
  3411. workspace.hide (Panel::channelRack); // one click away, on the toolbar
  3412. workspace.show (Panel::playlist);
  3413. }
  3414. else if (style == Style::simple)
  3415. {
  3416. // one window: the tracks and the timeline fill it; the other panels stay one click away (View, F5…F9)
  3417. for (auto panel : { Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser })
  3418. workspace.hide (panel);
  3419. workspace.show (Panel::playlist);
  3420. if (! workspace.isMaximised (Panel::playlist))
  3421. workspace.toggleMaximised (Panel::playlist);
  3422. }
  3423. refreshPanelButtons();
  3424. if (isShowing())
  3425. grabKeyboardFocus(); // (the new layout must not leave the keys in the Browser's search box)
  3426. }
  3427. // Clip-launch workflow shows the automation lanes; going back restores the user's setting
  3428. const auto clipLaunch = style == Style::clipLaunch;
  3429. if (clipLaunch != (from == Style::clipLaunch))
  3430. {
  3431. if (clipLaunch && swapLayout) // (at startup, the saved value holds)
  3432. lanesBeforeClipLaunch = autolanes::shown();
  3433. autolanes::setShown (clipLaunch || lanesBeforeClipLaunch);
  3434. playlist.repaint();
  3435. }
  3436. if (! clipLaunch && detailView != nullptr) // (round 183a: a docked Piano roll goes back to its panel)
  3437. detailView->releaseEditor();
  3438. layoutStyle = style;
  3439. layoutstyle::setCurrent (style); // (round 190cm: the clip grid's and the audio editor's Ableton-style keys follow it)
  3440. if (! clipLaunch && getMapMode() != remotemap::Mode::off) // (round 190ef: the map modes belong to the Clip-launch layout)
  3441. setMapMode (remotemap::Mode::off);
  3442. browser.setLiveItemMenus (clipLaunch); // (round 190cy: Live's flat collection labels in the rows' menus)
  3443. EditorGlobals::get().clipLaunchWorkflow = clipLaunch; // (round 190db: the audio editor's beat-time view)
  3444. EditorGlobals::get().sendChangeMessage(); // (round 190el: the Piano roll's Drum Rack pad rows follow the layout)
  3445. if (clipGridView != nullptr || clipLaunch)
  3446. {
  3447. playlistArea.setClipGrid (clipLaunch ? clipGridView.get() : nullptr, PlaylistArea::GridView::beside);
  3448. // the detail view docks under the grid and the Playlist (round 183a); other workflows: nothing docked
  3449. if (detailView != nullptr)
  3450. detailView->setVisible (clipLaunch && DetailView::shownSetting);
  3451. playlistArea.setDetailView (clipLaunch ? detailView.get() : nullptr,
  3452. [this] (int available) { return detailView != nullptr ? detailView->heightFor (available) : 0; });
  3453. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  3454. flip->show (PlaylistArea::GridView::beside);
  3455. workspace.setTitleAccessory (Panel::playlist, clipLaunch ? clipGridSwitch.get() : nullptr, clipLaunch ? ClipGridSwitch::width : 0);
  3456. }
  3457. // the Simple workflow's track headers and no pattern picker (no-ops for the other two styles: nothing changes there)
  3458. playlist.setSimpleHeaders (style == Style::simple);
  3459. playlist.setLiveStyle (style == Style::clipLaunch);
  3460. playlistArea.setPickerHidden (style == Style::simple || ! pickerPanelOn);
  3461. if (style == Style::simple && simpleWorkflow != nullptr)
  3462. simpleWorkflow->entered(); // (after the grid's title accessory is gone: the Add track button takes its place)
  3463. // round 184a S11 (D15): the Key panel shows in the Simple and Clip-launch workflows, not in FL's Pattern workflow,
  3464. // until the user shows or hides it by hand
  3465. if (keyPanelFollowsStyle && toolbarLayout.isShown (toolbarlayout::Group::key) != (style != Style::pattern))
  3466. {
  3467. toolbarLayout.setShown (toolbarlayout::Group::key, style != Style::pattern);
  3468. resized();
  3469. repaint();
  3470. }
  3471. // round 190gl: the Link toggle shows in the Clip-launch workflow (the reference DAW's default "Show Link Toggle"),
  3472. // not in FL's Pattern workflow (FL has no Link) nor the Simple one, until the user shows or hides it
  3473. if (linkToggleFollowsStyle && toolbarLayout.isShown (toolbarlayout::Group::link) != (style == Style::clipLaunch))
  3474. {
  3475. toolbarLayout.setShown (toolbarlayout::Group::link, style == Style::clipLaunch);
  3476. resized();
  3477. repaint();
  3478. }
  3479. }
  3480. void MainComponent::setPickerPanelOn (bool on)
  3481. {
  3482. // FL's Playlist menu › Picker panel › Enable (issue #175): the Playlist without its Picker column; clicked clips are
  3483. // still what the Pencil and the Brush paint (core/PaintTemplate.h). The Simple workflow never shows it.
  3484. pickerPanelOn = on;
  3485. playlistArea.setPickerHidden (layoutStyle == layoutstyle::Style::simple || ! pickerPanelOn);
  3486. saveUiSettings();
  3487. }
  3488. void MainComponent::addLayoutStyleItems (juce::PopupMenu& menu)
  3489. {
  3490. using layoutstyle::Style;
  3491. juce::PopupMenu styles;
  3492. const auto item = [this, &styles] (const juce::String& text, Style style) {
  3493. styles.addItem (text, true, layoutStyle == style, [this, style] {
  3494. setLayoutStyle (style);
  3495. saveUiSettings();
  3496. });
  3497. };
  3498. item (tr ("Pattern workflow (default)"), Style::pattern);
  3499. item (tr ("Clip-launch workflow"), Style::clipLaunch);
  3500. item (tr ("Simple workflow"), Style::simple);
  3501. menu.addSubMenu (tr ("Layout style"), styles);
  3502. // round 183a: the detail view's items, only in Clip-launch workflow (the reference DAW's View menu [SHOT] d05)
  3503. if (isClipLaunchWorkflow() && detailView != nullptr)
  3504. {
  3505. menu.addItem (tr ("Detail view") + shortcutText ("view.detailToggle"), true, DetailView::shownSetting, [this] { runAction ("view.detailToggle"); });
  3506. menu.addItem (tr ("Clip view") + shortcutText ("view.detailClip"), true, DetailView::shownSetting && ! DetailView::devicesPage,
  3507. [this] { runAction ("view.detailClip"); });
  3508. menu.addItem (tr ("Device view") + shortcutText ("view.detailDevices"), true, DetailView::shownSetting && DetailView::devicesPage,
  3509. [this] { runAction ("view.detailDevices"); });
  3510. menu.addItem (tr ("Switch between clip view and device view") + shortcutText ("view.detailSwitch"), [this] { runAction ("view.detailSwitch"); });
  3511. }
  3512. // round 190ef: the reference's View › Scene Tempo And Time Signature
  3513. if (isClipLaunchWorkflow() && clipGridView != nullptr)
  3514. menu.addItem (tr ("Scene tempo and time signature"), true, clipGridSceneTempoShown(), [this] {
  3515. clipGridSceneTempoShown() = ! clipGridSceneTempoShown();
  3516. refreshClipGrid (*clipGridView);
  3517. saveUiSettings();
  3518. });
  3519. // round 190bu: the Simple workflow's dock for the selected track (its sound and its effects)
  3520. if (layoutStyle == Style::simple && simpleWorkflow != nullptr)
  3521. menu.addItem (tr ("Track dock") + shortcutText ("view.detailToggle"), true, SimpleDock::shownSetting, [this] { runAction ("view.detailToggle"); });
  3522. }
  3523. void MainComponent::makeDetailView()
  3524. {
  3525. DetailView::Hooks h;
  3526. // the out meter: the Mixer's own level while its strips are on screen (they take the peaks), else the peaks
  3527. h.levelOf = [this] (int insert, int side) {
  3528. return mixer.metersShowing() ? mixer.shownLevel (insert, side) : engine.getMeters().takePeak (insert, side);
  3529. };
  3530. h.toggleChannelWindow = [this] (int channel) { rack.toggleEditor (channel, true); };
  3531. h.selectInMixer = [this] (int insert) { mixer.selectTrack (insert); };
  3532. h.instrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); }; // (as on the Mixer)
  3533. h.openClip = [this] (int track, int scene) { openGridClip (track, scene); };
  3534. h.dockPianoRoll = [this] (int pattern) { return dockPianoRoll (pattern); };
  3535. h.undockPianoRoll = [this] { undockPianoRoll(); };
  3536. h.selectPattern = [this] (int pattern) { selectPattern (pattern); };
  3537. h.toggleHotSwap = [this] (const hotswap::Target& target) { toggleHotSwap (target); };
  3538. h.hotSwapTarget = [this] { return browser.hotSwapTarget(); };
  3539. h.typingKeyboardOn = [this] { return typingPiano; };
  3540. // any way the Piano roll panel comes up (F7, its button, a layout) takes the docked editor back first
  3541. workspace.onWillShow = [this] (Panel panel) { pianoRollPanelWillShow (panel); };
  3542. h.layoutChanged = [this] {
  3543. if (detailView != nullptr)
  3544. detailView->setVisible (isClipLaunchWorkflow() && DetailView::shownSetting);
  3545. playlistArea.resized();
  3546. saveUiSettings();
  3547. };
  3548. detailView = std::make_unique<DetailView> (engine, std::move (h));
  3549. setClipGridSceneFieldsListener (*clipGridView, [this] { saveUiSettings(); }); // round 190ef
  3550. setClipGridPickListener (*clipGridView, [this] (int track, int scene, GridPick pick) {
  3551. if (detailView == nullptr)
  3552. return;
  3553. detailView->showSelection (track, scene);
  3554. if (pick == GridPick::openClip)
  3555. detailView->setPage (DetailView::Page::clip);
  3556. else if (pick == GridPick::openTrack)
  3557. detailView->setPage (DetailView::Page::devices);
  3558. });
  3559. const auto selected = clipGridSelection (*clipGridView);
  3560. detailView->showSelection (selected.first, selected.second);
  3561. }
  3562. // Any way the Piano roll panel comes up (F7, its button, a layout) takes a docked editor back first: from the Clip-launch
  3563. // detail view (round 183a) or the Simple dock's Editor tab (round 190ds)
  3564. void MainComponent::pianoRollPanelWillShow (Panel panel)
  3565. {
  3566. if (panel != Panel::pianoRoll || ! pianoRollDocked)
  3567. return;
  3568. undockPianoRoll();
  3569. if (detailView != nullptr)
  3570. detailView->editorTakenBack();
  3571. if (simpleWorkflow != nullptr)
  3572. simpleWorkflow->editorTakenBack();
  3573. }
  3574. juce::Component* MainComponent::dockPianoRoll (int pattern)
  3575. {
  3576. if (pattern >= 0 && pattern < (int) engine.getSong().patterns.size() && pattern != engine.getSong().currentPattern)
  3577. selectPattern (pattern);
  3578. if (! pianoRollDocked)
  3579. {
  3580. if (workspace.isPanelVisible (Panel::pianoRoll))
  3581. {
  3582. workspace.hide (Panel::pianoRoll);
  3583. refreshPanelButtons();
  3584. }
  3585. workspace.releaseContent (Panel::pianoRoll);
  3586. pianoRollDocked = true;
  3587. pianoRollDockActive = false;
  3588. pianoRoll.setDocked (true); // (a short velocity lane and the keys fitted to the notes in the short dock)
  3589. dockClickWatcher.down = [this] (const juce::MouseEvent& e) {
  3590. pianoRollDockActive = e.eventComponent != nullptr && (e.eventComponent == &pianoRoll || pianoRoll.isParentOf (e.eventComponent));
  3591. };
  3592. juce::Desktop::getInstance().addGlobalMouseListener (&dockClickWatcher);
  3593. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<PianoRollComponent> (&pianoRoll)] {
  3594. if (safe != nullptr)
  3595. safe->scrollToNotes();
  3596. });
  3597. }
  3598. return &pianoRoll;
  3599. }
  3600. void MainComponent::undockPianoRoll()
  3601. {
  3602. if (! pianoRollDocked)
  3603. return;
  3604. pianoRollDocked = false;
  3605. pianoRollDockActive = false;
  3606. pianoRoll.setDocked (false);
  3607. juce::Desktop::getInstance().removeGlobalMouseListener (&dockClickWatcher);
  3608. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll); // (its panel has it again)
  3609. }
  3610. // Round 190ce: links the Browser to `target` (showing the Browser), or ends the link when it is linked to it already.
  3611. void MainComponent::toggleHotSwap (const hotswap::Target& target)
  3612. {
  3613. if (browser.isHotSwapping() && browser.hotSwapTarget() == target)
  3614. {
  3615. browser.endHotSwap();
  3616. return;
  3617. }
  3618. showPanel (Panel::browser);
  3619. browser.beginHotSwap (target);
  3620. }
  3621. // Round 190fc (0.1.27 RC H2, the #161 family inside the app): in the Simple layout Space often did nothing after a click
  3622. // in the window. Its own controls (the dock's tabs and cards, the Lyrics and Finish buttons, the looks) take the keyboard
  3623. // focus on a click, unlike the Pattern layout's panels, and JUCE then hands the keys to whatever child takes them — the
  3624. // dock's sound search box or the Lyrics text, where Space typed a space; the Finish looks and the chooser's tiles also
  3625. // take Space as a click. FL's rule (issue #9): a click anywhere but in a text field leaves the keys with the main window,
  3626. // so Space plays. So after each click in the main window or one of its panels: unless the click was in a text field, or
  3627. // in a part that keeps its own keys (the overlays with their list and tile keys: property "lynxKeepsKeys"; a dock knob
  3628. // just clicked, for its arrow keys: "lynxClickKeepsKeys"), the main window takes the keys back from a text field, from a
  3629. // panel's control, or from nobody.
  3630. // Plugin windows, dialogs and menus are left alone.
  3631. void MainComponent::simpleClickEnded (juce::Component* clicked)
  3632. {
  3633. if (layoutStyle != layoutstyle::Style::simple || clicked == nullptr || ! isShowing())
  3634. return;
  3635. auto inside = clicked == this || isParentOf (clicked);
  3636. for (int i = 0; ! inside && i < workspace::panelCount; ++i)
  3637. {
  3638. auto& frame = workspace.getFrame ((Panel) i);
  3639. inside = &frame == clicked || frame.isParentOf (clicked);
  3640. }
  3641. if (! inside)
  3642. return;
  3643. const auto keepsKeys = [] (juce::Component* c) {
  3644. for (; c != nullptr; c = c->getParentComponent())
  3645. if ((bool) c->getProperties().getWithDefault ("lynxKeepsKeys", false))
  3646. return true;
  3647. return false;
  3648. };
  3649. const auto inTextField = [] (juce::Component* c) {
  3650. for (; c != nullptr; c = c->getParentComponent())
  3651. if (dynamic_cast<juce::TextEditor*> (c) != nullptr)
  3652. return true;
  3653. return false;
  3654. };
  3655. if (inTextField (clicked) || keepsKeys (clicked) || (bool) clicked->getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  3656. return; // (a knob clicked keeps the arrow keys until the next click elsewhere)
  3657. // now (the clicked control has acted: this listener runs after its own mouseUp, where a button's click and the Lyrics
  3658. // panel's text focus happen), and once more after what the click posted has run
  3659. const auto takeKeys = [keepsKeys, inTextField] (MainComponent* self) {
  3660. if (self == nullptr || self->layoutStyle != layoutstyle::Style::simple || ! self->isShowing()
  3661. || juce::Component::getCurrentlyModalComponent() != nullptr) // (a menu or a dialog the click opened)
  3662. return;
  3663. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  3664. if (focused != nullptr && ! inTextField (focused) && (focused == self || self->isParentOf (focused) || keepsKeys (focused)))
  3665. return; // (the main window, or a part with its own keys, has them)
  3666. self->grabKeyboardFocus();
  3667. };
  3668. takeKeys (this);
  3669. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this), takeKeys] { takeKeys (safe.getComponent()); });
  3670. }
  3671. bool MainComponent::pianoRollKeysHere() const
  3672. {
  3673. return pianoRollDocked && pianoRollDockActive && pianoRoll.isShowing();
  3674. }
  3675. bool MainComponent::runDetailAction (const std::string& id)
  3676. {
  3677. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr) // round 190bu: the same keys, the track dock
  3678. {
  3679. if (id == "view.detailToggle")
  3680. simpleWorkflow->toggleDock();
  3681. else if (id == "view.detailSwitch")
  3682. simpleWorkflow->cycleDockTab();
  3683. else
  3684. return false;
  3685. return true;
  3686. }
  3687. if (! isClipLaunchWorkflow() || detailView == nullptr) // (Pattern workflow: the keys keep their old meaning)
  3688. return false;
  3689. if (id == "view.detailToggle")
  3690. {
  3691. DetailView::shownSetting = ! DetailView::shownSetting;
  3692. detailView->setVisible (DetailView::shownSetting);
  3693. playlistArea.resized();
  3694. saveUiSettings();
  3695. }
  3696. else if (id == "view.detailClip")
  3697. detailView->setPage (DetailView::Page::clip);
  3698. else if (id == "view.detailDevices")
  3699. detailView->setPage (DetailView::Page::devices);
  3700. else if (id == "view.detailSwitch")
  3701. detailView->togglePage();
  3702. else
  3703. return false;
  3704. return true;
  3705. }
  3706. void MainComponent::openGridClip (int track, int scene)
  3707. {
  3708. const auto& song = engine.getSong();
  3709. if (! song.clipGrid)
  3710. return;
  3711. const auto* clip = launcher::clipAt (*song.clipGrid, track, scene);
  3712. if (clip == nullptr)
  3713. return;
  3714. if (clip->kind == ClipKind::audio)
  3715. {
  3716. if (clip->channel >= 0 && clip->channel < (int) song.channels.size())
  3717. openAudioEditorForChannel (engine, clip->channel);
  3718. }
  3719. else if (clip->kind == ClipKind::pattern && clip->pattern >= 0 && clip->pattern < (int) song.patterns.size())
  3720. {
  3721. selectPattern (clip->pattern);
  3722. openPianoRoll();
  3723. }
  3724. }
  3725. void MainComponent::setClipGridView (PlaylistArea::GridView view)
  3726. {
  3727. if (clipGridView != nullptr)
  3728. playlistArea.setClipGrid (clipGridView.get(), view);
  3729. if (auto* flip = dynamic_cast<ClipGridSwitch*> (clipGridSwitch.get()))
  3730. flip->show (view);
  3731. }
  3732. void MainComponent::selectTabForSnapshot (int tab)
  3733. {
  3734. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  3735. const auto panel = panels[juce::jlimit (0, 3, tab)];
  3736. if (panel == Panel::pianoRoll)
  3737. {
  3738. const auto& song = engine.getSong();
  3739. std::vector<int> counts (song.channels.size(), 0);
  3740. for (const auto& n : song.activePattern().notes)
  3741. if (n.channel >= 0 && n.channel < (int) counts.size())
  3742. ++counts[(std::size_t) n.channel];
  3743. if (! counts.empty())
  3744. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  3745. }
  3746. // each view on its own: the panel maximized over the workspace
  3747. workspace.resetLayout();
  3748. workspace.show (panel);
  3749. workspace.toggleMaximised (panel);
  3750. refreshPanelButtons();
  3751. if (panel == Panel::pianoRoll)
  3752. pianoRoll.scrollToNotes();
  3753. if (panel == Panel::playlist)
  3754. playlist.resized(); // update the scrollbars for the loaded song
  3755. if (panel == Panel::mixer)
  3756. mixer.selectFirstTrackWithEffects();
  3757. }
  3758. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  3759. {
  3760. workspace.resetLayout();
  3761. if (auto* stage = dynamic_cast<DanceStage*> (danceStage.get()))
  3762. stage->update(); // (the project's dancers now: no timer runs before the picture)
  3763. if (extraPanels)
  3764. {
  3765. workspace.show (Panel::mixer);
  3766. workspace.show (Panel::pianoRoll);
  3767. pianoRoll.scrollToNotes();
  3768. workspace.show (Panel::channelRack);
  3769. }
  3770. refreshPanelButtons();
  3771. }
  3772. void MainComponent::showPanelsForSnapshot (std::initializer_list<Panel> panels)
  3773. {
  3774. workspace.resetLayout();
  3775. for (const auto panel : panels)
  3776. workspace.show (panel);
  3777. refreshPanelButtons();
  3778. }
  3779. // --- patterns ------------------------------------------------------------------------------------
  3780. void MainComponent::selectPattern (int index)
  3781. {
  3782. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  3783. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  3784. }
  3785. void MainComponent::stepPatternFromSelector (int delta)
  3786. {
  3787. // FL's selector goes on past the last pattern (rack ops stepPatternCreating: one new empty pattern at most)
  3788. const auto& song = engine.getSong();
  3789. const auto last = (int) song.patterns.size() - 1;
  3790. if (delta > 0 && last >= 0 && song.currentPattern + delta > last && ! isPatternEmpty (song.patterns[(std::size_t) last]))
  3791. engine.editSong ([delta] (Song& s) { s.currentPattern = stepPatternCreating (s, delta); });
  3792. else
  3793. selectPattern (stepPattern (song, delta));
  3794. }
  3795. void MainComponent::nextEmptyPattern()
  3796. {
  3797. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  3798. showRenamePattern (engine.getSong().currentPattern);
  3799. }
  3800. void MainComponent::deleteCurrentPattern()
  3801. {
  3802. // FL's Patterns › Delete (Ctrl+Shift+Del); the last pattern stays
  3803. if (engine.getSong().patterns.size() > 1)
  3804. engine.editSong ([] (Song& s) { s.removePattern (s.currentPattern); });
  3805. }
  3806. void MainComponent::insertPatternHere()
  3807. {
  3808. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  3809. }
  3810. // --- window menus ------------------------------------------------------------------------------
  3811. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  3812. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  3813. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  3814. {
  3815. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  3816. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  3817. };
  3818. auto zoomMenu = [&action] (const juce::String& prefix) {
  3819. juce::PopupMenu zoom;
  3820. const std::pair<const char*, const char*> items[] = {
  3821. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  3822. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  3823. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  3824. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  3825. };
  3826. for (const auto& [id, text] : items)
  3827. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  3828. action (zoom, a->id, tr (text));
  3829. return zoom;
  3830. };
  3831. switch (panel)
  3832. {
  3833. case Panel::channelRack:
  3834. {
  3835. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  3836. menu.addSeparator();
  3837. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  3838. action (menu, "rack.pianoRollView", tr ("Piano-roll view of all channels"), true, rack.isPianoRollView());
  3839. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  3840. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  3841. juce::PopupMenu sort;
  3842. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  3843. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  3844. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  3845. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  3846. menu.addSubMenu (tr ("Sort channels"), sort);
  3847. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  3848. action (menu, "rack.groupSelected", tr ("Group selected..."));
  3849. menu.addSectionHeader (tr ("Options")); // (FL's SSMenu: "Mute removed steps" is in its Options part)
  3850. menu.addItem (tr ("Mute removed steps"), true, ChannelRackComponent::muteRemovedSteps, [this] {
  3851. ChannelRackComponent::muteRemovedSteps = ! ChannelRackComponent::muteRemovedSteps;
  3852. saveUiSettings();
  3853. });
  3854. // FL's place for it (round 190cj, seen in FL 2026: Channel rack menu > Options, after "Mute removed steps" and
  3855. // "Show mixer track selectors"; it was in Settings > General): a row's miniature shows the whole pattern
  3856. menu.addItem (tr ("Show complete piano roll preview"), true, ChannelRackComponent::completePreview.load(), [this] {
  3857. ChannelRackComponent::completePreview.store (! ChannelRackComponent::completePreview.load());
  3858. rack.repaint();
  3859. saveUiSettings();
  3860. });
  3861. break;
  3862. }
  3863. case Panel::playlist:
  3864. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  3865. workspace.toggleMaximised (Panel::playlist);
  3866. refreshPanelButtons();
  3867. });
  3868. menu.addSeparator();
  3869. // FL's Playlist menu › Edit and › Select (round 189e: FL's items and order; the clip items below moved there)
  3870. menu.addSubMenu (tr ("Edit"), playlist.editMenu());
  3871. menu.addSubMenu (tr ("Select"), playlist.selectMenu());
  3872. menu.addSeparator();
  3873. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  3874. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  3875. // FL's legacy Pattern Blocks (round 170f, issue #60): FL 10's "Enable legacy pattern blocks", per project here
  3876. action (menu, "playlist.patternBlocks", tr ("Pattern blocks (current project)"), true, engine.getSong().patternBlocksOn);
  3877. action (menu, "playlist.blocksToClips", tr ("Turn pattern blocks into clips"), ! engine.getSong().blocks.empty());
  3878. action (menu, "playlist.automationLanes", tr ("Automation lanes"), true, autolanes::shown()); // round 177b
  3879. action (menu, "playlist.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (false));
  3880. action (menu, "playlist.quantizeStarts", tr ("Quantize the clips' starts"));
  3881. action (menu, "playlist.quantizeHalf", tr ("Quantize the clips' starts 50% (halfway to the grid)"));
  3882. {
  3883. // (round 177d: FL's Playlist menu › Picker panel; round 190he, issue #175: its first item, Enable, Alt+P)
  3884. juce::PopupMenu pickerPanel;
  3885. action (pickerPanel, "playlist.pickerPanel", tr ("Enable"), layoutStyle != layoutstyle::Style::simple, pickerPanelOn);
  3886. pickerPanel.addSeparator();
  3887. const auto tools = picker.pickerMenu();
  3888. for (juce::PopupMenu::MenuItemIterator it (tools); it.next();)
  3889. pickerPanel.addItem (it.getItem());
  3890. menu.addSubMenu (tr ("Picker panel"), pickerPanel);
  3891. }
  3892. action (menu, "playlist.stretchMode", tr ("Stretch audio when resizing audio clips"), true, EditorGlobals::get().stretchOnResize);
  3893. {
  3894. // FL 2026's Playlist menu › View › Track headers (round 190w; [DFM] EEViewMenu, FL's defaults)
  3895. juce::PopupMenu view;
  3896. view.addSectionHeader (tr ("Track headers"));
  3897. auto option = [this, &view] (const juce::String& text, bool& setting) {
  3898. view.addItem (text, true, setting, [this, &setting] {
  3899. setting = ! setting;
  3900. playlist.headerOptionsChanged();
  3901. });
  3902. };
  3903. option (tr ("Show controls on audio tracks"), PlaylistComponent::showAudioTrackControls);
  3904. option (tr ("Show levels on audio tracks"), PlaylistComponent::showAudioTrackLevels);
  3905. option (tr ("Show levels on instrument tracks"), PlaylistComponent::showInstrumentTrackLevels);
  3906. menu.addSubMenu (tr ("View"), view);
  3907. }
  3908. {
  3909. juce::PopupMenu trackTools;
  3910. action (trackTools, "playlist.cloneTracks", tr ("Clone selected playlist track(s)"));
  3911. action (trackTools, "playlist.lockAllToContent", tr ("Lock all playlist tracks to content"));
  3912. action (trackTools, "playlist.unlockAllFromContent", tr ("Unlock all playlist tracks from content"));
  3913. action (trackTools, "playlist.resetEmptyTracks", tr ("Reset empty playlist tracks"));
  3914. action (trackTools, "playlist.collapseAllGroups", tr ("Collapse all grouped tracks"));
  3915. action (trackTools, "playlist.expandAllGroups", tr ("Expand all grouped tracks"));
  3916. menu.addSubMenu (tr ("Tools"), trackTools);
  3917. }
  3918. {
  3919. // FL's Playlist Tools › EERenderPLSelectionMenu, EEPLRenderAllTracksMenu, EEPLRenderAllTrackGroupsMenu (round 168e)
  3920. juce::PopupMenu consolidate;
  3921. action (consolidate, "tools.consolidateSelection", tr ("From selection start"));
  3922. action (consolidate, "tools.consolidateSelectionSongStart", tr ("From song start"));
  3923. menu.addSubMenu (tr ("Consolidate playlist selection"), consolidate);
  3924. menu.addSubMenu (tr ("Export all playlist tracks"), playlistTrackExportMenu (false));
  3925. menu.addSubMenu (tr ("Export all playlist track groups"), playlistTrackExportMenu (true));
  3926. }
  3927. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  3928. menu.addSeparator();
  3929. // FL's Performance mode (round 165m)
  3930. action (menu, "playlist.performanceMode", tr ("Performance mode"), true, engine.getSong().performanceMode);
  3931. action (menu, "playlist.zoomPerformance", tr ("Zoom on performance clips"), engine.getSong().performanceZoneEnd() > 0);
  3932. action (menu, "playlist.perfClipProgress", tr ("Performance clip progress"), true, playlist.clipProgressShown());
  3933. action (menu, "playlist.perfTrackProgress", tr ("Performance track progress"), true, playlist.trackProgressShown());
  3934. break;
  3935. case Panel::pianoRoll:
  3936. {
  3937. juce::PopupMenu tools;
  3938. for (const auto* id : { "pianoRoll.riffMachine", "pianoRoll.chordProgression", "pianoRoll.articulate", "pianoRoll.quantize",
  3939. "pianoRoll.chop", "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flam", "pianoRoll.claw",
  3940. "pianoRoll.limit", "pianoRoll.flip", "pianoRoll.randomise", "pianoRoll.scaleLevels", "pianoRoll.lfo",
  3941. "pianoRoll.runLastScript" })
  3942. if (const auto* a = keys::findAction (id))
  3943. action (tools, a->id, tr (a->description));
  3944. menu.addSubMenu (tr ("Tools"), tools);
  3945. action (menu, "pianoRoll.quickQuantize", tr ("Quick quantize (starts and lengths)"));
  3946. action (menu, "pianoRoll.quantizeStarts", tr ("Quantize starts"));
  3947. action (menu, "pianoRoll.quantizeHalf", tr ("Quantize starts 50% (halfway to the grid)"));
  3948. action (menu, "pianoRoll.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (true));
  3949. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  3950. menu.addItem (tr ("Snap notes to the scale") + shortcutText ("pianoRoll.scaleSnap"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  3951. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  3952. break;
  3953. }
  3954. case Panel::mixer:
  3955. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  3956. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  3957. menu.addSeparator();
  3958. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  3959. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  3960. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  3961. break;
  3962. case Panel::browser:
  3963. action (menu, "browser.search", tr ("Search the Browser"));
  3964. browser.addViewItems (menu); // what it lists, which folders it shows (round 163)
  3965. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  3966. action (menu, "view.sampleBrowser", tr ("Sample browser (separate window)"));
  3967. menu.addSeparator();
  3968. // the search index (round 162, issue #9): searches read it; it follows changed folders by itself
  3969. menu.addSectionHeader (browser.searchIndexStatus());
  3970. menu.addItem (tr ("Refresh search index"), [this] { browser.refreshSearchIndex (false); });
  3971. menu.addItem (tr ("Rebuild search index"), [this] { browser.refreshSearchIndex (true); });
  3972. break;
  3973. default:
  3974. break;
  3975. }
  3976. }
  3977. // --- quick-add palette and history -------------------------------------------------------------
  3978. void MainComponent::togglePluginPicker()
  3979. {
  3980. // FL's ShowPluginPickerAction (F8): opens the picker over the main window, or closes it (REA_rodada169k §2.5)
  3981. if (pluginPickerView != nullptr)
  3982. {
  3983. auto old = std::move (pluginPickerView);
  3984. juce::MessageManager::callAsync ([keep = std::shared_ptr<juce::Component> (std::move (old))] {}); // (it may be on the stack)
  3985. return;
  3986. }
  3987. PluginPickerTargets targets;
  3988. auto safe = juce::Component::SafePointer<MainComponent> (this);
  3989. targets.addInstrument = [safe] (ChannelDef c) {
  3990. if (safe == nullptr)
  3991. return;
  3992. safe->rack.addChannel (std::move (c), true);
  3993. safe->showPanel (Panel::channelRack);
  3994. };
  3995. targets.addEffect = [safe] (EffectSlot slot) {
  3996. if (safe == nullptr)
  3997. return;
  3998. if (! safe->mixer.addEffectToSelected (std::move (slot)))
  3999. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin picker"), tr ("The selected insert has no free effect slot."));
  4000. else
  4001. {
  4002. safe->showPanel (Panel::mixer);
  4003. // FL opens the new effect's window (round 171c, its "insert effect plugin")
  4004. const auto track = safe->mixer.getSelectedTrack();
  4005. if (track >= 0 && track < (int) safe->engine.getSong().mixer.size())
  4006. safe->mixer.openSlotEditor (track, (int) safe->engine.getSong().mixer[(std::size_t) track].effects.size() - 1);
  4007. }
  4008. };
  4009. targets.close = [safe] {
  4010. if (safe != nullptr && safe->pluginPickerView != nullptr)
  4011. safe->togglePluginPicker();
  4012. };
  4013. targets.showMixer = [safe] { // (an effect dragged out of the picker: FL brings up the Mixer)
  4014. if (safe != nullptr)
  4015. safe->showPanel (Panel::mixer);
  4016. };
  4017. targets.openBrowser = [safe] (const std::string& category, bool generators) {
  4018. if (safe == nullptr)
  4019. return;
  4020. safe->showPanel (Panel::browser);
  4021. safe->browser.showPluginDatabase (category.empty() ? juce::String() : tr (category.c_str()), category.empty() ? -1 : (generators ? 1 : 0));
  4022. };
  4023. targets.dragOwner = [safe]() -> juce::Component* { return safe.getComponent(); };
  4024. pluginPickerView = makePluginPickerView (engine, std::move (targets));
  4025. // FL's picker form covers the work area of the main window's monitor, whatever the main window's size (round 175b:
  4026. // FL at 1280 × 720 in a 1920 screen still opens it over the whole screen), and lets the screen show through
  4027. const auto* top = getTopLevelComponent();
  4028. const auto& displays = juce::Desktop::getInstance().getDisplays();
  4029. const auto* display = displays.getDisplayForRect (top != nullptr ? top->getScreenBounds() : getScreenBounds());
  4030. const auto area = display != nullptr ? display->userArea : getScreenBounds();
  4031. takePluginPickerBackdrop (*pluginPickerView, area);
  4032. pluginPickerView->setBounds (area);
  4033. pluginPickerView->addToDesktop (0); // (no frame, not on the taskbar)
  4034. pluginPickerView->setVisible (true);
  4035. pluginPickerView->toFront (true);
  4036. pluginPickerView->grabKeyboardFocus();
  4037. }
  4038. void MainComponent::showQuickAdd()
  4039. {
  4040. QuickAddTargets targets;
  4041. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  4042. targets.addInstrument = [this] (ChannelDef c) {
  4043. rack.addChannel (std::move (c), true);
  4044. showPanel (Panel::channelRack);
  4045. };
  4046. targets.addEffect = [this] (EffectSlot slot) {
  4047. if (! mixer.addEffectToSelected (std::move (slot)))
  4048. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  4049. tr ("The selected insert has no free effect slot."));
  4050. else
  4051. showPanel (Panel::mixer);
  4052. };
  4053. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  4054. }
  4055. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  4056. {
  4057. QuickAddTargets targets;
  4058. targets.addInstrument = [] (ChannelDef) {};
  4059. targets.addEffect = [] (EffectSlot) {};
  4060. return makeQuickAddPalette (engine, std::move (targets));
  4061. }
  4062. // --- round 190ch: Lyrics / Notes and Reference match ------------------------------------------------------------------
  4063. bool MainComponent::isLyricsShowing() const
  4064. {
  4065. return (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr) || lyricsWindowPanel != nullptr;
  4066. }
  4067. LyricsPanel* MainComponent::getLyricsPanelForSnapshot()
  4068. {
  4069. showLyrics (false);
  4070. return static_cast<LyricsPanel*> (lyricsDock.get());
  4071. }
  4072. void MainComponent::hideLyrics()
  4073. {
  4074. if (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr)
  4075. {
  4076. static_cast<LyricsPanel&> (*lyricsDock).commit();
  4077. playlistArea.setSideDock (nullptr, 0);
  4078. }
  4079. if (lyricsWindowPanel != nullptr)
  4080. closeToolWindowOf (*lyricsWindowPanel);
  4081. }
  4082. void MainComponent::toggleLyrics()
  4083. {
  4084. if (isLyricsShowing())
  4085. hideLyrics();
  4086. else
  4087. showLyrics (false);
  4088. }
  4089. void MainComponent::showLyrics (bool floating)
  4090. {
  4091. hideLyrics();
  4092. if (floating)
  4093. {
  4094. LyricsPanel::Hooks hooks;
  4095. hooks.toggleFloating = [this] { juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  4096. if (safe != nullptr)
  4097. safe->showLyrics (false);
  4098. }); };
  4099. auto panel = std::make_unique<LyricsPanel> (engine, std::move (hooks));
  4100. panel->setFloating (true);
  4101. panel->setSize (420, 560);
  4102. lyricsWindowPanel = panel.get();
  4103. openToolWindow (std::move (panel), tr ("Lyrics and notes"), "lyrics");
  4104. return;
  4105. }
  4106. if (lyricsDock == nullptr)
  4107. {
  4108. LyricsPanel::Hooks hooks;
  4109. hooks.close = [this] { hideLyrics(); };
  4110. hooks.toggleFloating = [this] { juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  4111. if (safe != nullptr)
  4112. safe->showLyrics (true);
  4113. }); };
  4114. lyricsDock = std::make_unique<LyricsPanel> (engine, std::move (hooks));
  4115. }
  4116. // the dock on the right of the Playlist is one place: the Simple workflow's Finish dock gives way
  4117. if (simpleWorkflow != nullptr && simpleWorkflow->isFinishShowing())
  4118. simpleWorkflow->hideFinish();
  4119. static_cast<LyricsPanel&> (*lyricsDock).refresh();
  4120. if (! workspace.isPanelVisible (Panel::playlist))
  4121. {
  4122. workspace.show (Panel::playlist);
  4123. refreshPanelButtons();
  4124. }
  4125. playlistArea.setSideDock (lyricsDock.get(), LyricsPanel::width);
  4126. }
  4127. void MainComponent::showReferenceMatch()
  4128. {
  4129. if (auto* open = findToolWindow ("referenceMatch"))
  4130. {
  4131. open->toFront (true);
  4132. return;
  4133. }
  4134. ReferenceMatchPanel::Hooks hooks;
  4135. hooks.showMaster = [this] {
  4136. workspace.show (Panel::mixer);
  4137. mixer.selectTrack (0);
  4138. refreshPanelButtons();
  4139. };
  4140. auto panel = std::make_unique<ReferenceMatchPanel> (engine, std::move (hooks));
  4141. referenceMatchPanel = panel.get();
  4142. openToolWindow (std::move (panel), tr ("Reference match"), "referenceMatch");
  4143. }
  4144. void MainComponent::commitSongNotes()
  4145. {
  4146. if (lyricsDock != nullptr)
  4147. static_cast<LyricsPanel&> (*lyricsDock).commit();
  4148. if (auto* panel = dynamic_cast<LyricsPanel*> (lyricsWindowPanel.getComponent()))
  4149. panel->commit();
  4150. }
  4151. void MainComponent::refreshSongNotes()
  4152. {
  4153. if (lyricsDock != nullptr && lyricsDock->getParentComponent() != nullptr)
  4154. static_cast<LyricsPanel&> (*lyricsDock).refresh();
  4155. if (auto* panel = dynamic_cast<LyricsPanel*> (lyricsWindowPanel.getComponent()))
  4156. panel->refresh();
  4157. if (auto* panel = dynamic_cast<ReferenceMatchPanel*> (referenceMatchPanel.getComponent()))
  4158. panel->refresh();
  4159. }
  4160. void MainComponent::showHistory()
  4161. {
  4162. if (auto* open = findToolWindow ("history"))
  4163. {
  4164. open->toFront (true);
  4165. return;
  4166. }
  4167. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  4168. }
  4169. // --- recording options ---------------------------------------------------------------------------
  4170. void MainComponent::updateRecordQuantise()
  4171. {
  4172. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  4173. std::int64_t ticks = 0;
  4174. // (the grid is kept even with "Note start time" off: "Note end time" uses it too)
  4175. {
  4176. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  4177. if (option.kind == grid::Kind::ticks)
  4178. ticks = option.ticks;
  4179. else if (option.kind == grid::Kind::bar)
  4180. ticks = engine.getSong().barTicks();
  4181. }
  4182. if (engine.getRecordOptions().quantise != ticks || engine.getRecordOptions().quantiseStarts != recordQuantiseOn)
  4183. {
  4184. auto o = engine.getRecordOptions();
  4185. o.quantise = ticks;
  4186. o.quantiseStarts = recordQuantiseOn;
  4187. engine.setRecordOptions (o);
  4188. }
  4189. }
  4190. void MainComponent::addRecordQuantizeItems (juce::PopupMenu& menu)
  4191. {
  4192. const auto o = engine.getRecordOptions();
  4193. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  4194. auto options = engine.getRecordOptions();
  4195. change (options);
  4196. engine.setRecordOptions (options);
  4197. saveUiSettings();
  4198. };
  4199. // FL's record menu "Quantize" items (REA round 139), to the global snap
  4200. menu.addItem (tr ("Note start time"), ! o.toStepSequencer, recordQuantiseOn && ! o.toStepSequencer, [this] {
  4201. recordQuantiseOn = ! recordQuantiseOn;
  4202. updateRecordQuantise();
  4203. saveUiSettings();
  4204. });
  4205. menu.addItem (tr ("Note end time"), ! o.toStepSequencer, o.noteEnd == NoteEnd::quantize && ! o.toStepSequencer, [set] {
  4206. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::quantize ? NoteEnd::keepEnd : NoteEnd::quantize; });
  4207. });
  4208. menu.addItem (tr ("Leave note duration"), ! o.toStepSequencer, o.noteEnd == NoteEnd::keepLength && ! o.toStepSequencer, [set] {
  4209. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::keepLength ? NoteEnd::keepEnd : NoteEnd::keepLength; });
  4210. });
  4211. menu.addItem (tr ("Record to step sequencer"), true, o.toStepSequencer,
  4212. [set] { set ([] (AudioEngine::RecordOptions& r) { r.toStepSequencer = ! r.toStepSequencer; }); });
  4213. // FL's "Automations" (RecQuantizeAutomationsMenu, setting QuantizeAutomations; REA round 143): recorded automation
  4214. // points go to the snap
  4215. menu.addItem (tr ("Automations"), true, o.quantiseAutomation,
  4216. [set] { set ([] (AudioEngine::RecordOptions& r) { r.quantiseAutomation = ! r.quantiseAutomation; }); });
  4217. }
  4218. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  4219. {
  4220. const auto o = engine.getRecordOptions();
  4221. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  4222. auto options = engine.getRecordOptions();
  4223. change (options);
  4224. engine.setRecordOptions (options);
  4225. refreshRecordOptionButtons();
  4226. saveUiSettings();
  4227. };
  4228. juce::PopupMenu countIn;
  4229. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set ([] (AudioEngine::RecordOptions& r) { r.countInBars = 0; }); });
  4230. for (int bars : { 1, 2, 4 })
  4231. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars,
  4232. [set, bars] { set ([bars] (AudioEngine::RecordOptions& r) { r.countInBars = bars; }); });
  4233. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), countIn);
  4234. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  4235. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  4236. menu.addItem (tr ("Loop record") + shortcutText ("record.loop"), true, o.loopRecord,
  4237. [set] { set ([] (AudioEngine::RecordOptions& r) { r.loopRecord = ! r.loopRecord; }); });
  4238. menu.addItem (tr ("After loop recording, only the last pass plays"), true, o.lastLoopPassPlays,
  4239. [set] { set ([] (AudioEngine::RecordOptions& r) { r.lastLoopPassPlays = ! r.lastLoopPassPlays; }); });
  4240. menu.addItem (tr ("Step edit") + shortcutText ("record.stepEdit"), true, engine.isStepEdit(), [this] { runAction ("record.stepEdit"); });
  4241. // round 170d: notes played during the count-in are kept; the ones just before the start go onto it
  4242. {
  4243. juce::PopupMenu catchMenu;
  4244. catchMenu.addItem (tr ("Off (keep their real time)"), true, o.catchWindow == 0,
  4245. [set] { set ([] (AudioEngine::RecordOptions& r) { r.catchWindow = 0; }); });
  4246. const std::pair<std::int64_t, const char*> windows[] = { { ppq / 8, TR_NOOP ("1/32 note") },
  4247. { ppq / 4, TR_NOOP ("1/16 note") },
  4248. { ppq / 2, TR_NOOP ("1/8 note") },
  4249. { ppq, TR_NOOP ("1/4 note") } };
  4250. for (const auto& [ticks, name] : windows)
  4251. catchMenu.addItem (tr (name), true, o.catchWindow == ticks,
  4252. [set, ticks = ticks] { set ([ticks] (AudioEngine::RecordOptions& r) { r.catchWindow = ticks; }); });
  4253. menu.addSubMenu (tr ("Notes played just before the start go onto it"), catchMenu);
  4254. }
  4255. menu.addItem (tr ("Played notes: compensate the output latency"), true, o.compensateOutput,
  4256. [set] { set ([] (AudioEngine::RecordOptions& r) { r.compensateOutput = ! r.compensateOutput; }); });
  4257. menu.addItem (tr ("Capture MIDI: the notes just played without recording into the pattern") + shortcutText ("record.captureMidi"),
  4258. [this] { runAction ("record.captureMidi"); });
  4259. // round 163: punch in/out on the loop region, pre-roll and post-roll (bars)
  4260. {
  4261. auto bars = [&set] (juce::PopupMenu& m, int now, std::function<void (AudioEngine::RecordOptions&, int)> apply) {
  4262. m.addItem (tr ("Off"), true, now == 0, [set, apply] { set ([apply] (AudioEngine::RecordOptions& r) { apply (r, 0); }); });
  4263. for (int n : { 1, 2, 4 })
  4264. m.addItem (n == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (n) }), true, now == n,
  4265. [set, apply, n] { set ([apply, n] (AudioEngine::RecordOptions& r) { apply (r, n); }); });
  4266. };
  4267. juce::PopupMenu pre, post;
  4268. bars (pre, o.preRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.preRollBars = n; });
  4269. bars (post, o.postRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.postRollBars = n; });
  4270. menu.addItem (tr ("Audio: punch in/out on the loop region (plays through it, keeps only the region)"), true, o.punchLoopRegion,
  4271. [set] { set ([] (AudioEngine::RecordOptions& r) { r.punchLoopRegion = ! r.punchLoopRegion; }); });
  4272. menu.addSubMenu (tr ("Audio: pre-roll (plays before the punch-in or the start position)"), pre);
  4273. menu.addSubMenu (tr ("Audio: post-roll (plays after the punch-out, then stops)"), post);
  4274. }
  4275. menu.addSeparator();
  4276. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  4277. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  4278. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  4279. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  4280. menu.addSeparator();
  4281. {
  4282. juce::PopupMenu quantize;
  4283. addRecordQuantizeItems (quantize);
  4284. menu.addSubMenu (tr ("Quantize recorded notes to the global snap"), quantize);
  4285. }
  4286. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  4287. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  4288. }
  4289. void MainComponent::toggleRecording()
  4290. {
  4291. if (engine.isRecording())
  4292. {
  4293. engine.setRecording (false);
  4294. return;
  4295. }
  4296. if (! engine.getRecordOptions().askWhatToRecord || ! persistent)
  4297. {
  4298. engine.setRecording (true);
  4299. if (engine.getRecordOptions().startsPlayback && ! engine.getTransport().playing.load()) // FL's "Recording starts playback"
  4300. engine.startPlayback();
  4301. return;
  4302. }
  4303. juce::Component::SafePointer<MainComponent> safe (this);
  4304. showRecordChoiceDialog ([safe] (int choice, bool dontAsk) {
  4305. if (safe == nullptr)
  4306. return;
  4307. if (choice == recordChoiceAudioEditor)
  4308. {
  4309. openAudioEditorRecording (safe->engine);
  4310. if (! safe->engine.getTransport().playing.load())
  4311. safe->engine.play();
  4312. return;
  4313. }
  4314. auto o = safe->engine.getRecordOptions();
  4315. o.recordNotes = choice != recordChoiceAudio;
  4316. o.recordAudio = choice != recordChoiceNotes;
  4317. o.recordAutomation = choice != recordChoiceAudio;
  4318. if (dontAsk)
  4319. o.askWhatToRecord = false;
  4320. safe->engine.setRecordOptions (o);
  4321. if (dontAsk)
  4322. safe->saveUiSettings();
  4323. if (choice == recordChoiceAudio && safe->engine.getArmedInserts().empty())
  4324. safe->armSelectedInsertForAudio();
  4325. safe->engine.setRecording (true);
  4326. if (o.startsPlayback && ! safe->engine.getTransport().playing.load()) // FL's "Recording starts playback"
  4327. safe->engine.startPlayback();
  4328. });
  4329. }
  4330. // Round 163: the fastest way from "press record" to a clip on the Playlist — one key arms the selected insert (or the
  4331. // one with an input), records audio only (no question) and starts playback (count-in / pre-roll as set); pressed
  4332. // again it stops, and the take is on the Playlist.
  4333. void MainComponent::quickRecordAudio()
  4334. {
  4335. auto& transport = engine.getTransport();
  4336. if (engine.isRecording() && (transport.playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  4337. {
  4338. engine.stop();
  4339. engine.setRecording (false);
  4340. return;
  4341. }
  4342. if (engine.getArmedInserts().empty())
  4343. armSelectedInsertForAudio();
  4344. if (engine.getArmedInserts().empty()) // no input yet: its menu is open, nothing to record
  4345. return;
  4346. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  4347. {
  4348. o.recordAudio = true;
  4349. engine.setRecordOptions (o);
  4350. }
  4351. engine.setRecording (true);
  4352. if (! transport.playing.load())
  4353. engine.startPlayback();
  4354. }
  4355. void MainComponent::oneClickRecord (int into)
  4356. {
  4357. // FL: FUN_0120d380 (round 190dx, /mnt/e/lynx-work/flpl190dx/FL-FACTS.md item 20)
  4358. const auto plan = oneclick::plan (engine.getSong(), engine.getArmedInserts(), this->mixer.getStripsForSnapshot().getSelectedTrack(),
  4359. (oneclick::Into) into);
  4360. if (plan.insert > 0)
  4361. {
  4362. showPanel (Panel::mixer);
  4363. this->mixer.selectTrack (plan.insert);
  4364. }
  4365. if (plan.loadEdison)
  4366. {
  4367. // FL loads Edison set to record on play on the selected mixer track (its "Open audio editor and record"), then plays
  4368. this->mixer.runAction ("mixer.audioEditorRecord");
  4369. if (! engine.getTransport().playing.load())
  4370. engine.startPlayback();
  4371. return;
  4372. }
  4373. if (! plan.recordOn)
  4374. return;
  4375. const auto start = [this] {
  4376. if (engine.getSong().mode != PlayMode::song) // FL switches to Song mode
  4377. engine.editSong ([] (Song& s) { s.mode = PlayMode::song; }, false);
  4378. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  4379. {
  4380. o.recordAudio = true;
  4381. engine.setRecordOptions (o);
  4382. }
  4383. engine.setRecording (true);
  4384. if (! engine.getTransport().playing.load())
  4385. engine.startPlayback();
  4386. };
  4387. if (plan.armInsert && plan.askInput)
  4388. {
  4389. // FL asks for the selected mixer track's input first; nothing records until one is picked
  4390. mixerinput::showMenu (engine, plan.insert, &this->mixer, [this, insert = plan.insert, start] {
  4391. engine.setInsertArmed (insert, true);
  4392. start();
  4393. });
  4394. return;
  4395. }
  4396. if (plan.armInsert)
  4397. engine.setInsertArmed (plan.insert, true);
  4398. start();
  4399. }
  4400. void MainComponent::armSelectedInsertForAudio()
  4401. {
  4402. const auto& mixer = engine.getSong().mixer;
  4403. // the selected insert, else the first one with an input, else a free one
  4404. auto target = this->mixer.getStripsForSnapshot().getSelectedTrack();
  4405. for (int t = 1; target <= 0 && t < (int) mixer.size(); ++t)
  4406. if (mixer[(std::size_t) t].inputChannel >= 0)
  4407. target = t;
  4408. if (target <= 0)
  4409. target = engine.getSong().nextFreeInsert();
  4410. if (target <= 0 || target >= (int) mixer.size())
  4411. return;
  4412. showPanel (Panel::mixer);
  4413. this->mixer.selectTrack (target);
  4414. if (engine.isInsertArmed (target))
  4415. return;
  4416. // this menu item says "(choose its input)": without one, the input menu comes first and arms after the choice
  4417. if (mixer[(std::size_t) target].inputChannel < 0)
  4418. mixerinput::showMenu (engine, target, &this->mixer, [this, target] { engine.setInsertArmed (target, true); });
  4419. else
  4420. mixerinput::toggleArm (engine, target, &this->mixer);
  4421. }
  4422. void MainComponent::showMetronomeMenu()
  4423. {
  4424. // FL 2026's right-click on the metronome button, as it is (REA round 165z-a2): the "Metronome sound" choice only,
  4425. // in FL's order. The volume trim is in Options, the count-in has its own button and the track the click plays
  4426. // through is in Settings › Audio › Mixer.
  4427. auto& transport = engine.getTransport();
  4428. juce::PopupMenu menu;
  4429. menu.addSectionHeader (tr ("Metronome sound"));
  4430. for (int i = 0; i < metronome::soundCount; ++i)
  4431. menu.addItem (tr (metronome::soundName (i)), true, metronome::clampSound (transport.metronomeSound.load()) == i, [this, i] {
  4432. engine.getTransport().metronomeSound.store (i);
  4433. saveUiSettings();
  4434. });
  4435. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&metronomeButton));
  4436. }
  4437. void MainComponent::showTypingPianoMenu()
  4438. {
  4439. // FL 2026's right-click on the typing keyboard button (KbToMIDIPopup, measured round 168t2): Root note C..B,
  4440. // Octave 2..6 (where the Z row starts), Options › Reset, Layout (FL's .scr names and order, core/KeyMap.h).
  4441. // FL's Reset (KbToMIDIResetClick 0x121ac70) releases the held notes and puts Root note C, Octave 4 and Layout Piano back.
  4442. static const char* const names[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  4443. juce::PopupMenu menu;
  4444. menu.addSectionHeader (tr ("Root note"));
  4445. for (int r = 0; r < 12; ++r)
  4446. menu.addItem (names[r], true, typingRoot == r, [this, r] { typingRoot = r; saveUiSettings(); });
  4447. menu.addSectionHeader (tr ("Octave"));
  4448. for (int o = keys::typingpiano::minOctave; o <= keys::typingpiano::maxOctave; ++o)
  4449. menu.addItem (juce::String (o), true, typingOctave == o, [this, o] { typingOctave = o; saveUiSettings(); });
  4450. menu.addSectionHeader (tr ("Options"));
  4451. menu.addItem (tr ("Reset"), [this] {
  4452. heldKeys.releaseAll();
  4453. releaseTypingLaunches (true);
  4454. typingOctave = keys::typingpiano::defaultOctave;
  4455. typingRoot = 0;
  4456. typingLayout = keys::typingpiano::pianoLayout();
  4457. saveUiSettings();
  4458. });
  4459. menu.addSectionHeader (tr ("Layout"));
  4460. for (int l = 0; l < keys::typingpiano::layoutCount(); ++l) // (FL's file names, untranslated as in FL)
  4461. menu.addItem (keys::typingpiano::layoutName (l), true, typingLayout == l, [this, l] {
  4462. heldKeys.releaseAll(); // a held key's notes belong to the old layout
  4463. releaseTypingLaunches (true);
  4464. typingLayout = l;
  4465. saveUiSettings();
  4466. });
  4467. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&typingPianoButton));
  4468. }
  4469. void MainComponent::dumpScoreLog (int minutes)
  4470. {
  4471. const auto& song = engine.getSong();
  4472. scorelog::DumpOptions options;
  4473. options.minutes = minutes;
  4474. options.bpm = song.bpm;
  4475. options.beatsPerBar = song.beatsPerBar;
  4476. options.beatUnit = song.beatUnit;
  4477. auto notes = scorelog::dump (engine.scoreLogSnapshot(), options);
  4478. // (channels deleted since the notes were played are left out)
  4479. notes.erase (std::remove_if (notes.begin(), notes.end(), [&song] (const Note& n) { return n.channel < 0 || n.channel >= (int) song.channels.size(); }),
  4480. notes.end());
  4481. if (notes.empty())
  4482. {
  4483. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Score logger"),
  4484. tr ("The score log is empty: no notes were played on a MIDI keyboard or the typing keyboard in that time."));
  4485. return;
  4486. }
  4487. auto apply = [this] (std::vector<Note> logged, bool replace) {
  4488. const auto count = logged.size();
  4489. engine.editSong ([&logged, replace] (Song& s) {
  4490. if (s.patterns.empty())
  4491. s.patterns.emplace_back();
  4492. s.currentPattern = juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern);
  4493. auto& pattern = s.activePattern();
  4494. if (replace)
  4495. pattern.notes.clear();
  4496. pattern.notes.insert (pattern.notes.end(), logged.begin(), logged.end());
  4497. pattern.sortNotes();
  4498. });
  4499. ui::postHint ({ tr ("Score log: {0} notes put in the pattern", { juce::String ((int) count) }), {}, false, false }, 4000);
  4500. };
  4501. const auto& patterns = song.patterns;
  4502. const auto current = song.currentPattern;
  4503. if (current < 0 || current >= (int) patterns.size() || patterns[(std::size_t) current].notes.empty())
  4504. {
  4505. apply (std::move (notes), false);
  4506. return;
  4507. }
  4508. auto box = juce::MessageBoxOptions()
  4509. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  4510. .withTitle (tr ("Score logger"))
  4511. .withMessage (tr ("The current pattern isn't empty. Do you want the score log to be merged, or to replace the current content?"))
  4512. .withButton (tr ("Merge"))
  4513. .withButton (tr ("Replace"))
  4514. .withButton (tr ("Cancel"));
  4515. juce::AlertWindow::showAsync (box, [apply, notes] (int result) mutable {
  4516. if (result == 1 || result == 2)
  4517. apply (std::move (notes), result == 2);
  4518. });
  4519. }
  4520. void MainComponent::showMetronomeVolume()
  4521. {
  4522. // a callout with the volume knob; the click plays at the new level at once (Transport::metronomeVolume)
  4523. struct VolumePanel final : public juce::Component
  4524. {
  4525. VolumePanel (MainComponent& m) : owner (m)
  4526. {
  4527. title.setText (tr ("Metronome volume"), juce::dontSendNotification);
  4528. title.setJustificationType (juce::Justification::centred);
  4529. addAndMakeVisible (title);
  4530. knob.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  4531. knob.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 120, 18);
  4532. knob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  4533. knob.setDoubleClickReturnValue (true, 1.0);
  4534. knob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  4535. knob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  4536. knob.setValue (owner.engine.getTransport().metronomeVolume.load(), juce::dontSendNotification);
  4537. knob.onValueChange = [this] { owner.engine.getTransport().metronomeVolume.store ((float) knob.getValue()); };
  4538. knob.onDragEnd = [this] { owner.saveUiSettings(); };
  4539. ui::setHint (knob, tr ("Metronome volume: 100% is the default click level, up to 125% [2xLMB] 100%"));
  4540. addAndMakeVisible (knob);
  4541. setSize (170, 150);
  4542. }
  4543. ~VolumePanel() override { owner.saveUiSettings(); }
  4544. void resized() override
  4545. {
  4546. auto r = getLocalBounds().reduced (8);
  4547. title.setBounds (r.removeFromTop (20));
  4548. knob.setBounds (r);
  4549. }
  4550. MainComponent& owner;
  4551. juce::Label title;
  4552. juce::Slider knob;
  4553. };
  4554. juce::CallOutBox::launchAsynchronously (std::make_unique<VolumePanel> (*this), metronomeButton.getScreenBounds(), nullptr);
  4555. }
  4556. void MainComponent::openAudioEditorForSelection()
  4557. {
  4558. const auto& song = engine.getSong();
  4559. const auto channel = engine.getSelectedChannel();
  4560. if (juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  4561. {
  4562. const auto& c = song.channels[(std::size_t) channel];
  4563. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty())
  4564. {
  4565. openAudioEditorForChannel (engine, channel);
  4566. return;
  4567. }
  4568. }
  4569. openAudioEditor (engine);
  4570. }
  4571. void MainComponent::showRecordMenu()
  4572. {
  4573. buildRecordMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  4574. : (juce::Component*) &recordButton));
  4575. }
  4576. juce::PopupMenu MainComponent::buildRecordMenu()
  4577. {
  4578. const auto o = engine.getRecordOptions();
  4579. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  4580. auto options = engine.getRecordOptions();
  4581. change (options);
  4582. engine.setRecordOptions (options);
  4583. saveUiSettings();
  4584. };
  4585. juce::PopupMenu menu;
  4586. menu.addSectionHeader (tr ("Recording filter"));
  4587. // FL's filter order (RecMenu, REA round 143): Automation, Notes, Audio
  4588. menu.addItem (tr ("Automation (the controls you move: automation clips in song mode, pattern events in pattern mode)"), true,
  4589. o.recordAutomation, [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAutomation = ! r.recordAutomation; }); });
  4590. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), true, o.recordNotes,
  4591. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordNotes = ! r.recordNotes; }); });
  4592. menu.addItem (tr ("Audio of the armed mixer inserts (becomes Playlist clips)"), true, o.recordAudio,
  4593. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAudio = ! r.recordAudio; }); });
  4594. menu.addItem (tr ("Clips (Performance mode: the launched clips are written into the arrangement)"), true, o.recordClips,
  4595. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordClips = ! r.recordClips; }); });
  4596. menu.addItem (tr ("Ask what to record when recording starts"), true, o.askWhatToRecord,
  4597. [set] { set ([] (AudioEngine::RecordOptions& r) { r.askWhatToRecord = ! r.askWhatToRecord; }); });
  4598. // FL's "Options" section (REA round 134)
  4599. menu.addSectionHeader (tr ("Options"));
  4600. menu.addItem (tr ("Recording starts playback"), true, o.startsPlayback,
  4601. [set] { set ([] (AudioEngine::RecordOptions& r) { r.startsPlayback = ! r.startsPlayback; }); });
  4602. menu.addItem (tr ("Disarm on stop (recording switches off when playback stops)"), true, o.recordOffOnStop,
  4603. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordOffOnStop = ! r.recordOffOnStop; }); });
  4604. // LYNX's own (issue #16; FL has no such option): also in Mixer › Disk recording
  4605. menu.addItem (tr ("Disarm the inserts when recording stops"), true, o.disarmOnStop,
  4606. [set] { set ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  4607. // LYNX's own (round 190aq, core/LowLatency.h; FL has no such switch): also in Mixer › Disk recording
  4608. menu.addItem (tr ("Low latency while recording (bypasses effects that add latency on armed or monitored inserts)"), true, o.lowLatencyRecording,
  4609. [set] { set ([] (AudioEngine::RecordOptions& r) { r.lowLatencyRecording = ! r.lowLatencyRecording; }); });
  4610. menu.addItem (tr ("Enable recording markers (Start / Stop recording markers in the Playlist)"), true, o.recordingMarkers,
  4611. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordingMarkers = ! r.recordingMarkers; }); });
  4612. // FL's "Quantize" section (REA round 139): to the global snap
  4613. menu.addSectionHeader (tr ("Quantize"));
  4614. addRecordQuantizeItems (menu);
  4615. menu.addItem (tr ("Record into the audio editor..."), [this] { openAudioEditor (engine); });
  4616. menu.addSeparator();
  4617. menu.addItem (tr ("Arm the selected mixer insert for audio (choose its input)..."), [this] { armSelectedInsertForAudio(); });
  4618. menu.addItem (tr ("Audio settings (input device)..."), [this] { openSettings ((int) SettingsPage::audio); });
  4619. menu.addItem (tr ("Open recordings folder"), [this] {
  4620. const auto folder = engine.getRecordingFolder();
  4621. folder.createDirectory();
  4622. folder.startAsProcess();
  4623. });
  4624. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  4625. menu.addSeparator();
  4626. addRecordOptions (menu);
  4627. return menu;
  4628. }
  4629. void MainComponent::refreshRecordOptionButtons()
  4630. {
  4631. auto withKey = [this] (const juce::String& text, const char* id) {
  4632. const auto key = shortcutText (id).trim();
  4633. return key.isEmpty() ? text : text + " (" + key + ")";
  4634. };
  4635. const auto o = engine.getRecordOptions();
  4636. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  4637. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  4638. : tr ("Count-in before recording: off"),
  4639. "record.countIn"));
  4640. blendButton.setToggleState (o.mode == RecordMode::overdub, juce::dontSendNotification);
  4641. {
  4642. const auto blend = o.mode == RecordMode::overdub;
  4643. auto tip = blend ? tr ("Blend recorded notes: on (new notes join the pattern's notes)")
  4644. : tr ("Blend recorded notes: off (a recorded channel's old notes are replaced)");
  4645. if (! o.lastLoopPassPlays)
  4646. tip << "\n" << (blend ? tr ("Loop-recorded audio: every pass plays") : tr ("Loop-recorded audio: every pass is muted"));
  4647. blendButton.setTooltip (tip);
  4648. }
  4649. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  4650. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  4651. "record.waitForInput"));
  4652. blendButton.setTooltip (withKey (blendButton.getTooltip(), "record.blend"));
  4653. loopRecordButton.setToggleState (o.loopRecord, juce::dontSendNotification);
  4654. loopRecordButton.setTooltip (withKey (o.loopRecord ? tr ("Loop record: on (recording loops: the loop region in Song mode, one take per pass; the pattern in Pattern mode)")
  4655. : tr ("Loop record: off (recording plays straight on: through the loop region, or past the pattern's end, which grows)"),
  4656. "record.loop"));
  4657. stepEditButton.setToggleState (engine.isStepEdit(), juce::dontSendNotification);
  4658. stepEditButton.setTooltip (withKey (engine.isStepEdit() ? tr ("Step edit: on (stopped, played notes go into the pattern one snap step after another)")
  4659. : tr ("Step edit: off"),
  4660. "record.stepEdit"));
  4661. punchButton.setToggleState (o.punchLoopRegion, juce::dontSendNotification);
  4662. punchButton.setTooltip (withKey (o.punchLoopRegion ? tr ("Punch in/out: on (audio is kept only inside the loop region)") : tr ("Punch in/out: off"),
  4663. "record.punch"));
  4664. }
  4665. void MainComponent::clonePatternNow()
  4666. {
  4667. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  4668. }
  4669. void MainComponent::movePatternNow (int delta)
  4670. {
  4671. engine.editSongPatternOrder ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  4672. }
  4673. void MainComponent::splitPatternByChannelNow()
  4674. {
  4675. int created = 0;
  4676. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  4677. if (created == 0)
  4678. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  4679. }
  4680. void MainComponent::showRenamePattern (int index)
  4681. {
  4682. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  4683. return;
  4684. const auto& p = engine.getSong().patterns[(std::size_t) index];
  4685. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  4686. [this, index] (const juce::String& name, std::uint32_t colour) {
  4687. if (index < (int) engine.getSong().patterns.size())
  4688. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  4689. s.patterns[(std::size_t) index].name = n;
  4690. s.patterns[(std::size_t) index].colour = colour;
  4691. });
  4692. });
  4693. }
  4694. void MainComponent::refreshToolbar()
  4695. {
  4696. const auto& song = engine.getSong();
  4697. patternBox.clear (juce::dontSendNotification);
  4698. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  4699. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  4700. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  4701. swingSlider.setValue (song.swing, juce::dontSendNotification);
  4702. tempoDisplay.repaint();
  4703. refreshModeButton();
  4704. refreshRackPatternSelector();
  4705. refreshRackLengthBox();
  4706. }
  4707. void MainComponent::refreshRackPatternSelector()
  4708. {
  4709. const auto& song = engine.getSong();
  4710. const auto valid = song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size();
  4711. const auto text = valid ? juce::String::fromUTF8 (song.activePattern().name.c_str()) : juce::String();
  4712. const auto colour = valid ? PlaylistComponent::patternColour (song, song.currentPattern) : juce::Colour();
  4713. if (text != rackPatternSelector.text || colour != rackPatternSelector.colour)
  4714. {
  4715. rackPatternSelector.text = text;
  4716. rackPatternSelector.colour = colour;
  4717. rackPatternSelector.repaint();
  4718. }
  4719. }
  4720. void MainComponent::showRackPatternList()
  4721. {
  4722. const auto& song = engine.getSong();
  4723. juce::PopupMenu menu;
  4724. for (int i = 0; i < (int) song.patterns.size(); ++i)
  4725. menu.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), true, i == song.currentPattern, [this, i] { selectPattern (i); });
  4726. menu.addSeparator();
  4727. menu.addItem (tr ("New pattern"), [this] { newPatternButton.onClick(); });
  4728. menu.addItem (tr ("Rename and color the pattern") + shortcutText ("pattern.rename"), [this] { runAction ("pattern.rename"); });
  4729. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackPatternSelector));
  4730. }
  4731. // --- the Channel Rack's pattern length box (issue #12) ---------------------------------------------------------
  4732. int MainComponent::PatternLengthBox::stepBars (int value, int delta)
  4733. {
  4734. static const int steps[] = { 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 };
  4735. constexpr int count = (int) (sizeof (steps) / sizeof (steps[0]));
  4736. int i = 0;
  4737. while (i + 1 < count && steps[i + 1] <= value)
  4738. ++i;
  4739. if (delta < 0 && steps[i] < value) // between two steps: going down lands on the lower one
  4740. ++delta;
  4741. return steps[juce::jlimit (0, count - 1, i + delta)];
  4742. }
  4743. void MainComponent::PatternLengthBox::paint (juce::Graphics& g)
  4744. {
  4745. using namespace theme;
  4746. const auto area = getLocalBounds().toFloat();
  4747. g.setColour (hovered ? colour::bg3 : colour::bg1);
  4748. g.fillRoundedRectangle (area, radius::sm);
  4749. g.setColour (hovered ? colour::borderStrong : colour::border);
  4750. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  4751. auto r = getLocalBounds().reduced (3, 0);
  4752. // round 170e: a length icon instead of the letters "A" / "L" (unreadable); dim = automatic (from the notes)
  4753. icons::draw (g, Icon::span, r.removeFromLeft (13).toFloat().withSizeKeepingCentre (13.0f, 13.0f),
  4754. automatic ? colour::textDisabled : colour::textSecondary);
  4755. g.setFont (font (type::small, true));
  4756. g.setColour (automatic ? colour::textSecondary : colour::textPrimary);
  4757. g.drawText (juce::String (bars), r, juce::Justification::centred, false);
  4758. }
  4759. void MainComponent::PatternLengthBox::mouseDown (const juce::MouseEvent& e)
  4760. {
  4761. dragStartBars = bars;
  4762. if (e.mods.isPopupMenu() && onMenu)
  4763. onMenu();
  4764. }
  4765. void MainComponent::PatternLengthBox::mouseDrag (const juce::MouseEvent& e)
  4766. {
  4767. if (e.mods.isPopupMenu() || onSet == nullptr)
  4768. return;
  4769. // one step of the list per 14 px up (as the rack's insert number box: drag up = more)
  4770. const auto delta = -e.getDistanceFromDragStartY() / 14;
  4771. const auto value = delta == 0 ? dragStartBars : stepBars (dragStartBars, delta);
  4772. if (value != bars || automatic)
  4773. if (delta != 0)
  4774. onSet (value);
  4775. }
  4776. void MainComponent::PatternLengthBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  4777. {
  4778. if (onSet != nullptr && wheel.deltaY != 0.0f)
  4779. onSet (stepBars (bars, wheel.deltaY > 0.0f ? 1 : -1));
  4780. }
  4781. void MainComponent::refreshRackLengthBox()
  4782. {
  4783. const auto& song = engine.getSong();
  4784. if (song.currentPattern < 0 || song.currentPattern >= (int) song.patterns.size())
  4785. return;
  4786. const auto& pattern = song.activePattern();
  4787. const auto bar = song.barTicks();
  4788. const auto bars = (int) juce::jmax<std::int64_t> (1, (pattern.effectiveLength (song.meter()) + bar - 1) / bar);
  4789. const auto automatic = pattern.lengthTicks == 0;
  4790. if (bars != rackLengthBox.bars || automatic != rackLengthBox.automatic)
  4791. {
  4792. rackLengthBox.bars = bars;
  4793. rackLengthBox.automatic = automatic;
  4794. rackLengthBox.setTooltip (automatic ? tr ("Pattern length: {0} (automatic, from the notes)", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) })
  4795. : tr ("Pattern length: {0}", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) }));
  4796. rackLengthBox.repaint();
  4797. }
  4798. }
  4799. void MainComponent::showPatternLengthMenu()
  4800. {
  4801. const auto& song = engine.getSong();
  4802. const auto& pattern = song.activePattern();
  4803. const auto bar = song.barTicks();
  4804. juce::PopupMenu menu;
  4805. menu.addSectionHeader (tr ("Pattern length"));
  4806. menu.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0, [this] { rackLengthBox.onSet (0); });
  4807. for (int bars : { 1, 2, 4, 8, 16, 32 })
  4808. menu.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == bars * bar,
  4809. [this, bars] { rackLengthBox.onSet (bars); });
  4810. menu.addSeparator();
  4811. menu.addItem (tr ("Type value..."), [this] {
  4812. ui::ValueSpec spec;
  4813. spec.name = tr ("Pattern length (bars, 0 = automatic)");
  4814. spec.minimum = 0.0;
  4815. spec.maximum = 999.0;
  4816. spec.interval = 1.0;
  4817. ui::typeValue (rackLengthBox, spec, rackLengthBox.automatic ? 0.0 : (double) rackLengthBox.bars,
  4818. [this] (double v) { rackLengthBox.onSet (juce::roundToInt (v)); });
  4819. });
  4820. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackLengthBox));
  4821. }
  4822. void MainComponent::PatternSelector::paint (juce::Graphics& g)
  4823. {
  4824. using namespace theme;
  4825. auto area = getLocalBounds().toFloat();
  4826. g.setColour (hoveredPart >= 0 ? colour::bg3 : colour::bg1);
  4827. g.fillRoundedRectangle (area, radius::sm);
  4828. g.setColour (hoveredPart >= 0 ? colour::borderStrong : colour::border);
  4829. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  4830. // the pattern's colour as a thin stripe at the left of the name
  4831. if (! colour.isTransparent())
  4832. {
  4833. g.setColour (colour);
  4834. g.fillRect (juce::Rectangle<float> ((float) arrowWidth + 1.0f, 4.0f, 3.0f, (float) getHeight() - 8.0f));
  4835. }
  4836. auto arrow = [&g, this] (int part, bool left) {
  4837. const auto box = juce::Rectangle<float> (left ? 0.0f : (float) (getWidth() - arrowWidth), 0.0f, (float) arrowWidth, (float) getHeight());
  4838. const auto c = box.getCentre();
  4839. juce::Path p;
  4840. if (left)
  4841. p.addTriangle (c.x + 2.5f, c.y - 4.0f, c.x + 2.5f, c.y + 4.0f, c.x - 2.5f, c.y);
  4842. else
  4843. p.addTriangle (c.x - 2.5f, c.y - 4.0f, c.x - 2.5f, c.y + 4.0f, c.x + 2.5f, c.y);
  4844. g.setColour (hoveredPart == part ? colour::textPrimary : colour::textSecondary);
  4845. g.fillPath (p);
  4846. };
  4847. arrow (0, true);
  4848. arrow (2, false);
  4849. g.setColour (colour::textPrimary);
  4850. g.setFont (font (type::small, true));
  4851. const auto name = getLocalBounds().withTrimmedLeft (arrowWidth + 7).withTrimmedRight (arrowWidth + 14);
  4852. g.drawText (text, name, juce::Justification::centredLeft, true);
  4853. icons::draw (g, Icon::chevronDown, juce::Rectangle<float> ((float) (getWidth() - arrowWidth - 14), 0.0f, 12.0f, (float) getHeight()).reduced (1.0f, 4.0f),
  4854. hoveredPart == 1 ? colour::textPrimary : colour::textSecondary);
  4855. g.setColour (colour::border);
  4856. g.fillRect (arrowWidth, 3, 1, getHeight() - 6);
  4857. g.fillRect (getWidth() - arrowWidth - 1, 3, 1, getHeight() - 6);
  4858. }
  4859. void MainComponent::PatternSelector::mouseDown (const juce::MouseEvent& e)
  4860. {
  4861. const auto part = partAt (e.x);
  4862. namePressed = dragging = false;
  4863. appliedSteps = 0;
  4864. if (e.mods.isPopupMenu())
  4865. {
  4866. if (onMenu)
  4867. onMenu();
  4868. }
  4869. else if (part == 1)
  4870. namePressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  4871. else if (onStep)
  4872. onStep (part == 0 ? -1 : 1);
  4873. }
  4874. void MainComponent::PatternSelector::mouseDrag (const juce::MouseEvent& e)
  4875. {
  4876. if (! namePressed)
  4877. return;
  4878. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  4879. if (! dragging)
  4880. return;
  4881. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  4882. if (steps != appliedSteps && onStep)
  4883. onStep (steps - appliedSteps);
  4884. appliedSteps = steps;
  4885. }
  4886. void MainComponent::PatternSelector::mouseUp (const juce::MouseEvent&)
  4887. {
  4888. if (namePressed && ! dragging && onMenu)
  4889. onMenu();
  4890. namePressed = dragging = false;
  4891. }
  4892. void MainComponent::PatternSelector::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  4893. {
  4894. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  4895. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  4896. onStep (n);
  4897. }
  4898. void MainComponent::PatternBox::mouseDown (const juce::MouseEvent& e)
  4899. {
  4900. pressed = dragging = false;
  4901. appliedSteps = 0;
  4902. if (! isEnabled() || e.mods.isPopupMenu())
  4903. return;
  4904. pressed = true; // the list opens on release unless the mouse dragged (FL's pattern selector)
  4905. }
  4906. void MainComponent::PatternBox::mouseDrag (const juce::MouseEvent& e)
  4907. {
  4908. if (! pressed)
  4909. return;
  4910. dragging = dragging || std::abs (e.getDistanceFromDragStartY()) >= patterndrag::threshold;
  4911. if (! dragging)
  4912. return;
  4913. const auto steps = patterndrag::steps ((float) e.getDistanceFromDragStartY());
  4914. if (steps != appliedSteps && onStep)
  4915. onStep (steps - appliedSteps);
  4916. appliedSteps = steps;
  4917. }
  4918. void MainComponent::PatternBox::mouseUp (const juce::MouseEvent&)
  4919. {
  4920. if (pressed && ! dragging)
  4921. showPopup();
  4922. pressed = dragging = false;
  4923. }
  4924. void MainComponent::PatternBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  4925. {
  4926. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  4927. if (wheel.isInertial)
  4928. return;
  4929. if (const auto n = wheelSteps.take (delta); n != 0 && onStep)
  4930. onStep (n);
  4931. }
  4932. juce::PopupMenu MainComponent::playlistTrackExportMenu (bool groups)
  4933. {
  4934. // FL: From song start... / From track start... / Time selection... (the last does nothing without a time selection)
  4935. juce::PopupMenu menu;
  4936. auto add = [&] (const juce::String& text, quickrender::Start start, bool enabled) {
  4937. menu.addItem (text, enabled, false, [this, start, groups] { exportAllPlaylistTracks (engine, projectName, start, groups); });
  4938. };
  4939. add (tr ("From song start..."), quickrender::Start::songStart, true);
  4940. add (tr ("From track start..."), quickrender::Start::clipStart, true);
  4941. add (tr ("Time selection..."), quickrender::Start::timeSelection, engine.getSong().hasLoop());
  4942. return menu;
  4943. }
  4944. juce::PopupMenu MainComponent::makePatternMenu (std::vector<int> picked)
  4945. {
  4946. const auto& song = engine.getSong();
  4947. const auto index = song.currentPattern;
  4948. const auto& pattern = song.patterns[(std::size_t) index];
  4949. auto colours = ui::colourMenu (pattern.colour, [this, index] (std::uint32_t c) {
  4950. if (index < (int) engine.getSong().patterns.size())
  4951. engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; });
  4952. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  4953. juce::PopupMenu lengths;
  4954. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  4955. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  4956. for (int bars : { 1, 2, 4, 8, 16, 32 })
  4957. {
  4958. const auto ticks = (std::int64_t) bars * song.barTicks();
  4959. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  4960. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  4961. }
  4962. juce::PopupMenu menu;
  4963. // a double-click on the title renames the pattern (issue #12)
  4964. ui::addItemHeader (menu, tr ("Pattern"), juce::String::fromUTF8 (pattern.name.c_str()), PlaylistComponent::patternColour (song, index),
  4965. [this, index] { showRenamePattern (index); });
  4966. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  4967. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  4968. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  4969. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  4970. menu.addItem (tr ("First empty pattern (and name it)") + shortcutText ("pattern.firstEmpty"), [this] { runAction ("pattern.firstEmpty"); });
  4971. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  4972. menu.addItem (tr ("Next empty pattern (no naming)") + shortcutText ("pattern.nextEmptyNoName"), [this] { runAction ("pattern.nextEmptyNoName"); });
  4973. menu.addSeparator();
  4974. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  4975. menu.addSubMenu (tr ("Color"), colours);
  4976. menu.addSubMenu (tr ("Length"), lengths);
  4977. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  4978. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  4979. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  4980. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  4981. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  4982. // FL's Patterns › PSPatQuickRenderMenu / PSPatRenderMenu / PSPatRenderReplaceMenu (PSPatQuickRenderMenuClick, tags 1 / 0 / 2;
  4983. // REA round 168e); opened from the picker, every picked pattern is rendered (round 169k)
  4984. if (picked.empty())
  4985. picked = { index };
  4986. menu.addItem (tr ("Quick render as audio clip"), [this, picked] { renderPatternsAsAudioClips (engine, picked, 1); });
  4987. menu.addItem (tr ("Render as audio clip..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 0); });
  4988. menu.addItem (tr ("Render and replace..."), [this, picked] { renderPatternsAsAudioClips (engine, picked, 2); });
  4989. juce::PopupMenu signatures;
  4990. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  4991. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats && song.beatUnit == 4,
  4992. [this, beats] { engine.editSong ([beats] (Song& s) {
  4993. s.beatsPerBar = beats;
  4994. s.beatUnit = 4;
  4995. }); });
  4996. menu.addSubMenu (tr ("Song time signature"), signatures);
  4997. menu.addSeparator();
  4998. menu.addItem (tr ("Delete pattern") + shortcutText ("pattern.delete"), song.patterns.size() > 1, false,
  4999. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  5000. return menu;
  5001. }
  5002. void MainComponent::showPatternMenu()
  5003. {
  5004. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  5005. }
  5006. void MainComponent::refreshModeButton()
  5007. {
  5008. const auto recording = engine.isRecording();
  5009. recordButton.setToggleState (recording, juce::dontSendNotification);
  5010. const auto inputs = engine.getActiveMidiInputs();
  5011. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  5012. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  5013. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  5014. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  5015. recordMenuButton.setOnColour (theme::colour::accentMuted);
  5016. const auto songMode = engine.getSong().mode == PlayMode::song;
  5017. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  5018. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  5019. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  5020. multilinkButton.setToggleState (engine.isMultilinkOn(), juce::dontSendNotification);
  5021. }
  5022. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  5023. {
  5024. // round 190ap: the title says while third-party plugins are off; the last one switched on takes the note away
  5025. if (const auto off = engine.pluginsOff(); off != shownPluginsOff)
  5026. {
  5027. shownPluginsOff = off;
  5028. updateTitle();
  5029. }
  5030. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none && persistent)
  5031. mixerinput::explain (notice);
  5032. // round 165c: hardware inserts measured for another device setup (the device or its buffer size changed, or the project
  5033. // was measured elsewhere): a prompt that pings them on request, nothing pinged by itself (pings make clicks)
  5034. if (auto stale = engine.takeHardwareInsertNotice(); ! stale.empty() && persistent)
  5035. {
  5036. const auto count = (int) stale.size();
  5037. auto options = juce::MessageBoxOptions()
  5038. .withIconType (juce::MessageBoxIconType::InfoIcon)
  5039. .withTitle (tr ("Hardware Insert"))
  5040. .withMessage ((count == 1 ? tr ("The round trip of a hardware insert was measured for another audio setup (the device or its "
  5041. "buffer size changed), so its return is no longer lined up with the rest of the mix.")
  5042. : tr ("The round trip of {0} hardware inserts was measured for another audio setup (the device or its "
  5043. "buffer size changed), so their returns are no longer lined up with the rest of the mix.",
  5044. { juce::String (count) }))
  5045. + "\n\n" + tr ("Ping now? Each one sends a few clicks out to its gear and listens for them on its return."))
  5046. .withButton (tr ("Ping now"))
  5047. .withButton (tr ("Later"));
  5048. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), stale = std::move (stale)] (int result) {
  5049. if (result == 1 && safe != nullptr)
  5050. safe->engine.pingHardwareInserts (stale);
  5051. });
  5052. }
  5053. const auto& song = engine.getSong();
  5054. // FL's Auto select linked modules [DECOMP FUN_00ffe510 -> FUN_011e84e0] (round 187a): selecting one channel selects
  5055. // its mixer track
  5056. if (const auto selected = engine.getSelectedChannel(); selected != lastLinkedChannel)
  5057. {
  5058. lastLinkedChannel = selected;
  5059. if (ChannelRackComponent::autoSelectLinked && selected >= 0 && selected < (int) song.channels.size() && engine.getSelectedChannels().size() == 1)
  5060. if (const auto insert = song.channels[(std::size_t) selected].mixerTrack; insert >= 0 && insert < (int) song.mixer.size()
  5061. && insert != mixer.getStripsForSnapshot().getSelectedTrack())
  5062. mixer.selectTrack (insert);
  5063. }
  5064. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr)
  5065. simpleWorkflow->songChanged(); // (an empty project opens on the New track chooser)
  5066. refreshSongNotes(); // (round 190ch: the Lyrics / Notes panel and Reference match show the project's own state)
  5067. // FL's "Select first channel with notes when the pattern changes" (Settings › General, REA round 167j §5)
  5068. if (song.currentPattern != lastCurrentPattern)
  5069. {
  5070. const auto changedPattern = lastCurrentPattern >= 0;
  5071. lastCurrentPattern = song.currentPattern;
  5072. if (changedPattern && ChannelRackComponent::selectFirstChannelWithNotes)
  5073. if (const auto first = firstChannelWithNotes (song, song.currentPattern); first >= 0 && first != engine.getSelectedChannel())
  5074. engine.setSelectedChannel (first);
  5075. }
  5076. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  5077. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  5078. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  5079. refreshModeButton();
  5080. tempoDisplay.repaint();
  5081. // a project with other filter groups (or none): the rack's filter falls back to "All"
  5082. if (rack.getFilterGroup() >= (int) song.channelGroups.size())
  5083. rack.setFilterGroup (-1);
  5084. if (rackFilterBox.text != rack.filterName())
  5085. {
  5086. rackFilterBox.text = rack.filterName();
  5087. rackFilterBox.repaint();
  5088. }
  5089. if (rackLoopButton.getToggleState() != rack.isLoopingOn()) // (another pattern, undo)
  5090. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  5091. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  5092. fitChannelRack (false);
  5093. refreshKeyPanel(); // (undo, another project; cheap: it repaints only on a change)
  5094. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  5095. refreshToolbar();
  5096. else
  5097. {
  5098. refreshRackPatternSelector(); // a new pattern colour
  5099. refreshRackLengthBox(); // (notes added: the automatic length grows)
  5100. }
  5101. }
  5102. // --- tempo display -------------------------------------------------------------------------------
  5103. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  5104. {
  5105. ui::ValueSpec s;
  5106. s.name = tr ("Tempo");
  5107. s.minimum = minTempo;
  5108. s.maximum = maxTempo;
  5109. s.defaultValue = 130.0;
  5110. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  5111. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  5112. return s;
  5113. }
  5114. void MainComponent::TempoDisplay::setBpm (double bpm)
  5115. {
  5116. bpm = controls::clampTempo (bpm);
  5117. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  5118. engine.editSong ([bpm] (Song& s) { clipops::followTempo (s, bpm); });
  5119. engine.getLink().proposeTempo (bpm); // (round 190gl: the peers follow; also when the project already had this tempo)
  5120. repaint();
  5121. }
  5122. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  5123. {
  5124. return decimalX > 0 && x > decimalX;
  5125. }
  5126. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  5127. {
  5128. using namespace theme;
  5129. const auto area = getLocalBounds().toFloat();
  5130. g.setColour (colour::bg1);
  5131. g.fillRoundedRectangle (area, radius::md);
  5132. if (dragging)
  5133. {
  5134. g.setColour (colour::accent.withAlpha (0.6f));
  5135. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  5136. }
  5137. // (round 190gl: the Link session's tempo while Link is on; to the thousandth shown, so 96.99995 reads 97.000 — the
  5138. // whole number and the decimals used to be cut apart and showed 96.000)
  5139. const auto bpm = linksync::displayTempo (engine.shownTempo());
  5140. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  5141. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  5142. const juce::Font big (monoFont (18.0f)), small (monoFont (11.0f)), caption (font (type::caption - 1.0f));
  5143. const auto wholeWidth = juce::GlyphArrangement::getStringWidth (big, whole);
  5144. const auto fracWidth = juce::GlyphArrangement::getStringWidth (small, "." + fraction);
  5145. const auto unitWidth = juce::GlyphArrangement::getStringWidth (caption, "BPM");
  5146. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  5147. const auto baseline = area.getCentreY() + 5.0f;
  5148. g.setColour (colour::textPrimary);
  5149. g.setFont (big);
  5150. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  5151. x += wholeWidth;
  5152. decimalX = juce::roundToInt (x);
  5153. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  5154. g.setFont (small);
  5155. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  5156. x += fracWidth + 6.0f;
  5157. g.setColour (colour::textDisabled);
  5158. g.setFont (caption);
  5159. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  5160. }
  5161. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  5162. {
  5163. if (e.mods.isPopupMenu())
  5164. {
  5165. showMenu();
  5166. return;
  5167. }
  5168. if (ui::isResetClick (e))
  5169. {
  5170. setBpm (spec().defaultValue);
  5171. return;
  5172. }
  5173. startBpm = engine.shownTempo();
  5174. dragOnDecimals = isOnDecimals (e.x);
  5175. dragging = true;
  5176. repaint();
  5177. }
  5178. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  5179. {
  5180. if (dragging)
  5181. {
  5182. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  5183. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  5184. }
  5185. }
  5186. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  5187. {
  5188. dragging = false;
  5189. repaint();
  5190. }
  5191. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  5192. {
  5193. if (! e.mods.isPopupMenu())
  5194. ui::typeValue (*this, spec(), engine.shownTempo(), [this] (double v) { setBpm (v); });
  5195. }
  5196. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  5197. {
  5198. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  5199. if (delta == 0.0f)
  5200. return;
  5201. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  5202. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  5203. setBpm (engine.shownTempo() + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  5204. }
  5205. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  5206. {
  5207. return ui::valueHint (spec(), engine.shownTempo(),
  5208. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  5209. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  5210. }
  5211. void MainComponent::TempoDisplay::showMenu()
  5212. {
  5213. const auto bpm = engine.getSong().bpm;
  5214. juce::PopupMenu menu;
  5215. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  5216. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  5217. menu.addItem (tr ("Tempo tapper..."), [this] { showTap(); });
  5218. // FL's tempo menu (WheelMenu N80BPM...N160BPM; round 190bt): the fixed tempos 80 to 160 BPM
  5219. // (flat items after the tapper and before "Half", as FL's menu resource orders them)
  5220. for (int t = 80; t <= 160; t += 10)
  5221. menu.addItem (juce::String (t) + " BPM", [this, t] { setBpm ((double) t); });
  5222. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  5223. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  5224. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  5225. menu.addSeparator();
  5226. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  5227. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  5228. }
  5229. void MainComponent::TempoDisplay::showTap()
  5230. {
  5231. openTempoTapper (engine); // FL's tempo menu opens its tempo tapper too
  5232. }
  5233. // --- hint bar ------------------------------------------------------------------------------------
  5234. juce::String MainComponent::idleHint() const
  5235. {
  5236. if (engine.isWaitingForInput())
  5237. return tr ("Recording: waiting for the first note ([Space] cancels)");
  5238. if (engine.isCountingIn())
  5239. return tr ("Recording: count-in...");
  5240. if (engine.isLinkWaiting()) // (round 190gl)
  5241. return tr ("Ableton Link: playback starts with the session's next cycle ([Space] cancels)");
  5242. // FL's text while "Multilink to controllers" is on (round 177b-4); the controls moved show their own hint
  5243. if (engine.isMultilinkOn())
  5244. return tr ("Please tweak the controls you want to link...");
  5245. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.running)
  5246. return tr ("Scanning for plugins in the background: {0}% {1}", { juce::String (juce::roundToInt (scan.progress * 100.0f)), scan.file });
  5247. // round 170e3: one line at 1920 (the typing piano's state shows on its own button)
  5248. return tr ("Point at anything for help [F1] shortcuts [F5]-[F9] windows [Space] play/stop");
  5249. }
  5250. juce::String MainComponent::keyMarkup (const char* actionId) const
  5251. {
  5252. const auto& chords = keyMap.chordsFor (actionId);
  5253. if (chords.empty())
  5254. return {};
  5255. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  5256. const auto text = juce::String (keys::displayString (chords.front()));
  5257. juce::String out;
  5258. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  5259. {
  5260. if (! hintmarkup::isToken (part.toStdString()))
  5261. return "(" + text + ")";
  5262. out << "[" << part << "]";
  5263. }
  5264. return out;
  5265. }
  5266. void MainComponent::setControlHints()
  5267. {
  5268. auto with = [this] (const juce::String& text, const char* actionId) {
  5269. const auto key = keyMarkup (actionId);
  5270. return key.isEmpty() ? text : text + " " + key;
  5271. };
  5272. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  5273. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, Ableton Live .als, FL Studio Mobile .flm, MIDI)"), "file.open"));
  5274. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  5275. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  5276. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  5277. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  5278. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  5279. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  5280. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  5281. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start (or the remembered position; again: the start) "
  5282. "[2xLMB] back to the start and all notes off (panic) [RMB] remember seek time")
  5283. + " " + keyMarkup ("tools.stopSound") + " " + tr ("Stop sound (all notes off)"), // round 170h2
  5284. true);
  5285. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  5286. true);
  5287. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  5288. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  5289. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  5290. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing [RMB] volume and options"), "transport.metronome"), true);
  5291. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  5292. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  5293. ui::setHint (blendButton, tr ("Blend recorded notes: on, a take adds its notes to the pattern (overdub); off, a recorded channel's old notes are replaced"));
  5294. ui::setHint (loopRecordButton, with (tr ("Loop record: on, recording loops (Song mode: the loop region, one take per pass; Pattern mode: the pattern); off, it "
  5295. "plays straight on, through the loop region or past the pattern's end, and keeps everything where it "
  5296. "was played (the pattern grows)"), "record.loop"));
  5297. ui::setHint (stepEditButton, with (tr ("Step edit: with the transport stopped, notes you play go into the current pattern at the position, "
  5298. "a snap step long; release the keys and the position moves on one step (chords: hold them together)"),
  5299. "record.stepEdit"));
  5300. ui::setHint (punchButton, with (tr ("Punch in/out: audio recording keeps only the loop region (playback runs through it; pre- and "
  5301. "post-roll in the recording options)"), "record.punch"));
  5302. ui::setHint (tapTempoButton, with (tr ("Tempo tapper: tap the beat to set the tempo"), "view.tempoTapper"));
  5303. ui::setHint (typingPianoButton, with (tr ("Typing keyboard to piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  5304. "view.typingPiano"));
  5305. ui::setHint (snapToggleButton, tr ("Snap (magnet): [LMB] turns the snap off and back on (as [Backspace]); lit while it snaps. "
  5306. "The Playlist and Piano Roll snap boxes show the same magnet"));
  5307. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  5308. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  5309. true);
  5310. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  5311. "[F4] next empty [F2] rename") + " " + tr ("[LMB] drag up / down: step through the patterns"));
  5312. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  5313. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  5314. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  5315. TR_NOOP ("the instruments and their step sequencer"),
  5316. TR_NOOP ("the notes of the selected channel in the current pattern"),
  5317. TR_NOOP ("inserts, effects and routing"),
  5318. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  5319. for (int i = 0; i < workspace::panelCount; ++i)
  5320. ui::setHint (panelButtons[(std::size_t) i],
  5321. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  5322. panelAction ((Panel) i)));
  5323. setQuickTips();
  5324. }
  5325. std::vector<std::pair<juce::Rectangle<int>, juce::String>> MainComponent::getQuickTipsForSnapshot()
  5326. {
  5327. std::vector<std::pair<juce::Rectangle<int>, juce::String>> tips;
  5328. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  5329. for (auto* child : c.getChildren())
  5330. {
  5331. if (! child->isVisible())
  5332. continue;
  5333. if (const auto tip = ui::quickTipOf (*child); tip.isNotEmpty() && ! child->getBounds().isEmpty())
  5334. tips.emplace_back (getLocalArea (child->getParentComponent(), child->getBounds()), tip);
  5335. visit (*child);
  5336. }
  5337. };
  5338. visit (*this);
  5339. return tips;
  5340. }
  5341. // the small name bubble of every toolbar control (the hint bar keeps the full description)
  5342. void MainComponent::setQuickTips()
  5343. {
  5344. auto tip = [this] (juce::Component& c, const juce::String& name, const char* actionId = nullptr) {
  5345. ui::setQuickTip (c, name, actionId != nullptr ? shortcutText (actionId).trim() : juce::String());
  5346. };
  5347. tip (newButton, tr ("New project"), "file.new");
  5348. tip (openButton, tr ("Open project"), "file.open");
  5349. tip (saveButton, tr ("Save project"), "file.save");
  5350. tip (exportButton, tr ("Export audio"), "file.export");
  5351. tip (undoButton, tr ("Undo"), "edit.undo");
  5352. tip (redoButton, tr ("Redo"), "edit.redo");
  5353. tip (pluginPickerButton, tr ("Plugin picker"), "panel.quickAdd");
  5354. tip (playButton, tr ("Play"), "transport.playStop");
  5355. tip (stopButton, tr ("Stop"));
  5356. tip (recordButton, tr ("Record"), "transport.record");
  5357. tip (recordMenuButton, tr ("Recording options"));
  5358. tip (patternModeButton, tr ("Pattern mode"), "transport.toggleMode");
  5359. tip (songModeButton, tr ("Song mode"), "transport.toggleMode");
  5360. tip (metronomeButton, tr ("Metronome"), "transport.metronome");
  5361. tip (countInButton, tr ("Count-in"), "record.countIn");
  5362. tip (waitInputButton, tr ("Wait for input"), "record.waitForInput");
  5363. tip (blendButton, tr ("Blend recorded notes"), "record.blend");
  5364. tip (loopRecordButton, tr ("Loop record"), "record.loop");
  5365. tip (stepEditButton, tr ("Step edit"), "record.stepEdit");
  5366. tip (multilinkButton, tr ("Multilink to controllers"), "options.multilink"); // (FL's hint: "Ctrl+J Multilink to controllers")
  5367. tip (punchButton, tr ("Punch in/out"), "record.punch");
  5368. tip (tapTempoButton, tr ("Tempo tapper"), "view.tempoTapper");
  5369. tip (typingPianoButton, tr ("Typing keyboard to piano"), "view.typingPiano");
  5370. tip (tempoDisplay, tr ("Tempo (BPM)"));
  5371. tip (timeDisplay, tr ("Song time"));
  5372. tip (songPosition, tr ("Song position"));
  5373. tip (masterVolume, tr ("Master volume"));
  5374. tip (masterPitch, tr ("Master pitch"));
  5375. tip (gridBox, tr ("Snap"));
  5376. tip (snapToggleButton, tr ("Snap on / off"));
  5377. tip (patternBox, tr ("Pattern"));
  5378. tip (newPatternButton, tr ("New pattern"));
  5379. tip (patternMenuButton, tr ("Pattern options"));
  5380. tip (perfMeter, tr ("CPU, memory and polyphony"));
  5381. tip (chordPanel, tr ("Detected chord"));
  5382. tip (output, tr ("Output monitor"));
  5383. tip (swingSlider, tr ("Swing"));
  5384. tip (rackFilterBox, tr ("Channel filter group"));
  5385. tip (rackGraphButton, tr ("Graph editor"));
  5386. tip (rackPianoRollButton, tr ("Piano-roll view"), "rack.pianoRollView");
  5387. tip (rackLoopButton, tr ("Channel looping"));
  5388. tip (rackLoopStarterButton, tr ("Loop Starter"));
  5389. for (int i = 0; i < workspace::panelCount; ++i)
  5390. tip (panelButtons[(std::size_t) i], tr (panelName ((Panel) i)), panelAction ((Panel) i));
  5391. }
  5392. // FL's Step edit (round 170e3): the notes played since the last tick go into the current pattern at the position, a
  5393. // snap step of the Piano Roll long; when every key is up the position moves on a step (core/StepEdit.h). While the
  5394. // transport plays they are left to the recording, as in FL.
  5395. void MainComponent::applyStepEdit()
  5396. {
  5397. auto played = engine.takeStepEditNotes();
  5398. if (played.empty() || engine.getTransport().playing.load())
  5399. return;
  5400. const auto now = engine.getTransport().positionTicks.load();
  5401. // the position moved by anything else (a click on a ruler, Stop): start from there
  5402. if (now != stepSeekTick && now != stepPrevTick)
  5403. {
  5404. const auto& song = engine.getSong();
  5405. const auto at = transportedit::patternPlayhead (song, song.currentPattern, now);
  5406. stepWriter.reset (at >= 0.0 ? (std::int64_t) std::llround (at) : 0);
  5407. stepSeekTick = stepPrevTick = now;
  5408. }
  5409. // the toolbar (main) snap is FL's step-edit step (round 170e5)
  5410. const auto& mainSnap = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  5411. const auto mainTicks = mainSnap.kind == grid::Kind::ticks ? (std::int64_t) mainSnap.ticks
  5412. : mainSnap.kind == grid::Kind::bar ? engine.getSong().barTicks()
  5413. : 0;
  5414. const auto step = stepedit::stepLength (mainTicks, pianoRoll.gridForSnapshot());
  5415. for (const auto& p : played)
  5416. {
  5417. auto moved = false;
  5418. engine.editSong ([&] (Song& s) {
  5419. if (! s.patterns.empty())
  5420. moved = stepWriter.play (p, s.patterns[(std::size_t) juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern)], step);
  5421. }, p.on);
  5422. if (! moved)
  5423. continue;
  5424. const auto& song = engine.getSong();
  5425. const auto target = transportedit::patternSeekTarget (song, song.currentPattern, (double) stepWriter.getPosition(), now);
  5426. if (target >= 0.0)
  5427. {
  5428. stepPrevTick = engine.getTransport().positionTicks.load();
  5429. stepSeekTick = target;
  5430. engine.seek (target);
  5431. }
  5432. }
  5433. }
  5434. bool MainComponent::toolbarFrame (double nowMs)
  5435. {
  5436. const auto moved = output.update (nowMs);
  5437. timeDisplay.update();
  5438. songPosition.update();
  5439. return moved || engine.getTransport().playing.load (std::memory_order_relaxed);
  5440. }
  5441. void MainComponent::refreshChordOptions()
  5442. {
  5443. auto options = chordReadout.getOptions();
  5444. options.sharps = ! notenames::flats();
  5445. for (int pc = 0; pc < 12; ++pc)
  5446. {
  5447. // the chosen note names, with FL's accidentals ("C♯", "B♭", "Sol♯")
  5448. auto name = juce::String (notenames::pitchName (pc));
  5449. if (name.endsWithChar ('#'))
  5450. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266F);
  5451. else if (name.length() > 1 && name.endsWithChar ('b'))
  5452. name = name.dropLastCharacters (1) + juce::String::charToString ((juce::juce_wchar) 0x266D);
  5453. chordNotes[(std::size_t) pc] = name.toStdString();
  5454. }
  5455. options.notes = &chordNotes;
  5456. // Roman (a LYNX choice, FL's item changes nothing): against the Piano Roll's scale, when one is set
  5457. const auto& highlight = engine.getSong().scaleHighlight;
  5458. options.tonic = pianoRoll.scaleTonic() >= 0 ? pianoRoll.scaleTonic() : highlight.scale >= 0 ? highlight.root : -1;
  5459. chordReadout.setOptions (options);
  5460. }
  5461. void MainComponent::showChordText()
  5462. {
  5463. auto text = juce::String::fromUTF8 (chordReadout.text().c_str());
  5464. if (chordReadout.lastWasNovelty())
  5465. text = tr (text);
  5466. chordPanel.setText (text);
  5467. if (chordShowNearHint)
  5468. {
  5469. // as FL: it follows the panel, leaves with "---", and with a display delay stays that long at most (15 s at most)
  5470. const auto chord = chordReadout.text() != chordread::noChord && text.isNotEmpty();
  5471. chordNearHint.setText (text);
  5472. const auto width = juce::roundToInt (juce::GlyphArrangement::getStringWidth (theme::font (theme::type::body, true).withHeight (17.0f), text)) + 8;
  5473. chordNearHint.setBounds (hintBar.getX() + 8, hintBar.getBottom() + 2, width, 24);
  5474. chordNearHint.setVisible (chord);
  5475. if (chord)
  5476. {
  5477. chordNearHint.toFront (false);
  5478. chordNearHintUntil = juce::Time::getMillisecondCounter() + juce::jmin<std::uint32_t> (15000, chordReadout.getDelayMs());
  5479. }
  5480. }
  5481. }
  5482. void MainComponent::updateChordPanel()
  5483. {
  5484. if (! chordPanel.isVisible() && ! chordShowNearHint)
  5485. return;
  5486. const auto now = juce::Time::getMillisecondCounter();
  5487. auto changed = false;
  5488. for (int channel = 0; channel < chordread::channels; ++channel)
  5489. {
  5490. const auto bits = engine.heldInputKeyBits (channel);
  5491. auto& before = chordHeld[(std::size_t) channel];
  5492. if (bits == before)
  5493. continue;
  5494. if (! changed)
  5495. refreshChordOptions();
  5496. changed = true;
  5497. // what ended first: a chord changed between two ticks reads as the new chord, not as both
  5498. for (const auto on : { false, true })
  5499. for (int word = 0; word < 2; ++word)
  5500. {
  5501. auto diff = (on ? bits[(std::size_t) word] & ~before[(std::size_t) word] : before[(std::size_t) word] & ~bits[(std::size_t) word]);
  5502. for (int b = 0; diff != 0; ++b, diff >>= 1)
  5503. if ((diff & 1u) != 0)
  5504. chordReadout.note (channel, word * 64 + b, on, now);
  5505. }
  5506. before = bits;
  5507. }
  5508. if (chordReadout.tick (now))
  5509. changed = true;
  5510. if (changed)
  5511. showChordText();
  5512. if (chordNearHint.isVisible() && chordReadout.getDelayMs() > 0 && (int) (now - chordNearHintUntil) > 0)
  5513. chordNearHint.setVisible (false);
  5514. }
  5515. void MainComponent::showChordPanelMenu()
  5516. {
  5517. juce::PopupMenu menu;
  5518. menu.addSectionHeader (tr ("Chord style"));
  5519. const auto roman = chordReadout.getOptions().roman;
  5520. auto setRoman = [this] (bool on) {
  5521. auto o = chordReadout.getOptions();
  5522. o.roman = on;
  5523. chordReadout.setOptions (o);
  5524. saveUiSettings();
  5525. };
  5526. menu.addItem (tr ("Standard"), true, ! roman, [setRoman] { setRoman (false); });
  5527. menu.addItem (tr ("Roman"), true, roman, [setRoman] { setRoman (true); });
  5528. menu.addSectionHeader (tr ("Display delay for played chords"));
  5529. const auto delay = chordReadout.getDelayMs();
  5530. auto delayItem = [&] (const juce::String& name, std::uint32_t seconds) {
  5531. menu.addItem (name, true, delay == seconds * 1000u, [this, seconds] {
  5532. chordReadout.setDelayMs (seconds * 1000u);
  5533. saveUiSettings();
  5534. });
  5535. };
  5536. delayItem (tr ("None"), 0);
  5537. delayItem (tr ("1 second"), 1);
  5538. delayItem (tr ("3 seconds"), 3);
  5539. delayItem (tr ("5 seconds"), 5);
  5540. delayItem (tr ("Show forever"), chordread::foreverSeconds);
  5541. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&chordPanel));
  5542. }
  5543. namespace
  5544. {
  5545. // "A minor", "C# Dorian": the root and the short scale name (round 184a S11)
  5546. juce::String keyLabel (const projectkey::Key& key)
  5547. {
  5548. return juce::String (projectkey::rootName (key.root)) + " " + tr (juce::String (projectkey::shortScaleName (key.flScale)));
  5549. }
  5550. } // namespace
  5551. void MainComponent::refreshKeyPanel()
  5552. {
  5553. const auto key = projectkey::get (engine.getSong());
  5554. keyPanel.setText (key ? keyLabel (*key) : juce::String());
  5555. }
  5556. void MainComponent::setProjectKey (std::optional<projectkey::Key> key)
  5557. {
  5558. if (projectkey::get (engine.getSong()) == key)
  5559. return;
  5560. engine.editSong ([key] (Song& s) { projectkey::set (s, key); }); // one undo step; no note moves
  5561. refreshKeyPanel();
  5562. pianoRoll.repaint(); // (its scale highlight is this key)
  5563. }
  5564. // The Key menu (round 184a S11, design §3.1): the best guesses from the song's notes, the root, the scale (the common ones,
  5565. // then "More scales"), and None. Every choice writes the one stored key, FL's project scale (.flp 0xF3).
  5566. void MainComponent::showKeyMenu()
  5567. {
  5568. makeKeyMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&keyPanel));
  5569. }
  5570. juce::PopupMenu MainComponent::makeKeyMenu()
  5571. {
  5572. const auto current = projectkey::get (engine.getSong());
  5573. juce::PopupMenu menu;
  5574. menu.addSectionHeader (tr ("Guess from notes"));
  5575. const auto guesses = keyguess::guess (engine.getSong(), 3);
  5576. if (guesses.empty())
  5577. menu.addItem (tr ("No notes to guess from yet"), false, false, [] {});
  5578. for (const auto& g : guesses)
  5579. menu.addItem (keyLabel (g.key) + " (" + tr ("{0} of {1} notes in scale", { juce::String (g.notesInScale), juce::String (g.notes) }) + ")",
  5580. true, current == g.key, [this, key = g.key] { setProjectKey (key); });
  5581. const auto root = current ? current->root : 0;
  5582. const auto scale = current ? current->flScale : projectkey::commonFirst().front(); // (no key yet: Major)
  5583. menu.addSectionHeader (tr ("Root"));
  5584. juce::PopupMenu roots;
  5585. for (int r = 0; r < 12; ++r)
  5586. roots.addItem (juce::String (projectkey::rootName (r)), true, current && current->root == r,
  5587. [this, r, scale] { setProjectKey (projectkey::Key { r, scale }); });
  5588. menu.addSubMenu (current ? juce::String (projectkey::rootName (root)) : tr ("Choose the root"), roots);
  5589. menu.addSectionHeader (tr ("Scale"));
  5590. const auto order = projectkey::commonFirst();
  5591. juce::PopupMenu more;
  5592. for (std::size_t i = 0; i < order.size(); ++i)
  5593. {
  5594. const auto flScale = order[i];
  5595. const auto ticked = current && current->flScale == flScale;
  5596. auto choose = [this, root, flScale] { setProjectKey (projectkey::Key { root, flScale }); };
  5597. if ((int) i < keyguess::commonScales)
  5598. {
  5599. const auto name = tr (juce::String (projectkey::shortScaleName (flScale))); // ("minor" in "A minor"; "Minor" in the list)
  5600. menu.addItem (name.substring (0, 1).toUpperCase() + name.substring (1), true, ticked, choose);
  5601. }
  5602. else // FL's own scale names (its Reference scales folder), as its Piano roll lists them
  5603. more.addItem (juce::String (notetools::flReferenceScales()[(std::size_t) flScale].name), true, ticked, choose);
  5604. }
  5605. menu.addSubMenu (tr ("More scales"), more);
  5606. menu.addSeparator();
  5607. menu.addItem (tr ("None"), true, ! current, [this] { setProjectKey (std::nullopt); });
  5608. return menu;
  5609. }
  5610. void MainComponent::addAudioLoggerMenu (juce::PopupMenu& menu)
  5611. {
  5612. // FL 2026's Tools › Audio logger, item for item (REA_rodada181b.md)
  5613. auto& log = engine.getRollingLog();
  5614. const auto on = log.isEnabled();
  5615. auto title = tr ("Audio logger");
  5616. if (on)
  5617. title << " (" << tr ("memory used: {0}MB", { juce::String (juce::roundToInt ((double) log.bytesInUse() / 1048576.0)) }) << ")";
  5618. menu.addSectionHeader (title);
  5619. menu.addItem (tr ("Enabled"), true, on, [this, on] {
  5620. engine.getRollingLog().setEnabled (! on);
  5621. saveUiSettings();
  5622. });
  5623. juce::PopupMenu settings;
  5624. settings.addSectionHeader (tr ("Maximum length"));
  5625. const auto seconds = log.lengthSeconds();
  5626. auto lengthItem = [&] (const juce::String& name, int minutes) {
  5627. settings.addItem (name, true, seconds == minutes * 60, [this, minutes] {
  5628. engine.getRollingLog().setLengthSeconds (minutes * 60);
  5629. saveUiSettings();
  5630. });
  5631. };
  5632. lengthItem (tr ("1 minute"), 1);
  5633. lengthItem (tr ("2 minutes"), 2);
  5634. lengthItem (tr ("5 minutes"), 5);
  5635. lengthItem (tr ("10 minutes"), 10);
  5636. settings.addSectionHeader (tr ("Recording position"));
  5637. const auto pre = log.getPosition() == RollingAudioLog::Position::preEffects;
  5638. auto positionItem = [&] (const juce::String& name, RollingAudioLog::Position p, bool ticked) {
  5639. settings.addItem (name, true, ticked, [this, p] {
  5640. engine.getRollingLog().setPosition (p);
  5641. saveUiSettings();
  5642. });
  5643. };
  5644. positionItem (tr ("Pre effects"), RollingAudioLog::Position::preEffects, pre);
  5645. positionItem (tr ("Post effects, pre fader"), RollingAudioLog::Position::postEffects, ! pre);
  5646. menu.addSubMenu (tr ("Settings"), settings);
  5647. menu.addItem (tr ("Dump to audio editor"), on, false, [this] { dumpAudioLog(); });
  5648. }
  5649. void MainComponent::dumpAudioLog()
  5650. {
  5651. auto dump = std::make_shared<RollingAudioLog::Dump>();
  5652. if (! engine.getRollingLog().dump (*dump))
  5653. {
  5654. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Audio logger is empty"),
  5655. tr ("The audio logger doesn't contain any audio at the moment"));
  5656. return;
  5657. }
  5658. const auto folder = AudioLogger::defaultFolder();
  5659. folder.createDirectory();
  5660. const auto target = folder.getNonexistentChildFile ("Audiolog-" + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S"), ".wav", false);
  5661. juce::Component::SafePointer<MainComponent> self (this);
  5662. // (a long log takes a moment to write: not on the UI thread)
  5663. juce::Thread::launch ([self, dump, target] {
  5664. auto saved = false;
  5665. {
  5666. juce::WavAudioFormat wav;
  5667. std::unique_ptr<juce::OutputStream> stream (target.createOutputStream().release());
  5668. if (stream != nullptr)
  5669. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (stream.get(), dump->rate, 2, 32, {}, 0) }; writer != nullptr)
  5670. {
  5671. stream.release(); // owned by the writer now
  5672. const float* channels[] = { dump->left.data(), dump->right.data() };
  5673. saved = writer->writeFromFloatArrays (channels, 2, (int) dump->left.size());
  5674. }
  5675. }
  5676. juce::MessageManager::callAsync ([self, target, saved] {
  5677. if (self == nullptr)
  5678. return;
  5679. if (saved)
  5680. openAudioEditor (self->engine, target);
  5681. else
  5682. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio logger"),
  5683. tr ("Could not create a file in {0}", { target.getParentDirectory().getFullPathName() }));
  5684. });
  5685. });
  5686. }
  5687. void MainComponent::readPluginDatabaseAgain()
  5688. {
  5689. // the Plugin database folder as it is on disk now (issue #104): the Browser is built again when it changed; open
  5690. // menus and an open Plugin picker stay as they are (FL, fl190be Q2 / Q4), the next ones read the new state
  5691. auto& host = engine.getPluginHost();
  5692. const auto folders = host.databaseFolders();
  5693. const auto names = host.pluginNames();
  5694. quickpick::markPluginDatabaseChanged();
  5695. quickpick::refreshPluginDatabase (engine, true);
  5696. const auto& now = host.databaseFolders();
  5697. if (now.of != folders.of || now.effects != folders.effects || now.generators != folders.generators || now.hidden != folders.hidden
  5698. || now.top != folders.top || host.pluginNames() != names)
  5699. browser.pluginDatabaseChanged();
  5700. }
  5701. // FL's Settings › Audio › "Auto close" (round 190bx, core/FlSettings.h): the audio device is free for other programs
  5702. // while LYNX is not in front and has no use for it; it opens again when LYNX comes back or needs it.
  5703. void MainComponent::autoCloseDevice()
  5704. {
  5705. if (! persistent)
  5706. return;
  5707. auto& devices = engine.getDeviceManager();
  5708. flsettings::DeviceUse use;
  5709. use.foreground = juce::Process::isForegroundProcess();
  5710. use.busy = engine.getTransport().playing.load() || engine.isRecording() || engine.isLiveRecording() || engine.isCountingIn()
  5711. || engine.isWaitingForInput() || engine.isAudioRecordingArmed() || engine.isBouncing() || engine.isPinging();
  5712. const auto open = devices.getCurrentAudioDevice() != nullptr;
  5713. switch (flsettings::autoCloseAction (flsettings::options().autoCloseDevice.load(), use, open, deviceClosedByAutoClose))
  5714. {
  5715. case flsettings::DeviceAction::close:
  5716. devices.closeAudioDevice();
  5717. deviceClosedByAutoClose = true;
  5718. break;
  5719. case flsettings::DeviceAction::reopen:
  5720. devices.restartLastAudioDevice();
  5721. deviceClosedByAutoClose = false;
  5722. break;
  5723. case flsettings::DeviceAction::none:
  5724. if (open)
  5725. deviceClosedByAutoClose = false; // (opened again by something else: the Settings page, a device change)
  5726. break;
  5727. }
  5728. }
  5729. void MainComponent::timerCallback()
  5730. {
  5731. const auto remoteHistoryError = engine.getRemoteHistoryError();
  5732. const auto showRemote = remoteui::enabled() || remoteui::active() || remoteHistoryError.isNotEmpty();
  5733. remoteControlBar.setText (remoteHistoryError.isNotEmpty() ? remoteHistoryError : tr (remoteui::status()), juce::dontSendNotification);
  5734. if (remoteControlBar.isVisible() != showRemote)
  5735. {
  5736. remoteControlBar.setVisible (showRemote);
  5737. resized();
  5738. }
  5739. const uitrace::Scope trace ("MainComponent timer", false);
  5740. {
  5741. const uitrace::Scope part ("timer: toolbar displays", false);
  5742. masterVolume.update();
  5743. masterPitch.update();
  5744. updateRecordQuantise();
  5745. snapToggleButton.setToggleState (EditorGlobals::get().getGridOption() != grid::noneOption, juce::dontSendNotification);
  5746. }
  5747. if (engine.isStepEdit())
  5748. applyStepEdit();
  5749. if (engine.isModified() != lastModified)
  5750. {
  5751. const uitrace::Scope part ("timer: title", false);
  5752. lastModified = engine.isModified();
  5753. updateTitle();
  5754. }
  5755. // the Browser's "Project folder" follows the project's file (.lynx, or the .flp it was imported from)
  5756. const uitrace::Scope partFolders ("timer: project folder / recording target", false);
  5757. browser.setProjectFile (currentFile != juce::File() ? currentFile : importedFlpFile);
  5758. // and so does where audio is recorded ("<project folder>/Audio/Recorded", FL-like take names)
  5759. engine.setRecordingTarget (recordingFolderFor (currentFile != juce::File() ? currentFile : importedFlpFile),
  5760. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String());
  5761. // a backup copy every few minutes (Settings › General) when there are changes
  5762. // (not in the middle of a recording: FL also postpones the timed backup until the transport is free; round 177d:
  5763. // with "Wait with backups..." on, also while playing and for a few seconds after MIDI input, so writing the plugin
  5764. // states never stutters the sound, up to the longest wait set there)
  5765. if (const auto midi = engine.getMidiPlayed(); midi != backupMidiSeen)
  5766. {
  5767. backupMidiSeen = midi;
  5768. backupMidiMs = juce::Time::getMillisecondCounterHiRes();
  5769. }
  5770. const auto backupDueTicks = 30 * 60 * autosaveMinutes;
  5771. if (autosaveMinutes > 0 && ++autosaveTicks >= backupDueTicks
  5772. && prefs::backupMayRun (engine.isRecording(), engine.getTransport().playing.load(),
  5773. juce::Time::getMillisecondCounterHiRes() - backupMidiMs, backupWaitsForQuiet,
  5774. autosaveTicks * 1000.0 / 30.0, backupLongestWaitMinutes * 60000.0))
  5775. {
  5776. autosaveTicks = 0;
  5777. if (engine.isModified())
  5778. autosave();
  5779. }
  5780. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.finished != scansSeen)
  5781. {
  5782. scansSeen = scan.finished;
  5783. ui::postHint ({ scan.found == 1 ? tr ("Plugin scan finished: 1 new plugin.")
  5784. : tr ("Plugin scan finished: {0} new plugins.", { juce::String (scan.found) }), {}, false, false },
  5785. 6000);
  5786. }
  5787. // round 190gg (B4, Linux / macOS): a hosted plugin's own thread faulted; that thread was parked, and every instance
  5788. // of the plugin is switched off now (counted as crashes: the prompt below)
  5789. switchOffPluginsOfThreadFaults();
  5790. // a hosted plugin crashed inside a call: it was switched off (bypassed / silent) and LYNX kept running
  5791. if (const auto crashes = pluginCrashCount(); crashes != pluginCrashesSeen)
  5792. {
  5793. pluginCrashesSeen = crashes;
  5794. juce::StringArray names, lines;
  5795. for (const auto& c : pluginCrashes())
  5796. {
  5797. const auto name = juce::String::fromUTF8 (c.plugin.c_str());
  5798. names.addIfNotAlreadyThere (name);
  5799. lines.add (juce::Time::getCurrentTime().toISO8601 (true) + " " + name + " " + crashguard::describe (c.code) + " 0x"
  5800. + juce::String::toHexString ((juce::int64) c.code));
  5801. }
  5802. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (lines[lines.size() - 1] + "\n");
  5803. // round 190ao: "Reload" starts it again without reopening the project (only on request: a plugin that crashes
  5804. // again shows this again)
  5805. const auto crashedName = names[names.size() - 1];
  5806. // round 190dt: it crashed on its saved settings (it was left out as the project opened): the same settings would
  5807. // crash it again, so no Reload; the project keeps them for the save
  5808. const auto all = pluginCrashes();
  5809. const auto onLoad = ! all.empty() && all.back().onLoad;
  5810. // round 190gg (B1): Reload, or from now on in a process of its own, where its next crash cannot reach LYNX
  5811. const auto prompt = PluginWindows::crashPrompt (crashedName, onLoad);
  5812. auto options = juce::MessageBoxOptions().withIconType (juce::MessageBoxIconType::WarningIcon).withTitle (prompt.title).withMessage (prompt.message);
  5813. for (const auto& button : prompt.buttons)
  5814. options = options.withButton (button);
  5815. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), crashedName, prompt] (int result) {
  5816. // (JUCE: the first button is 1, the last one 0)
  5817. if (safe == nullptr || result == 0)
  5818. return;
  5819. if (result == 1 && prompt.reload)
  5820. safe->reloadCrashedPlugins (crashedName);
  5821. else if (prompt.separate && result == (prompt.reload ? 2 : 1))
  5822. PluginWindows::alwaysRunSeparately (safe->engine, crashedName);
  5823. });
  5824. }
  5825. // round 176a: a plugin in a separate process (Make bridged, or a 32-bit plugin in the 32-bit bridge) crashed or hung:
  5826. // only that process went; the plugin is muted. Round 174a's prompt, logged like the other plugin crashes.
  5827. if (const auto deaths = pluginSandboxDeathCount(); deaths != sandboxDeathsSeen)
  5828. {
  5829. sandboxDeathsSeen = deaths;
  5830. const auto all = pluginSandboxDeaths();
  5831. if (! all.empty())
  5832. {
  5833. const auto& d = all.back();
  5834. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (
  5835. juce::Time::getCurrentTime().toISO8601 (true) + " " + d.plugin + " " + (d.crashed ? "crashed" : "stopped responding")
  5836. + (d.bits32 ? " (32-bit bridge)" : " (separate process)") + "\n");
  5837. announceSeparateProcessCrash (d.plugin, d.crashed, d.bits32);
  5838. }
  5839. }
  5840. // issue #32 (round 174a): a plugin's own editor window faulted; LYNX closed that editor and kept running
  5841. if (const auto crashes = PluginWindows::editorCrashCount(); crashes != editorCrashesSeen)
  5842. {
  5843. editorCrashesSeen = crashes;
  5844. const auto all = PluginWindows::editorCrashes();
  5845. if (! all.empty())
  5846. announceEditorCrash (all.back().plugin);
  5847. }
  5848. autoCloseDevice();
  5849. // back from another app (the file manager, perhaps: issue #104): the Plugin database folder is read again
  5850. if (const auto foreground = juce::Process::isForegroundProcess(); foreground != wasForeground)
  5851. {
  5852. wasForeground = foreground;
  5853. if (foreground && persistent)
  5854. readPluginDatabaseAgain();
  5855. }
  5856. auto& transport = engine.getTransport();
  5857. if (! heldKeys.empty())
  5858. {
  5859. if (! juce::Process::isForegroundProcess()) // switched to another app with keys down: no key-up will come
  5860. heldKeys.releaseAll();
  5861. else // keys released while another window (a detached panel, a dialog) had the focus
  5862. keyStateChanged (false);
  5863. }
  5864. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  5865. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  5866. // recording states first
  5867. if (! hintsFrozen)
  5868. {
  5869. const uitrace::Scope part ("timer: hint", false);
  5870. ui::Hint hint;
  5871. bool live = false;
  5872. juce::Component* hovered = nullptr;
  5873. if (engine.isLearningMidi())
  5874. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  5875. else if (engine.isWaitingForInput() || engine.isCountingIn() || engine.isLinkWaiting())
  5876. hint.text = idleHint();
  5877. else if (auto posted = ui::postedHint())
  5878. {
  5879. hint = *posted;
  5880. live = true;
  5881. }
  5882. else if (isShowing())
  5883. {
  5884. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  5885. if (auto* under = source.getComponentUnderMouse())
  5886. {
  5887. live = source.isDragging();
  5888. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  5889. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  5890. hovered = under;
  5891. }
  5892. }
  5893. if (hint.isEmpty())
  5894. {
  5895. hint.text = idleHint();
  5896. live = false;
  5897. }
  5898. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  5899. if (hoverValues)
  5900. updateHoverValue (hovered, hint, live);
  5901. if (++tweakTicks >= 3) // 10 times a second
  5902. {
  5903. tweakTicks = 0;
  5904. refreshTweakReadout();
  5905. }
  5906. }
  5907. // Ableton Link (round 190gl): the toggle's peers, the tempo the session plays, and Start Stop Sync from a peer
  5908. // (Play / Stop pressed as the user would)
  5909. linkToggle.update();
  5910. if (const auto linkTempo = engine.getLink().isEnabled() ? engine.getLink().sessionTempo() : 0.0; linkTempo != shownLinkTempo)
  5911. {
  5912. shownLinkTempo = linkTempo;
  5913. tempoDisplay.repaint();
  5914. }
  5915. if (engine.getLink().takeRemoteStart() && ! transport.playing.load() && ! engine.isLinkWaiting() && ! engine.isCountingIn())
  5916. playStop();
  5917. if (engine.getLink().takeRemoteStop() && (transport.playing.load() || engine.isLinkWaiting()))
  5918. playStop();
  5919. const auto playing = transport.playing.load() || engine.isLinkWaiting(); // (lit while the start waits for Link)
  5920. playButton.setToggleState (playing, juce::dontSendNotification);
  5921. updateChordPanel();
  5922. // CPU / memory / polyphony, a few times a second
  5923. if (++meterTicks >= 8 && perfMeter.isVisible() && ! hintsFrozen)
  5924. {
  5925. const uitrace::Scope part ("timer: performance meter", false);
  5926. meterTicks = 0;
  5927. const auto held = (int) heldKeys.size();
  5928. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  5929. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  5930. const auto rt = engine.getRtStats().snapshot();
  5931. juce::StringArray heaviest;
  5932. for (const auto& u : engine.getHeaviestUnits())
  5933. if (heaviest.size() < 3 && u.load >= 0.01)
  5934. heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
  5935. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  5936. perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest,
  5937. device != nullptr ? device->getXRunCount() : -1);
  5938. perfMeter.setDropouts (describeDropouts (engine)); // (round 190gg: how many, when, why)
  5939. // dropouts on Windows shared mode: suggest the interface's ASIO driver (round 160), worked out once per device type
  5940. if (device != nullptr && (rt.overBudget > 0 || rt.lateCalls > 0) && device->getTypeName() != driverTipType)
  5941. {
  5942. driverTipType = device->getTypeName();
  5943. std::vector<std::string> asio;
  5944. for (auto* type : engine.getDeviceManager().getAvailableDeviceTypes())
  5945. if (type->getTypeName() == "ASIO")
  5946. for (const auto& name : type->getDeviceNames())
  5947. asio.push_back (name.toStdString());
  5948. perfMeter.setDriverTip (juce::String::fromUTF8 (prefs::suggestedAsioDriver (driverTipType.toStdString(), asio).c_str()));
  5949. }
  5950. // Linux: the first dropouts without real-time priority explain how to get it, once per installation (round 161)
  5951. if (device != nullptr && ! realtimeHintChecked && (rt.overBudget > 0 || device->getXRunCount() > 0)
  5952. && lynx::rt::status() == lynx::rt::Status::denied)
  5953. {
  5954. realtimeHintChecked = true;
  5955. if (lynx::rt::shouldShowHint (PluginHost::settingsFolder().getChildFile ("realtime-hint-shown")))
  5956. juce::AlertWindow::showMessageBoxAsync (
  5957. juce::MessageBoxIconType::InfoIcon, tr ("Real-time priority"),
  5958. tr ("The sound broke up, and Linux runs LYNX SHARE's audio thread at normal priority. Real-time priority makes dropouts much rarer:\n\n"
  5959. "- install rtkit (package \"rtkit\"; most desktops already have it), or\n"
  5960. "- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\n"
  5961. "then log out and in again. LYNX SHARE never needs root. Options > Audio settings shows the current state."));
  5962. }
  5963. }
  5964. if (++midiInputTicks % 30 == 1) // the open MIDI inputs, once a second
  5965. midiLightInputs = engine.getActiveMidiInputs();
  5966. midiLight.update (engine.getMidiActivity(), midiLightInputs);
  5967. // If a closed dialog left the main window without a focused component, take it back so the PC keyboard
  5968. // keeps playing. Only while the main window itself is the active one: another LYNX window (Audio editor,
  5969. // Quick-add palette, a plugin's editor, a detached panel) keeps its focus (issue #4: grabbing it here, 30
  5970. // times a second, pulled the main window to the front and closed the plugins' drop-down menus).
  5971. if (shouldReclaimKeyboardFocus())
  5972. grabKeyboardFocus();
  5973. }
  5974. bool MainComponent::shouldReclaimKeyboardFocus()
  5975. {
  5976. auto* peer = getPeer();
  5977. return ! hasKeyboardFocus (true) && isShowing() && peer != nullptr && peer->isFocused() && juce::Process::isForegroundProcess()
  5978. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive();
  5979. }
  5980. void MainComponent::updateTitle()
  5981. {
  5982. repaint (titleArea); // the project name in the toolbar
  5983. if (! engine.isModified()) // what is on disk now: the reference for "unused recordings" after a Discard
  5984. savedSamples = safety::referencedSamples (engine.getSong());
  5985. if (auto* window = getTopLevelComponent())
  5986. {
  5987. // a live session's state (round 169j): LIVE, or what it is waiting for
  5988. juce::String liveState;
  5989. if (live != nullptr && live->isActive())
  5990. {
  5991. using S = LiveSessionManager::State;
  5992. const auto st = live->getState();
  5993. liveState = " [" + (st == S::live ? tr ("LIVE") : st == S::reconnecting ? tr ("Reconnecting...") : st == S::waitingHost ? tr ("Waiting for the host...") : tr ("Connecting...")) + "]";
  5994. }
  5995. // round 190ap: opened without third-party plugins, while some are still off
  5996. const auto pluginsOff = engine.pluginsOff() ? " " + tr ("(third-party plugins off)") : juce::String();
  5997. window->setName ((engine.isModified() ? "* " : "")
  5998. + (projectName.isNotEmpty() ? "LYNX SHARE - " + projectName : juce::String ("LYNX SHARE")) + importedSuffix + pluginsOff + liveState);
  5999. }
  6000. }
  6001. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  6002. {
  6003. auto window = std::make_unique<juce::AlertWindow> (tr ("Save changes?"), tr ("The project has unsaved changes."),
  6004. juce::MessageBoxIconType::QuestionIcon);
  6005. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6006. window->addButton (tr ("Discard"), 2);
  6007. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6008. return window;
  6009. }
  6010. void MainComponent::confirmDiscard (std::function<void()> then)
  6011. {
  6012. if (! engine.isModified())
  6013. {
  6014. offerToDeleteUnusedRecordings (true, std::move (then));
  6015. return;
  6016. }
  6017. auto* window = makeConfirmDiscardWindow().release();
  6018. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  6019. if (result == 1)
  6020. save (false, [this, then] { offerToDeleteUnusedRecordings (true, then); }); // (not after a cancelled "save as")
  6021. else if (result == 2)
  6022. offerToDeleteUnusedRecordings (false, then);
  6023. }),
  6024. true);
  6025. }
  6026. juce::File MainComponent::recordingFolderFor (const juce::File& projectFile) const
  6027. {
  6028. // FL records into the project data folder's "Audio\Recorded" (REA round 134); LYNX's data folder is the folder of
  6029. // the project file. Unsaved projects record into the global recordings folder.
  6030. return projectFile == juce::File() ? AudioEngine::defaultRecordingFolder()
  6031. : projectFile.getParentDirectory().getChildFile (safety::recordedSubfolder);
  6032. }
  6033. namespace
  6034. {
  6035. // FL's Keep / Delete question about recorded files nothing uses (FLEngine FUN_00ed1380, REA round 134)
  6036. void askKeepOrDelete (const juce::String& message, const std::vector<juce::File>& files, std::function<void (bool)> done)
  6037. {
  6038. juce::String list;
  6039. for (std::size_t i = 0; i < files.size() && i < 8; ++i)
  6040. list << "\n " << files[i].getFileName();
  6041. if (files.size() > 8)
  6042. list << "\n " << tr ("...and {0} more", { juce::String ((int) files.size() - 8) });
  6043. auto* w = new juce::AlertWindow (tr ("Unused recordings"), message + list, juce::MessageBoxIconType::QuestionIcon);
  6044. w->addButton (tr ("Keep"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6045. w->addButton (tr ("Delete"), 1);
  6046. w->enterModalState (true, juce::ModalCallbackFunction::create ([done] (int result) { done (result == 1); }), true);
  6047. }
  6048. // to the recycle bin when the system has one (FL's "Delete recorded files to recycle bin")
  6049. int removeFiles (const std::vector<juce::File>& files)
  6050. {
  6051. int removed = 0;
  6052. for (const auto& f : files)
  6053. removed += f.existsAsFile() && (f.moveToTrash() || f.deleteFile());
  6054. return removed;
  6055. }
  6056. } // namespace
  6057. void MainComponent::offerToDeleteUnusedRecordings (bool keepsCurrentState, std::function<void()> then)
  6058. {
  6059. // the takes of this session the project on disk will not use: deleted takes, undone recordings, a project closed
  6060. // without saving (FL: "You created ... sample file(s) that are no longer used if the project isn't saved")
  6061. std::vector<std::string> recorded;
  6062. for (const auto& f : engine.getSessionRecordings())
  6063. if (f.existsAsFile())
  6064. recorded.push_back (f.getFullPathName().toStdString());
  6065. const auto referenced = keepsCurrentState ? safety::referencedSamples (engine.getSong()) : savedSamples;
  6066. std::vector<juce::File> unused;
  6067. for (const auto& path : safety::unusedRecordings (recorded, referenced))
  6068. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  6069. if (unused.empty() || ! askUnusedRecordings || ! persistent)
  6070. {
  6071. then();
  6072. return;
  6073. }
  6074. askKeepOrDelete (unused.size() == 1 ? tr ("You recorded 1 audio file that this project will not use.")
  6075. : tr ("You recorded {0} audio files that this project will not use.", { juce::String ((int) unused.size()) }),
  6076. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused, then] (bool remove) {
  6077. if (safe == nullptr)
  6078. return;
  6079. if (remove)
  6080. removeFiles (unused);
  6081. safe->engine.forgetRecordings (unused); // asked once per file
  6082. then();
  6083. });
  6084. }
  6085. void MainComponent::deleteUnusedRecordingsAndSave()
  6086. {
  6087. // FL's Tools › Macros "Delete unused files and save project", for the files this project recorded: every take in
  6088. // its recording folder (and this session's takes elsewhere) that no channel or clip uses
  6089. if (currentFile == juce::File())
  6090. {
  6091. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Delete unused recordings"),
  6092. tr ("Save the project first: its recordings are kept next to it, in {0}.", { juce::String (safety::recordedSubfolder) }));
  6093. return;
  6094. }
  6095. std::vector<std::string> recorded;
  6096. const auto stem = currentFile.getFileNameWithoutExtension() + "_";
  6097. for (const auto& f : recordingFolderFor (currentFile).findChildFiles (juce::File::findFiles, false, "*.wav"))
  6098. if (f.getFileName().startsWithIgnoreCase (stem)) // other projects in the same folder record there too
  6099. recorded.push_back (f.getFullPathName().toStdString());
  6100. for (const auto& f : engine.getSessionRecordings())
  6101. if (f.existsAsFile())
  6102. recorded.push_back (f.getFullPathName().toStdString());
  6103. std::vector<juce::File> unused;
  6104. for (const auto& path : safety::unusedRecordings (recorded, safety::referencedSamples (engine.getSong())))
  6105. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  6106. if (unused.empty())
  6107. {
  6108. save (false);
  6109. ui::postHint ({ tr ("No unused recordings. Project saved."), {}, false, false }, 4000);
  6110. return;
  6111. }
  6112. askKeepOrDelete (tr ("This project has {0} unused recording(s). Deleting them cannot be undone (they go to the recycle bin).",
  6113. { juce::String ((int) unused.size()) }),
  6114. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused] (bool remove) {
  6115. if (safe == nullptr)
  6116. return;
  6117. if (remove)
  6118. {
  6119. const auto n = removeFiles (unused);
  6120. safe->engine.forgetRecordings (unused);
  6121. ui::postHint ({ tr ("Deleted {0} unused recording(s).", { juce::String (n) }), {}, false, false }, 4000);
  6122. }
  6123. safe->save (false);
  6124. });
  6125. }
  6126. namespace
  6127. {
  6128. juce::String projectStem (const juce::String& projectName)
  6129. {
  6130. return projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  6131. }
  6132. // the backup folder's projects with their modification times (for rotation and "revert to last backup")
  6133. std::vector<safety::BackupFile> backupFiles (const juce::File& folder)
  6134. {
  6135. std::vector<safety::BackupFile> files;
  6136. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::extension))
  6137. files.push_back ({ f.getFileNameWithoutExtension().toStdString(), f.getLastModificationTime().toMilliseconds() });
  6138. return files;
  6139. }
  6140. // "Song (autosaved on 2026-10-20 at 14h19)" in `folder`, "_2"... when that minute is taken (FL's naming, REA round 118)
  6141. juce::File newBackupFile (const juce::File& folder, const juce::String& stem, safety::BackupKind kind)
  6142. {
  6143. const auto now = juce::Time::getCurrentTime();
  6144. const auto name = safety::backupName (stem.toStdString(), kind, now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(), now.getMinutes());
  6145. const auto unique = safety::uniqueName (name, [&folder] (const std::string& n) {
  6146. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  6147. });
  6148. return folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ProjectFile::extension);
  6149. }
  6150. } // namespace
  6151. void MainComponent::autosave()
  6152. {
  6153. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  6154. // backup copy of the open project, so work isn't lost if something crashes ("Song (autosaved on 2026-10-20 at
  6155. // 14h19).lynx" in the backup folder, like FL's Backup folder); only the newest few of each project are kept
  6156. // The plugins' settings are read here (they answer on the message thread); writing the file (the big part:
  6157. // every plugin's state, encoded) runs on a thread of its own, so the timed backup no longer freezes the screen
  6158. // (round 151: 180 ms every two minutes on a project with 71 plugins). One at a time.
  6159. if (autosaveRunning->load())
  6160. return;
  6161. const auto folder = autosaveFolder();
  6162. folder.createDirectory();
  6163. const auto stem = projectStem (projectName);
  6164. {
  6165. const uitrace::Scope trace ("autosave: plugin states", false);
  6166. engine.capturePluginStates();
  6167. }
  6168. auto copy = std::make_shared<Song> (engine.getSong());
  6169. const auto file = newBackupFile (folder, stem, safety::BackupKind::autosaved);
  6170. autosaveRunning->store (true);
  6171. juce::Thread::launch ([copy, file, running = autosaveRunning, safe = juce::Component::SafePointer<MainComponent> (this), stem] {
  6172. juce::String error;
  6173. const auto ok = ProjectFile::save (*copy, file, error);
  6174. running->store (false);
  6175. juce::MessageManager::callAsync ([safe, ok, error, stem] {
  6176. if (safe == nullptr)
  6177. return;
  6178. if (! ok)
  6179. ui::postHint ({ tr ("Autosave failed: {0}", { error }), {}, false, false }, 6000);
  6180. else
  6181. {
  6182. safe->rotateBackups (stem);
  6183. safe->lastBackupMs = juce::Time::currentTimeMillis(); // (the Simple workflow's "Backed up ... ago")
  6184. safe->lastBackupProject = safe->engine.getSong().projectId;
  6185. }
  6186. });
  6187. });
  6188. }
  6189. // The Simple workflow's line beside "+ Add track" (round 190t): what a beginner needs to know about their work — LYNX
  6190. // backs it up by itself. Empty when there is nothing to say (a new project with nothing in it yet).
  6191. juce::String MainComponent::simpleSaveStatus() const
  6192. {
  6193. return simpleSaveStatusText (engine.isModified(), currentFile.existsAsFile(),
  6194. lastBackupProject == engine.getSong().projectId ? lastBackupMs : 0, juce::Time::currentTimeMillis());
  6195. }
  6196. juce::String MainComponent::simpleSaveStatusText (bool modified, bool hasFile, juce::int64 backupMs, juce::int64 nowMs)
  6197. {
  6198. if (! modified)
  6199. return hasFile ? tr ("All changes saved") : juce::String();
  6200. if (backupMs <= 0)
  6201. return tr ("Not saved yet");
  6202. const auto minutes = (int) ((nowMs - backupMs) / 60000);
  6203. return minutes < 1 ? tr ("Backed up just now") : tr ("Backed up {0} min ago", { juce::String (minutes) });
  6204. }
  6205. void MainComponent::rotateBackups (const juce::String& stem)
  6206. {
  6207. const auto folder = autosaveFolder();
  6208. // (round 190ap: a backup the user labelled in the Versions panel is one to find again: it is left alone and does
  6209. // not count toward the number kept; without labels the rotation is exactly as before)
  6210. const auto files = safety::versions::withoutLabelled (backupFiles (folder), backupLabels (folder, stem));
  6211. for (const auto& old : safety::backupsToRemove (files, stem.toStdString(), autosaveKeep))
  6212. {
  6213. const auto f = folder.getChildFile (juce::String::fromUTF8 (old.c_str()) + ProjectFile::extension);
  6214. f.setReadOnly (false); // (FL clears the read-only flag before deleting an old backup too)
  6215. f.deleteFile();
  6216. }
  6217. }
  6218. void MainComponent::keepOverwrittenCopy (const juce::File& file)
  6219. {
  6220. // FL moves the file a save replaces into its Backup folder as "Song (overwritten on ... at ...)"; LYNX copies it
  6221. // (the save itself still goes through a temporary file and a rename)
  6222. const auto folder = autosaveFolder();
  6223. if (! file.existsAsFile() || file.isAChildOf (folder))
  6224. return;
  6225. folder.createDirectory();
  6226. const auto stem = projectStem (file.getFileNameWithoutExtension());
  6227. if (file.copyFileTo (newBackupFile (folder, stem, safety::BackupKind::overwritten)))
  6228. rotateBackups (stem);
  6229. }
  6230. void MainComponent::saveNewVersion()
  6231. {
  6232. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  6233. // FL's "Save new version": Song.flp -> Song_2.flp -> Song_3.flp, next to the current file
  6234. if (currentFile == juce::File())
  6235. {
  6236. save (true);
  6237. return;
  6238. }
  6239. const auto folder = currentFile.getParentDirectory();
  6240. const auto name = safety::nextVersionName (currentFile.getFileNameWithoutExtension().toStdString(), [&folder] (const std::string& n) {
  6241. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  6242. });
  6243. const auto file = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  6244. juce::String error;
  6245. engine.capturePluginStates();
  6246. if (! ProjectFile::save (engine.getSong(), file, error))
  6247. {
  6248. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6249. return;
  6250. }
  6251. engine.markSaved();
  6252. rememberRecent (file);
  6253. currentFile = file;
  6254. projectName = file.getFileNameWithoutExtension();
  6255. importedSuffix = {};
  6256. updateTitle();
  6257. ui::postHint ({ tr ("Saved as a new version: {0}", { file.getFileName() }), {}, false, false }, 5000);
  6258. }
  6259. void MainComponent::showVersions()
  6260. {
  6261. if (auto* open = findToolWindow ("versions"))
  6262. {
  6263. open->toFront (true);
  6264. return;
  6265. }
  6266. VersionsActions actions;
  6267. const juce::Component::SafePointer<MainComponent> safe (this);
  6268. actions.context = [safe] {
  6269. VersionsContext c;
  6270. if (safe == nullptr)
  6271. return c;
  6272. c.projectFile = safe->currentFile;
  6273. c.projectStem = projectStem (safe->projectName);
  6274. c.backupFolder = autosaveFolder();
  6275. c.extension = ProjectFile::extension;
  6276. return c;
  6277. };
  6278. actions.openAsCopy = [safe] (const juce::File& file, const juce::String& name) {
  6279. if (safe != nullptr)
  6280. safe->confirmDiscard ([safe, file, name] {
  6281. if (safe != nullptr)
  6282. safe->openProjectAsCopy (file, name);
  6283. });
  6284. };
  6285. actions.saveNewVersion = [safe] {
  6286. if (safe != nullptr)
  6287. safe->saveNewVersion();
  6288. };
  6289. if (auto* window = openToolWindow (makeVersionsPanel (std::move (actions)), tr ("Versions"), "versions"))
  6290. window->setResizable (true, false);
  6291. }
  6292. void MainComponent::openProjectAsCopy (const juce::File& file, const juce::String& name)
  6293. {
  6294. // A version or a backup opened to look at or to carry on from: it becomes an unsaved project under `name`, so
  6295. // neither that file nor the project that was open is written over (Save asks where to put it).
  6296. juce::String error;
  6297. auto song = ProjectFile::load (file, error);
  6298. if (! song)
  6299. {
  6300. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6301. return;
  6302. }
  6303. engine.getPluginHost().applySubstitutes (*song);
  6304. engine.stop();
  6305. engine.rewind();
  6306. engine.setSong (std::move (*song));
  6307. currentFile = juce::File();
  6308. importedFlpFile = juce::File();
  6309. projectName = name;
  6310. importedSuffix = {};
  6311. updateTitle();
  6312. playlist.showSongAfterOpen();
  6313. ui::postHint ({ tr ("Opened as a copy: {0}", { file.getFileName() }), tr ("Save asks where to keep it; the original file is untouched") }, 7000);
  6314. }
  6315. void MainComponent::revertToLastBackup()
  6316. {
  6317. const auto stem = projectStem (projectName);
  6318. const auto name = safety::newestBackup (backupFiles (autosaveFolder()), stem.toStdString());
  6319. if (name.empty())
  6320. {
  6321. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Revert to last backup"),
  6322. tr ("There is no backup of this project yet."));
  6323. return;
  6324. }
  6325. const auto backup = autosaveFolder().getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  6326. const auto when = backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M");
  6327. auto* w = new juce::AlertWindow (tr ("Revert to last backup"),
  6328. tr ("Replace the open project with its backup from {0}?\n{1}\n\nThe project file itself only changes when you save.",
  6329. { when, backup.getFileName() }),
  6330. juce::MessageBoxIconType::QuestionIcon);
  6331. w->addButton (tr ("Revert"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6332. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6333. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup] (int result) {
  6334. if (safe == nullptr || result != 1)
  6335. return;
  6336. juce::String error;
  6337. auto song = ProjectFile::load (backup, error);
  6338. if (! song)
  6339. {
  6340. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6341. return;
  6342. }
  6343. safe->engine.getPluginHost().applySubstitutes (*song);
  6344. safe->engine.stop();
  6345. safe->engine.rewind();
  6346. safe->engine.setSong (std::move (*song));
  6347. safe->engine.markModified(); // Save writes it back to the project's own file
  6348. safe->updateTitle();
  6349. safe->playlist.showSongAfterOpen();
  6350. }),
  6351. true);
  6352. }
  6353. sessionui::Context MainComponent::sessionContext()
  6354. {
  6355. return { engine, currentFile, projectName, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::File& project) {
  6356. if (safe != nullptr)
  6357. safe->openLynxProject (project);
  6358. } };
  6359. }
  6360. liveui::Context MainComponent::liveContext()
  6361. {
  6362. return { engine, *live, currentFile, [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  6363. if (safe != nullptr)
  6364. safe->confirmDiscard (std::move (then));
  6365. } };
  6366. }
  6367. void MainComponent::startLiveFromCommandLine()
  6368. {
  6369. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  6370. auto value = [&] (const char* flag) {
  6371. const auto at = cli.indexOf (flag);
  6372. return at >= 0 && at + 1 < cli.size() ? cli[at + 1].unquoted() : juce::String();
  6373. };
  6374. auto o = LiveSessionManager::Options();
  6375. o.name = value ("--live-name").isNotEmpty() ? value ("--live-name") : liveui::myName();
  6376. o.projectFile = currentFile;
  6377. if (const auto relay = value ("--live-relay"); relay.isNotEmpty())
  6378. o.relay = relay;
  6379. // round 169j: --live-chat "text" (sent once in), --live-follow (follow the host's transport), --live-resume (the
  6380. // host resumes its interrupted session without asking)
  6381. if (const auto text = value ("--live-chat"); text.isNotEmpty())
  6382. juce::Timer::callAfterDelay (9000, [safe = juce::Component::SafePointer<MainComponent> (this), text] {
  6383. if (safe != nullptr)
  6384. {
  6385. safe->live->sendChat (text);
  6386. liveui::showChat (*safe->live);
  6387. }
  6388. });
  6389. if (cli.contains ("--live-follow"))
  6390. juce::Timer::callAfterDelay (8500, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  6391. if (safe != nullptr)
  6392. safe->live->setFollowTransport (true);
  6393. });
  6394. if (cli.contains ("--live-resume"))
  6395. {
  6396. o.projectFile = juce::File();
  6397. o.autoAccept = true;
  6398. if (! live->resumeHost (LiveSessionManager::defaultJournal(), o))
  6399. platform::testModeLog ("live session: nothing to resume");
  6400. return;
  6401. }
  6402. if (cli.contains ("--live-rejoin"))
  6403. {
  6404. // (round 190ah, scripted: a guest goes back into its session without the question)
  6405. if (! live->resumeGuest (LiveSessionManager::defaultGuestJournal(), o))
  6406. platform::testModeLog ("live session: nothing to go back to");
  6407. return;
  6408. }
  6409. if (! cli.contains ("--live-host") && ! cli.contains ("--live-join"))
  6410. {
  6411. if (! platform::testMode())
  6412. liveui::offerResume (liveContext());
  6413. return;
  6414. }
  6415. if (const auto codeFile = value ("--live-host"); codeFile.isNotEmpty())
  6416. {
  6417. o.autoAccept = true; // (scripted: nobody to click "Let them in")
  6418. live->start (o);
  6419. auto poll = std::make_shared<std::function<void (int)>>();
  6420. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), codeFile, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  6421. if (safe == nullptr)
  6422. return;
  6423. if (safe->live->getState() == LiveSessionManager::State::live)
  6424. return (void) juce::File (codeFile).replaceWithText (safe->live->getInviteCode());
  6425. if (safe->live->isActive() && left > 0)
  6426. juce::Timer::callAfterDelay (200, [poll = weak.lock(), left] {
  6427. if (poll != nullptr)
  6428. (*poll) (left - 1);
  6429. });
  6430. else
  6431. juce::File (codeFile).replaceWithText ("ERROR " + safe->live->getStatus());
  6432. };
  6433. (*poll) (150);
  6434. // round 190ai: --live-share file.vst3 — once live, the host shares that plugin and shows its list
  6435. if (const auto pluginFile = value ("--live-share"); pluginFile.isNotEmpty())
  6436. juce::Timer::callAfterDelay (6000, [safe = juce::Component::SafePointer<MainComponent> (this), pluginFile] {
  6437. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  6438. return;
  6439. auto& plugins = safe->engine.getPluginHost();
  6440. plugins.addPluginFile (juce::File (pluginFile));
  6441. juce::String why = "not found";
  6442. bool ok = false;
  6443. for (const auto& type : plugins.getKnownPlugins().getTypes())
  6444. if (! ok && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginFile).getFileName())
  6445. ok = safe->live->sharePlugin (type.createIdentifierString().toStdString(), true, &why);
  6446. platform::testModeLog ("live session: --live-share " + pluginFile + (ok ? " shared" : " NOT shared: " + why));
  6447. liveui::showSharePlugins (*safe->live, safe->engine);
  6448. });
  6449. }
  6450. else if (auto code = value ("--live-join"); code.isNotEmpty())
  6451. {
  6452. if (code.startsWith ("@"))
  6453. code = juce::File (code.substring (1)).loadFileAsString().trim();
  6454. live->join (code, o);
  6455. // round 190ai: --live-use — when the host shares a plugin, a channel of one's own with it, a riff, and its
  6456. // parameter editor (the GUI check of remote plugins)
  6457. if (cli.contains ("--live-use"))
  6458. {
  6459. auto poll = std::make_shared<std::function<void (int)>>();
  6460. *poll = [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name, weak = std::weak_ptr<std::function<void (int)>> (poll)] (int left) {
  6461. if (safe == nullptr)
  6462. return;
  6463. if (! safe->live->mayUseSharedPlugins())
  6464. {
  6465. if (left > 0)
  6466. juce::Timer::callAfterDelay (500, [poll = weak.lock(), left] {
  6467. if (poll != nullptr)
  6468. (*poll) (left - 1);
  6469. });
  6470. return;
  6471. }
  6472. std::uint64_t uid = 0;
  6473. const auto channelName = (name + " remote").toStdString();
  6474. safe->engine.editSong ([&] (Song& s) {
  6475. ChannelDef c;
  6476. c.name = channelName;
  6477. c.instrument = InstrumentKind::plugin;
  6478. c.plugin = safe->live->sharedPluginRef (safe->live->sharedPlugins().front());
  6479. const auto* me = s.session.find (s.session.me);
  6480. c.mixerTrack = me != nullptr ? me->insertFirst : 0;
  6481. s.channels.push_back (c);
  6482. Pattern p;
  6483. p.name = channelName + " riff";
  6484. for (int n = 0; n < 4; ++n)
  6485. p.notes.push_back ({ (std::int64_t) n * ppq, ppq / 2, (int) s.channels.size() - 1, 57 + 2 * n, 0.9f });
  6486. s.patterns.push_back (p);
  6487. });
  6488. for (const auto& c : safe->engine.getSong().channels)
  6489. if (c.name == channelName)
  6490. uid = c.uid;
  6491. platform::testModeLog ("live session: --live-use channel " + juce::String (channelName) + " uid " + juce::String ((juce::int64) uid));
  6492. liveui::showHostedEditor ({ { live::Kind::channel, uid, 0 }, -1 });
  6493. };
  6494. (*poll) (120);
  6495. }
  6496. // --live-edit: once in, add a channel of one's own (the GUI check sees it arrive on the host)
  6497. if (cli.contains ("--live-edit"))
  6498. juce::Timer::callAfterDelay (8000, [safe = juce::Component::SafePointer<MainComponent> (this), name = o.name] {
  6499. if (safe == nullptr || safe->live->getState() != LiveSessionManager::State::live)
  6500. return;
  6501. safe->engine.editSong ([&] (Song& s) {
  6502. ChannelDef c;
  6503. c.name = (name + " synth").toStdString();
  6504. c.instrument = InstrumentKind::synth;
  6505. s.channels.push_back (c);
  6506. });
  6507. });
  6508. }
  6509. }
  6510. void MainComponent::exportPackage()
  6511. {
  6512. // FL's zipped loop package: the project and every sample it uses in one .zip
  6513. const auto stem = projectStem (projectName);
  6514. const auto start = (currentFile != juce::File() ? currentFile.getParentDirectory()
  6515. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  6516. .getChildFile (stem + ".zip");
  6517. fileChooser = lynx::ui::makeFileChooser (tr ("Export project with samples"), start, "*.zip");
  6518. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  6519. [safe = juce::Component::SafePointer<MainComponent> (this), stem] (const juce::FileChooser& chooser) {
  6520. auto zip = chooser.getResult();
  6521. if (safe == nullptr || zip == juce::File())
  6522. return;
  6523. zip = zip.withFileExtension (".zip");
  6524. safe->engine.capturePluginStates();
  6525. ProjectPackage::Result result;
  6526. juce::String error;
  6527. if (! ProjectPackage::exportZip (safe->engine.getSong(), stem, zip, result, error))
  6528. {
  6529. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6530. return;
  6531. }
  6532. auto text = tr ("{0} saved with {1} samples.", { zip.getFileName(), juce::String (result.files) });
  6533. if (! result.missing.isEmpty())
  6534. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  6535. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Export project with samples"), text);
  6536. });
  6537. }
  6538. void MainComponent::collectSamples()
  6539. {
  6540. // FL's "Export project data files": copy the samples the project uses into one folder (and use the copies)
  6541. fileChooser = lynx::ui::makeFileChooser (tr ("Copy the project's samples to..."),
  6542. currentFile != juce::File() ? currentFile.getParentDirectory()
  6543. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  6544. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  6545. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  6546. const auto folder = chooser.getResult();
  6547. if (safe == nullptr || folder == juce::File())
  6548. return;
  6549. std::map<std::string, std::string> relink;
  6550. ProjectPackage::Result result;
  6551. juce::String error;
  6552. if (! ProjectPackage::collectSamples (safe->engine.getSong(), folder, relink, result, error))
  6553. {
  6554. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not copy"), error);
  6555. return;
  6556. }
  6557. safe->engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  6558. auto text = tr ("{0} samples copied to {1}. The project now uses the copies.", { juce::String (result.files), folder.getFullPathName() });
  6559. if (! result.missing.isEmpty())
  6560. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  6561. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Collect project samples"), text);
  6562. });
  6563. }
  6564. void MainComponent::saveToNewProjectFolder()
  6565. {
  6566. // FL's "Save to new project folder...": <chosen name>/<name>.lynx, so the project gets its own data folder (its
  6567. // recordings go to <name>/Audio/Recorded). This session's takes still in the global recordings folder move along
  6568. // (copied there, the project uses the copies; the originals are then offered for deletion as unused).
  6569. const auto start = currentFile != juce::File() ? currentFile.getParentDirectory()
  6570. : lynx::platform::documentsFolder().getChildFile ("LYNX/Projects");
  6571. start.createDirectory();
  6572. fileChooser = lynx::ui::makeFileChooser (tr ("Save to new project folder"),
  6573. start.getChildFile (projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled")),
  6574. juce::String ("*") + ProjectFile::extension);
  6575. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  6576. const auto chosen = chooser.getResult();
  6577. if (safe == nullptr || chosen == juce::File())
  6578. return;
  6579. const auto name = chosen.getFileNameWithoutExtension();
  6580. auto folder = chosen.getParentDirectory().getChildFile (name);
  6581. if (folder.exists() && ! folder.findChildFiles (juce::File::findFilesAndDirectories, false).isEmpty())
  6582. folder = folder.getNonexistentSibling (false);
  6583. if (! folder.createDirectory())
  6584. {
  6585. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  6586. tr ("Could not create the folder {0}", { folder.getFullPathName() }));
  6587. return;
  6588. }
  6589. auto& self = *safe;
  6590. const auto recorded = folder.getChildFile (safety::recordedSubfolder);
  6591. std::map<std::string, std::string> relink;
  6592. const auto used = safety::referencedSamples (self.engine.getSong());
  6593. for (const auto& take : self.engine.getSessionRecordings())
  6594. if (take.existsAsFile() && take.isAChildOf (AudioEngine::defaultRecordingFolder())
  6595. && std::any_of (used.begin(), used.end(), [&take] (const std::string& p) { return safety::samePath (p, take.getFullPathName().toStdString()); }))
  6596. {
  6597. recorded.createDirectory();
  6598. const auto copy = recorded.getNonexistentChildFile (take.getFileNameWithoutExtension(), take.getFileExtension(), false);
  6599. if (take.copyFileTo (copy))
  6600. relink[take.getFullPathName().toStdString()] = copy.getFullPathName().toStdString();
  6601. }
  6602. if (! relink.empty())
  6603. self.engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  6604. const auto file = folder.getChildFile (name + ProjectFile::extension);
  6605. juce::String error;
  6606. self.engine.capturePluginStates();
  6607. if (! ProjectFile::save (self.engine.getSong(), file, error))
  6608. {
  6609. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6610. return;
  6611. }
  6612. self.engine.markSaved();
  6613. self.rememberRecent (file);
  6614. self.currentFile = file;
  6615. self.projectName = name;
  6616. self.importedSuffix = {};
  6617. self.updateTitle();
  6618. ui::postHint ({ tr ("Saved in its own folder: {0}", { folder.getFullPathName() }), {}, false, false }, 5000);
  6619. });
  6620. }
  6621. void MainComponent::startSession()
  6622. {
  6623. // Like FL's backup on crash: a marker exists while LYNX runs; finding one at start means the last session
  6624. // ended without closing (crash, power loss), so the newest backup written during it is offered.
  6625. sessionLock = std::make_unique<juce::InterProcessLock> ("LYNX-ui-session");
  6626. if (! sessionLock->enter (0))
  6627. {
  6628. sessionLock.reset(); // another LYNX window is running: it owns the marker
  6629. return;
  6630. }
  6631. sessionMarker = lynx::platform::settingsFile ("session-running.txt");
  6632. if (sessionMarker.existsAsFile())
  6633. {
  6634. const auto previousStart = juce::Time (sessionMarker.loadFileAsString().trim().getLargeIntValue());
  6635. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this), previousStart] {
  6636. if (safe != nullptr)
  6637. safe->checkPreviousSession (previousStart);
  6638. });
  6639. }
  6640. sessionMarker.getParentDirectory().createDirectory();
  6641. sessionMarker.replaceWithText (juce::String (juce::Time::getCurrentTime().toMilliseconds()));
  6642. // takes that were recording when LYNX stopped (crash, power loss, closed while recording): after the backup offer
  6643. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  6644. if (safe != nullptr)
  6645. safe->checkInterruptedTakes();
  6646. });
  6647. }
  6648. void MainComponent::checkInterruptedTakes()
  6649. {
  6650. if (juce::Component::getCurrentlyModalComponent() != nullptr) // a dialog is open (the backup offer): ask later
  6651. {
  6652. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  6653. if (safe != nullptr)
  6654. safe->checkInterruptedTakes();
  6655. });
  6656. return;
  6657. }
  6658. std::vector<juce::File> folders { engine.getRecordingFolder() };
  6659. const auto takes = engine.recoverInterruptedTakes (folders);
  6660. if (takes.empty())
  6661. return;
  6662. juce::StringArray names;
  6663. for (const auto& j : takes)
  6664. names.add (juce::File (juce::String::fromUTF8 (j.wav.c_str())).getFileName());
  6665. const auto folder = juce::File (juce::String::fromUTF8 (takes.front().wav.c_str())).getParentDirectory();
  6666. auto* w = new juce::AlertWindow (tr ("Recordings recovered"),
  6667. tr ("LYNX SHARE was recording when it stopped. These takes were saved and repaired:\n{0}\n\nPut them on the Playlist "
  6668. "where they were recorded?", { names.joinIntoString ("\n") }),
  6669. juce::MessageBoxIconType::InfoIcon);
  6670. w->addButton (tr ("Put them on the Playlist"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6671. w->addButton (tr ("Show the folder"), 2);
  6672. w->addButton (tr ("Keep the files only"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6673. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), takes, folder] (int result) {
  6674. if (safe == nullptr)
  6675. return;
  6676. if (result == 1)
  6677. {
  6678. const auto placed = safe->engine.placeRecoveredTakes (takes);
  6679. ui::postHint ({ tr ("{0} recovered take(s) placed on the Playlist", { juce::String (placed) }), {}, false, false }, 5000);
  6680. }
  6681. else
  6682. {
  6683. if (result == 2)
  6684. folder.startAsProcess();
  6685. safe->engine.forgetInterruptedTakes (takes);
  6686. }
  6687. }),
  6688. true);
  6689. }
  6690. void MainComponent::checkPreviousSession (juce::Time sessionStart)
  6691. {
  6692. if (juce::Component::getCurrentlyModalComponent() != nullptr) // the setup wizard or another dialog: ask later
  6693. {
  6694. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this), sessionStart] {
  6695. if (safe != nullptr)
  6696. safe->checkPreviousSession (sessionStart);
  6697. });
  6698. return;
  6699. }
  6700. const auto folder = autosaveFolder();
  6701. const auto name = safety::crashRecoveryCandidate (backupFiles (folder), sessionStart.toMilliseconds());
  6702. if (name.empty())
  6703. return; // nothing was saved in that session
  6704. const auto backup = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  6705. auto* w = new juce::AlertWindow (tr ("LYNX SHARE did not close properly"),
  6706. tr ("The last session ended unexpectedly. Open the newest backup it saved?\n{0} ({1})",
  6707. { backup.getFileName(), backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M") }),
  6708. juce::MessageBoxIconType::WarningIcon);
  6709. w->addButton (tr ("Open backup"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6710. w->addButton (tr ("Open backup folder"), 2);
  6711. w->addButton (tr ("Ignore"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6712. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup, folder] (int result) {
  6713. if (safe == nullptr)
  6714. return;
  6715. if (result == 1)
  6716. safe->confirmDiscard ([safe, backup] {
  6717. if (safe != nullptr)
  6718. safe->openLynxProject (backup);
  6719. });
  6720. else if (result == 2)
  6721. folder.startAsProcess();
  6722. }),
  6723. true);
  6724. }
  6725. void MainComponent::newProject (bool askAlways)
  6726. {
  6727. confirmDiscard ([this, askAlways] {
  6728. if (! askAlways && ! newProjectDialogEnabled())
  6729. {
  6730. // FL's File › New: a new project from the default template (issue #123)
  6731. bool missing = false;
  6732. auto song = makeDefaultTemplateProject (&missing);
  6733. startNewProject (std::move (song), {});
  6734. if (missing)
  6735. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  6736. return;
  6737. }
  6738. showNewProjectDialog ([safe = juce::Component::SafePointer<MainComponent> (this)] (Song song, juce::File file) {
  6739. if (safe != nullptr)
  6740. safe->startNewProject (std::move (song), file);
  6741. });
  6742. });
  6743. }
  6744. void MainComponent::openStartupProject()
  6745. {
  6746. // (only over the untouched start-up song: a file, a resumed session or an edit made meanwhile stays)
  6747. if (currentFile != juce::File() || projectName.isNotEmpty() || engine.isModified())
  6748. return;
  6749. switch (startupProject())
  6750. {
  6751. case StartupProject::lastProject:
  6752. // FL's "Last used project": the project itself (saving goes to it), when it is still there
  6753. if (const auto last = recent.getFile (0); last.existsAsFile())
  6754. {
  6755. openFile (last);
  6756. return;
  6757. }
  6758. break; // (none, or gone: the default template, as FL's default)
  6759. case StartupProject::emptyProject:
  6760. if (const auto empty = builtInTemplateIndex ("Empty"); empty >= 0)
  6761. startNewProject (makeNewProject (empty), {});
  6762. return;
  6763. case StartupProject::defaultTemplate:
  6764. break;
  6765. }
  6766. if (defaultTemplate().isLynxDefault())
  6767. return; // (the start-up song is LYNX's default already)
  6768. bool missing = false;
  6769. auto song = makeDefaultTemplateProject (&missing);
  6770. if (missing)
  6771. {
  6772. ui::postHint ({ tr ("The default template was not found; LYNX SHARE's default project opened instead") }, 6000);
  6773. return;
  6774. }
  6775. startNewProject (std::move (song), {});
  6776. }
  6777. void MainComponent::startNewProject (Song song, const juce::File& file)
  6778. {
  6779. forgetSeekMark();
  6780. engine.stop();
  6781. engine.rewind();
  6782. engine.setSong (std::move (song));
  6783. engine.markCreatedNow(); // Project info › created (a template's own date is kept, as FL does)
  6784. currentFile = juce::File();
  6785. projectName = {};
  6786. importedSuffix = {};
  6787. if (file != juce::File())
  6788. {
  6789. juce::String error;
  6790. file.getParentDirectory().createDirectory();
  6791. if (ProjectFile::save (engine.getSong(), file, error))
  6792. {
  6793. engine.markSaved();
  6794. rememberRecent (file);
  6795. currentFile = file;
  6796. projectName = file.getFileNameWithoutExtension();
  6797. }
  6798. else
  6799. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6800. }
  6801. updateTitle();
  6802. }
  6803. // The user's choice after a plugin's editor crashed (issue #32): save under a new name now, and/or run that plugin in a
  6804. // separate process from now on (like Processing › "Always run … in a separate process": persisted, applied at once)
  6805. void MainComponent::announceEditorCrash (const juce::String& plugin)
  6806. {
  6807. const auto offerSeparate = ! pluginSandboxEnabled() && ! pluginAlwaysSeparate (plugin) && plugin != "?";
  6808. auto options = juce::MessageBoxOptions()
  6809. .withIconType (juce::MessageBoxIconType::WarningIcon)
  6810. .withTitle (tr ("Plugin crashed"))
  6811. .withMessage (tr ("{0} crashed. Save your project now (as a new file is safest).", { plugin }) + "\n\n"
  6812. + tr ("Its window was closed so that LYNX SHARE could keep running. The plugin may not work "
  6813. "properly until the project is opened again."))
  6814. .withButton (tr ("Save as..."));
  6815. if (offerSeparate)
  6816. options = options.withButton (tr ("Always run {0} in a separate process", { plugin }));
  6817. options = options.withButton (tr ("Close"));
  6818. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin, offerSeparate] (int result) {
  6819. if (safe == nullptr)
  6820. return;
  6821. if (result == 1)
  6822. safe->save (true);
  6823. else if (result == 2 && offerSeparate)
  6824. PluginWindows::alwaysRunSeparately (safe->engine, plugin); // (round 190gg: the same as the crash prompt's)
  6825. });
  6826. }
  6827. // Round 190ao: "Reload" of a crash prompt: the plugins of that name that are down (the prompt only knows the name the
  6828. // plugin reports; when the project knows it under another name, every plugin that is down)
  6829. void MainComponent::reloadCrashedPlugins (const juce::String& plugin)
  6830. {
  6831. auto which = engine.downHostedPlugins (plugin.toStdString());
  6832. if (which.empty())
  6833. which = engine.downHostedPlugins();
  6834. if (! which.empty())
  6835. PluginWindows::reload (engine, which);
  6836. }
  6837. // Round 176a: round 174a's "Plugin crashed" prompt for a plugin whose separate process died. LYNX itself is unharmed
  6838. // (the plugin ran in its own process), so it offers the save and says how to get the plugin back.
  6839. void MainComponent::announceSeparateProcessCrash (const juce::String& plugin, bool crashed, bool bits32)
  6840. {
  6841. const auto name = plugin.isNotEmpty() ? plugin : tr ("A plugin");
  6842. const auto where = bits32 ? tr ("{0} crashed in the 32-bit bridge.", { name }) : tr ("{0} crashed in its separate process.", { name });
  6843. auto options = juce::MessageBoxOptions()
  6844. .withIconType (juce::MessageBoxIconType::WarningIcon)
  6845. .withTitle (tr ("Plugin crashed"))
  6846. .withMessage ((crashed ? where : tr ("{0} stopped responding (separate process).", { name })) + "\n\n"
  6847. + tr ("Only its process was affected: LYNX SHARE and your project kept running, and the plugin "
  6848. "was muted. Save your project.")
  6849. + " " + tr ("Reload starts it again with the settings from the last save or backup."))
  6850. .withButton (tr ("Reload")) // (round 190ao: without reopening the project; only on request)
  6851. .withButton (tr ("Save as..."))
  6852. .withButton (tr ("Close"));
  6853. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), plugin] (int result) {
  6854. if (safe == nullptr)
  6855. return;
  6856. if (result == 1)
  6857. safe->reloadCrashedPlugins (plugin);
  6858. else if (result == 2)
  6859. safe->save (true);
  6860. });
  6861. }
  6862. void MainComponent::saveAsTemplate()
  6863. {
  6864. auto* w = new juce::AlertWindow (tr ("Save as template"), tr ("The template appears in File › New project... (saved in {0})", { userTemplatesFolder().getFullPathName() }),
  6865. juce::MessageBoxIconType::NoIcon);
  6866. w->addTextEditor ("name", projectName.isNotEmpty() ? projectName : tr ("My template"));
  6867. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  6868. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  6869. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  6870. if (result != 1 || safe == nullptr)
  6871. return;
  6872. safe->engine.capturePluginStates();
  6873. juce::String error;
  6874. if (! saveUserTemplate (safe->engine.getSong(), w->getTextEditorContents ("name"), error))
  6875. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  6876. }), true);
  6877. }
  6878. void MainComponent::chooseFileToOpen()
  6879. {
  6880. confirmDiscard ([this] { chooseFileToOpenNow(); });
  6881. }
  6882. void MainComponent::chooseFileToOpenNow()
  6883. {
  6884. fileChooser = lynx::ui::makeFileChooser (tr ("Open project"), currentFile.getParentDirectory(),
  6885. juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.als;*.flm;*.zip;*.lynxpack;*.mid;*.midi");
  6886. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  6887. [this] (const juce::FileChooser& chooser) {
  6888. if (chooser.getResult().existsAsFile())
  6889. openFile (chooser.getResult());
  6890. });
  6891. }
  6892. void MainComponent::openFileRequest (const juce::File& file)
  6893. {
  6894. const juce::Component::SafePointer<MainComponent> safe (this);
  6895. if (projectLoadRunning())
  6896. {
  6897. juce::Timer::callAfterDelay (500, [safe, file] {
  6898. if (safe != nullptr)
  6899. safe->openFileRequest (file);
  6900. });
  6901. return;
  6902. }
  6903. confirmDiscard ([safe, file] {
  6904. if (safe != nullptr)
  6905. safe->openFile (file);
  6906. });
  6907. }
  6908. void MainComponent::openFile (const juce::File& file)
  6909. {
  6910. forgetSeekMark(); // (another project: FL's mark and a pause don't carry over)
  6911. juce::String error;
  6912. crashguard::note (("opening project " + file.getFileName()).toStdString()); // session breadcrumb (round 111)
  6913. if (file.hasFileExtension ("zip"))
  6914. {
  6915. // a project package (File › Export project with samples, or FL's zipped loop package): extracted into a
  6916. // folder of its own, then the project inside is opened (its samples are found next to it)
  6917. const auto project = ProjectPackage::extractZip (file, ProjectPackage::defaultExtractRoot(), error);
  6918. if (project == juce::File())
  6919. {
  6920. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6921. return;
  6922. }
  6923. openFile (project);
  6924. return;
  6925. }
  6926. if (file.hasFileExtension (sessionpack::extension))
  6927. {
  6928. // Online Sessions (round 168a): a project a friend sent (opened after a summary) or a part sent back (merged)
  6929. sessionui::openPackage (sessionContext(), file);
  6930. return;
  6931. }
  6932. if (file.hasFileExtension ("mid;midi"))
  6933. {
  6934. auto song = MidiFileIo::loadSong (file, error);
  6935. if (! song)
  6936. {
  6937. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6938. return;
  6939. }
  6940. engine.stop();
  6941. engine.rewind();
  6942. engine.setSong (std::move (*song));
  6943. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  6944. projectName = file.getFileNameWithoutExtension();
  6945. rememberRecent (file);
  6946. importedSuffix = " " + tr ("(imported from MIDI)");
  6947. updateTitle();
  6948. return;
  6949. }
  6950. // (a Live set takes the .flp import's path, round 175a; an FL Studio Mobile project too, round 182c)
  6951. if (file.hasFileExtension ("flp;als;flm;songtmpl"))
  6952. {
  6953. if (! persistent) // (command-line modes open synchronously, without scanning)
  6954. {
  6955. importFlp (file);
  6956. return;
  6957. }
  6958. // behind a progress panel (round 112): the project's unknown plugins get a targeted scan of just their files,
  6959. // the samples are decoded off the message thread, the hosted plugins are created one by one with their names
  6960. // shown; the panel's bar never sits still at 0 %
  6961. if (projectLoadRunning())
  6962. return;
  6963. openFlpWithProgress (*this, engine, file, [safe = juce::Component::SafePointer<MainComponent> (this), file] (bool ok, const juce::String& error) {
  6964. if (safe == nullptr)
  6965. return;
  6966. if (! ok)
  6967. {
  6968. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6969. return;
  6970. }
  6971. safe->flpImported (file);
  6972. });
  6973. return;
  6974. }
  6975. openLynxProject (file);
  6976. }
  6977. void MainComponent::importFlp (const juce::File& file)
  6978. {
  6979. juce::String error;
  6980. loadtrace::begin (file.getFullPathName().toStdString());
  6981. const auto ok = engine.importFlpFile (file, error);
  6982. loadtrace::end();
  6983. if (! ok)
  6984. {
  6985. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  6986. return;
  6987. }
  6988. flpImported (file);
  6989. }
  6990. void MainComponent::flpImported (const juce::File& file)
  6991. {
  6992. {
  6993. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  6994. importedFlpFile = file;
  6995. projectName = file.getFileNameWithoutExtension();
  6996. rememberRecent (file);
  6997. importedSuffix = " " + (file.hasFileExtension ("als") ? tr ("(imported from .als)")
  6998. : file.hasFileExtension ("flm;songtmpl") ? tr ("(imported from FL Studio Mobile)")
  6999. : tr ("(imported from FL Studio)"));
  7000. updateTitle();
  7001. playlist.showSongAfterOpen();
  7002. showMissingFiles (true);
  7003. // FL opens Project info when the project's "Show on opening" box is on (event 0x0A, REA round 167g)
  7004. if (engine.getSong().info.showOnOpen && platform::testMode())
  7005. platform::testModeLog ("project info shown on open");
  7006. else if (engine.getSong().info.showOnOpen)
  7007. openSettings ((int) SettingsPage::info);
  7008. }
  7009. }
  7010. void MainComponent::chooseFileToOpenWithoutPlugins()
  7011. {
  7012. confirmDiscard ([this] {
  7013. fileChooser = lynx::ui::makeFileChooser (tr ("Open without third-party plugins"), currentFile.getParentDirectory(), juce::String ("*") + ProjectFile::extension);
  7014. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  7015. [this] (const juce::FileChooser& chooser) {
  7016. if (chooser.getResult().existsAsFile())
  7017. {
  7018. crashguard::note (("opening project without plugins " + chooser.getResult().getFileName()).toStdString());
  7019. openLynxProject (chooser.getResult(), true);
  7020. }
  7021. });
  7022. });
  7023. }
  7024. void MainComponent::showPluginsOff()
  7025. {
  7026. if (auto* open = findToolWindow ("pluginsOff"))
  7027. {
  7028. open->toFront (true);
  7029. return;
  7030. }
  7031. if (auto* window = openToolWindow (makePluginsOffPanel (engine), tr ("Third-party plugins"), "pluginsOff"))
  7032. window->setResizable (true, false);
  7033. }
  7034. void MainComponent::openLynxProject (const juce::File& file, bool withoutPlugins)
  7035. {
  7036. juce::String error, savedBy;
  7037. auto song = ProjectFile::load (file, error, &savedBy);
  7038. if (! song)
  7039. {
  7040. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  7041. return;
  7042. }
  7043. withoutPlugins = withoutPlugins || std::exchange (nextOpenWithoutPlugins, false);
  7044. engine.stop();
  7045. engine.rewind();
  7046. if (withoutPlugins)
  7047. {
  7048. // round 190ap: no hosted plugin is created and no slot is changed (no substitutes either): each keeps the
  7049. // settings the file has, which is also what a save made now writes
  7050. engine.setSongWithPluginsOff (std::move (*song));
  7051. }
  7052. else
  7053. {
  7054. // missing plugins get their LYNX substitute; substitutes whose original is installed now go back to it
  7055. engine.getPluginHost().applySubstitutes (*song);
  7056. engine.setSong (std::move (*song));
  7057. }
  7058. currentFile = file;
  7059. importedFlpFile = juce::File();
  7060. projectName = file.getFileNameWithoutExtension();
  7061. importedSuffix = {};
  7062. rememberRecent (file);
  7063. updateTitle();
  7064. playlist.showSongAfterOpen();
  7065. // pain point 37 (round 177d): a project from a newer LYNX SHARE opens, but saving it here would drop what that
  7066. // version added, so say so once (FL warns about a project from a more recent version too)
  7067. if (safety::savedByNewerVersion (savedBy.toStdString(), JUCE_APPLICATION_VERSION_STRING))
  7068. {
  7069. platform::testModeLog ("project saved by newer version " + savedBy);
  7070. if (! platform::testMode())
  7071. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Saved by a newer version"),
  7072. tr ("This project was saved by LYNX SHARE {0}, and this is {1}. What the newer version added may be "
  7073. "lost if you save it here: use File › Save as... to keep the original.",
  7074. { savedBy, JUCE_APPLICATION_VERSION_STRING }));
  7075. }
  7076. if (engine.pluginsOff())
  7077. {
  7078. platform::testModeLog ("project opened without third-party plugins");
  7079. ui::postHint ({ tr ("Opened without third-party plugins: their settings are kept"), {}, false, false }, 8000);
  7080. if (persistent && ! engine.hostedPluginUses().empty())
  7081. showPluginsOff();
  7082. }
  7083. if (persistent)
  7084. {
  7085. showMissingFiles (true);
  7086. if (engine.getSong().info.showOnOpen && platform::testMode())
  7087. platform::testModeLog ("project info shown on open");
  7088. else if (engine.getSong().info.showOnOpen)
  7089. openSettings (1);
  7090. }
  7091. }
  7092. void MainComponent::openSettings (int page)
  7093. {
  7094. lastSettingsPage = page; // (issue #181: Ctrl+, opens this page next time)
  7095. const juce::Component::SafePointer<MainComponent> safe (this);
  7096. SettingsHooks hooks;
  7097. hooks.browserFoldersChanged = [safe] {
  7098. if (safe != nullptr)
  7099. safe->browser.reloadUserFolders();
  7100. };
  7101. hooks.getGeneral = [safe] {
  7102. GeneralOptions o;
  7103. if (safe == nullptr)
  7104. return o;
  7105. o.language = i18n::saved();
  7106. o.uiFont = theme::savedUiFont();
  7107. o.uiScale = safe->toolbarLayout.uiScale;
  7108. o.compactMenus = theme::menus::compact();
  7109. o.waveSpectral = ui::WaveformCache::spectral;
  7110. o.waveStereo = ui::WaveformCache::stereo;
  7111. o.noteNames = notenames::currentStyle.load();
  7112. o.noteFlats = notenames::currentFlats.load();
  7113. o.noteNamesEveryKey = notenames::everyKey.load();
  7114. o.rackPlayheadColumn = ChannelRackComponent::playheadColumn.load();
  7115. o.rackStepsChannelColour = ChannelRackComponent::stepsChannelColour.load();
  7116. o.reducedEffects = skin::reducedEffects();
  7117. o.animationRate = ui::FrameTicker::rateLimit();
  7118. o.artMotion = skin::artMotion();
  7119. o.uiAnimations = ui::motion::enabled();
  7120. o.gpuRendering = gpuRenderingEnabled();
  7121. o.pluginStyle = skin::forcedStyle();
  7122. o.splash = safe->startup.splash;
  7123. o.startupSound = safe->startup.sound;
  7124. o.scanAtStart = backgroundScanAtStart();
  7125. o.supportNote = support::noteEnabled();
  7126. o.defaultTemplate = juce::String::fromUTF8 (defaultTemplate().toText().c_str());
  7127. o.startupProject = (int) startupProject();
  7128. o.typingPiano = safe->typingPiano;
  7129. o.keepEditorsOpen = ChannelRackComponent::keepEditorsOpen;
  7130. o.selectFirstChannelWithNotes = ChannelRackComponent::selectFirstChannelWithNotes;
  7131. o.monophonicPainting = PianoRollComponent::monophonicPainting;
  7132. o.detachNewPlugins = safe->engine.detachesNewPlugins();
  7133. o.autoSelectLinked = ChannelRackComponent::autoSelectLinked;
  7134. o.alternateUndo = safe->alternateUndo;
  7135. o.rememberSeek = EditorGlobals::get().rememberSeek;
  7136. o.stretchedClipsLoop = stretchedClipsLoop();
  7137. o.autoClipsAtPlayback = autoclipplace::atPlayback();
  7138. o.disableTypingPriority = pluginkeys::newPluginsHostFirst().load();
  7139. o.layoutStyle = (int) safe->layoutStyle;
  7140. o.alsSessionOnPlaylist = AudioEngine::alsSessionOnPlaylist.load();
  7141. o.editPatternsIn = PlaylistComponent::editPatternsIn;
  7142. o.undoLevels = safe->engine.getUndoLevels();
  7143. o.autosaveMinutes = safe->autosaveMinutes;
  7144. o.autosaveKeep = safe->autosaveKeep;
  7145. o.askUnusedRecordings = safe->askUnusedRecordings;
  7146. o.backupWaitsForQuiet = safe->backupWaitsForQuiet;
  7147. o.backupLongestWaitMinutes = safe->backupLongestWaitMinutes;
  7148. o.hoverValues = safe->hoverValues;
  7149. o.crossfadesInNewProjects = newProjectDefaults().autoCrossfades;
  7150. o.linkTracksInNewProjects = newProjectDefaults().linkTracks;
  7151. o.pluginSandbox = pluginSandboxEnabled();
  7152. o.menuEntry = appImageMenuEntryInstalled();
  7153. o.pluginSubstitutes = pluginSubstitutesEnabled();
  7154. o.limitEditors = editorlimit::enabled();
  7155. o.crashReports = (int) crashreporter::consent();
  7156. o.checkUpdates = updater::automatic();
  7157. o.remoteControl = remoteui::enabled();
  7158. return o;
  7159. };
  7160. hooks.setGeneral = [safe] (const GeneralOptions& o) {
  7161. if (safe == nullptr)
  7162. return;
  7163. auto& self = *safe;
  7164. if (o.uiScale != self.toolbarLayout.uiScale)
  7165. {
  7166. auto layout = self.toolbarLayout;
  7167. layout.uiScale = toolbarlayout::clampScale (o.uiScale);
  7168. self.setToolbarLayout (layout, true);
  7169. }
  7170. theme::menus::setCompact (o.compactMenus);
  7171. ui::FrameTicker::rateLimit() = o.animationRate; // (the tickers read it every frame)
  7172. ui::motion::enabled() = o.uiAnimations;
  7173. if (o.reducedEffects != skin::reducedEffects() || o.pluginStyle != skin::forcedStyle() || o.artMotion != skin::artMotion())
  7174. {
  7175. skin::setArtMotion (o.artMotion);
  7176. skin::setReducedEffects (o.reducedEffects);
  7177. skin::setForcedStyle (o.pluginStyle);
  7178. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // open editors redraw at once
  7179. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  7180. }
  7181. if (o.noteNames != notenames::currentStyle.load() || o.noteFlats != notenames::currentFlats.load()
  7182. || o.noteNamesEveryKey != notenames::everyKey.load())
  7183. {
  7184. notenames::currentStyle.store (juce::jlimit (0, 2, o.noteNames));
  7185. notenames::currentFlats.store (o.noteFlats);
  7186. notenames::everyKey.store (o.noteNamesEveryKey);
  7187. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // the keyboards redraw with the new names
  7188. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  7189. }
  7190. if (o.rackPlayheadColumn != ChannelRackComponent::playheadColumn.load()
  7191. || o.rackStepsChannelColour != ChannelRackComponent::stepsChannelColour.load())
  7192. {
  7193. ChannelRackComponent::playheadColumn.store (o.rackPlayheadColumn);
  7194. ChannelRackComponent::stepsChannelColour.store (o.rackStepsChannelColour);
  7195. self.rack.repaint();
  7196. }
  7197. if (o.gpuRendering != gpuRenderingEnabled())
  7198. setGpuRenderingEnabled (o.gpuRendering);
  7199. if (o.waveSpectral != ui::WaveformCache::spectral || o.waveStereo != ui::WaveformCache::stereo)
  7200. {
  7201. ui::WaveformCache::spectral = o.waveSpectral;
  7202. ui::WaveformCache::stereo = o.waveStereo;
  7203. ui::WaveformCache::getInstance()->settingsChanged();
  7204. }
  7205. if (o.typingPiano != self.typingPiano)
  7206. self.setTypingPiano (o.typingPiano);
  7207. if (o.scanAtStart != backgroundScanAtStart())
  7208. setBackgroundScanAtStart (o.scanAtStart);
  7209. if (o.defaultTemplate.toStdString() != defaultTemplate().toText())
  7210. setDefaultTemplate (TemplateChoice::parse (o.defaultTemplate.toStdString()));
  7211. if (o.startupProject != (int) startupProject())
  7212. setStartupProject ((StartupProject) juce::jlimit (0, 2, o.startupProject));
  7213. if (o.pluginSandbox != pluginSandboxEnabled())
  7214. setPluginSandboxEnabled (o.pluginSandbox);
  7215. if (runningAsAppImage() && o.menuEntry != appImageMenuEntryInstalled())
  7216. setAppImageMenuEntry (o.menuEntry);
  7217. editorlimit::enabled() = o.limitEditors;
  7218. if (o.pluginSubstitutes != pluginSubstitutesEnabled())
  7219. setPluginSubstitutesEnabled (o.pluginSubstitutes);
  7220. if (o.crashReports != (int) crashreporter::consent())
  7221. crashreporter::setConsent ((crashreport::Consent) juce::jlimit (0, 2, o.crashReports));
  7222. updater::setAutomatic (o.checkUpdates);
  7223. remoteui::setEnabled (o.remoteControl);
  7224. ChannelRackComponent::keepEditorsOpen = o.keepEditorsOpen;
  7225. ChannelRackComponent::selectFirstChannelWithNotes = o.selectFirstChannelWithNotes;
  7226. PianoRollComponent::monophonicPainting = o.monophonicPainting;
  7227. self.engine.setDetachNewPlugins (o.detachNewPlugins);
  7228. setEditorsDetached (o.detachNewPlugins); // (round 190ev)
  7229. ChannelRackComponent::autoSelectLinked = o.autoSelectLinked;
  7230. self.alternateUndo = o.alternateUndo;
  7231. EditorGlobals::get().rememberSeek = o.rememberSeek;
  7232. autoclipplace::setAtPlayback (o.autoClipsAtPlayback);
  7233. pluginkeys::newPluginsHostFirst() = o.disableTypingPriority;
  7234. self.setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, o.layoutStyle));
  7235. AudioEngine::alsSessionOnPlaylist = o.alsSessionOnPlaylist;
  7236. if (o.stretchedClipsLoop != stretchedClipsLoop())
  7237. {
  7238. setStretchedClipsLoop (o.stretchedClipsLoop);
  7239. self.repaint(); // the Playlist draws what plays
  7240. }
  7241. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, o.editPatternsIn);
  7242. self.startup.splash = o.splash;
  7243. if (o.supportNote != support::noteEnabled())
  7244. support::setNoteEnabled (o.supportNote);
  7245. self.startup.sound = o.startupSound;
  7246. self.engine.setUndoLevels (o.undoLevels);
  7247. self.autosaveMinutes = prefs::clampAutosaveMinutes (o.autosaveMinutes);
  7248. self.autosaveKeep = prefs::clampAutosaveKeep (o.autosaveKeep);
  7249. self.askUnusedRecordings = o.askUnusedRecordings;
  7250. self.backupWaitsForQuiet = o.backupWaitsForQuiet;
  7251. self.backupLongestWaitMinutes = prefs::clampBackupLongestWait (o.backupLongestWaitMinutes);
  7252. if (self.hoverValues && ! o.hoverValues && self.hoverTipShown)
  7253. ui::hideValueTip();
  7254. self.hoverValues = o.hoverValues;
  7255. self.hoverTipShown = false;
  7256. newProjectDefaults().autoCrossfades = o.crossfadesInNewProjects;
  7257. newProjectDefaults().linkTracks = o.linkTracksInNewProjects;
  7258. self.autosaveTicks = 0;
  7259. self.saveUiSettings();
  7260. if (o.uiFont != theme::savedUiFont())
  7261. theme::saveUiFont (o.uiFont);
  7262. if (o.language != i18n::saved())
  7263. self.showLanguageChoice (o.language);
  7264. };
  7265. hooks.manageShortcuts = [safe] {
  7266. if (safe != nullptr)
  7267. safe->showShortcutManager();
  7268. };
  7269. hooks.managePlugins = [safe] {
  7270. if (safe != nullptr)
  7271. safe->showPluginManager();
  7272. };
  7273. hooks.runAction = [safe] (const std::string& id) { return safe != nullptr && safe->runAction (id); };
  7274. hooks.linkToggleShown = [safe] { return safe != nullptr && safe->toolbarLayout.isShown (toolbarlayout::Group::link); };
  7275. hooks.showLinkToggle = [safe] (bool on) {
  7276. if (safe != nullptr)
  7277. safe->showLinkToggle (on);
  7278. };
  7279. hooks.midiChanged = [safe] {
  7280. if (safe != nullptr)
  7281. safe->updateGamepad();
  7282. };
  7283. showSettings (engine, (SettingsPage) juce::jlimit (0, (int) SettingsPage::link, page), std::move (hooks)); // (Theme was clamped to MIDI)
  7284. }
  7285. void MainComponent::showPluginManager()
  7286. {
  7287. lynx::showPluginManager (engine, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  7288. if (safe != nullptr)
  7289. safe->openSettings ((int) SettingsPage::files);
  7290. });
  7291. }
  7292. void MainComponent::showShortcutManager()
  7293. {
  7294. lynx::showShortcutManager ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  7295. if (safe == nullptr)
  7296. return;
  7297. safe->loadKeyMap();
  7298. safe->setControlHints();
  7299. safe->menuItemsChanged();
  7300. });
  7301. }
  7302. void MainComponent::showMissingFiles (bool afterOpening)
  7303. {
  7304. if (afterOpening && platform::testMode()) // (LYNX_TEST_MODE: nothing waits for a click)
  7305. {
  7306. platform::testModeLog ("Missing files dialog after opening " + projectName);
  7307. return;
  7308. }
  7309. MissingFilesInfo info;
  7310. info.projectName = projectName;
  7311. const auto fromFlp = importedFlpFile.existsAsFile() && currentFile == juce::File();
  7312. const auto exists = [] (const std::string& path) { return juce::File::isAbsolutePath (juce::String::fromUTF8 (path.c_str())) && juce::File (juce::String::fromUTF8 (path.c_str())).existsAsFile(); };
  7313. if (fromFlp)
  7314. {
  7315. // the import dropped the samples it couldn't find: its report keeps them (minus the ones located since)
  7316. const auto& report = engine.getImportReport();
  7317. for (const auto& m : report.missingFiles)
  7318. info.files.push_back (m);
  7319. info.plugins = engine.getMissingPluginDetails();
  7320. info.autoRelocated = report.relocatedFiles;
  7321. info.searchFolders.add (importedFlpFile.getParentDirectory().getFullPathName());
  7322. }
  7323. else
  7324. {
  7325. const auto& song = engine.getSong();
  7326. info.files = findMissingSamples (song, exists);
  7327. auto& host = engine.getPluginHost();
  7328. auto addPlugin = [&info] (const PluginRef& ref, const std::string& user, const char* replacement) {
  7329. const auto name = ref.name.empty() ? ref.id : ref.name;
  7330. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  7331. if (it == info.plugins.end())
  7332. it = info.plugins.insert (info.plugins.end(), MissingPlugin { name, {}, replacement });
  7333. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  7334. it->usedBy.push_back (user);
  7335. };
  7336. for (const auto& c : song.channels)
  7337. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty() && host.find (juce::String::fromUTF8 (c.plugin.id.c_str())) == nullptr)
  7338. addPlugin (c.plugin, c.name, "Silence: the channel keeps the plugin's settings until it is installed");
  7339. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  7340. for (const auto& fx : song.mixer[t].effects)
  7341. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
  7342. addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
  7343. "Bypassed: the slot keeps the plugin's settings until it is installed");
  7344. // played by a LYNX substitute until the original is installed
  7345. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  7346. for (const auto& fx : song.mixer[t].effects)
  7347. if (fx.isSubstitute())
  7348. {
  7349. const auto name = substituteOriginalName (fx);
  7350. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  7351. if (it == info.plugins.end())
  7352. it = info.plugins.insert (info.plugins.end(),
  7353. MissingPlugin { name, {}, TR_NOOP ("LYNX SHARE substitute: {0} (the original plugin is used again once it is installed). FL Studio plays a missing plugin's slot unprocessed: a substitute slot's menu › Bypass all LYNX SHARE substitutes of this project does the same"),
  7354. effectInfo (fx.kind).name });
  7355. const auto user = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
  7356. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  7357. it->usedBy.push_back (user);
  7358. }
  7359. // installed, but failed to load: they play silence / are bypassed
  7360. for (const auto& line : host.getLoadFailures())
  7361. if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
  7362. info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
  7363. if (currentFile.existsAsFile())
  7364. info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
  7365. }
  7366. if (afterOpening && info.files.empty() && info.plugins.empty())
  7367. {
  7368. if (fromFlp)
  7369. showImportReport();
  7370. return;
  7371. }
  7372. auto safe = juce::Component::SafePointer<MainComponent> (this);
  7373. const auto flp = fromFlp ? importedFlpFile : juce::File();
  7374. showMissingFilesDialog (
  7375. std::move (info),
  7376. [safe, flp] (const std::map<std::string, std::string>& relocations) {
  7377. if (safe == nullptr)
  7378. return;
  7379. if (flp != juce::File())
  7380. {
  7381. // FL import: imported again with the located samples (the channels become samplers, slices are read...)
  7382. juce::String error;
  7383. if (! safe->engine.importFlpFile (flp, error, relocations, true))
  7384. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  7385. }
  7386. else
  7387. safe->engine.editSong ([&relocations] (Song& s) { applyRelocations (s, relocations); });
  7388. safe->updateTitle();
  7389. },
  7390. [safe, afterOpening, fromFlp] {
  7391. if (safe != nullptr && afterOpening && fromFlp)
  7392. safe->showImportReport();
  7393. });
  7394. }
  7395. juce::PopupMenu MainComponent::makeSwitchAudioClipsMenu (bool selectedOnly)
  7396. {
  7397. // FL's groups where LYNX has a match (Realtime: Resample), LYNX's stretch engine, and its Ableton-style warp modes
  7398. juce::PopupMenu m;
  7399. auto item = [this, &m, selectedOnly] (const char* name, bool keepPitch, StretchMethod method) {
  7400. m.addItem (tr (name), [this, selectedOnly, keepPitch, method, name] { switchAudioClips (selectedOnly, keepPitch, method, tr (name)); });
  7401. };
  7402. m.addSectionHeader (tr ("Realtime"));
  7403. item (TR_NOOP ("Resample"), false, StretchMethod::general);
  7404. m.addSectionHeader (tr ("Stretch engine"));
  7405. item (TR_NOOP ("General"), true, StretchMethod::general);
  7406. item (TR_NOOP ("Drums / transients"), true, StretchMethod::transients);
  7407. item (TR_NOOP ("Vocal / mono"), true, StretchMethod::mono);
  7408. m.addSectionHeader (tr ("Warp (Ableton-style)"));
  7409. item (TR_NOOP ("Beats"), true, StretchMethod::beats);
  7410. item (TR_NOOP ("Tones"), true, StretchMethod::tones);
  7411. item (TR_NOOP ("Texture"), true, StretchMethod::texture);
  7412. item (TR_NOOP ("Complex"), true, StretchMethod::complex);
  7413. return m;
  7414. }
  7415. void MainComponent::switchAudioClips (bool selectedOnly, bool keepPitch, StretchMethod method, const juce::String& modeName)
  7416. {
  7417. // FL's FUN_01213a20 (REA round 181b): the error when there is none, else a question, then the change (undoable)
  7418. std::vector<int> channels;
  7419. if (selectedOnly)
  7420. channels = engine.getSelectedChannels();
  7421. else
  7422. for (int i = 0; i < (int) engine.getSong().channels.size(); ++i)
  7423. channels.push_back (i);
  7424. if (audioClipsAmong (engine.getSong(), channels) == 0)
  7425. {
  7426. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  7427. selectedOnly ? tr ("No audio clip channels were selected.") : tr ("No audio clip channels were found."));
  7428. return;
  7429. }
  7430. const auto text = selectedOnly ? tr ("Selected audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName })
  7431. : tr ("All audio clip channels will be set to {0} mode. Some channels may need manual time adjustment.", { modeName });
  7432. auto options = juce::MessageBoxOptions()
  7433. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  7434. .withTitle (tr ("Confirm"))
  7435. .withMessage (text)
  7436. .withButton (tr ("OK"))
  7437. .withButton (tr ("Cancel"));
  7438. juce::AlertWindow::showAsync (options, [this, channels, keepPitch, method] (int result) {
  7439. if (result == 1)
  7440. engine.editSong ([&channels, keepPitch, method] (Song& s) { setStretchOfAudioClips (s, channels, keepPitch, method); });
  7441. });
  7442. }
  7443. void MainComponent::saveClipboardToBrowser (bool midi)
  7444. {
  7445. // FL's FUN_0124d070 (REA round 181b): the clipboard as "Audio clipboard.wav" / "MIDI clipboard.mid" in the
  7446. // Browser's Clipboard files
  7447. juce::File file;
  7448. if (midi)
  7449. {
  7450. if (const auto smf = midiclipboard::get())
  7451. file = audioclipboard::save ("MIDI clipboard", ".mid", smf->getData(), smf->getSize());
  7452. else
  7453. return;
  7454. }
  7455. else
  7456. {
  7457. const auto data = audioclipboard::wav();
  7458. if (data.empty())
  7459. return;
  7460. file = audioclipboard::save ("Audio clipboard", ".wav", data.data(), data.size());
  7461. }
  7462. if (file == juce::File())
  7463. {
  7464. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Error"),
  7465. tr ("Unable to create folder: {0}", { audioclipboard::folder().getFullPathName() }));
  7466. return;
  7467. }
  7468. browser.refreshRoots();
  7469. ui::postHint ({ tr ("Saved to Clipboard files: {0}", { file.getFileName() }), {}, false, false }, 5000);
  7470. }
  7471. void MainComponent::confirmPrepareForMidiExport()
  7472. {
  7473. // FL's text, without its "(no undo)": this edit can be undone in LYNX
  7474. auto options = juce::MessageBoxOptions()
  7475. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  7476. .withTitle (tr ("Confirm"))
  7477. .withMessage (tr ("All of the channels are about to be turned into MIDI Out channels in order to allow output to a MIDI file."))
  7478. .withButton (tr ("OK"))
  7479. .withButton (tr ("Cancel"));
  7480. juce::AlertWindow::showAsync (options, [this] (int result) {
  7481. if (result == 1)
  7482. engine.editSongStructural ([] (Song& s) { prepareForMidiExport (s); });
  7483. });
  7484. }
  7485. void MainComponent::changeDeclickOfSelectedClips (int mode)
  7486. {
  7487. const auto selected = engine.getSelectedChannels();
  7488. if (audioClipsAmong (engine.getSong(), selected) == 0)
  7489. {
  7490. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("No selection"), tr ("There are no audio clip channels selected."));
  7491. return;
  7492. }
  7493. auto options = juce::MessageBoxOptions()
  7494. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  7495. .withTitle (tr ("Change declicking mode?"))
  7496. .withMessage (tr ("Change the declicking mode of all selected audio clip channels?"))
  7497. .withButton (tr ("OK"))
  7498. .withButton (tr ("Cancel"));
  7499. juce::AlertWindow::showAsync (options, [this, selected, mode] (int result) {
  7500. if (result == 1)
  7501. engine.editSong ([&selected, mode] (Song& s) { setDeclickOfAudioClips (s, selected, mode); });
  7502. });
  7503. }
  7504. void MainComponent::switchSmartDisableForAll()
  7505. {
  7506. // FL's Tools › Macros › "Switch smart disable for all plugins" (FLEngine FUN_0124d430, REA round 139): every
  7507. // effect slot of every insert is set to smart disable
  7508. engine.editSong ([] (Song& s) {
  7509. for (auto& track : s.mixer)
  7510. for (auto& slot : track.effects)
  7511. slot.smartDisable = true;
  7512. });
  7513. }
  7514. void MainComponent::exportAudio (int format)
  7515. {
  7516. showExportDialog (engine, currentFile.getParentDirectory(), projectName, format);
  7517. }
  7518. void MainComponent::exportForOtherApps()
  7519. {
  7520. engine.capturePluginStates();
  7521. showOtherAppsExportDialog (engine,
  7522. currentFile != juce::File() ? currentFile.getParentDirectory()
  7523. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  7524. projectStem (projectName));
  7525. }
  7526. void MainComponent::importMidiFile()
  7527. {
  7528. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  7529. fileChooser = lynx::ui::makeFileChooser (tr ("Import MIDI file"), folder, "*.mid;*.midi");
  7530. juce::Component::SafePointer<MainComponent> safe (this);
  7531. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe] (const juce::FileChooser& fc) {
  7532. const auto file = fc.getResult();
  7533. if (safe == nullptr || file == juce::File())
  7534. return;
  7535. juce::String error;
  7536. const auto midi = MidiFileIo::parseFile (file, error);
  7537. if (! midi)
  7538. {
  7539. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  7540. return;
  7541. }
  7542. static MidiFileIo::ImportOptions remembered; // FL keeps the window's choices
  7543. showMidiImportDialog (file.getFileName(), *midi, remembered, false, [safe, file] (const MidiFileIo::ImportOptions& o) {
  7544. remembered = o;
  7545. if (safe != nullptr)
  7546. safe->importMidiFile (file, o);
  7547. });
  7548. });
  7549. }
  7550. void MainComponent::importMidiFile (const juce::File& file, const MidiFileIo::ImportOptions& o)
  7551. {
  7552. juce::String error;
  7553. if (o.newProject)
  7554. {
  7555. confirmDiscard ([this, file, o] {
  7556. Song song;
  7557. juce::String err;
  7558. if (! MidiFileIo::importInto (song, file, o, err))
  7559. {
  7560. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), err);
  7561. return;
  7562. }
  7563. engine.stop();
  7564. engine.rewind();
  7565. engine.setSong (std::move (song));
  7566. currentFile = juce::File();
  7567. projectName = file.getFileNameWithoutExtension();
  7568. importedSuffix = " " + tr ("(imported from MIDI)");
  7569. updateTitle();
  7570. });
  7571. return;
  7572. }
  7573. auto song = engine.getSong();
  7574. if (! MidiFileIo::importInto (song, file, o, error))
  7575. {
  7576. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  7577. return;
  7578. }
  7579. engine.editSong ([&song] (Song& s) { s = std::move (song); });
  7580. showPanel (Panel::channelRack);
  7581. }
  7582. void MainComponent::exportMidiFile()
  7583. {
  7584. // FL's File › Export › "MIDI file...": the arrangement's notes (or the current pattern's) as a Standard MIDI File
  7585. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  7586. const auto name = projectName.isNotEmpty() ? projectName : juce::String ("LYNX SHARE");
  7587. fileChooser = lynx::ui::makeFileChooser (tr ("Export MIDI file"), folder.getChildFile (name + ".mid"), "*.mid");
  7588. juce::Component::SafePointer<MainComponent> safe (this);
  7589. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  7590. [safe] (const juce::FileChooser& fc) {
  7591. auto file = fc.getResult();
  7592. if (safe == nullptr || file == juce::File())
  7593. return;
  7594. if (! file.hasFileExtension (".mid;.midi"))
  7595. file = file.withFileExtension (".mid");
  7596. juce::String error;
  7597. if (! MidiFileIo::saveSong (safe->engine.getSong(), file, error))
  7598. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not export"), error);
  7599. else
  7600. file.revealToUser();
  7601. });
  7602. }
  7603. void MainComponent::save (bool askForFile, std::function<void()> afterSaved)
  7604. {
  7605. commitSongNotes(); // (round 190ch: notes still being typed are part of what is saved)
  7606. auto write = [this, afterSaved] (const juce::File& file) {
  7607. juce::String error;
  7608. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  7609. keepOverwrittenCopy (file); // the version this save replaces goes to the backup folder (like FL)
  7610. if (ProjectFile::save (engine.getSong(), file, error))
  7611. {
  7612. engine.markSaved();
  7613. rememberRecent (file);
  7614. currentFile = file;
  7615. projectName = file.getFileNameWithoutExtension();
  7616. importedSuffix = {};
  7617. updateTitle();
  7618. if (afterSaved)
  7619. afterSaved();
  7620. }
  7621. else
  7622. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  7623. };
  7624. // a project opened from the backup folder is saved somewhere else (old backups there are deleted)
  7625. if (! askForFile && currentFile != juce::File() && ! currentFile.isAChildOf (autosaveFolder()))
  7626. {
  7627. write (ProjectFile::withProjectExtension (currentFile));
  7628. return;
  7629. }
  7630. const auto startFolder = currentFile.isAChildOf (autosaveFolder()) ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
  7631. : currentFile.getParentDirectory();
  7632. fileChooser = lynx::ui::makeFileChooser (tr ("Save project"), startFolder, juce::String ("*") + ProjectFile::extension);
  7633. lynx::ui::launchChooser (fileChooser, juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  7634. [this, write] (const juce::FileChooser& chooser) {
  7635. const auto chosen = chooser.getResult();
  7636. if (chosen == juce::File())
  7637. return;
  7638. const auto file = ProjectFile::withProjectExtension (chosen);
  7639. // the dialog's overwrite warning was about the name typed, without the extension
  7640. if (file != chosen && file != currentFile && file.existsAsFile())
  7641. {
  7642. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  7643. tr ("{0} already exists. Choose another name or folder.", { file.getFullPathName() }));
  7644. return;
  7645. }
  7646. if (! file.isAChildOf (autosaveFolder()))
  7647. {
  7648. write (file);
  7649. return;
  7650. }
  7651. // FL warns the same way: the backup folder is cleaned up as new backups arrive
  7652. auto* w = new juce::AlertWindow (tr ("Save in the backup folder?"),
  7653. tr ("This folder keeps LYNX SHARE's automatic backups and old ones are deleted as new "
  7654. "ones arrive, so a project saved here can be lost. If you opened a backup, save it "
  7655. "somewhere else."),
  7656. juce::MessageBoxIconType::WarningIcon);
  7657. w->addButton (tr ("Save anyway"), 1);
  7658. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  7659. w->enterModalState (true, juce::ModalCallbackFunction::create ([write, file] (int r) {
  7660. if (r == 1)
  7661. write (file);
  7662. }),
  7663. true);
  7664. });
  7665. }
  7666. void MainComponent::placeHintBar (juce::Rectangle<int> row)
  7667. {
  7668. // the read-out takes the right part of the hint row once something was tweaked (2/5 of it, 170..280 px), and
  7669. // only when the hint keeps at least 220 px
  7670. const auto readoutWidth = juce::jlimit (170, 280, row.getWidth() * 2 / 5);
  7671. if (tweakReadout.hasContent() && row.getWidth() - readoutWidth - 6 >= 220)
  7672. {
  7673. tweakReadout.setBounds (row.removeFromRight (readoutWidth));
  7674. tweakReadout.setVisible (true);
  7675. row.removeFromRight (6);
  7676. }
  7677. else
  7678. {
  7679. tweakReadout.setVisible (false);
  7680. tweakReadout.setBounds ({});
  7681. }
  7682. hintBar.setVisible (true);
  7683. hintBar.setBounds (row);
  7684. }
  7685. // Settings › General › "Show a control's value next to the mouse..." (round 177d, pain point 10; off by default = FL,
  7686. // whose value shows in the hint bar only): the value the hint bar shows for the control under the mouse, in the
  7687. // drag read-out's pill just above the cursor. A drag shows its own read-out, so nothing here while one runs.
  7688. void MainComponent::updateHoverValue (juce::Component* hovered, const ui::Hint& hint, bool live)
  7689. {
  7690. if (live)
  7691. {
  7692. hoverTipShown = false; // (the drag's read-out owns the pill now)
  7693. return;
  7694. }
  7695. const auto at = juce::Desktop::getInstance().getMainMouseSource().getScreenPosition().roundToInt();
  7696. const auto show = hovered != nullptr && hint.value.isNotEmpty() && ! juce::ModifierKeys::currentModifiers.isAnyMouseButtonDown()
  7697. && (hovered->getTopLevelComponent() == getTopLevelComponent()
  7698. || (bool) hovered->getTopLevelComponent()->getProperties().getWithDefault ("lynxNativeChild", false));
  7699. if (! show)
  7700. {
  7701. if (hoverTipShown)
  7702. ui::hideValueTip();
  7703. hoverTipShown = false;
  7704. return;
  7705. }
  7706. if (hoverTipShown && hint.value == hoverTipText && at == hoverTipAt)
  7707. return;
  7708. hoverTipShown = true;
  7709. hoverTipText = hint.value;
  7710. hoverTipAt = at;
  7711. ui::showValueTip (*hovered, juce::Rectangle<int> (1, 18).withCentre (hovered->getLocalPoint (nullptr, at)), hint.value);
  7712. }
  7713. void MainComponent::refreshTweakReadout()
  7714. {
  7715. const auto had = tweakReadout.hasContent();
  7716. if (const auto t = engine.getLastTweaked (0))
  7717. tweakReadout.setContent (describeAutomationTarget (engine, *t), describeTargetValue (engine, *t));
  7718. else
  7719. tweakReadout.setContent ({}, {});
  7720. if (had != tweakReadout.hasContent())
  7721. resized(); // the read-out appears (or goes, with its target)
  7722. }
  7723. juce::PopupMenu MainComponent::makeLastTweakedMenu (int which)
  7724. {
  7725. juce::PopupMenu menu;
  7726. const auto target = engine.getLastTweaked (which);
  7727. if (! target)
  7728. {
  7729. menu.addItem (tr ("No parameter"), false, false, [] {});
  7730. return menu;
  7731. }
  7732. // as FL: the parameter's name, then the items of its own menu (events, automation clip, remote control, value)
  7733. const auto valueNow = describeTargetValue (engine, *target); // (round 162d: with its value, as the read-out shows it)
  7734. ui::addItemHeader (menu, tr ("Parameter"), describeAutomationTarget (engine, *target) + (valueNow.isNotEmpty() ? ": " + valueNow : juce::String()),
  7735. juce::Colours::transparentBlack);
  7736. addLastTweakedItems (menu, *target);
  7737. return menu;
  7738. }
  7739. juce::PopupMenu MainComponent::getMultilinkMenuForSnapshot()
  7740. {
  7741. // (round 190df: FL's menu, then LYNX's own items; round 190ey: with multilink off, the last tweaked control's own
  7742. // menu as FL's left column, captioned with its name)
  7743. return multilinkButtonMenu (engine, [this] (juce::PopupMenu& column) {
  7744. if (const auto target = engine.getLastTweaked (0))
  7745. {
  7746. column.addSectionHeader (describeAutomationTarget (engine, *target));
  7747. addLastTweakedItems (column, *target);
  7748. }
  7749. });
  7750. }
  7751. void MainComponent::addLastTweakedItems (juce::PopupMenu& menu, const AutomationTarget& target)
  7752. {
  7753. addAutomationItem (menu, engine, target, true);
  7754. menu.addSectionHeader (tr ("Value"));
  7755. const auto value = engine.currentTargetValue (target);
  7756. menu.addItem (tr ("Copy value"), value >= 0.0f, false, [value] { lastTweakedClipboard() = value; });
  7757. menu.addItem (tr ("Paste value"), lastTweakedClipboard() >= 0.0f, false, [this, t = target] { setTweakedValue (t, lastTweakedClipboard()); });
  7758. menu.addItem (tr ("Type in value..."), value >= 0.0f, false, [this, t = target, value] {
  7759. auto spec = ui::percentSpec (describeAutomationTarget (engine, t), value);
  7760. ui::typeValue (*this, spec, value, [this, t] (double v) { setTweakedValue (t, (float) v); });
  7761. });
  7762. }
  7763. float& MainComponent::lastTweakedClipboard()
  7764. {
  7765. static float copied = -1.0f;
  7766. return copied;
  7767. }
  7768. void MainComponent::setTweakedValue (const AutomationTarget& target, float value)
  7769. {
  7770. value = juce::jlimit (0.0f, 1.0f, value);
  7771. auto plugin = false;
  7772. engine.editSong ([&] (Song& s) {
  7773. if (target.kind == AutomationTargetKind::tempo)
  7774. clipops::followTempo (s, tempoFromValue (value)); // (issue #87: audio clips follow)
  7775. else
  7776. plugin = ! s.setTargetValue (target, value);
  7777. });
  7778. if (plugin)
  7779. {
  7780. if (target.kind == AutomationTargetKind::channelParam)
  7781. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (target.index).get()))
  7782. p->setParameterFromUi (target.param, value);
  7783. if (target.kind == AutomationTargetKind::effectParam)
  7784. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (target.index, target.slot).get()))
  7785. p->setParameterFromUi (target.param, value);
  7786. }
  7787. engine.noteTweaked (target);
  7788. }
  7789. juce::StringArray MainComponent::getMenuBarNames()
  7790. {
  7791. // FL's menu bar order (REA round 139): FILE EDIT ADD PATTERNS VIEW OPTIONS TOOLS HELP
  7792. return { tr ("File"), tr ("Edit"), tr ("Add"), tr ("Patterns"), tr ("View"), tr ("Options"), tr ("Tools"), tr ("Help") };
  7793. }
  7794. juce::PopupMenu MainComponent::getMenuForIndex (int barIndex, const juce::String&)
  7795. {
  7796. juce::PopupMenu menu;
  7797. // the bar's position → the menu built below (0 File, 1 Edit, 2 View, 3 Patterns, 4 Options, 5 Help, 10 Add, 11 Tools)
  7798. static constexpr int menus[] = { 0, 1, 10, 3, 2, 4, 11, 5 };
  7799. const auto index = juce::isPositiveAndBelow (barIndex, (int) std::size (menus)) ? menus[barIndex] : 5;
  7800. if (index == 10)
  7801. {
  7802. // FL's ADD menu: a channel (LYNX's instruments and the installed plugins), a pattern, the plugin tools
  7803. menu.addSectionHeader (tr ("Channel"));
  7804. rack.addInstrumentItems (menu, -1);
  7805. // the Channel Rack's and the mixer slots' view switch (Categories / Simple / Tree), so that the three menus are
  7806. // one (issue #104)
  7807. quickpick::addFolderViewItems (menu, engine);
  7808. menu.addSectionHeader (tr ("Other"));
  7809. // FL's "Automation for last tweaked parameter" (Add_AutoLastMenu → FUN_01231100, REA round 143)
  7810. const auto last = engine.getLastTweaked (0);
  7811. menu.addItem ((last ? tr ("Automation for last tweaked parameter ({0})", { describeAutomationTarget (engine, *last) })
  7812. : tr ("Automation for last tweaked parameter"))
  7813. + shortcutText ("automation.lastTweaked"),
  7814. last.has_value(), false, [this] { runAction ("automation.lastTweaked"); });
  7815. menu.addItem (tr ("Pattern"), [this] { newPatternButton.onClick(); });
  7816. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  7817. return menu;
  7818. }
  7819. if (index == 11)
  7820. {
  7821. // FL's TOOLS menu, with the tools LYNX has (REA round 139)
  7822. menu.addItem (tr ("Browser find") + shortcutText ("browser.search"), [this] {
  7823. showPanel (Panel::browser);
  7824. browser.focusSearch();
  7825. });
  7826. {
  7827. // FL's One-click audio recording submenu (OneClickRecMenu, round 190dx; [FORM] and live 190cq): a caption, then
  7828. // Into Edison (FL's default item) and Into playlist
  7829. juce::PopupMenu oneClick;
  7830. oneClick.addSectionHeader (tr ("I want to record audio..."));
  7831. oneClick.addItem (tr ("Into Edison audio editor/recorder"), [this] { oneClickRecord ((int) oneclick::Into::edison); });
  7832. oneClick.addItem (tr ("Into playlist as an audio clip"), [this] { oneClickRecord ((int) oneclick::Into::playlist); });
  7833. menu.addSubMenu (tr ("One-click audio recording"), oneClick);
  7834. }
  7835. // FL's Tools menu has these two here; they work on the selected channel's Piano Roll (round 181b)
  7836. menu.addItem (tr ("Riff machine..."), [this] {
  7837. openPianoRoll();
  7838. pianoRoll.runAction ("pianoRoll.riffMachine");
  7839. });
  7840. menu.addItem (tr ("Chord progression tool..."), [this] {
  7841. openPianoRoll();
  7842. pianoRoll.runAction ("pianoRoll.chordProgression");
  7843. });
  7844. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  7845. menu.addItem (tr ("Modulators..."), [this] { openModulators (engine); }); // round 177b: LYNX's own (FL has none)
  7846. // FL's Clipboard and Score logger sections, in FL's place (round 181b)
  7847. menu.addSectionHeader (tr ("Clipboard"));
  7848. menu.addItem (tr ("Save audio clipboard to browser"), audioclipboard::hasAudio(), false, [this] { saveClipboardToBrowser (false); });
  7849. menu.addItem (tr ("Save MIDI clipboard to browser"), midiclipboard::hasMidi(), false, [this] { saveClipboardToBrowser (true); });
  7850. {
  7851. // FL's score logger (REA round 165f): the notes played lately, recording or not, into the current pattern
  7852. menu.addSectionHeader (tr ("Score logger"));
  7853. juce::PopupMenu dumpMenu;
  7854. for (const auto minutes : { 2, 5, 10, 20, 30 })
  7855. dumpMenu.addItem (tr ("Last {0} minutes", { juce::String (minutes) }), [this, minutes] { dumpScoreLog (minutes); });
  7856. menu.addSubMenu (tr ("Dump score log to selected pattern"), dumpMenu);
  7857. menu.addItem (tr ("Clear log"), ! engine.scoreLogEmpty(), false, [this] {
  7858. auto options = juce::MessageBoxOptions()
  7859. .withIconType (juce::MessageBoxIconType::WarningIcon)
  7860. .withTitle (tr ("Score logger"))
  7861. .withMessage (tr ("This will clear all logged notes!"))
  7862. .withButton (tr ("Clear log"))
  7863. .withButton (tr ("Cancel"));
  7864. juce::AlertWindow::showAsync (options, [this] (int result) {
  7865. if (result == 1)
  7866. engine.clearScoreLog();
  7867. });
  7868. });
  7869. }
  7870. addAudioLoggerMenu (menu); // FL's Tools menu has it just above "Last tweaked parameters"
  7871. // FL's "Last tweaked parameters" section (LastTweaked1Menu / LastTweaked2Menu → FUN_0123d1d0, REA round 143):
  7872. // the parameter's own menu for the last two moved controls
  7873. menu.addSectionHeader (tr ("Last tweaked parameters"));
  7874. menu.addSubMenu (tr ("Last tweaked"), makeLastTweakedMenu (0), engine.getLastTweaked (0).has_value());
  7875. menu.addSubMenu (tr ("Next to last tweaked"), makeLastTweakedMenu (1), engine.getLastTweaked (1).has_value());
  7876. menu.addSectionHeader (tr ("Macros"));
  7877. menu.addItem (tr ("Stop sound") + shortcutText ("tools.stopSound"), [this] { engine.stopSound(); });
  7878. // FL's next item, MacroCancelRecordingAction (round 187a; REA 169k §2.3): greyed while not recording
  7879. menu.addItem (tr ("Cancel recording"), engine.isRecording(), false, [this] { engine.cancelRecording(); });
  7880. menu.addSeparator();
  7881. // FL's Macros order (round 181b; [DFM] mainmenu, round 168f)
  7882. menu.addItem (tr ("Prepare for performance mode..."), [this] { prepareForPerformance(); });
  7883. menu.addItem (tr ("Prepare for MIDI export"), [this] { confirmPrepareForMidiExport(); });
  7884. menu.addItem (tr ("Select unused channels"), [this] {
  7885. showPanel (Panel::channelRack);
  7886. rack.selectUnused();
  7887. });
  7888. menu.addItem (tr ("Purge unused audio clips"), [this] { playlist.runAction ("playlist.purgeUnusedAudio"); });
  7889. menu.addItem (tr ("Switch smart disable for all plugins"), [this] { switchSmartDisableForAll(); });
  7890. // FL's two Switch items, with LYNX's own modes inside (user's decision, round 181b)
  7891. menu.addSubMenu (tr ("Switch all audio clip channels to"), makeSwitchAudioClipsMenu (false));
  7892. menu.addSubMenu (tr ("Switch selected audio clip channels to"), makeSwitchAudioClipsMenu (true));
  7893. menu.addItem (tr ("Lock all playlist tracks to content"), [this] { playlist.runAction ("playlist.lockAllToContent"); });
  7894. menu.addItem (tr ("Unlock all playlist tracks from content"), [this] { playlist.runAction ("playlist.unlockAllFromContent"); });
  7895. menu.addItem (tr ("Reset empty playlist tracks"), [this] { playlist.runAction ("playlist.resetEmptyTracks"); });
  7896. // FL's next item (round 190cd; FL's main menu, rea190bc mainmenu_toolbar-0262): every audio editor loaded in a
  7897. // mixer slot is taken out, its slot left empty. FL asks first and keeps the item enabled with no instance (live
  7898. // check 190cq, shots edison190cd-07a / 07b); LYNX keeps it one undo step.
  7899. menu.addItem (tr ("Remove all Edison instances"), [this] { askRemoveAllEdisonInstances (engine); });
  7900. // greyed until the project has a file, as in FL 2026 (seen in an unsaved project, round 181b)
  7901. menu.addItem (tr ("Delete unused files and save project"), currentFile != juce::File(), false, [this] { deleteUnusedRecordingsAndSave(); });
  7902. // FL's next item (round 190i, issue #116; FL 2026's Tools menu, shots fl2-01 / fl2-02): every plugin editor
  7903. // docked in the desktop (FL's word: Attached) or in a window of its own
  7904. if (nativechild::dockingEnabled())
  7905. {
  7906. juce::PopupMenu editors;
  7907. editors.addItem (tr ("Attached"), [this] { PluginWindows::setAllDetached (engine, false); });
  7908. editors.addItem (tr ("Detached"), [this] { PluginWindows::setAllDetached (engine, true); });
  7909. menu.addSubMenu (tr ("Switch all plugin editors to"), editors);
  7910. }
  7911. {
  7912. juce::PopupMenu declick;
  7913. int mode = 0;
  7914. for (const auto* name : { TR_NOOP ("Out only (no bleeding)"), TR_NOOP ("Transient (no bleeding)"), TR_NOOP ("Transient (bleeding)"),
  7915. TR_NOOP ("Generic (bleeding)"), TR_NOOP ("Smooth (bleeding)"), TR_NOOP ("Crossfade (bleeding)") })
  7916. {
  7917. declick.addItem (tr (name), [this, mode] { changeDeclickOfSelectedClips (mode); });
  7918. ++mode;
  7919. }
  7920. menu.addSubMenu (tr ("Change declicking for selected channels to"), declick);
  7921. }
  7922. menu.addItem (tr ("Collect project samples into a folder..."), [this] { collectSamples(); });
  7923. return menu;
  7924. }
  7925. if (index == 0)
  7926. {
  7927. // FL names the default template in the item ("New (Basic with limiter)", REA_rodada186a); LYNX's own default: "New"
  7928. const auto startTemplate = defaultTemplate();
  7929. menu.addItem ((startTemplate.isLynxDefault() ? tr ("New") : tr ("New") + " (" + templateChoiceName (startTemplate) + ")") + shortcutText ("file.new"),
  7930. [this] { newProject(); });
  7931. menu.addItem (tr ("New project..."), [this] { newProject (true); });
  7932. // FL's File › New from template (REA_rodada186a): the templates, the user's after LYNX's own, then "Change default
  7933. // template..." (FL's last item; it opens Settings › General where the default is chosen)
  7934. juce::PopupMenu templates;
  7935. bool userSection = false;
  7936. for (const auto& choice : availableTemplates())
  7937. {
  7938. if (choice.isLynxDefault())
  7939. continue;
  7940. if (choice.kind == TemplateChoice::Kind::user && ! userSection)
  7941. {
  7942. templates.addSeparator();
  7943. userSection = true;
  7944. }
  7945. templates.addItem (templateChoiceName (choice), [this, choice] {
  7946. confirmDiscard ([this, choice] {
  7947. auto song = makeFromTemplate (choice);
  7948. if (! song)
  7949. {
  7950. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("New from template"),
  7951. tr ("{0} could not be opened.", { templateChoiceName (choice) }));
  7952. return;
  7953. }
  7954. startNewProject (std::move (*song), {});
  7955. });
  7956. });
  7957. }
  7958. templates.addSeparator();
  7959. templates.addItem (tr ("Change default template..."), [this] { openSettings (3); });
  7960. menu.addSubMenu (tr ("New from template"), templates);
  7961. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  7962. // round 190ap: a project that will not open, or crashes while it loads: its plugins stay off until switched on
  7963. menu.addItem (tr ("Open without third-party plugins..."), [this] { chooseFileToOpenWithoutPlugins(); });
  7964. if (engine.pluginsOff())
  7965. menu.addItem (tr ("Switch plugins back on..."), [this] { showPluginsOff(); });
  7966. menu.addSeparator();
  7967. // FL's order (REA round 139): saving, then Export, then the recent projects listed in the menu itself
  7968. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  7969. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  7970. menu.addItem (tr ("Save new version") + shortcutText ("file.saveNewVersion"), [this] { saveNewVersion(); });
  7971. menu.addItem (tr ("Save to new project folder..."), [this] { saveToNewProjectFolder(); });
  7972. menu.addItem (tr ("Save as template..."), [this] { saveAsTemplate(); });
  7973. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  7974. menu.addSeparator();
  7975. {
  7976. // FL's File › Import (ImportMenu › ImportMIDIMenu → FileImportMIDIFileAction, REA round 143)
  7977. juce::PopupMenu imports;
  7978. imports.addItem (tr ("MIDI file..."), [this] { importMidiFile(); });
  7979. imports.addItem (tr ("Video file..."), [this] { videotracks::chooseAndImport (engine, this); }); // round 174d
  7980. menu.addSubMenu (tr ("Import"), imports);
  7981. }
  7982. {
  7983. // FL's File › Export (REA round 139): one entry per format, then the formats of the last export
  7984. juce::PopupMenu exports;
  7985. exports.addItem (tr ("Wave file..."), [this] { exportAudio (0); });
  7986. exports.addItem (tr ("MP3 file...") + shortcutText ("file.exportMp3"), [this] { exportAudio (1); });
  7987. exports.addItem (tr ("OGG file..."), [this] { exportAudio (2); });
  7988. exports.addItem (tr ("FLAC file..."), [this] { exportAudio (3); });
  7989. exports.addItem (tr ("MIDI file...") + shortcutText ("file.exportMidi"), [this] { exportMidiFile(); });
  7990. exports.addItem (tr ("Last exported format(s)...") + shortcutText ("file.export"), [this] { exportAudio(); });
  7991. exports.addSeparator();
  7992. // FL's FileExportMasterAction ("Render the project to a file and master it"; FL Cloud there, on the computer here)
  7993. exports.addItem (tr ("Master...") + shortcutText ("file.exportMaster"), [this] { showMasterDialog (engine, currentFile.getParentDirectory(), projectName); });
  7994. exports.addSeparator();
  7995. // FL's ExportAllPLTracksMenu / ExportAllPLTrackGroupsMenu (FileExportPLTracks… / FileExportPLGroups…, REA round 168e)
  7996. exports.addSubMenu (tr ("All playlist tracks"), playlistTrackExportMenu (false));
  7997. exports.addSubMenu (tr ("All playlist track groups"), playlistTrackExportMenu (true));
  7998. exports.addSeparator();
  7999. exports.addItem (tr ("Project with samples (.zip)..."), [this] { exportPackage(); });
  8000. // Export to FL Studio (round 171e, idea by Tookolld): a .flp or FL's zipped loop package
  8001. exports.addItem (tr ("FL Studio project..."), [this] {
  8002. engine.capturePluginStates();
  8003. showFlStudioExportDialog (engine,
  8004. currentFile != juce::File() ? currentFile.getParentDirectory()
  8005. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  8006. projectStem (projectName));
  8007. });
  8008. // Export to Live 12 / Live 11 (round 175a, N2): "<name> Project/<name>.als" with the samples alongside
  8009. exports.addItem (tr ("Ableton Live set (.als)..."), [this] {
  8010. showAlsExportDialog (engine,
  8011. currentFile != juce::File() ? currentFile.getParentDirectory()
  8012. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory),
  8013. projectStem (projectName));
  8014. });
  8015. // Export for other apps (round 184a, S9): stems, MIDI, a Live set, an FL Studio project, the mixdown and a README
  8016. exports.addItem (tr ("For other apps..."), [this] { exportForOtherApps(); });
  8017. // FL's "Project bones..." (FileExportProjectBonesAction; REA round 168e)
  8018. exports.addItem (tr ("Project bones..."), [this] { exportProjectBones (engine, currentFile.getParentDirectory(), projectName); });
  8019. exports.addItem (tr ("Project data files (collect the samples into a folder)..."), [this] { collectSamples(); });
  8020. menu.addSubMenu (tr ("Export"), exports);
  8021. }
  8022. {
  8023. // Online Sessions, phase 1 (docs/design/ONLINE_SESSIONS.md, round 168a): a project goes to a friend as a
  8024. // .lynxpack, his part comes back the same way
  8025. const auto guestCopy = engine.getSong().session.isGuestCopy();
  8026. juce::PopupMenu online;
  8027. online.addItem (tr ("Send project..."), ! guestCopy, false, [this] { sessionui::sendProject (sessionContext()); });
  8028. online.addItem (tr ("Send my part back..."), guestCopy, false, [this] { sessionui::sendPartBack (sessionContext()); });
  8029. online.addItem (tr ("Merge a part..."), ! guestCopy, false, [this] { sessionui::mergePart (sessionContext()); });
  8030. online.addSeparator();
  8031. liveui::addMenuItems (online, liveContext());
  8032. menu.addSubMenu (tr ("Online session"), online);
  8033. }
  8034. menu.addSectionHeader (tr ("Recent projects"));
  8035. const auto shown = juce::jmin (recent.getNumFiles(), 10);
  8036. for (int i = 0; i < shown; ++i)
  8037. {
  8038. const auto file = recent.getFile (i);
  8039. juce::PopupMenu::Item item (file.getFileName());
  8040. item.shortcutKeyDescription = file.getParentDirectory().getFileName(); // its folder on the right
  8041. item.setEnabled (file.existsAsFile()).setAction ([this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  8042. menu.addItem (std::move (item));
  8043. }
  8044. if (recent.getNumFiles() > shown)
  8045. {
  8046. juce::PopupMenu more;
  8047. for (int i = shown; i < recent.getNumFiles(); ++i)
  8048. {
  8049. const auto file = recent.getFile (i);
  8050. more.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  8051. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  8052. }
  8053. menu.addSubMenu (tr ("More recent projects"), more);
  8054. }
  8055. if (recent.getNumFiles() == 0)
  8056. menu.addItem (tr ("(none)"), false, false, [] {});
  8057. menu.addSeparator();
  8058. menu.addItem (tr ("Versions..."), [this] { showVersions(); }); // round 190ap: the saved versions and the backups in one list
  8059. menu.addItem (tr ("Revert to last backup..."), [this] { revertToLastBackup(); });
  8060. menu.addItem (tr ("Open autosave folder"), [] {
  8061. autosaveFolder().createDirectory();
  8062. autosaveFolder().startAsProcess();
  8063. });
  8064. menu.addSeparator();
  8065. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  8066. }
  8067. else if (index == 1)
  8068. {
  8069. // FL's Edit menu: "Undo backwards" (Ctrl+Alt+Z) above "Undo" (Ctrl+Z: undo, or redo after an undo)
  8070. // ("Alternate undo mode" swaps the two shortcuts, as FL's menu does: round 190b)
  8071. const auto backwardsId = alternateUndo ? "edit.undo" : "edit.undoBackwards";
  8072. const auto toggleId = alternateUndo ? "edit.undoBackwards" : "edit.undo";
  8073. menu.addItem (tr ("Undo backwards") + shortcutText (backwardsId), engine.canUndo(), false, [this] { undoRedo (false); });
  8074. menu.addItem ((engine.canRedo() ? tr ("Undo (redo)") : tr ("Undo")) + shortcutText (toggleId), engine.canUndo() || engine.canRedo(), false,
  8075. [this] { runUndoStep (undokeys::toggle (engine.canUndo(), engine.canRedo())); });
  8076. menu.addItem (tr ("Redo") + shortcutText ("edit.redo"), engine.canRedo(), false, [this] { undoRedo (true); });
  8077. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  8078. menu.addItem (tr ("Audio editor..."), [this] { openAudioEditor (engine); });
  8079. menu.addSeparator();
  8080. menu.addItem (tr ("Plugin picker") + shortcutText ("view.pluginPicker"), [this] { togglePluginPicker(); });
  8081. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  8082. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  8083. showPanel (Panel::browser);
  8084. browser.focusSearch();
  8085. });
  8086. }
  8087. else if (index == 2)
  8088. {
  8089. for (auto panel : panelOrder)
  8090. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  8091. menu.addSeparator();
  8092. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  8093. workspace.toggleMaximised (Panel::playlist);
  8094. refreshPanelButtons();
  8095. });
  8096. {
  8097. juce::PopupMenu detach;
  8098. for (auto panel : panelOrder)
  8099. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  8100. workspace.setDetached (panel, ! workspace.isDetached (panel));
  8101. refreshPanelButtons();
  8102. });
  8103. menu.addSubMenu (tr ("Detached panels (own window)"), detach);
  8104. }
  8105. menu.addSeparator();
  8106. menu.addItem (tr ("Reset layout"), [this] {
  8107. workspace.resetLayout();
  8108. refreshPanelButtons();
  8109. });
  8110. menu.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  8111. menu.addSubMenu (tr ("Load layout"), layoutsMenu());
  8112. addLayoutStyleItems (menu);
  8113. menu.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  8114. menu.addItem (tr ("Close all windows (plugins, channel settings, tools)") + shortcutText ("view.closeWindows"), [this] { runAction ("view.closeWindows"); });
  8115. menu.addItem (tr ("Close all plugin windows") + shortcutText ("view.closePluginWindows"), [this] { runAction ("view.closePluginWindows"); });
  8116. menu.addItem (tr ("Close all windows except the focused one") + shortcutText ("view.closeUnfocusedWindows"), [this] { runAction ("view.closeUnfocusedWindows"); });
  8117. menu.addItem (tr ("Align all channel editors") + shortcutText ("view.alignChannelEditors"), [this] { runAction ("view.alignChannelEditors"); });
  8118. menu.addSeparator();
  8119. menu.addItem (tr ("Plugin database (in the Browser)") + shortcutText ("view.pluginDatabase"), [this] { runAction ("view.pluginDatabase"); });
  8120. menu.addItem (tr ("Audio editor") + shortcutText ("view.audioEditor"), [this] { openAudioEditorForSelection(); });
  8121. menu.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  8122. menu.addItem (tr ("Sample browser (separate window)") + shortcutText ("view.sampleBrowser"), true, findToolWindow ("sampleBrowser") != nullptr,
  8123. [this] { toggleSampleBrowser(); });
  8124. // round 190ch (LYNX's own): the project's lyrics / notes beside the Playlist, and matching a reference track
  8125. menu.addItem (tr ("Lyrics and notes"), true, isLyricsShowing(), [this] { toggleLyrics(); });
  8126. menu.addItem (tr ("Reference match..."), [this] { showReferenceMatch(); });
  8127. menu.addSeparator();
  8128. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  8129. menu.addItem (tr ("Touch keyboard") + shortcutText ("view.touchKeyboard"), true, isTouchKeyboardOpen(), [this] { toggleTouchKeyboard (engine); });
  8130. {
  8131. // FL's View › Background (audit round 165z-a): the workspace image and colour of Options › Theme
  8132. juce::PopupMenu background;
  8133. background.addItem (tr ("Set image wallpaper..."), [] { themeui::setImageWallpaper(); });
  8134. background.addItem (tr ("Remove image wallpaper"), ! themeui::current().image.empty(), false, [] { themeui::removeImageWallpaper(); });
  8135. background.addItem (tr ("Set background color..."), [this] { openSettings ((int) SettingsPage::theme); });
  8136. menu.addSubMenu (tr ("Background"), background);
  8137. }
  8138. menu.addSeparator();
  8139. // FL's "Auto scrolling" (round 162, issue #9)
  8140. menu.addItem (tr ("Playlist follows the playhead (auto scrolling)") + shortcutText ("playlist.follow"), true,
  8141. EditorGlobals::get().isFollowing (false), [this] { runAction ("playlist.follow"); });
  8142. menu.addItem (tr ("Piano Roll follows the playhead (auto scrolling)") + shortcutText ("pianoRoll.follow"), true,
  8143. EditorGlobals::get().isFollowing (true), [this] { runAction ("pianoRoll.follow"); });
  8144. }
  8145. else if (index == 3)
  8146. {
  8147. menu = makePatternMenu();
  8148. }
  8149. else if (index == 4)
  8150. {
  8151. // the Settings window's pages (Settings › General gathers the app options that were menu items here)
  8152. menu.addItem (tr ("Audio settings..."), [this] { openSettings ((int) SettingsPage::audio); });
  8153. menu.addItem (tr ("MIDI settings...") + shortcutText ("view.midiSettings"), [this] { openSettings ((int) SettingsPage::midi); });
  8154. // round 190gl: Ableton Link (LYNX's own in FL's menu: FL has no Link), the switch and its settings page
  8155. menu.addItem (tr ("Ableton Link"), true, engine.getLink().isEnabled(), [this] { engine.setLinkEnabled (! engine.getLink().isEnabled()); });
  8156. menu.addItem (tr ("Ableton Link settings..."), [this] { openSettings ((int) SettingsPage::link); });
  8157. menu.addItem (tr ("General settings...") + shortcutText ("view.settings"), [this] { openSettings ((int) SettingsPage::general); });
  8158. menu.addItem (tr ("Theme (colors, background)..."), [this] { openSettings ((int) SettingsPage::theme); });
  8159. menu.addItem (tr ("File settings (search folders)..."), [this] { openSettings ((int) SettingsPage::files); });
  8160. menu.addItem (tr ("LYNX extras..."), [this] { openSettings ((int) SettingsPage::extras); }); // round 190am
  8161. menu.addItem (tr ("Project settings (tempo, time signature)..."), [this] { openSettings ((int) SettingsPage::project); });
  8162. menu.addItem (tr ("Project info...") + shortcutText ("view.projectInfo"), [this] { openSettings ((int) SettingsPage::info); });
  8163. {
  8164. juce::PopupMenu mixerMenu; // round 163: clean mixer, inserts and Master chain of new projects
  8165. mixeroptions::addItems (mixerMenu, engine, true);
  8166. menu.addSubMenu (tr ("Mixer"), mixerMenu);
  8167. }
  8168. menu.addSeparator();
  8169. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  8170. const auto scanning = engine.getPluginHost().backgroundScan().running;
  8171. menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins ({0})", { platform::pluginFormatNames() }), [this, scanning] {
  8172. if (scanning)
  8173. engine.getPluginHost().cancelBackgroundScan();
  8174. else
  8175. engine.getPluginHost().startBackgroundScan(); // progress in the hint bar; LYNX stays usable
  8176. });
  8177. menu.addItem (tr ("Manage shortcuts..."), [this] { showShortcutManager(); });
  8178. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  8179. menu.addSeparator();
  8180. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  8181. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  8182. });
  8183. // FL's Options menu, "Switches" section (TFruityLoopsMainForm DFM: KBToMIDIMenu = OptionsTypingKbToPianoAction,
  8184. // "Typing keyboard to piano", Ctrl+T, checkable, right before Metronome; round 168t, issue #34)
  8185. menu.addItem (tr ("Typing keyboard to piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { toggleTypingPiano(); });
  8186. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  8187. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  8188. });
  8189. menu.addItem (tr ("Metronome volume ({0})...", { ui::utilityVolumeText (engine.getTransport().metronomeVolume.load()) }),
  8190. [this] { showMetronomeVolume(); });
  8191. {
  8192. // FL's Options › "Auto scrolling" (audit round 165z-a): one switch for every editor's Follow (Playlist,
  8193. // Piano roll, Channel rack, Audio editor); each window's own Follow button still sets just that window
  8194. auto& globals = EditorGlobals::get();
  8195. const auto on = globals.isFollowing (false) && globals.isFollowing (true);
  8196. menu.addItem (tr ("Auto scrolling"), true, on, [on] {
  8197. auto& g = EditorGlobals::get();
  8198. for (auto v : { EditorGlobals::FollowView::playlist, EditorGlobals::FollowView::pianoRoll,
  8199. EditorGlobals::FollowView::channelRack, EditorGlobals::FollowView::audioEditor })
  8200. g.setFollowingView (v, ! on);
  8201. });
  8202. }
  8203. // FL's "Multilink to controllers" (Ctrl+J), the last of FL's Switches (after Auto scrolling and Enable groups;
  8204. // round 177b-4): the controls moved while it is on link, in that order, to the controllers moved next
  8205. menu.addItem (tr ("Multilink to controllers") + shortcutText ("options.multilink"), true, engine.isMultilinkOn(),
  8206. [this] { runAction ("options.multilink"); });
  8207. // round 190ef: the reference's Options › Draw Mode (B), in the Clip-launch layout: a drag in an automation lane
  8208. // draws steps at the grid width, or freehand without a grid (core/DrawMode.h)
  8209. if (layoutStyle == layoutstyle::Style::clipLaunch)
  8210. menu.addItem (tr ("Draw Mode") + sessionkeys::menuKey (sessionkeys::Command::drawMode), true, drawmode::isOn(), [] { drawmode::toggle(); });
  8211. {
  8212. juce::PopupMenu recording;
  8213. addRecordOptions (recording);
  8214. menu.addSubMenu (tr ("Recording"), recording);
  8215. }
  8216. // LYNX's own ADR (round 174d, issue #83): cues, the record cycle with streamers and beeps, takes, comp, Align
  8217. menu.addItem (tr ("ADR (dialogue replacement)..."), [this] { adrwindow::show (engine); });
  8218. {
  8219. // LYNX's own (REA round 153): everything the Master plays, after the fader, goes to a WAV in the background
  8220. auto& logger = engine.getAudioLogger();
  8221. menu.addItem (tr ("Record the Master to a file"), true, logger.isLogging(), [this] {
  8222. auto& log = engine.getAudioLogger();
  8223. if (log.isLogging())
  8224. {
  8225. const auto file = log.currentFile();
  8226. const auto seconds = log.secondsWritten();
  8227. log.stop();
  8228. ui::postHint ({ tr ("Recording of the Master saved: {0} ({1} s)", { file.getFileName(), juce::String (seconds, 1) }), {}, false, false }, 5000);
  8229. }
  8230. else if (! log.start (AudioLogger::defaultFolder(), engine.getTransport().sampleRate.load()))
  8231. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Record the Master to a file"),
  8232. tr ("Could not create a file in {0}", { AudioLogger::defaultFolder().getFullPathName() }));
  8233. else
  8234. ui::postHint ({ tr ("Recording the Master to {0}", { log.currentFile().getFileName() }), {}, false, false }, 5000);
  8235. });
  8236. menu.addItem (tr ("Show the recordings of the Master"), [] {
  8237. const auto folder = AudioLogger::defaultFolder();
  8238. folder.createDirectory();
  8239. folder.startAsProcess();
  8240. });
  8241. }
  8242. menu.addSubMenu (tr ("Toolbar"), makeToolbarMenu());
  8243. menu.addSeparator();
  8244. menu.addItem (tr ("Setup wizard (language, audio, plugin folders)..."), [this] { showSetupWizard(); });
  8245. }
  8246. else
  8247. {
  8248. // round 190dv: the Simple workflow's Welcome screen and first-song tour (only in that workflow)
  8249. if (layoutStyle == layoutstyle::Style::simple && simpleWorkflow != nullptr)
  8250. {
  8251. menu.addItem (simpleWorkflow->tourCanContinue() ? tr ("Continue the first-song tour (step {0} of {1})", { juce::String (simpleWorkflow->tourStep() + 1),
  8252. juce::String (tour::stepCount) })
  8253. : tr ("First-song tour"),
  8254. [this] {
  8255. if (simpleWorkflow != nullptr)
  8256. simpleWorkflow->startOrContinueTour();
  8257. });
  8258. menu.addItem (tr ("Welcome screen..."), [this] {
  8259. if (simpleWorkflow != nullptr)
  8260. simpleWorkflow->showWelcome();
  8261. });
  8262. menu.addSeparator();
  8263. }
  8264. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  8265. menu.addItem (tr ("Missing files..."), [this] { showMissingFiles (false); });
  8266. menu.addItem (tr ("Last project import report"), [this] {
  8267. const auto& r = engine.getImportReport();
  8268. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.partialEffects.empty() && r.missingSamples == 0
  8269. && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
  8270. && engine.getPluginHost().getLoadFailures().isEmpty())
  8271. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"),
  8272. tr ("Nothing to report (no .flp, .als or .flm project imported in this session, or everything was converted)."));
  8273. else
  8274. showImportReport();
  8275. });
  8276. menu.addItem (tr ("Built-in plugins (online list)..."), [] {
  8277. juce::URL ("https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/PLUGINS.md").launchInDefaultBrowser();
  8278. });
  8279. menu.addItem (tr ("Test audio output..."), [this] { showAudioCheck (engine); }); // (round 190gh, B23)
  8280. menu.addItem (tr ("Report a problem..."), [this] { crashreporter::showManualReport (&engine.getDeviceManager()); });
  8281. if (updater::offered()) // (not in the Store build: the Store updates it)
  8282. {
  8283. menu.addItem (tr ("Check for updates..."), [] { updater::checkNow(); });
  8284. // round 190gh (B2): back to the version before the last update
  8285. const auto previous = updater::previousVersion();
  8286. menu.addItem (previous.isNotEmpty() ? tr ("Go back to {0}...", { previous }) : tr ("Go back to the previous version..."),
  8287. [] { updater::goBack(); });
  8288. }
  8289. // round 190fq (LYNX's own): an optional way to donate, next to About in every layout; it never unlocks anything
  8290. menu.addItem (tr ("Support LYNX SHARE..."), [] { support::showSupportWindow(); });
  8291. menu.addItem (tr ("About LYNX SHARE"), [] {
  8292. auto* window = makeAboutWindow().release();
  8293. window->enterModalState (true, juce::ModalCallbackFunction::create ([] (int result) {
  8294. if (result == 2) // "Support LYNX SHARE"
  8295. support::showSupportWindow();
  8296. }),
  8297. true);
  8298. keepAboveMainWindow (*window);
  8299. });
  8300. }
  8301. return menu;
  8302. }
  8303. support::StartupNote& MainComponent::supportNoteForSnapshot()
  8304. {
  8305. if (supportNote == nullptr)
  8306. supportNote = std::make_unique<support::StartupNote> (*this, [this] { return supportNoteMoment(); }, [] { return 0; });
  8307. return *supportNote;
  8308. }
  8309. supportnote::Moment MainComponent::supportNoteMoment()
  8310. {
  8311. supportnote::Moment m;
  8312. m.playing = engine.getTransport().playing.load();
  8313. m.recording = engine.isRecording() || engine.isRecordingAudioTakes();
  8314. m.dialogOpen = juce::ModalComponentManager::getInstance()->getNumModalComponents() > 0 || setupOverlay != nullptr
  8315. || (simpleWorkflow != nullptr && (simpleWorkflow->tourRunning() || (simpleWorkflow->tourForSnapshot() != nullptr
  8316. && simpleWorkflow->tourForSnapshot()->isWelcomeShowing())));
  8317. auto* peer = getPeer();
  8318. m.windowShowing = isShowing() && (peer == nullptr || ! peer->isMinimised());
  8319. return m;
  8320. }
  8321. void MainComponent::startSupportNote (bool quietRun)
  8322. {
  8323. supportNoteForSnapshot().begin (quietRun);
  8324. }
  8325. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  8326. {
  8327. struct Logo final : juce::Component
  8328. {
  8329. Logo() { setSize (300, 150); }
  8330. void paint (juce::Graphics& g) override
  8331. {
  8332. g.drawImageWithin (logoImage(), 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred);
  8333. }
  8334. };
  8335. struct About final : juce::AlertWindow
  8336. {
  8337. About()
  8338. : juce::AlertWindow ("LYNX SHARE " JUCE_APPLICATION_VERSION_STRING,
  8339. tr ("Lightweight C++/JUCE DAW: FL Studio-style patterns and Ableton Live-style clips.\n"
  8340. "Independent implementation: no Image-Line or Ableton code was copied.")
  8341. + "\n\n" + tr ("Logo by {0}", { "w3teal" }) // the community member who made it
  8342. // round 190gl: Ableton Link's credit (GPL-2.0-or-later; THIRD_PARTY.md lists every component)
  8343. + "\n" + tr ("Ableton Link by Ableton AG (GPL 2.0 or later). Every open-source component and its licence: THIRD_PARTY.md"),
  8344. juce::MessageBoxIconType::NoIcon)
  8345. {
  8346. addCustomComponent (&logo);
  8347. // round 190fq: one short line under the logo, and a button to the Support window (Help › Support LYNX SHARE...)
  8348. supportLine.setText (tr ("LYNX SHARE is free and open source. Donations are optional and help it keep going."), juce::dontSendNotification);
  8349. supportLine.setJustificationType (juce::Justification::centred);
  8350. supportLine.setFont (theme::font (theme::type::body));
  8351. supportLine.setColour (juce::Label::textColourId, theme::colour::textSecondary);
  8352. supportLine.setMinimumHorizontalScale (1.0f);
  8353. supportLine.setSize (360, 40);
  8354. addCustomComponent (&supportLine);
  8355. }
  8356. Logo logo;
  8357. juce::Label supportLine;
  8358. };
  8359. auto window = std::make_unique<About>();
  8360. window->addButton (tr ("Support LYNX SHARE"), 2);
  8361. if (auto* supportButton = window->getButton (0))
  8362. supportButton->setComponentID ("about.support");
  8363. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8364. return std::unique_ptr<juce::AlertWindow> (window.release());
  8365. }
  8366. void MainComponent::showLanguageChoice (const juce::String& id)
  8367. {
  8368. if (id == i18n::saved())
  8369. return;
  8370. i18n::save (id);
  8371. const auto restart = [this] {
  8372. confirmDiscard ([] {
  8373. lynx::platform::relaunchApp(); // through the package in the Store build (platform/Package.h)
  8374. juce::JUCEApplication::quit();
  8375. });
  8376. };
  8377. // the message is shown in the language just chosen
  8378. const auto table = i18n::tableText (id);
  8379. const juce::LocalisedStrings strings (table, false);
  8380. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  8381. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX SHARE restarts.")),
  8382. juce::MessageBoxIconType::InfoIcon);
  8383. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8384. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8385. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  8386. if (result == 1)
  8387. restart();
  8388. }),
  8389. true);
  8390. }
  8391. void MainComponent::rememberRecent (const juce::File& file)
  8392. {
  8393. recent.addFile (file);
  8394. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  8395. menuItemsChanged();
  8396. }
  8397. std::unique_ptr<juce::Component> MainComponent::makeHelpContent (const keys::KeyMap* keyMapIn)
  8398. {
  8399. // shortcut sheet: sections of "keys - action" rows, in two columns
  8400. struct Row
  8401. {
  8402. const char* keys;
  8403. const char* action;
  8404. };
  8405. struct Section
  8406. {
  8407. const char* title;
  8408. std::vector<Row> rows;
  8409. };
  8410. static const std::vector<Section> sections {
  8411. { TR_NOOP ("General"),
  8412. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  8413. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  8414. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  8415. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  8416. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  8417. { "Ctrl+R", TR_NOOP ("Export audio") },
  8418. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  8419. { "L", TR_NOOP ("Pattern / song mode") },
  8420. { "Ctrl+T", TR_NOOP ("Typing keyboard to piano on/off") },
  8421. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  8422. { "Numpad +/-", TR_NOOP ("Next / previous pattern") },
  8423. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  8424. { TR_NOOP ("Workspace"),
  8425. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  8426. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  8427. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  8428. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  8429. { TR_NOOP ("Channel Rack and Mixer"),
  8430. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  8431. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  8432. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  8433. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  8434. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  8435. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  8436. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  8437. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  8438. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  8439. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  8440. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  8441. { "Piano Roll",
  8442. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  8443. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  8444. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  8445. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  8446. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  8447. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  8448. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  8449. { "Alt+M / Shift+Alt+M", TR_NOOP ("Mute / unmute") },
  8450. { "Ctrl+P / Ctrl+D", TR_NOOP ("Portamento / deselect") },
  8451. { TR_NOOP ("Shift+arrows"), TR_NOOP ("Transpose a semitone / move by the grid (Ctrl+Up/Down: an octave)") },
  8452. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  8453. { "Playlist",
  8454. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  8455. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  8456. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  8457. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  8458. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  8459. };
  8460. // the fourth column: every F-key of the live key map (issue #23: the sheet listed no F-keys), custom keys included
  8461. const keys::KeyMap defaults;
  8462. const auto& map = keyMapIn != nullptr ? *keyMapIn : defaults;
  8463. std::vector<std::pair<juce::String, juce::String>> functionKeys;
  8464. for (const auto& b : map.functionKeyBindings())
  8465. if (const auto* action = keys::findAction (b.actionId))
  8466. {
  8467. auto text = tr (action->description);
  8468. if (b.context != keys::Context::global)
  8469. text << " (" << tr (b.context == keys::Context::browser ? "Browser"
  8470. : b.context == keys::Context::mixer ? "Mixer"
  8471. : b.context == keys::Context::playlist ? "Playlist"
  8472. : b.context == keys::Context::pianoRoll ? "Piano Roll"
  8473. : "Channel Rack")
  8474. << ")";
  8475. functionKeys.push_back ({ juce::String (keys::displayString (b.chord)), text });
  8476. }
  8477. struct Sheet final : juce::Component
  8478. {
  8479. explicit Sheet (std::vector<std::pair<juce::String, juce::String>> f) : fkeys (std::move (f))
  8480. {
  8481. setSize (1500, juce::jmax (520, 20 + 28 + (int) fkeys.size() * 22 + 20));
  8482. }
  8483. void paint (juce::Graphics& g) override
  8484. {
  8485. using namespace theme;
  8486. g.fillAll (colour::bg2);
  8487. const auto columnWidth = (getWidth() - 5 * 24) / 4;
  8488. int column = 0, y = 20;
  8489. for (std::size_t i = 0; i < sections.size(); ++i)
  8490. {
  8491. if (i == 2 || i == 3) // next column
  8492. {
  8493. ++column;
  8494. y = 20;
  8495. }
  8496. const auto x = 24 + column * (columnWidth + 24);
  8497. const auto& section = sections[i];
  8498. g.setColour (colour::accent);
  8499. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  8500. g.setColour (colour::textPrimary);
  8501. g.setFont (font (type::title, true));
  8502. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  8503. y += 28;
  8504. for (const auto& row : section.rows)
  8505. {
  8506. const auto keys = tr (row.keys);
  8507. g.setFont (font (type::small, true));
  8508. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  8509. g.setColour (colour::bg4);
  8510. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  8511. g.setColour (colour::textPrimary);
  8512. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  8513. g.setColour (colour::textSecondary);
  8514. g.setFont (font (type::body));
  8515. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  8516. y += 24;
  8517. }
  8518. y += 14;
  8519. }
  8520. // Function keys
  8521. const auto x = 24 + 3 * (columnWidth + 24);
  8522. y = 20;
  8523. g.setColour (colour::accent);
  8524. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  8525. g.setColour (colour::textPrimary);
  8526. g.setFont (font (type::title, true));
  8527. g.drawText (tr ("Function keys"), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  8528. y += 28;
  8529. g.setFont (font (type::small, true));
  8530. int keyWidth = 0;
  8531. for (const auto& [keys, text] : fkeys)
  8532. keyWidth = juce::jmax (keyWidth, juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14);
  8533. for (const auto& [keys, text] : fkeys)
  8534. {
  8535. g.setFont (font (type::small, true));
  8536. g.setColour (colour::bg4);
  8537. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  8538. g.setColour (colour::textPrimary);
  8539. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  8540. g.setColour (colour::textSecondary);
  8541. g.setFont (font (type::body));
  8542. g.drawFittedText (text, x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.8f);
  8543. y += 22;
  8544. }
  8545. }
  8546. std::vector<std::pair<juce::String, juce::String>> fkeys;
  8547. };
  8548. return std::make_unique<Sheet> (std::move (functionKeys));
  8549. }
  8550. void MainComponent::showHelp()
  8551. {
  8552. juce::DialogWindow::LaunchOptions options;
  8553. options.content.setOwned (makeHelpContent (&keyMap).release());
  8554. options.dialogTitle = tr ("LYNX SHARE shortcuts");
  8555. options.dialogBackgroundColour = theme::colour::bg2;
  8556. options.useNativeTitleBar = true;
  8557. options.resizable = true;
  8558. options.escapeKeyTriggersCloseButton = true;
  8559. if (auto* dialog = options.launchAsync())
  8560. {
  8561. keepAboveMainWindow (*dialog);
  8562. helpWindow = dialog;
  8563. }
  8564. }
  8565. void MainComponent::closeHelp()
  8566. {
  8567. // (the key may come from the sheet itself: delete it after this call stack)
  8568. if (helpWindow == nullptr)
  8569. return;
  8570. helpWindow->setVisible (false);
  8571. juce::MessageManager::callAsync ([w = helpWindow] { delete w.getComponent(); });
  8572. helpWindow = nullptr;
  8573. }
  8574. void MainComponent::closeUnfocusedWindows()
  8575. {
  8576. // FL's Ctrl+F12 (CloseAllUnfocusedWindowsAction, round 167o): every window but the focused one closes. LYNX's
  8577. // docked or detached panels and dialogs that wait for an answer stay, as for F12.
  8578. auto* focused = juce::TopLevelWindow::getActiveTopLevelWindow();
  8579. auto* main = getTopLevelComponent();
  8580. juce::Array<juce::Component::SafePointer<juce::DocumentWindow>> close;
  8581. for (int i = 0; i < juce::TopLevelWindow::getNumTopLevelWindows(); ++i)
  8582. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (i)))
  8583. if (w != focused && w != main && w->isVisible() && ! w->isCurrentlyModal() && ! (bool) w->getProperties()["lynxPanel"])
  8584. close.add (w);
  8585. for (auto& w : close)
  8586. if (w != nullptr)
  8587. w->closeButtonPressed();
  8588. }
  8589. void MainComponent::showSetupWizard()
  8590. {
  8591. // on top of the main window (round 140), so the DAW is visible behind it from the first start on
  8592. if (setupOverlay != nullptr)
  8593. return;
  8594. auto safe = juce::Component::SafePointer<MainComponent> (this);
  8595. setupOverlay = lynx::makeSetupWizardOverlay (
  8596. engine,
  8597. [safe] (const juce::String& language) {
  8598. if (safe != nullptr)
  8599. safe->showLanguageChoice (language);
  8600. },
  8601. [safe] {
  8602. juce::MessageManager::callAsync ([safe] { // the overlay's own button is still running
  8603. if (safe != nullptr)
  8604. safe->setupOverlay.reset();
  8605. });
  8606. },
  8607. (int) layoutStyle,
  8608. [safe] (int style) { // round 184a S17: the workflow chosen in the wizard (Pattern stays selected unless changed)
  8609. juce::MessageManager::callAsync ([safe, style] {
  8610. if (safe == nullptr)
  8611. return;
  8612. safe->setLayoutStyle ((layoutstyle::Style) juce::jlimit (0, layoutstyle::count - 1, style));
  8613. safe->saveUiSettings();
  8614. });
  8615. });
  8616. addAndMakeVisible (*setupOverlay);
  8617. setupOverlay->setBounds (getLocalBounds());
  8618. setupOverlay->toFront (true);
  8619. hostSetupOverlayNatively();
  8620. }
  8621. void MainComponent::showImportReport()
  8622. {
  8623. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  8624. const auto& r = engine.getImportReport();
  8625. const auto& missing = engine.getMissingPlugins();
  8626. auto list = [] (const std::map<std::string, int>& items) {
  8627. std::vector<std::pair<int, std::string>> sorted;
  8628. for (const auto& [name, count] : items)
  8629. sorted.push_back ({ count, name });
  8630. std::sort (sorted.rbegin(), sorted.rend());
  8631. juce::StringArray lines;
  8632. for (const auto& [count, name] : sorted)
  8633. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  8634. return lines.joinIntoString ("\n");
  8635. };
  8636. juce::String text;
  8637. if (! r.approximated.empty())
  8638. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  8639. if (! r.unsupported.empty())
  8640. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  8641. if (const auto& matched = engine.getMatchedPlugins(); ! matched.isEmpty())
  8642. text << tr ("Plugins found on this PC:") << "\n " << matched.joinIntoString ("\n ") << "\n\n";
  8643. if (! missing.isEmpty())
  8644. text << tr ("Plugins not installed on this PC (or in a folder LYNX SHARE doesn't scan; Options > Setup wizard):") << "\n "
  8645. << missing.joinIntoString ("\n ") << "\n\n";
  8646. if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
  8647. text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n "
  8648. << lost.joinIntoString ("\n ") << "\n\n";
  8649. if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
  8650. text << tr ("Plugins installed but not loaded (silent):") << "\n " << failed.joinIntoString ("\n ") << "\n\n";
  8651. if (! r.droppedEffects.empty())
  8652. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  8653. if (! r.partialEffects.empty())
  8654. text << tr ("Effects kept but approximated or partly reproduced:") << "\n" << list (r.partialEffects) << "\n\n";
  8655. if (r.missingSamples > 0)
  8656. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  8657. if (r.relocatedSamples > 0)
  8658. text << tr ("Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}",
  8659. { juce::String (r.relocatedSamples) }) << "\n";
  8660. if (text.isNotEmpty())
  8661. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Project import"), text.trimEnd());
  8662. }
  8663. void MainComponent::showAudioSettings()
  8664. {
  8665. openSettings ((int) SettingsPage::audio);
  8666. }
  8667. // --- the Channel Rack's filter box ---------------------------------------------------------------
  8668. void MainComponent::FilterBox::paint (juce::Graphics& g)
  8669. {
  8670. using namespace theme;
  8671. auto area = getLocalBounds().toFloat();
  8672. g.setColour (hovered ? colour::bg3 : colour::bg1);
  8673. g.fillRoundedRectangle (area, radius::sm);
  8674. g.setColour (hovered ? colour::borderStrong : colour::border);
  8675. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  8676. // round 170e2: a funnel names the box (it showed only "All")
  8677. icons::draw (g, Icon::filter, area.withWidth (22.0f).withSizeKeepingCentre (13.0f, 13.0f), colour::textSecondary);
  8678. g.setColour (colour::textPrimary);
  8679. g.setFont (font (type::small));
  8680. g.drawText (text, getLocalBounds().withTrimmedLeft (22).withTrimmedRight (16), juce::Justification::centredLeft, true);
  8681. icons::draw (g, Icon::chevronDown, area.removeFromRight (16.0f).reduced (3.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  8682. }
  8683. // FL's Tools › Macros › Prepare for performance mode ([DECOMP] FUN_0122d010, its "Marker settings" dialog: marker count
  8684. // 4 / 8 / 16 / 32 / 64, default 16; spacing 1…128 steps, default 16 = a bar): room for a launch grid before the song,
  8685. // a marker per column, a Start marker, Performance mode on, the zone in view. FL warns it can't be undone; in LYNX it
  8686. // is one undo step.
  8687. void MainComponent::prepareForPerformance()
  8688. {
  8689. auto* window = new juce::AlertWindow (tr ("Prepare for performance mode"),
  8690. tr ("Inserts empty columns before the song for the clips to launch, a marker on each, and a Start "
  8691. "marker where the song begins; Performance mode is turned on."),
  8692. juce::MessageBoxIconType::NoIcon);
  8693. window->addComboBox ("count", { "4", "8", "16", "32", "64" }, tr ("Marker count"));
  8694. window->addComboBox ("spacing", { tr ("1 step"), tr ("2 steps"), tr ("1 beat"), tr ("2 beats"), tr ("1 bar"), tr ("2 bars"), tr ("4 bars"), tr ("8 bars") },
  8695. tr ("Spacing"));
  8696. if (auto* c = window->getComboBoxComponent ("count"))
  8697. c->setSelectedItemIndex (2, juce::dontSendNotification);
  8698. if (auto* c = window->getComboBoxComponent ("spacing"))
  8699. c->setSelectedItemIndex (4, juce::dontSendNotification);
  8700. window->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  8701. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  8702. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  8703. if (result != 1)
  8704. return;
  8705. const auto count = 4 << juce::jlimit (0, 4, window->getComboBoxComponent ("count")->getSelectedItemIndex());
  8706. const auto steps = 1 << juce::jlimit (0, 7, window->getComboBoxComponent ("spacing")->getSelectedItemIndex());
  8707. engine.editSong ([count, steps] (Song& s) { perf::prepareForPerformance (s, count, (std::int64_t) steps * (ppq / 4)); });
  8708. showPanel (Panel::playlist);
  8709. playlist.runAction ("playlist.zoomPerformance");
  8710. }),
  8711. true);
  8712. keepAboveMainWindow (*window);
  8713. }
  8714. } // namespace lynx
  8715. // --- the game controller (round 184a, S16) ---------------------------------------------------------------------------
  8716. namespace lynx
  8717. {
  8718. void MainComponent::updateGamepad()
  8719. {
  8720. const auto on = engine.getMidiPrefs().gamepad;
  8721. if (on == (gamepadInput != nullptr))
  8722. return;
  8723. if (! on)
  8724. {
  8725. gamepadInput.reset();
  8726. if (gamepadHints != nullptr)
  8727. removeChildComponent (gamepadHints.get());
  8728. gamepadHints.reset();
  8729. return;
  8730. }
  8731. gamepadInput = std::make_unique<GamepadInput> ([safe = juce::Component::SafePointer<MainComponent> (this)] (const gamepad::Changes& c,
  8732. const gamepad::State& s, double dt) {
  8733. if (safe != nullptr)
  8734. safe->gamepadChanges (c, s, dt);
  8735. });
  8736. if (! gamepadInput->available())
  8737. ui::postHint ({ tr ("Game controllers are not supported on this system yet."), {} }, 5000);
  8738. }
  8739. int MainComponent::gamepadInsert() const
  8740. {
  8741. const auto& song = engine.getSong();
  8742. const auto track = playlist.getCurrentTrack();
  8743. if (track >= 0 && track < (int) song.playlistTracks.size())
  8744. if (const auto insert = song.playlistTracks[(std::size_t) track].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  8745. return insert;
  8746. const auto channel = engine.getSelectedChannel();
  8747. if (channel >= 0 && channel < (int) song.channels.size())
  8748. if (const auto insert = song.channels[(std::size_t) channel].mixerTrack; insert >= 0 && insert < (int) song.mixer.size())
  8749. return insert;
  8750. return -1;
  8751. }
  8752. void MainComponent::gamepadChanges (const gamepad::Changes& c, const gamepad::State& s, double seconds)
  8753. {
  8754. using namespace gamepad;
  8755. // every change is also a MIDI controller on channel 16, so Link to controller can learn it
  8756. for (int i = 0; i < c.controllerCount; ++i)
  8757. engine.injectMidiInput (juce::MidiMessage::controllerEvent (midiChannel, c.controller[(std::size_t) i], c.value[(std::size_t) i]));
  8758. if (c.connectedChanged)
  8759. ui::postHint ({ s.connected ? tr ("Game controller connected") : tr ("Game controller disconnected"), {} }, 3000);
  8760. const auto& map = defaultMap();
  8761. for (int i = 0; i < c.pressedCount; ++i)
  8762. {
  8763. const auto action = map[(std::size_t) c.pressed[(std::size_t) i]];
  8764. switch (action)
  8765. {
  8766. case Action::playStop: runAction ("transport.playStop"); break;
  8767. case Action::record: runAction ("transport.record"); break;
  8768. case Action::undo: runAction ("edit.undo"); break;
  8769. case Action::metronome: runAction ("transport.metronome"); break;
  8770. case Action::previousPattern: runAction ("pattern.previous"); break;
  8771. case Action::nextPattern: runAction ("pattern.next"); break;
  8772. case Action::finish: runAction ("file.export"); break;
  8773. case Action::previousTrack:
  8774. case Action::nextTrack:
  8775. {
  8776. const auto t = playlist.getCurrentTrack();
  8777. playlist.selectTrack (t < 0 ? 0 : t + (action == Action::nextTrack ? 1 : -1));
  8778. const auto& song = engine.getSong();
  8779. const auto now = playlist.getCurrentTrack();
  8780. if (now >= 0 && now < (int) song.playlistTracks.size())
  8781. if (const auto ch = song.playlistTracks[(std::size_t) now].channel; ch >= 0 && ch < (int) song.channels.size())
  8782. engine.setSelectedChannel (ch); // an instrument track: its channel plays the keys
  8783. break;
  8784. }
  8785. case Action::barBack:
  8786. case Action::barForward:
  8787. {
  8788. // to the previous / next bar line (from inside a bar, back goes to its start)
  8789. const auto bar = (double) engine.getSong().barTicks();
  8790. const auto at = engine.getTransport().positionTicks.load() / bar;
  8791. const auto target = action == Action::barForward ? std::floor (at + 1e-6) + 1.0 : std::ceil (at - 1e-6) - 1.0;
  8792. engine.seek (juce::jmax (0.0, target) * bar);
  8793. break;
  8794. }
  8795. case Action::hints:
  8796. if (gamepadHints == nullptr)
  8797. {
  8798. gamepadHints = makeGamepadHints();
  8799. addChildComponent (*gamepadHints);
  8800. }
  8801. gamepadHints->setCentrePosition (getLocalBounds().getCentre());
  8802. gamepadHints->setVisible (true);
  8803. gamepadHints->toFront (false);
  8804. break;
  8805. case Action::none:
  8806. break;
  8807. }
  8808. }
  8809. for (int i = 0; i < c.releasedCount; ++i)
  8810. if (map[(std::size_t) c.released[(std::size_t) i]] == Action::hints && gamepadHints != nullptr)
  8811. gamepadHints->setVisible (false);
  8812. // the triggers: the selected track's volume; the left stick's X: its pan (only while pushed)
  8813. const auto insert = gamepadInsert();
  8814. if (insert < 0)
  8815. return;
  8816. if (const auto db = volumeStepDb (s, seconds); db != 0.0)
  8817. engine.editLevels ([insert, db] (Song& song) {
  8818. auto& v = song.mixer[(std::size_t) insert].volume;
  8819. v = juce::jlimit (0.0f, 1.0f, faderPosition (faderGain (v) * juce::Decibels::decibelsToGain ((float) db)));
  8820. });
  8821. if (const auto pan = axis (s, Axis::leftX); pan != 0.0f)
  8822. engine.editLevels ([insert, pan] (Song& song) { song.mixer[(std::size_t) insert].pan = juce::jlimit (-1.0f, 1.0f, pan); });
  8823. }
  8824. } // namespace lynx