MainComponent.cpp 266 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352
  1. #include "ui/ThemeSettings.h"
  2. #include "ui/ColourPicker.h"
  3. #include "core/NoteNames.h"
  4. #include "ui/ProjectLoading.h"
  5. #include "ui/UiTrace.h"
  6. #include "core/LoadTrace.h"
  7. #include "ui/MainComponent.h"
  8. #include "core/Performance.h"
  9. #include "core/TransportEdit.h"
  10. #include "ui/CrashReporter.h"
  11. #include "ui/DanceView.h"
  12. #include "engine/AudioLogger.h"
  13. #include "ui/PluginSkin.h"
  14. #include "platform/Paths.h"
  15. #include "ui/SetupWizard.h"
  16. #include "core/FlPluginDb.h"
  17. #include "core/Preferences.h"
  18. #include "core/EditorPolish.h"
  19. #include "ui/HistoryPanel.h"
  20. #include "ui/MissingFilesDialog.h"
  21. #include "ui/SettingsDialog.h"
  22. #include "ui/PluginManager.h"
  23. #include "ui/ShortcutManager.h"
  24. #include "ui/WaveformView.h"
  25. #include "ui/QuickAddPalette.h"
  26. #include "ui/PatcherEditor.h"
  27. #include "ui/ToolWindow.h"
  28. #include "ui/LoopStarterWindow.h"
  29. #include "ui/WindowOwner.h"
  30. #include "engine/PluginSandbox.h"
  31. #include "platform/FileTypes.h"
  32. #include "platform/CrashGuard.h"
  33. #include "platform/LinuxRealtime.h"
  34. #include "platform/Package.h"
  35. #include "engine/Text.h"
  36. #include "core/MetronomeVoice.h"
  37. #include "core/RackOps.h"
  38. #include "core/Templates.h"
  39. #include "ui/NewProjectDialog.h"
  40. #include "ui/PluginMonitorWindow.h"
  41. #include "ui/TouchKeyboard.h"
  42. #include "engine/MidiFileIo.h"
  43. #include "engine/ProjectFile.h"
  44. #include "engine/ProjectPackage.h"
  45. #include "core/ProjectSafety.h"
  46. #include "core/MissingFiles.h"
  47. #include "ui/AutomationUi.h"
  48. #include "ui/ChannelSettings.h"
  49. #include "ui/Dialogs.h"
  50. #include "ui/EditorTools.h"
  51. #include "ui/AudioEditor.h"
  52. #include "ui/TempoTapper.h"
  53. #include "ui/ExportDialog.h"
  54. #include "ui/ParametricEqEditor.h"
  55. #include "ui/PluginWindow.h"
  56. #include "ui/I18n.h"
  57. #include "ui/Theme.h"
  58. #include "ui/WaveformView.h"
  59. #include "core/HintMarkup.h"
  60. #include "core/SongStats.h"
  61. namespace lynx
  62. {
  63. namespace
  64. {
  65. using workspace::Panel;
  66. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  67. const char* panelAction (Panel p)
  68. {
  69. switch (p)
  70. {
  71. case Panel::playlist: return "panel.playlist";
  72. case Panel::channelRack: return "panel.channelRack";
  73. case Panel::pianoRoll: return "panel.pianoRoll";
  74. case Panel::mixer: return "panel.mixer";
  75. case Panel::browser: return "panel.browser";
  76. }
  77. return "";
  78. }
  79. juce::String panelName (Panel p)
  80. {
  81. switch (p)
  82. {
  83. case Panel::playlist: return "Playlist";
  84. case Panel::channelRack: return "Channel Rack";
  85. case Panel::pianoRoll: return "Piano Roll";
  86. case Panel::mixer: return "Mixer";
  87. case Panel::browser: return "Browser";
  88. }
  89. return {};
  90. }
  91. } // namespace
  92. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  93. : persistent (restoreUserSettings),
  94. engine (e),
  95. rack (e),
  96. pianoRoll (e),
  97. playlist (e),
  98. mixer (e),
  99. browser (e)
  100. {
  101. heldKeys.setSender ([this] (int channel, int key, float velocity, bool on) { engine.sendLiveNote (channel, key, velocity, on, true); });
  102. connectBrowser (browser);
  103. addChildComponent (updateBar);
  104. updateBar.onVisibilityChanged = [this] { resized(); };
  105. if (restoreUserSettings) // (the real window: Update saves the project as on quit and reopens it)
  106. updater::setHost ({ [safe = juce::Component::SafePointer<MainComponent> (this)] (std::function<void()> then) {
  107. if (safe != nullptr)
  108. safe->confirmDiscard (std::move (then));
  109. },
  110. [safe = juce::Component::SafePointer<MainComponent> (this)] {
  111. return safe != nullptr ? safe->currentFile : juce::File();
  112. } });
  113. mixeroptions::changed = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  114. if (safe != nullptr)
  115. {
  116. safe->saveUiSettings();
  117. safe->playlist.repaint();
  118. }
  119. };
  120. mixeroptions::setShowUsedOnly = [safe = juce::Component::SafePointer<MainComponent> (this)] (bool on) {
  121. if (safe != nullptr)
  122. safe->mixer.getStripsForSnapshot().setShowUsedOnly (on);
  123. };
  124. mixeroptions::renderTracks = [safe = juce::Component::SafePointer<MainComponent> (this)] (std::vector<int> tracks,
  125. std::function<void (const std::vector<juce::File>&)> done) {
  126. if (safe != nullptr)
  127. showExportDialogForTracks (safe->engine, safe->currentFile.getParentDirectory(), safe->projectName, tracks, std::move (done));
  128. };
  129. if (persistent)
  130. {
  131. loadUiSettings();
  132. // the start-up song follows Options › Mixer too (round 163) and the automatic crossfades of new projects (166e)
  133. engine.setSong (makeNewProject());
  134. skin::onStyleSettingsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // an editor's own style was picked
  135. if (safe != nullptr) safe->saveUiSettings();
  136. };
  137. loadKeyMap();
  138. startSession();
  139. if (BrowserComponent::sampleBrowserWasOpen()) // it was open when LYNX closed (round 163)
  140. juce::Timer::callAfterDelay (800, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  141. if (safe != nullptr && findToolWindow ("sampleBrowser") == nullptr)
  142. safe->openSampleBrowser();
  143. });
  144. EditorGlobals::get().onOptionsChanged = [safe = juce::Component::SafePointer<MainComponent> (this)] { // Follow on/off
  145. if (safe != nullptr) safe->saveUiSettings();
  146. };
  147. }
  148. PianoRollComponent::shortcutText = [this] (const std::string& id) { return shortcutText (id.c_str()); };
  149. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  150. newButton.onClick = [this] { newProject(); };
  151. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  152. openButton.onClick = [this] { chooseFileToOpen(); };
  153. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  154. saveButton.onClick = [this] { save (false); };
  155. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  156. exportButton.onClick = [this] { exportAudio(); };
  157. auto withKey = [this] (const juce::String& text, const char* id) {
  158. const auto key = shortcutText (id).trim();
  159. return key.isEmpty() ? text : text + " (" + key + ")";
  160. };
  161. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  162. undoButton.onClick = [this] { flUndo(); }; // FL's toolbar Undo is its Edit › Undo (UndoAction)
  163. undoButton.onRightClick = [this] { showHistory(); };
  164. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  165. redoButton.onClick = [this] { undoRedo (true); };
  166. redoButton.onRightClick = [this] { showHistory(); };
  167. pluginPickerButton.setTooltip (withKey (tr ("Plugin picker: add an instrument or plugin as a new channel"), "panel.quickAdd"));
  168. pluginPickerButton.onClick = [this] { showQuickAdd(); };
  169. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  170. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  171. playButton.onClick = [this] { playStop(); };
  172. stopButton.setTooltip (tr ("Stop and return to the start (double-click: back to the start and all notes off)"));
  173. stopButton.onClick = [this] { stopAndRewind(); };
  174. stopButton.onDoubleClick = [this] { // FL-like: a double Stop goes back to the very start (and silences hanging notes)
  175. engine.panic();
  176. stopAndRewind (true);
  177. };
  178. stopButton.onRightClick = [this] { showStopMenu(); };
  179. output.onModeChanged = [this] { saveUiSettings(); };
  180. recordButton.setOnColour (theme::colour::record);
  181. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  182. recordButton.onClick = [this] { toggleRecording(); };
  183. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  184. recordMenuButton.onClick = [this] { showRecordMenu(); };
  185. recordButton.onRightClick = [this] { showRecordMenu(); };
  186. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  187. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  188. patternModeButton.setText (tr ("Pattern"));
  189. songModeButton.setText (tr ("Song"));
  190. for (auto* b : { &patternModeButton, &songModeButton })
  191. {
  192. b->setOnColour (theme::colour::bg6);
  193. b->setIconColourWhenOn (theme::colour::textPrimary);
  194. }
  195. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  196. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  197. patternModeButton.onClick = [this] {
  198. if (engine.getSong().mode != PlayMode::pattern)
  199. toggleMode();
  200. };
  201. songModeButton.onClick = [this] {
  202. if (engine.getSong().mode != PlayMode::song)
  203. toggleMode();
  204. };
  205. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  206. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  207. metronomeButton.setClickingTogglesState (true);
  208. metronomeButton.setOnColour (theme::colour::bg6);
  209. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  210. metronomeButton.setTooltip (tr ("Metronome"));
  211. metronomeButton.onClick = [this] { engine.getTransport().metronome.store (metronomeButton.getToggleState()); };
  212. midiLight.onReconnect = [this] {
  213. engine.reconnectMidiInputs();
  214. midiInputTicks = 0; // shows the reopened inputs at the next tick
  215. };
  216. metronomeButton.onRightClick = [this] { showMetronomeMenu(); };
  217. typingPianoButton.setOnColour (theme::colour::bg6);
  218. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  219. typingPianoButton.onClick = [this] { setTypingPiano (! typingPiano); };
  220. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  221. for (auto* b : { &countInButton, &waitInputButton })
  222. {
  223. b->setOnColour (theme::colour::bg6);
  224. b->setIconColourWhenOn (theme::colour::accent);
  225. }
  226. countInButton.onClick = [this] { runAction ("record.countIn"); };
  227. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  228. for (int i = 0; i < workspace::panelCount; ++i)
  229. {
  230. const auto panel = (Panel) i;
  231. auto& b = panelButtons[(std::size_t) i];
  232. b.setFlat (true);
  233. b.setOnColour (theme::colour::bg5);
  234. b.setIconColourWhenOn (theme::colour::textPrimary);
  235. b.setTooltip (panelName (panel) + " (" + keys::toString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  236. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  237. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  238. b.onClick = [this, panel] { togglePanel (panel); };
  239. b.onRightClick = [this, panel] {
  240. showPanel (panel);
  241. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  242. workspace.toggleMaximised (panel);
  243. refreshPanelButtons();
  244. };
  245. }
  246. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  247. patternBox.setScrollWheelEnabled (true);
  248. gridBox.setScrollWheelEnabled (true);
  249. patternBox.onChange = [this]
  250. {
  251. const auto index = patternBox.getSelectedItemIndex();
  252. if (index >= 0 && index != engine.getSong().currentPattern)
  253. selectPattern (index);
  254. };
  255. newPatternButton.setTooltip (tr ("New pattern"));
  256. newPatternButton.onClick = [this]
  257. {
  258. engine.editSong ([] (Song& s) {
  259. Pattern p;
  260. p.name = newPatternName (s);
  261. s.patterns.push_back (std::move (p));
  262. s.currentPattern = (int) s.patterns.size() - 1;
  263. });
  264. };
  265. swingSlider.setRange (0.0, 1.0, 0.01);
  266. swingSlider.setDoubleClickReturnValue (true, 0.0);
  267. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  268. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  269. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  270. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  271. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  272. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  273. swingSlider.setWantsKeyboardFocus (false);
  274. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  275. patternMenuButton.onClick = [this] { showPatternMenu(); };
  276. // the workspace panels
  277. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  278. mixerinput::openAudioSettings = [this] { openSettings ((int) SettingsPage::audio); };
  279. PatcherWindows::onBrowsePluginDatabase = [this] (bool) {
  280. showPanel (Panel::browser);
  281. browser.showPluginDatabaseForSnapshot(); // (its Generators and Effects folders open)
  282. if (auto* w = getTopLevelComponent())
  283. w->toFront (true);
  284. };
  285. rack.onOpenMixerInsert = [this] (int insert) { // double-click on a channel's route box
  286. showPanel (Panel::mixer);
  287. mixer.selectTrack (insert);
  288. };
  289. mixer.onInstrumentDropped = [this] (int insert, ChannelDef c) { rack.addChannel (std::move (c), true, insert); };
  290. rackViewport.setViewedComponent (&rack, false);
  291. rackViewport.setScrollBarsShown (true, true);
  292. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  293. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  294. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  295. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  296. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  297. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  298. // FL keeps the channel filter, the global swing and the graph editor switch in the rack's title bar
  299. rackFilterBox.text = rack.filterName();
  300. rackFilterBox.onClick = [this] { rack.showFilterMenu (&rackFilterBox); };
  301. rack.onFilterChanged = [this] {
  302. rackFilterBox.text = rack.filterName();
  303. rackFilterBox.repaint();
  304. rackGraphButton.setToggleState (rack.areGraphLanesShown(), juce::dontSendNotification);
  305. rackPianoRollButton.setToggleState (rack.isPianoRollView(), juce::dontSendNotification);
  306. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  307. };
  308. rackGraphButton.setClickingTogglesState (false);
  309. rackGraphButton.onClick = [this] { rack.toggleGraphLanes(); };
  310. // the step sequencer / piano-roll view switch (FL keeps it in the rack's title bar too)
  311. rackPianoRollButton.setClickingTogglesState (false);
  312. rackPianoRollButton.setOnColour (theme::colour::bg6);
  313. rackPianoRollButton.setIconColourWhenOn (theme::colour::accent);
  314. rackPianoRollButton.onClick = [this] { runAction ("rack.pianoRollView"); };
  315. ui::setHint (rackPianoRollButton, tr ("Piano-roll view: every channel shows its notes as a miniature piano roll (click one to edit it) "
  316. "instead of the step buttons; click again for the steps"));
  317. rackTitleTools.addAndMakeVisible (rackPianoRollButton);
  318. // Follow (issue #12): a long pattern pages along with the playing step
  319. rackFollowButton.setClickingTogglesState (false);
  320. rackFollowButton.setOnColour (theme::colour::bg6);
  321. rackFollowButton.setIconColourWhenOn (theme::colour::accent);
  322. rackFollowButton.setWantsKeyboardFocus (false);
  323. rackFollowButton.setMouseClickGrabsKeyboardFocus (false);
  324. rackFollowButton.setToggleState (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  325. rackFollowButton.setTooltip (tr ("Follow: a pattern longer than the Channel Rack pages along with the playing step; off, it stays where you scrolled"));
  326. ui::setQuickTip (rackFollowButton, tr ("Follow the playhead"));
  327. rackFollowButton.onClick = [this] { runAction ("rack.follow"); };
  328. rackTitleTools.addAndMakeVisible (rackFollowButton);
  329. // FL's Loop button (round 165f-rack): click switches the pattern's channel looping, right-click its loop type and burns
  330. rackLoopButton.setClickingTogglesState (false);
  331. rackLoopButton.setOnColour (theme::colour::bg6);
  332. rackLoopButton.setIconColourWhenOn (theme::colour::accent);
  333. rackLoopButton.onClick = [this] { rack.toggleLooping(); };
  334. rackLoopButton.onRightClick = [this] { rack.showLoopMenu (&rackLoopButton); };
  335. ui::setHint (rackLoopButton, tr ("Channel looping: channels shorter than the pattern repeat to its end (polyrhythms) [LMB] on / off "
  336. "[RMB] loop type (step channels, all channels, advanced) and Burn to pattern"));
  337. rackTitleTools.addAndMakeVisible (rackLoopButton);
  338. // Loop Starter (round 168b; FL 25's dice in the Channel Rack): a drum loop of the genre's kit, re-rolled with dice
  339. rackLoopStarterButton.setWantsKeyboardFocus (false);
  340. rackLoopStarterButton.onClick = [this] { loopstarterui::open (engine); };
  341. 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"));
  342. rackTitleTools.addAndMakeVisible (rackLoopStarterButton);
  343. // the pattern selector (issue #9): change the pattern the rack edits right from its title bar
  344. rackPatternSelector.onStep = [this] (int delta) { selectPattern (stepPattern (engine.getSong(), delta)); };
  345. rackPatternSelector.onMenu = [this] { showRackPatternList(); };
  346. ui::setHint (rackPatternSelector, tr ("Pattern the Channel Rack edits: [LMB] on the name: the list of patterns, on the arrows: previous / next [Wheel] step"));
  347. rackTitleTools.addAndMakeVisible (rackPatternSelector);
  348. rackTitleTools.addAndMakeVisible (rackFilterBox);
  349. rackTitleTools.addAndMakeVisible (swingSlider);
  350. // the pattern length in bars (issue #12)
  351. rackLengthBox.onSet = [this] (int bars) {
  352. const auto index = engine.getSong().currentPattern;
  353. const auto ticks = (std::int64_t) juce::jlimit (0, 999, bars) * ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  354. if (index >= 0 && index < (int) engine.getSong().patterns.size() && engine.getSong().patterns[(std::size_t) index].lengthTicks != ticks)
  355. engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; });
  356. refreshRackLengthBox();
  357. };
  358. rackLengthBox.onMenu = [this] { showPatternLengthMenu(); };
  359. ui::setHint (rackLengthBox, tr ("Pattern length in bars: [LMB] drag or [Wheel] change it [2xLMB] automatic (from the notes) [RMB] menu"));
  360. rackTitleTools.addAndMakeVisible (rackLengthBox);
  361. rackTitleTools.addAndMakeVisible (rackGraphButton);
  362. rackTitleTools.layout = [this] {
  363. auto r = rackTitleTools.getLocalBounds();
  364. rackPatternSelector.setBounds (r.removeFromLeft (rackPatternSelectorWidth).reduced (0, 3));
  365. r.removeFromLeft (6);
  366. rackFilterBox.setBounds (r.removeFromLeft (96).reduced (0, 3));
  367. r.removeFromLeft (4);
  368. swingSlider.setBounds (r.removeFromLeft (26));
  369. r.removeFromLeft (4);
  370. rackLengthBox.setBounds (r.removeFromLeft (rackLengthBoxWidth).reduced (0, 3));
  371. r.removeFromLeft (4);
  372. rackGraphButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  373. r.removeFromLeft (4);
  374. rackPianoRollButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  375. r.removeFromLeft (4);
  376. rackFollowButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  377. r.removeFromLeft (4);
  378. rackLoopButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  379. r.removeFromLeft (4);
  380. rackLoopStarterButton.setBounds (r.removeFromLeft (24).reduced (0, 1));
  381. };
  382. workspace.setTitleAccessory (Panel::channelRack, &rackTitleTools, rackTitleToolsWidth);
  383. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  384. workspace.onFocusChanged = [this] (Panel panel) {
  385. refreshPanelButtons();
  386. // another panel took over (a click, F5..F9): the Browser's search box gives the keys back (issue #9)
  387. if (panel != Panel::browser)
  388. browser.leaveSearchBox();
  389. };
  390. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  391. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  392. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  393. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  394. };
  395. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  396. if (panel == Panel::channelRack)
  397. showPatternMenu();
  398. };
  399. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  400. workspace.setPersistent (persistent);
  401. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  402. playlist.onOpenPianoRoll = [this] {
  403. // edit a channel that plays in this pattern
  404. const auto& song = engine.getSong();
  405. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  406. const auto channel = engine.getSelectedChannel();
  407. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  408. engine.setSelectedChannel (notes.front().channel);
  409. openPianoRoll();
  410. };
  411. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  412. picker.onPatternMenu = [this] { makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition()); };
  413. picker.onNewPattern = [this] { newPatternButton.onClick(); };
  414. playlist.onRenamePattern = [this] (int p) { showRenamePattern (p); };
  415. playlist.onOpenInSampler = [this] (int channel) {
  416. // the audio clip's file in a new Sampler channel (to play it from notes), its settings open
  417. const auto& song = engine.getSong();
  418. if (channel < 0 || channel >= (int) song.channels.size())
  419. return;
  420. ChannelDef c;
  421. c.name = song.channels[(std::size_t) channel].name;
  422. c.instrument = InstrumentKind::sampler;
  423. c.samplePath = song.channels[(std::size_t) channel].samplePath;
  424. c.colour = song.channels[(std::size_t) channel].colour;
  425. const auto added = rack.addChannel (c, false);
  426. showPanel (Panel::channelRack);
  427. rack.toggleEditor (added, false);
  428. };
  429. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  430. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  431. // recent files (stored in %APPDATA%\LYNX)
  432. recent.setMaxNumberOfItems (12);
  433. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  434. addAndMakeVisible (menuBar);
  435. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  436. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  437. &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  438. &songPosition, &masterVolume, &masterPitch, &perfMeter, &output, &hintBar, &tweakReadout, &workspace, &midiLight })
  439. {
  440. addAndMakeVisible (c);
  441. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  442. }
  443. // the dancers of the project's dance channels (FL's Fruity Dance) over the workspace (round 165e)
  444. danceStage = std::make_unique<DanceStage> (engine);
  445. danceStage->setMouseClickGrabsKeyboardFocus (false);
  446. addAndMakeVisible (*danceStage);
  447. for (auto& b : panelButtons)
  448. {
  449. addAndMakeVisible (b);
  450. b.setMouseClickGrabsKeyboardFocus (false);
  451. b.setWantsKeyboardFocus (false);
  452. }
  453. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  454. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  455. &newPatternButton, &patternMenuButton, &pluginPickerButton })
  456. b->setWantsKeyboardFocus (false);
  457. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  458. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton })
  459. b->setFlat (true);
  460. // a light header: every toolbar button is flat; "on" is a faint wash, in the accent for the states that
  461. // matter while working (playing, recording, metronome, recording options)
  462. {
  463. using namespace theme;
  464. const auto onWash = colour::accent.withAlpha (0.16f), onIcon = colour::accentHover;
  465. for (auto* b : { &playButton, &stopButton, &recordButton, &patternModeButton, &songModeButton })
  466. b->setFlat (true);
  467. playButton.setOnColour (onWash);
  468. playButton.setIconColourWhenOn (onIcon);
  469. recordButton.setOnColour (colour::record.withAlpha (0.2f));
  470. recordButton.setIconColourWhenOn (colour::record);
  471. for (auto* b : { &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton, &patternModeButton, &songModeButton })
  472. {
  473. b->setOnColour (onWash);
  474. b->setIconColourWhenOn (onIcon);
  475. }
  476. for (auto& b : panelButtons)
  477. {
  478. b.setOnColour (colour::textPrimary.withAlpha (0.08f));
  479. b.setIconColourWhenOn (colour::textPrimary);
  480. }
  481. }
  482. quickTips = std::make_unique<ui::QuickTipWindow>();
  483. ui::installSliderContract();
  484. // FL's Last tweaked and automation recording (REA round 143): every automatable control reports its moves
  485. ui::onTweak = [this] (const AutomationTarget& t) { engine.noteTweaked (t); };
  486. // Options › Theme › Startup sound: its Play button (issue #12)
  487. themeui::previewStartupSound = [this] (const juce::String& path) {
  488. std::shared_ptr<const SampleData> sound;
  489. if (path.isNotEmpty() && juce::File (path).existsAsFile())
  490. sound = engine.getSampleLibrary().load (path);
  491. engine.previewSample (sound != nullptr ? sound : makeStartupSample());
  492. };
  493. // the toolbar's last-tweaked read-out opens the parameter's own menu (FL's Tools › Last tweaked; round 162d)
  494. tweakReadout.onClick = [this] {
  495. makeLastTweakedMenu (0).showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&tweakReadout));
  496. };
  497. // FL's "Edit events in piano roll" (REA round 146): the channel's own parameter selects its channel
  498. onEditEventsInPianoRoll = [this] (const AutomationTarget& t) {
  499. const auto onChannel = t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
  500. || t.kind == AutomationTargetKind::channelParam;
  501. if (onChannel && t.index >= 0 && t.index < (int) engine.getSong().channels.size())
  502. engine.setSelectedChannel (t.index);
  503. openPianoRoll();
  504. pianoRoll.showEventLane (t);
  505. };
  506. PluginWindows::onGesture = [this] (const juce::AudioPluginInstance& plugin, int param, bool starting) {
  507. if (const auto t = engine.targetOfPlugin (plugin, param))
  508. {
  509. if (starting)
  510. engine.noteTweaked (*t, true);
  511. else
  512. engine.tweakReleased (*t);
  513. }
  514. };
  515. engine.nameAutomation = [this] (const AutomationTarget& t) { return describeAutomationTarget (engine, t).toStdString(); };
  516. addAndMakeVisible (gridBox); // global grid (editors)
  517. engine.addChangeListener (this);
  518. setTypingPiano (typingPiano);
  519. refreshRecordOptionButtons();
  520. refreshToolbar();
  521. refreshPanelButtons();
  522. setToolbarLayout (toolbarLayout, false); // icon sizes and row height (loaded with the UI options)
  523. if (persistent && toolbarLayout.uiScale != 100)
  524. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  525. setControlHints();
  526. fittedChannelCount = (int) engine.getSong().channels.size();
  527. hintBar.setHint ({ idleHint(), {}, false, false });
  528. setWantsKeyboardFocus (true);
  529. installDialogTextFocus(); // dialogs open with their text field focused (round 165q)
  530. setSize (1180, 642);
  531. startTimerHz (30);
  532. uiTraceMonitor.start ([this, last = std::make_shared<RtStats::Snapshot>()] {
  533. // the audio side of the second (the watchdog thread: atomics only)
  534. const auto rt = engine.getRtStats().snapshot();
  535. const auto calls = rt.callbacks - last->callbacks;
  536. juce::String text;
  537. text << "audio: callbacks " << juce::String ((juce::int64) calls) << ", over deadline " << juce::String ((juce::int64) (rt.overBudget - last->overBudget))
  538. << ", late " << juce::String ((juce::int64) (rt.lateCalls - last->lateCalls)) << ", max load since start " << juce::String (rt.maxLoad * 100.0, 0)
  539. << "%, cpu " << juce::String (engine.getDeviceManager().getCpuUsage() * 100.0, 1) << "%";
  540. *last = rt;
  541. return text;
  542. });
  543. // new or updated plugins since the last run: an incremental scan in the background (unchanged files are
  544. // skipped), a few seconds after start so it doesn't compete with loading; the first run asks in the wizard
  545. if (persistent && setupWizardDone() && backgroundScanAtStart() && platform::testMode())
  546. platform::testModeLog ("background plugin scan at start");
  547. else if (persistent && setupWizardDone() && backgroundScanAtStart())
  548. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  549. if (safe != nullptr)
  550. safe->engine.getPluginHost().startBackgroundScan();
  551. });
  552. // the keys a secondary window (tool, plugin, channel window) leaves unused run the global shortcuts, as in FL
  553. setSecondaryWindowKeyHandler ([safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::KeyPress& key) {
  554. return safe != nullptr && safe->keyFromSecondaryWindow (key);
  555. });
  556. }
  557. MainComponent::~MainComponent()
  558. {
  559. setSecondaryWindowKeyHandler (nullptr);
  560. cancelProjectLoad(); // an open in progress uses the engine from its thread
  561. if (sessionLock != nullptr) // a clean exit: no "LYNX did not close properly" next time
  562. sessionMarker.deleteFile();
  563. mixerinput::openAudioSettings = nullptr;
  564. PatcherWindows::onBrowsePluginDatabase = nullptr;
  565. EditorGlobals::get().onOptionsChanged = nullptr;
  566. PianoRollComponent::shortcutText = nullptr;
  567. saveUiSettings();
  568. workspace.saveState();
  569. ui::uninstallSliderContract();
  570. ui::onTweak = nullptr;
  571. themeui::previewStartupSound = nullptr;
  572. onEditEventsInPianoRoll = nullptr;
  573. PluginWindows::onGesture = nullptr;
  574. removeDialogTextFocus();
  575. engine.nameAutomation = nullptr;
  576. PluginWindows::closeAll(); // plugin UIs before the engine
  577. ParametricEqWindows::closeAll();
  578. closeAutomationEditors();
  579. closeChannelSettings();
  580. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  581. engine.removeChangeListener (this);
  582. stopTimer();
  583. }
  584. void MainComponent::paint (juce::Graphics& g)
  585. {
  586. const uitrace::Scope trace ("MainComponent paint", true, g.getClipBounds());
  587. using namespace theme;
  588. g.fillAll (colour::bg1);
  589. // the toolbar: one band, its panels separated by hairlines
  590. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  591. g.setColour (colour::bg3);
  592. g.fillRect (bar);
  593. g.setColour (colour::border);
  594. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  595. g.setColour (colour::border.brighter (0.08f));
  596. if (toolbarLayout.separators) // (the toolbar menu's "Separators")
  597. for (auto x : dividers)
  598. g.fillRect (x, bar.getY() + 12, 1, bar.getHeight() - 24);
  599. // play, stop and record share one quiet well
  600. if (! transportArea.isEmpty())
  601. {
  602. g.setColour (colour::bg2);
  603. g.fillRoundedRectangle (transportArea.toFloat(), radius::lg);
  604. g.setColour (colour::border);
  605. g.drawRoundedRectangle (transportArea.toFloat().reduced (0.5f), radius::lg, 1.0f);
  606. }
  607. // the hint bar sits in an inset well under the menu
  608. if (! hintBar.getBounds().isEmpty())
  609. {
  610. g.setColour (colour::bg1);
  611. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  612. }
  613. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  614. if (! titleArea.isEmpty())
  615. {
  616. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  617. g.setFont (font (type::small, true));
  618. g.setColour (colour::textSecondary);
  619. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name, titleArea, juce::Justification::centredRight, 1, 0.8f);
  620. }
  621. // captions that name the snap and pattern selectors
  622. g.setFont (font (type::caption - 1.0f, true));
  623. g.setColour (colour::textDisabled);
  624. if (! snapLabelArea.isEmpty())
  625. g.drawText (tr ("SNAP"), snapLabelArea, juce::Justification::centredLeft, true);
  626. if (! patternLabelArea.isEmpty())
  627. g.drawText (tr ("PATTERN"), patternLabelArea, juce::Justification::centredLeft, true);
  628. }
  629. void MainComponent::resized()
  630. {
  631. using toolbarlayout::Group;
  632. dividers.clear();
  633. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  634. auto toolbar = bar.reduced (8, 3);
  635. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  636. const auto big = h + 6; // transport buttons: one slim row, centred on both
  637. const auto bigWidth = h + 4;
  638. constexpr int gap = 17; // a divider and the space around it
  639. const auto grow = h - toolbarlayout::rowHeight (toolbarlayout::IconSize::medium); // wider panels for bigger rows
  640. // panel widths
  641. auto& lf = getLookAndFeel();
  642. auto measureMenu = [&] {
  643. int w = 0;
  644. for (const auto& name : getMenuBarNames())
  645. w += lf.getMenuBarItemWidth (menuBar, 0, name);
  646. return w;
  647. };
  648. menuBar.getProperties().set ("lynxTightMenuBar", false);
  649. int menuWidth = measureMenu();
  650. if (menuWidth > 390) // translated menu titles (German, Russian...): English stays as it was
  651. {
  652. menuBar.getProperties().set ("lynxTightMenuBar", true);
  653. menuWidth = measureMenu();
  654. }
  655. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  656. const int tempoWidth = 90 + grow, timeWidth = 110 + grow, captionWidth = 50, gridWidth = 148;
  657. std::array<int, toolbarlayout::groupCount> widths {};
  658. widths[(std::size_t) Group::transport] = modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 6 + timeWidth;
  659. widths[(std::size_t) Group::master] = 92;
  660. widths[(std::size_t) Group::record] = 3 * h + 4;
  661. widths[(std::size_t) Group::snap] = captionWidth + gridWidth;
  662. widths[(std::size_t) Group::windows] = 3 * h + 4;
  663. widths[(std::size_t) Group::file] = 3 * h + 4;
  664. widths[(std::size_t) Group::meters] = 118;
  665. widths[(std::size_t) Group::output] = 116 + grow * 2;
  666. const auto room = toolbar.getWidth();
  667. const auto minHint = juce::jmax (menuWidth + 8, 320), maxHint = 620; // room for most hints on two lines
  668. auto visible = toolbarlayout::fit (toolbarLayout, widths, gap, room, minHint);
  669. if (! toolbarLayout.visible) // Ctrl+F11: only the menu and the hint bar, on one row
  670. visible.fill (false);
  671. panelBounds = {};
  672. int used = 0;
  673. for (int i = 0; i < toolbarlayout::groupCount; ++i)
  674. used += visible[(std::size_t) i] ? widths[(std::size_t) i] + gap : 0;
  675. const auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used)), maxHint, room - used);
  676. // the spare room goes before the first of the meters / output in the toolbar order (they sit on the right)
  677. auto spare = juce::jmax (0, room - used - hintWidth);
  678. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  679. auto divide = [&] {
  680. take (8);
  681. dividers.push_back (toolbar.getX());
  682. take (9);
  683. };
  684. auto hide = [] (std::initializer_list<juce::Component*> components) {
  685. for (auto* c : components)
  686. {
  687. c->setVisible (false);
  688. c->setBounds ({});
  689. }
  690. };
  691. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  692. c.setVisible (true);
  693. c.setBounds (r);
  694. };
  695. // a block of icon buttons, three per row on both rows
  696. auto grid = [&] (juce::Rectangle<int> panel, std::initializer_list<juce::Component*> buttons) {
  697. int i = 0;
  698. for (auto* b : buttons)
  699. {
  700. const auto x = panel.getX() + (i % 3) * (h + 2);
  701. put (*b, juce::Rectangle<int> (x, i < 3 ? row1 : row2, h, h));
  702. ++i;
  703. }
  704. };
  705. // 1. the menu (and the project name beside it) over the hint bar; always first
  706. if (! toolbarLayout.visible)
  707. {
  708. const auto row = toolbar.withHeight (h);
  709. const auto menu = row.withWidth (juce::jmin (menuWidth + 8, row.getWidth()));
  710. put (menuBar, menu);
  711. titleArea = {};
  712. placeHintBar (row.withTrimmedLeft (menu.getWidth() + 12).withWidth (juce::jmin (900, row.getWidth() - menu.getWidth() - 12)).reduced (0, 1));
  713. fixedToolbarArea = bar;
  714. }
  715. else
  716. {
  717. auto column = take (hintWidth);
  718. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  719. put (menuBar, menu);
  720. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  721. if (titleArea.getWidth() < 60)
  722. titleArea = {};
  723. placeHintBar (column.withY (row2).withHeight (h).reduced (0, 1));
  724. fixedToolbarArea = juce::Rectangle<int> (column.getX() - 4, 0, column.getWidth() + 8, toolbarHeight);
  725. }
  726. snapLabelArea = patternLabelArea = transportArea = {};
  727. for (const auto& entry : toolbarLayout.entries)
  728. {
  729. const auto group = entry.group;
  730. if (! visible[(std::size_t) group])
  731. {
  732. switch (group)
  733. {
  734. case Group::transport:
  735. hide ({ &patternModeButton, &songModeButton, &playButton, &stopButton, &recordButton, &tempoDisplay, &timeDisplay, &songPosition });
  736. break;
  737. case Group::master: hide ({ &masterVolume, &masterPitch }); break;
  738. case Group::record: hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton, &midiLight }); break;
  739. case Group::snap: hide ({ &gridBox, &patternBox, &newPatternButton, &patternMenuButton }); break;
  740. case Group::windows:
  741. for (auto& b : panelButtons)
  742. hide ({ &b });
  743. hide ({ &pluginPickerButton });
  744. break;
  745. case Group::file: hide ({ &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton }); break;
  746. case Group::meters: hide ({ &perfMeter }); break;
  747. case Group::output: hide ({ &output }); break;
  748. case Group::count_: break;
  749. }
  750. continue;
  751. }
  752. if (toolbarlayout::rightAligned (group) && spare > 0)
  753. {
  754. take (spare);
  755. spare = 0;
  756. }
  757. divide();
  758. auto panel = take (widths[(std::size_t) group]);
  759. panelBounds[(std::size_t) group] = juce::Rectangle<int> (panel.getX() - 5, 0, panel.getWidth() + 10, toolbarHeight);
  760. switch (group)
  761. {
  762. case Group::transport: // Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  763. {
  764. auto mode = panel.removeFromLeft (modeWidth);
  765. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  766. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  767. panel.removeFromLeft (8);
  768. const auto y = panel.getCentreY() - big / 2;
  769. transportArea = juce::Rectangle<int> (panel.getX(), y, 3 * bigWidth + 2 * 4, big);
  770. for (auto* b : { &playButton, &stopButton, &recordButton })
  771. {
  772. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big).reduced (0, 3));
  773. panel.removeFromLeft (bigWidth + 4);
  774. }
  775. panel.removeFromLeft (4);
  776. const auto displays = juce::Rectangle<int> (panel.getX(), row1 + 3, panel.getWidth(), 2 * h - 6);
  777. const auto displayHeight = displays.getHeight() - 10;
  778. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  779. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 6).withWidth (timeWidth).withHeight (displayHeight));
  780. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 6 + timeWidth));
  781. break;
  782. }
  783. case Group::master: // master volume over master pitch
  784. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  785. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  786. break;
  787. case Group::record: // metronome, count-in and wait for input over "what to record", typing piano and the MIDI light
  788. grid (panel, { &metronomeButton, &countInButton, &waitInputButton, &recordMenuButton, &typingPianoButton, &midiLight });
  789. break;
  790. case Group::snap: // global snap over the pattern selector, each with its name
  791. {
  792. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  793. snapLabelArea = first.removeFromLeft (captionWidth);
  794. put (gridBox, first.reduced (0, 1));
  795. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  796. patternLabelArea = second.removeFromLeft (captionWidth);
  797. put (patternMenuButton, second.removeFromRight (h));
  798. put (newPatternButton, second.removeFromRight (h));
  799. second.removeFromRight (2);
  800. put (patternBox, second.reduced (0, 1));
  801. break;
  802. }
  803. case Group::windows: // the windows and the plugin picker
  804. grid (panel, { &panelButtons[(std::size_t) Panel::playlist], &panelButtons[(std::size_t) Panel::channelRack],
  805. &panelButtons[(std::size_t) Panel::pianoRoll], &panelButtons[(std::size_t) Panel::mixer],
  806. &panelButtons[(std::size_t) Panel::browser], &pluginPickerButton });
  807. break;
  808. case Group::file: // new, open, save over export, undo, redo
  809. grid (panel, { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  810. break;
  811. case Group::meters: put (perfMeter, panel.withY (row1).withHeight (2 * h + 2)); break;
  812. case Group::output: put (output, panel.withY (row1).withHeight (2 * h + 2)); break;
  813. case Group::count_: break;
  814. }
  815. }
  816. // the toolbar's edit mode: its overlay over the toolbar, and its tray between the toolbar and the windows
  817. const auto tray = toolbarEditor != nullptr ? toolbar::EditOverlay::trayHeight : 0;
  818. if (toolbarEditor != nullptr)
  819. {
  820. toolbarEditor->setBounds (0, 0, getWidth(), toolbarHeight + tray);
  821. toolbarEditor->setToolbarHeight (toolbarHeight);
  822. toolbarEditor->toFront (false);
  823. }
  824. auto below = getLocalBounds().withTrimmedTop (toolbarHeight + tray);
  825. if (updateBar.isVisible())
  826. updateBar.setBounds (below.removeFromTop (updater::UpdateBar::height));
  827. workspace.setBounds (below);
  828. if (danceStage != nullptr)
  829. {
  830. danceStage->setBounds (getLocalBounds());
  831. danceStage->toFront (false);
  832. }
  833. if (setupOverlay != nullptr)
  834. {
  835. setupOverlay->setBounds (getLocalBounds());
  836. setupOverlay->toFront (false);
  837. }
  838. }
  839. // --- toolbar layout ------------------------------------------------------------------------------
  840. void MainComponent::setToolbarLayout (const toolbarlayout::Layout& layout, bool save)
  841. {
  842. const auto scaleChanged = layout.uiScale != toolbarLayout.uiScale;
  843. toolbarLayout = layout;
  844. const auto size = toolbarLayout.iconSize;
  845. rowHeight = toolbarlayout::rowHeight (size);
  846. toolbarHeight = toolbarLayout.visible ? 2 * rowHeight + 8 : rowHeight + 6;
  847. const auto fraction = toolbarlayout::iconFraction (size), maxPx = toolbarlayout::iconMaxPx (size);
  848. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton,
  849. &patternMenuButton, &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton })
  850. b->setIconSizing (fraction, maxPx);
  851. for (auto& b : panelButtons)
  852. b.setIconSizing (fraction, maxPx);
  853. for (auto* b : { &playButton, &stopButton, &recordButton }) // solid transport glyphs, a little smaller than the line icons
  854. b->setIconSizing (0.5f, maxPx - 2.0f);
  855. ToolStrip::iconSize = size;
  856. pianoRoll.resized();
  857. playlist.resized();
  858. if (save && scaleChanged)
  859. {
  860. juce::Desktop::getInstance().setGlobalScaleFactor ((float) toolbarLayout.uiScale / 100.0f);
  861. // the windows grow with the zoom: keep their title bars and close buttons on the screen (round 163)
  862. juce::Timer::callAfterDelay (200, [] { fitAllWindowsOnScreen(); });
  863. }
  864. resized();
  865. repaint();
  866. if (toolbarEditor != nullptr)
  867. toolbarEditor->layoutChanged();
  868. if (save)
  869. saveUiSettings();
  870. }
  871. juce::PopupMenu MainComponent::makeToolbarMenu()
  872. {
  873. using toolbarlayout::Group;
  874. juce::PopupMenu menu;
  875. // FL's toolbar menu (Edit, Separators, Hide, Presets), then LYNX's direct switches per panel
  876. menu.addSectionHeader (tr ("Toolbar"));
  877. menu.addItem (tr ("Edit toolbar (drag panels to move, add or remove them)"), true, toolbarEditor != nullptr,
  878. [this] { setToolbarEditing (toolbarEditor == nullptr); });
  879. menu.addItem (tr ("Separators"), true, toolbarLayout.separators, [this] {
  880. auto layout = toolbarLayout;
  881. layout.separators = ! layout.separators;
  882. setToolbarLayout (layout);
  883. });
  884. menu.addItem (tr ("Hide the toolbar panels") + shortcutText ("view.toolbar"), true, ! toolbarLayout.visible, [this] {
  885. auto layout = toolbarLayout;
  886. layout.visible = ! layout.visible;
  887. setToolbarLayout (layout);
  888. });
  889. juce::PopupMenu presets;
  890. const auto current = toolbarlayout::matchingPreset (toolbarLayout);
  891. for (int p = 0; p < toolbarlayout::presetCount; ++p)
  892. presets.addItem (tr (toolbarlayout::presetName ((toolbarlayout::Preset) p)), true, current == p, [this, p] {
  893. auto layout = toolbarlayout::applyPreset (toolbarLayout, (toolbarlayout::Preset) p);
  894. layout.visible = true;
  895. setToolbarLayout (layout);
  896. });
  897. menu.addSubMenu (tr ("Presets"), presets);
  898. menu.addSectionHeader (tr ("Panels"));
  899. for (const auto& entry : toolbarLayout.entries)
  900. {
  901. const auto group = entry.group;
  902. menu.addItem (tr (toolbarlayout::groupName (group)), true, entry.shown, [this, group] {
  903. auto layout = toolbarLayout;
  904. layout.setShown (group, ! layout.isShown (group));
  905. layout.visible = true;
  906. setToolbarLayout (layout);
  907. });
  908. }
  909. menu.addSeparator();
  910. juce::PopupMenu sizes;
  911. const char* sizeNames[] = { TR_NOOP ("Small icons"), TR_NOOP ("Medium icons"), TR_NOOP ("Large icons") };
  912. for (int i = 0; i < 3; ++i)
  913. sizes.addItem (tr (sizeNames[i]), true, (int) toolbarLayout.iconSize == i, [this, i] {
  914. auto layout = toolbarLayout;
  915. layout.iconSize = (toolbarlayout::IconSize) i;
  916. setToolbarLayout (layout);
  917. });
  918. menu.addSubMenu (tr ("Icon size"), sizes);
  919. juce::PopupMenu scales;
  920. for (auto percent : toolbarlayout::uiScales)
  921. scales.addItem (juce::String (percent) + "%", true, toolbarLayout.uiScale == percent, [this, percent] {
  922. auto layout = toolbarLayout;
  923. layout.uiScale = percent;
  924. setToolbarLayout (layout);
  925. });
  926. menu.addSubMenu (tr ("UI scale"), scales);
  927. menu.addSeparator();
  928. menu.addItem (tr ("Customize toolbar..."), [this] { showCustomizeToolbar(); });
  929. menu.addItem (tr ("Reset toolbar to default"), ! toolbarLayout.isDefault(), false, [this] {
  930. setToolbarLayout (toolbarlayout::Layout::makeDefault());
  931. });
  932. return menu;
  933. }
  934. void MainComponent::setToolbarEditing (bool editing)
  935. {
  936. if (editing == (toolbarEditor != nullptr))
  937. return;
  938. if (! editing)
  939. {
  940. removeChildComponent (toolbarEditor.get());
  941. toolbarEditor.reset();
  942. resized();
  943. repaint();
  944. return;
  945. }
  946. if (! toolbarLayout.visible) // editing shows the panels
  947. {
  948. auto layout = toolbarLayout;
  949. layout.visible = true;
  950. setToolbarLayout (layout);
  951. }
  952. toolbar::EditOverlay::Host host;
  953. host.layout = [this] { return toolbarLayout; };
  954. host.setLayout = [this] (const toolbarlayout::Layout& layout) { setToolbarLayout (layout); };
  955. host.panels = [this] { return panelBounds; };
  956. host.fixedArea = [this] { return fixedToolbarArea; };
  957. host.snapshot = [this] (juce::Rectangle<int> area) {
  958. // the panel as it looks, without the edit overlay on it
  959. if (toolbarEditor != nullptr)
  960. toolbarEditor->setVisible (false);
  961. auto image = createComponentSnapshot (area, true);
  962. if (toolbarEditor != nullptr)
  963. toolbarEditor->setVisible (true);
  964. return image;
  965. };
  966. host.done = [safe = juce::Component::SafePointer<MainComponent> (this)] {
  967. // after the click that asked for it
  968. juce::MessageManager::callAsync ([safe] {
  969. if (safe != nullptr)
  970. safe->setToolbarEditing (false);
  971. });
  972. };
  973. toolbarEditor = std::make_unique<toolbar::EditOverlay> (std::move (host), toolbarHeight);
  974. addAndMakeVisible (*toolbarEditor);
  975. resized();
  976. repaint();
  977. if (isShowing())
  978. toolbarEditor->grabKeyboardFocus();
  979. }
  980. void MainComponent::flUndo()
  981. {
  982. if (alternateUndo)
  983. undoRedo (false);
  984. else
  985. undoRedo (engine.canRedo()); // something undone: Ctrl+Z redoes the next step (FL: "undo/redo on the same shortcut")
  986. }
  987. void MainComponent::undoRedo (bool redo)
  988. {
  989. // FL says in the hint bar what was undone and the undo level ("Undone: ... Level 2/3")
  990. if (redo ? ! engine.canRedo() : ! engine.canUndo())
  991. return;
  992. const auto label = engine.getHistoryLabel (engine.getHistoryPosition() + (redo ? 1 : 0));
  993. if (redo)
  994. engine.redo();
  995. else
  996. engine.undo();
  997. ui::Hint h;
  998. h.text = (redo ? tr ("Redone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) })
  999. : tr ("Undone: {0}", { tr (label.text, { juce::String::fromUTF8 (label.arg.c_str()) }) }));
  1000. h.value = tr ("Level {0}/{1}", { juce::String (engine.getHistoryPosition() + 1), juce::String (engine.getHistorySize()) });
  1001. ui::postHint (h, 2500);
  1002. }
  1003. ui::Hint MainComponent::hintAt (juce::Point<int> p)
  1004. {
  1005. ui::Hint h;
  1006. if (p.y < toolbarHeight)
  1007. {
  1008. h.text = tr ("Toolbar: [RMB] toolbar menu (edit the panels: move, add, remove; presets; hide with Ctrl+F11)");
  1009. h.hasMenu = true;
  1010. }
  1011. return h;
  1012. }
  1013. void MainComponent::showToolbarMenu()
  1014. {
  1015. makeToolbarMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
  1016. }
  1017. void MainComponent::showCustomizeToolbar()
  1018. {
  1019. auto panel = std::make_unique<toolbar::CustomizePanel> (toolbarLayout);
  1020. panel->onChange = [safe = juce::Component::SafePointer<MainComponent> (this)] (const toolbarlayout::Layout& layout) {
  1021. if (safe != nullptr)
  1022. safe->setToolbarLayout (layout);
  1023. };
  1024. juce::DialogWindow::LaunchOptions options;
  1025. options.content.setOwned (fitContentToScreen (std::move (panel)).release());
  1026. options.dialogTitle = tr ("Customize toolbar");
  1027. options.dialogBackgroundColour = theme::colour::bg2;
  1028. options.useNativeTitleBar = true;
  1029. options.resizable = false;
  1030. options.escapeKeyTriggersCloseButton = true;
  1031. if (auto* dialog = options.launchAsync())
  1032. keepAboveMainWindow (*dialog);
  1033. }
  1034. void MainComponent::mouseDown (const juce::MouseEvent& e)
  1035. {
  1036. // a right-click on the toolbar's background (between the panels): show / hide groups, icon size, customize
  1037. if (e.mods.isPopupMenu() && e.y < toolbarHeight)
  1038. showToolbarMenu();
  1039. }
  1040. juce::Rectangle<int> MainComponent::getToolStripAreaForSnapshot (bool playlistStrip)
  1041. {
  1042. auto& editor = playlistStrip ? (juce::Component&) playlist : (juce::Component&) pianoRoll;
  1043. if (! editor.isVisible() || editor.getParentComponent() == nullptr || ! isParentOf (&editor))
  1044. return {};
  1045. const auto area = getLocalArea (&editor, editor.getLocalBounds());
  1046. return area.withHeight (40).withWidth (juce::jmin (area.getWidth(), 900)).getIntersection (getLocalBounds());
  1047. }
  1048. // --- keys --------------------------------------------------------------------------------------
  1049. keys::Context MainComponent::focusContext() const
  1050. {
  1051. switch (workspace.getFocused())
  1052. {
  1053. case Panel::playlist: return keys::Context::playlist;
  1054. case Panel::channelRack: return keys::Context::channelRack;
  1055. case Panel::pianoRoll: return keys::Context::pianoRoll;
  1056. case Panel::mixer: return keys::Context::mixer;
  1057. case Panel::browser: return keys::Context::browser;
  1058. }
  1059. return keys::Context::global;
  1060. }
  1061. void MainComponent::dragOperationStarted (const juce::DragAndDropTarget::SourceDetails&)
  1062. {
  1063. // a drop on a window above this one (the Sampler's waveform, a plugin...) lands there, not on the panel under it
  1064. matchWindowOrderToScreen();
  1065. }
  1066. bool MainComponent::keyPressed (const juce::KeyPress& key)
  1067. {
  1068. const auto chord = chordFromKeyPress (key);
  1069. // 1. the typing piano (its keys win over plain-letter shortcuts while it is on)
  1070. if (keys::KeyMap::playsNote (chord, typingPiano))
  1071. {
  1072. const auto note = keys::typingPianoNote (chord.key);
  1073. if (! heldKeys.hasTag (key.getKeyCode())) // key repeat: the note is already sounding
  1074. for (auto c : engine.getSelectedChannels())
  1075. heldKeys.press (c, note, 0.8f, key.getKeyCode());
  1076. return true;
  1077. }
  1078. // 2. a key the user gave an action himself (Options › Shortcuts) wins over the panels' built-in keys
  1079. // (issue #12: Metronome on 'C' did nothing while the Playlist, whose Knife is 'C', had the focus)
  1080. if (const auto own = keyMap.findUserBound (chord, focusContext(), typingPiano); ! own.empty() && runAction (own))
  1081. return true;
  1082. // 3. the focused panel's own keys
  1083. const auto focused = workspace.getFocused();
  1084. const auto panelShown = workspace.isPanelVisible (focused);
  1085. if (panelShown && focused == Panel::pianoRoll && pianoRoll.handleKey (key))
  1086. return true;
  1087. if (panelShown && focused == Panel::playlist && playlist.handleKey (key))
  1088. return true;
  1089. // 4. the key map
  1090. const auto action = keyMap.find (chord, focusContext(), typingPiano);
  1091. return ! action.empty() && runAction (action);
  1092. }
  1093. bool MainComponent::keyFromSecondaryWindow (const juce::KeyPress& key)
  1094. {
  1095. // (round 165q / issue #12) a text field keeps its typing keys; the rest runs the global actions
  1096. const auto typingIntoText = dynamic_cast<juce::TextEditor*> (juce::Component::getCurrentlyFocusedComponent()) != nullptr;
  1097. const auto action = keyMap.findFromSecondaryWindow (chordFromKeyPress (key), typingIntoText, typingPiano);
  1098. return ! action.empty() && runAction (action);
  1099. }
  1100. bool MainComponent::runAction (const std::string& id)
  1101. {
  1102. auto is = [&id] (const char* name) { return id == name; };
  1103. if (id == "rack.follow")
  1104. {
  1105. auto& g = EditorGlobals::get();
  1106. g.setFollowingView (EditorGlobals::FollowView::channelRack, ! g.isFollowingView (EditorGlobals::FollowView::channelRack));
  1107. rackFollowButton.setToggleState (g.isFollowingView (EditorGlobals::FollowView::channelRack), juce::dontSendNotification);
  1108. return true;
  1109. }
  1110. if (id.rfind ("pianoRoll.", 0) == 0 && pianoRoll.runKeyAction (id)) return true; // tools, slide, channel keys
  1111. if (id.rfind ("playlist.tool.", 0) == 0 && playlist.runKeyAction (id)) return true;
  1112. if (is ("transport.playStop")) playStop();
  1113. else if (is ("transport.pause")) playPause();
  1114. else if (is ("transport.playFromStart")) playFromStart();
  1115. else if (is ("transport.toggleMode")) toggleMode();
  1116. else if (is ("transport.nextMarker")) engine.jumpToNextMarker (true);
  1117. else if (is ("transport.previousMarker")) engine.jumpToNextMarker (false);
  1118. else if (is ("view.typingPiano")) setTypingPiano (! typingPiano);
  1119. else if (is ("view.toolbar"))
  1120. {
  1121. auto layout = toolbarLayout;
  1122. layout.visible = ! layout.visible;
  1123. setToolbarLayout (layout);
  1124. }
  1125. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  1126. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  1127. else if (is ("panel.pianoRoll"))
  1128. {
  1129. togglePanel (Panel::pianoRoll);
  1130. if (workspace.isPanelVisible (Panel::pianoRoll))
  1131. pianoRoll.scrollToNotes();
  1132. }
  1133. else if (is ("panel.browser")) togglePanel (Panel::browser);
  1134. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  1135. else if (is ("panel.maximisePlaylist"))
  1136. {
  1137. workspace.toggleMaximised (Panel::playlist);
  1138. refreshPanelButtons();
  1139. }
  1140. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  1141. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  1142. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  1143. else if (is ("pattern.firstEmpty")) { engine.editSong ([] (Song& s) { gotoFirstEmptyPattern (s); }); showRenamePattern (engine.getSong().currentPattern); }
  1144. else if (is ("pattern.nextEmptyNoName")) engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1145. else if (is ("pattern.delete")) deleteCurrentPattern();
  1146. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  1147. else if (is ("pattern.insert")) insertPatternHere();
  1148. else if (is ("pattern.clone")) clonePatternNow();
  1149. else if (is ("pattern.moveUp")) movePatternNow (-1);
  1150. else if (is ("pattern.moveDown")) movePatternNow (1);
  1151. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  1152. else if (is ("panel.quickAdd"))
  1153. {
  1154. // FL's F8 opens the plugin picker or closes it (FLEngine 0xebf510, round 167o)
  1155. if (auto* open = findToolWindow ("quickadd"))
  1156. closeToolWindowOf (*open->getContentComponent());
  1157. else
  1158. showQuickAdd();
  1159. }
  1160. else if (is ("edit.history")) showHistory();
  1161. else if (is ("browser.search"))
  1162. {
  1163. showPanel (Panel::browser);
  1164. browser.focusSearch();
  1165. }
  1166. else if (is ("transport.record")) toggleRecording();
  1167. else if (is ("record.quickAudio")) quickRecordAudio();
  1168. else if (is ("transport.metronome"))
  1169. {
  1170. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  1171. refreshModeButton();
  1172. }
  1173. else if (is ("record.countIn"))
  1174. {
  1175. auto o = engine.getRecordOptions();
  1176. o.countInBars = o.countInBars > 0 ? 0 : 1;
  1177. engine.setRecordOptions (o);
  1178. refreshRecordOptionButtons();
  1179. }
  1180. else if (is ("record.waitForInput"))
  1181. {
  1182. auto o = engine.getRecordOptions();
  1183. o.waitForInput = ! o.waitForInput;
  1184. engine.setRecordOptions (o);
  1185. refreshRecordOptionButtons();
  1186. }
  1187. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  1188. else if (is ("rack.pianoRollView"))
  1189. {
  1190. rack.setPianoRollView (! rack.isPianoRollView());
  1191. saveUiSettings();
  1192. }
  1193. else if (is ("view.audioEditor")) openAudioEditorForSelection();
  1194. else if (is ("view.tempoTapper")) openTempoTapper (engine);
  1195. else if (is ("view.sampleBrowser")) toggleSampleBrowser();
  1196. else if (is ("view.pluginDatabase"))
  1197. {
  1198. showPanel (Panel::browser);
  1199. browser.showPluginDatabase();
  1200. }
  1201. else if (is ("view.midiSettings") || is ("view.projectInfo"))
  1202. {
  1203. // FL's F10 / F11 (round 167o, issue #23): the same key closes Settings showing that page; on another page it
  1204. // switches in place
  1205. const auto page = is ("view.midiSettings") ? SettingsPage::midi : SettingsPage::info;
  1206. const auto shown = shownSettingsPage();
  1207. switch (keys::settingsKeyPress (shown >= 0, shown, (int) page))
  1208. {
  1209. case keys::SettingsKey::close: closeSettings(); break;
  1210. case keys::SettingsKey::switchPage: switchSettingsPage (page); break;
  1211. case keys::SettingsKey::open: openSettings ((int) page); break;
  1212. }
  1213. }
  1214. else if (is ("view.closeUnfocusedWindows")) closeUnfocusedWindows();
  1215. else if (is ("view.touchKeyboard")) toggleTouchKeyboard (engine);
  1216. else if (is ("view.closePluginWindows") || is ("view.closeWindows"))
  1217. {
  1218. PluginWindows::closeAll();
  1219. ParametricEqWindows::closeAll(); // every native effect / controller editor
  1220. if (is ("view.closeWindows")) // FL's F12: the editors and tool windows too (LYNX's docked panels stay)
  1221. {
  1222. closeAutomationEditors();
  1223. closeChannelSettings();
  1224. closeAllToolWindows();
  1225. closeHelp();
  1226. }
  1227. }
  1228. else if (is ("rack.groupSelected")) rack.groupSelected();
  1229. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  1230. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  1231. else if (is ("browser.previous")) browser.step (-1, false);
  1232. else if (is ("browser.next")) browser.step (1, false);
  1233. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  1234. else if (is ("browser.swapNext")) browser.step (1, true);
  1235. else if (is ("browser.load")) browser.loadSelected();
  1236. else if (is ("browser.closeFolder")) browser.openFolder (false);
  1237. else if (is ("browser.openFolder")) browser.openFolder (true);
  1238. else if (is ("browser.rename"))
  1239. {
  1240. if (! browser.renameSelectedPlugin()) // not a plugin: F2's global action (rename the pattern)
  1241. showRenamePattern (engine.getSong().currentPattern);
  1242. }
  1243. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  1244. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  1245. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  1246. else if (is ("file.new")) newProject();
  1247. else if (is ("file.open")) chooseFileToOpen();
  1248. else if (is ("file.save")) save (false);
  1249. else if (is ("file.saveAs")) save (true);
  1250. else if (is ("file.saveNewVersion")) saveNewVersion();
  1251. else if (is ("file.export")) exportAudio();
  1252. else if (is ("file.exportMp3")) exportAudio (1);
  1253. else if (is ("file.exportMidi")) exportMidiFile();
  1254. else if (is ("edit.undo")) flUndo();
  1255. else if (is ("edit.undoBackwards")) undoRedo (false);
  1256. else if (is ("edit.redo")) undoRedo (true);
  1257. else if (is ("help.shortcuts"))
  1258. {
  1259. if (helpWindow != nullptr) // F1 again closes the sheet (issue #23)
  1260. closeHelp();
  1261. else
  1262. showHelp();
  1263. }
  1264. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  1265. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  1266. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  1267. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  1268. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  1269. else if (is ("rack.moveDown")) rack.moveSelected (1);
  1270. else if (is ("rack.selectAll")) rack.selectAll();
  1271. else if (is ("rack.clone")) rack.cloneSelected();
  1272. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  1273. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  1274. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  1275. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  1276. else
  1277. return false;
  1278. return true;
  1279. }
  1280. bool MainComponent::keyStateChanged (bool)
  1281. {
  1282. // JUCE has no per-key "keyReleased"; check which held keys were released (each held note remembers its
  1283. // channel and key, so the selection changing meanwhile can't leave one sounding)
  1284. std::vector<int> released;
  1285. heldKeys.forEachTag ([&released] (int code) {
  1286. if (! juce::KeyPress::isKeyCurrentlyDown (code))
  1287. released.push_back (code);
  1288. });
  1289. for (auto code : released)
  1290. heldKeys.releaseTag (code);
  1291. return false;
  1292. }
  1293. juce::String MainComponent::shortcutText (const char* actionId) const
  1294. {
  1295. const auto& chords = keyMap.chordsFor (actionId);
  1296. return chords.empty() ? juce::String() : "\t" + juce::String (keys::toString (chords.front()));
  1297. }
  1298. void MainComponent::setTypingPiano (bool on)
  1299. {
  1300. typingPiano = on;
  1301. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  1302. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  1303. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard as a piano: on (Z..M and Q..P play the selected channels)")
  1304. : tr ("Typing keyboard as a piano: off (letter and number keys are shortcuts)"))
  1305. + juce::String (" (") + juce::String (keys::toString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  1306. : keyMap.chordsFor ("view.typingPiano").front()))
  1307. + ")");
  1308. // release anything still sounding from the keyboard
  1309. heldKeys.releaseAll();
  1310. }
  1311. void MainComponent::loadKeyMap()
  1312. {
  1313. keyMap.resetToDefaults();
  1314. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  1315. if (file.existsAsFile())
  1316. {
  1317. std::vector<std::string> errors;
  1318. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  1319. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  1320. for (const auto& e : errors)
  1321. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  1322. }
  1323. auto keyOf = [this] (const std::string& id) {
  1324. const auto& chords = keyMap.chordsFor (id);
  1325. return chords.empty() ? juce::String() : juce::String (keys::toString (chords.front()));
  1326. };
  1327. pianoRoll.refreshToolKeys (keyOf);
  1328. playlist.refreshToolKeys (keyOf);
  1329. }
  1330. // --- Browsers ------------------------------------------------------------------------------------
  1331. // The main Browser and the separate Sample browser window (round 163) act on the project the same way.
  1332. void MainComponent::connectBrowser (BrowserComponent& b)
  1333. {
  1334. b.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  1335. b.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  1336. b.onOpenMixerPreset = [this] (const juce::File& file) {
  1337. if (! mixerpresets::isMixerPreset (file))
  1338. return false;
  1339. if (! mixer.loadPresetOnSelection (file))
  1340. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Open mixer track state"),
  1341. tr ("This file is not a mixer track state LYNX SHARE can read."));
  1342. return true;
  1343. };
  1344. // the Browser's "Current project" items (REA_rodada115)
  1345. b.onOpenPattern = [this] (int pattern) {
  1346. selectPattern (pattern);
  1347. openPianoRoll();
  1348. };
  1349. b.onPatternMenu = [this] (int pattern) {
  1350. selectPattern (pattern);
  1351. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  1352. };
  1353. b.onOpenChannel = [this] (int channel) {
  1354. engine.setSelectedChannel (channel);
  1355. rack.toggleEditor (channel, true);
  1356. };
  1357. b.onOpenEffect = [this] (int track, int slot) {
  1358. showPanel (Panel::mixer);
  1359. mixer.openSlotEditor (track, slot);
  1360. };
  1361. b.onShowInsert = [this] (int track) {
  1362. showPanel (Panel::mixer);
  1363. mixer.selectTrack (track);
  1364. };
  1365. b.onOpenAutomation = [this] (int automation) { openAutomationEditor (engine, automation); };
  1366. // the Browser's Plugin database (round 142): the same targets as the quick-add palette
  1367. b.onAddInstrument = [this] (ChannelDef c) {
  1368. if (PatcherWindows::takeInstrumentFromBrowser (c)) // a Patcher's Add plugin › Browse plugin database (round 162)
  1369. return;
  1370. rack.addChannel (std::move (c), true);
  1371. showPanel (Panel::channelRack);
  1372. };
  1373. b.onAddEffect = [this] (EffectSlot slot) {
  1374. if (PatcherWindows::takeEffectFromBrowser (slot))
  1375. return;
  1376. if (! mixer.addEffectToSelected (std::move (slot)))
  1377. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugin database"),
  1378. tr ("The selected insert has no free effect slot."));
  1379. else
  1380. showPanel (Panel::mixer);
  1381. };
  1382. b.onPreviewVolumeChanged = [this] { saveUiSettings(); };
  1383. b.onSendToPlaylist = [this] (const juce::File& file) {
  1384. playlist.addAudioClipAtPlayhead (file);
  1385. showPanel (Panel::playlist);
  1386. };
  1387. b.onToggleSampleBrowser = [this] { toggleSampleBrowser(); };
  1388. }
  1389. void MainComponent::toggleSampleBrowser()
  1390. {
  1391. if (auto* w = findToolWindow ("sampleBrowser"))
  1392. {
  1393. w->closeButtonPressed(); // (hidden, then deleted: remembered as closed)
  1394. return;
  1395. }
  1396. openSampleBrowser();
  1397. }
  1398. void MainComponent::openSampleBrowser()
  1399. {
  1400. auto* window = openToolWindow (BrowserComponent::makeSampleBrowserContent (engine, [this] (BrowserComponent& b) { connectBrowser (b); }),
  1401. tr ("Sample browser"), "sampleBrowser");
  1402. if (window == nullptr)
  1403. return;
  1404. window->setResizable (true, false);
  1405. window->setResizeLimits (240, 260, 4000, 4000);
  1406. const auto saved = BrowserComponent::sampleBrowserBounds();
  1407. const auto area = juce::Desktop::getInstance().getDisplays().getTotalBounds (true);
  1408. if (saved.getWidth() >= 240 && saved.getHeight() >= 260 && area.intersects (saved))
  1409. window->setBounds (saved);
  1410. else if (auto* top = getTopLevelComponent())
  1411. window->setBounds (top->getScreenBounds().getRight() - 360, top->getScreenY() + 80, 340, juce::jmax (400, top->getHeight() - 160));
  1412. }
  1413. // --- UI options ----------------------------------------------------------------------------------
  1414. juce::File MainComponent::uiSettingsFile() const
  1415. {
  1416. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  1417. }
  1418. void MainComponent::loadUiSettings()
  1419. {
  1420. juce::StringArray lines;
  1421. lines.addLines (uiSettingsFile().loadFileAsString());
  1422. // the sound in FL's order (0.1.20) wins over the old key, wherever each line is
  1423. const auto flMetronomeSound = std::any_of (lines.begin(), lines.end(), [] (const juce::String& l) { return l.trim().startsWith ("metronomeSoundFl"); });
  1424. for (const auto& line : lines)
  1425. {
  1426. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  1427. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  1428. if (key == "typingPiano")
  1429. typingPiano = on;
  1430. else if (key == "keepEditorsOpen")
  1431. ChannelRackComponent::keepEditorsOpen = on;
  1432. else if (key == "selFirstChanPatChanges")
  1433. ChannelRackComponent::selectFirstChannelWithNotes = on;
  1434. else if (key == "alternateUndo")
  1435. alternateUndo = on;
  1436. else if (key == "waveSpectral") // ("waveColours", the old spectral-by-default key, is ignored)
  1437. ui::WaveformCache::spectral = on;
  1438. else if (key == "pluginStyle") // "Automatic" or a style forced on every plugin
  1439. {
  1440. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim();
  1441. skin::setForcedStyle (v.equalsIgnoreCase ("Automatic") || v.isEmpty() ? -1 : (int) skin::styleFromName (v));
  1442. }
  1443. else if (key == "pluginStyleOverrides")
  1444. skin::overridesFromString (line.fromFirstOccurrenceOf ("=", false, false).trim());
  1445. else if (key == "reducedEffects")
  1446. skin::setReducedEffects (on);
  1447. else if (key == "waveStereo")
  1448. ui::WaveformCache::stereo = on;
  1449. else if (key == "noteNames")
  1450. notenames::currentStyle.store (juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1451. else if (key == "noteFlats")
  1452. notenames::currentFlats.store (on);
  1453. else if (key == "rememberSeek")
  1454. EditorGlobals::get().rememberSeek = on;
  1455. else if (key == "followPlaylist" || key == "followPianoRoll")
  1456. EditorGlobals::get().setFollowing (key == "followPianoRoll", on, false);
  1457. else if (key == "followChannelRack" || key == "followAudioEditor")
  1458. EditorGlobals::get().setFollowingView (key == "followChannelRack" ? EditorGlobals::FollowView::channelRack
  1459. : EditorGlobals::FollowView::audioEditor, on, false);
  1460. else if (key == "scopeMode")
  1461. toolbar::OutputMonitor::mode = juce::jlimit (0, toolbar::OutputMonitor::modeCount - 1,
  1462. line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1463. else if (key == "toolbarGroups")
  1464. toolbarLayout.orderFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1465. else if (key == "toolbarIcons")
  1466. toolbarLayout.iconSize = toolbarlayout::Layout::iconSizeFromString (line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1467. else if (key == "toolbarSeparators")
  1468. toolbarLayout.separators = on;
  1469. else if (key == "toolbarVisible")
  1470. toolbarLayout.visible = on;
  1471. else if (key == "menuDensity")
  1472. theme::menus::setCompact (line.fromFirstOccurrenceOf ("=", false, false).trim() != "comfortable");
  1473. else if (key == "uiScale")
  1474. toolbarLayout.uiScale = toolbarlayout::clampScale (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1475. else if (key == "editPatternsIn")
  1476. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1477. else if (key == "autosaveMinutes")
  1478. autosaveMinutes = prefs::clampAutosaveMinutes (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1479. else if (key == "askUnusedRecordings")
  1480. askUnusedRecordings = on;
  1481. else if (key == "autosaveKeep")
  1482. autosaveKeep = prefs::clampAutosaveKeep (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1483. else if (key == "metronomeSound" && ! flMetronomeSound) // (before 0.1.20: 0 LYNX click, 1..5 hi-hat..pulse)
  1484. engine.getTransport().metronomeSound.store (metronome::soundFromLegacy (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1485. else if (key == "metronomeSoundFl") // FL's order: 0 Hi-hat, 1 Tick, 2 Beep, 3 Cowbell, 4 Pulse
  1486. engine.getTransport().metronomeSound.store (metronome::clampSound (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1487. else if (key == "metronomeTrack")
  1488. engine.getTransport().metronomeTrack.store (juce::jlimit (0, maxMixerTracks - 1, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1489. else if (key == "playTruncatedOnTransport")
  1490. engine.getTransport().playTruncatedOnTransport.store (on);
  1491. else if (key == "resetPluginsOnTransport")
  1492. engine.getTransport().resetPluginsOnTransport.store (on);
  1493. else if (key == "metronomeVolume")
  1494. engine.getTransport().metronomeVolume.store ((float) controls::clampUtilityVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue()));
  1495. else if (key == "previewVolume")
  1496. engine.setPreviewVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  1497. else if (key == "editorVolume")
  1498. engine.setEditorVolume (line.fromFirstOccurrenceOf ("=", false, false).trim().getDoubleValue());
  1499. else if (key == "rackPianoRollView")
  1500. rack.setPianoRollView (on);
  1501. else if (key == "undoLevels")
  1502. engine.setUndoLevels (line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1503. else if (key == "askWhatToRecord" || key == "recordNotes" || key == "recordAudio" || key == "recordStartsPlayback" || key == "disarmOnStop"
  1504. || key == "recordOffOnStop" || key == "unarmAfterRender" || key == "renderAutoClip")
  1505. {
  1506. auto o = engine.getRecordOptions();
  1507. (key == "askWhatToRecord" ? o.askWhatToRecord : key == "recordNotes" ? o.recordNotes : key == "recordAudio" ? o.recordAudio
  1508. : key == "disarmOnStop" ? o.disarmOnStop : key == "recordOffOnStop" ? o.recordOffOnStop : key == "unarmAfterRender" ? o.unarmAfterRender
  1509. : key == "renderAutoClip" ? o.autoCreateClip
  1510. : o.startsPlayback) = on;
  1511. engine.setRecordOptions (o);
  1512. }
  1513. else if (key == "recordAutomation" || key == "recordQuantiseAutomation" || key == "recordClips")
  1514. {
  1515. auto o = engine.getRecordOptions();
  1516. (key == "recordAutomation" ? o.recordAutomation : key == "recordClips" ? o.recordClips : o.quantiseAutomation) = on;
  1517. engine.setRecordOptions (o);
  1518. }
  1519. else if (key == "recordToStepSequencer" || key == "recordingMarkers" || key == "recordNoteEnd")
  1520. {
  1521. auto o = engine.getRecordOptions();
  1522. if (key == "recordNoteEnd")
  1523. o.noteEnd = (NoteEnd) juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  1524. else
  1525. (key == "recordToStepSequencer" ? o.toStepSequencer : o.recordingMarkers) = on;
  1526. engine.setRecordOptions (o);
  1527. }
  1528. else if (key == "recordPunchLoop" || key == "recordPreRoll" || key == "recordPostRoll")
  1529. {
  1530. auto o = engine.getRecordOptions();
  1531. const auto v = line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue();
  1532. if (key == "recordPunchLoop")
  1533. o.punchLoopRegion = v != 0;
  1534. else
  1535. (key == "recordPreRoll" ? o.preRollBars : o.postRollBars) = juce::jlimit (0, 8, v);
  1536. engine.setRecordOptions (o);
  1537. }
  1538. else if (key == "recordQuantiseStarts")
  1539. {
  1540. recordQuantiseOn = on;
  1541. updateRecordQuantise();
  1542. }
  1543. else if (key == "newInserts" || key == "newMasterChain" || key == "newCleanMixer" || key == "playlistTracks" || key == "newAutoCrossfades")
  1544. newProjectDefaults().readKey (key.toStdString(), line.fromFirstOccurrenceOf ("=", false, false).trim().toStdString());
  1545. else if (key == "mixerUsedOnly")
  1546. MixerStrips::showUsedOnly = on;
  1547. else if (key == "quantizeSongJumps")
  1548. engine.quantizeSongJumps.store (juce::jlimit (0, 5, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue()));
  1549. }
  1550. startup = StartupOptions::load();
  1551. browser.refreshPreviewVolume();
  1552. }
  1553. void MainComponent::saveUiSettings()
  1554. {
  1555. if (! persistent)
  1556. return;
  1557. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\nkeepEditorsOpen="
  1558. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0)
  1559. + "\nselFirstChanPatChanges=" + juce::String (ChannelRackComponent::selectFirstChannelWithNotes ? 1 : 0)
  1560. + "\nalternateUndo=" + juce::String (alternateUndo ? 1 : 0)
  1561. + "\neditPatternsIn="
  1562. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  1563. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0)
  1564. + "\nwaveSpectral=" + juce::String (ui::WaveformCache::spectral ? 1 : 0)
  1565. + "\nwaveStereo=" + juce::String (ui::WaveformCache::stereo ? 1 : 0)
  1566. + "\nnoteNames=" + juce::String (notenames::currentStyle.load())
  1567. + "\nnoteFlats=" + juce::String (notenames::currentFlats.load() ? 1 : 0)
  1568. + "\nreducedEffects=" + juce::String (skin::reducedEffects() ? 1 : 0)
  1569. + "\npluginStyle=" + juce::String (skin::forcedStyle() < 0 ? "Automatic" : skin::styleName ((skin::Style) skin::forcedStyle()))
  1570. + "\npluginStyleOverrides=" + skin::overridesToString()
  1571. + "\nrememberSeek=" + juce::String (EditorGlobals::get().rememberSeek ? 1 : 0)
  1572. + "\nfollowPlaylist=" + juce::String (EditorGlobals::get().isFollowing (false) ? 1 : 0)
  1573. + "\nfollowPianoRoll=" + juce::String (EditorGlobals::get().isFollowing (true) ? 1 : 0)
  1574. + "\nfollowChannelRack=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::channelRack) ? 1 : 0)
  1575. + "\nfollowAudioEditor=" + juce::String (EditorGlobals::get().isFollowingView (EditorGlobals::FollowView::audioEditor) ? 1 : 0)
  1576. + "\nscopeMode=" + juce::String (toolbar::OutputMonitor::mode)
  1577. + "\ntoolbarGroups=" + juce::String (toolbarLayout.orderToString())
  1578. + "\ntoolbarIcons=" + toolbarlayout::Layout::iconSizeId (toolbarLayout.iconSize)
  1579. + "\nuiScale=" + juce::String (toolbarLayout.uiScale)
  1580. + "\nmenuDensity=" + juce::String (theme::menus::compact() ? "compact" : "comfortable")
  1581. + "\ntoolbarSeparators=" + juce::String (toolbarLayout.separators ? 1 : 0)
  1582. + "\ntoolbarVisible=" + juce::String (toolbarLayout.visible ? 1 : 0)
  1583. + "\nautosaveMinutes=" + juce::String (autosaveMinutes) + "\nautosaveKeep=" + juce::String (autosaveKeep)
  1584. + "\naskUnusedRecordings=" + juce::String (askUnusedRecordings ? 1 : 0)
  1585. + "\nundoLevels=" + juce::String (engine.getUndoLevels())
  1586. + "\nmetronomeVolume=" + juce::String (engine.getTransport().metronomeVolume.load(), 2)
  1587. + "\nmetronomeSoundFl=" + juce::String (metronome::clampSound (engine.getTransport().metronomeSound.load()))
  1588. + "\nmetronomeTrack=" + juce::String (engine.getTransport().metronomeTrack.load())
  1589. + "\nplayTruncatedOnTransport=" + juce::String (engine.getTransport().playTruncatedOnTransport.load() ? 1 : 0)
  1590. + "\nresetPluginsOnTransport=" + juce::String (engine.getTransport().resetPluginsOnTransport.load() ? 1 : 0)
  1591. + "\npreviewVolume=" + juce::String (engine.getPreviewVolume(), 2)
  1592. + "\neditorVolume=" + juce::String (engine.getEditorVolume(), 2)
  1593. + "\nrackPianoRollView=" + juce::String (rack.isPianoRollView() ? 1 : 0)
  1594. + "\naskWhatToRecord=" + juce::String (engine.getRecordOptions().askWhatToRecord ? 1 : 0)
  1595. + "\nrecordNotes=" + juce::String (engine.getRecordOptions().recordNotes ? 1 : 0)
  1596. + "\nrecordAudio=" + juce::String (engine.getRecordOptions().recordAudio ? 1 : 0)
  1597. + "\nrecordStartsPlayback=" + juce::String (engine.getRecordOptions().startsPlayback ? 1 : 0)
  1598. + "\ndisarmOnStop=" + juce::String (engine.getRecordOptions().disarmOnStop ? 1 : 0)
  1599. + "\nrecordOffOnStop=" + juce::String (engine.getRecordOptions().recordOffOnStop ? 1 : 0)
  1600. + "\nunarmAfterRender=" + juce::String (engine.getRecordOptions().unarmAfterRender ? 1 : 0)
  1601. + "\nrenderAutoClip=" + juce::String (engine.getRecordOptions().autoCreateClip ? 1 : 0)
  1602. + "\nrecordQuantiseStarts=" + juce::String (recordQuantiseOn ? 1 : 0)
  1603. + "\nrecordNoteEnd=" + juce::String ((int) engine.getRecordOptions().noteEnd)
  1604. + "\nrecordToStepSequencer=" + juce::String (engine.getRecordOptions().toStepSequencer ? 1 : 0)
  1605. + "\nrecordingMarkers=" + juce::String (engine.getRecordOptions().recordingMarkers ? 1 : 0)
  1606. + "\nrecordAutomation=" + juce::String (engine.getRecordOptions().recordAutomation ? 1 : 0)
  1607. + "\nrecordClips=" + juce::String (engine.getRecordOptions().recordClips ? 1 : 0)
  1608. + "\nrecordQuantiseAutomation=" + juce::String (engine.getRecordOptions().quantiseAutomation ? 1 : 0)
  1609. + "\nrecordPunchLoop=" + juce::String (engine.getRecordOptions().punchLoopRegion ? 1 : 0)
  1610. + "\nrecordPreRoll=" + juce::String (engine.getRecordOptions().preRollBars)
  1611. + "\nrecordPostRoll=" + juce::String (engine.getRecordOptions().postRollBars) + "\nmixerUsedOnly=" + juce::String (MixerStrips::showUsedOnly ? 1 : 0)
  1612. + "\nquantizeSongJumps=" + juce::String (engine.quantizeSongJumps.load()) + "\n"
  1613. + juce::String (newProjectDefaults().toText()));
  1614. }
  1615. // --- transport -----------------------------------------------------------------------------------
  1616. void MainComponent::playStop()
  1617. {
  1618. auto& transport = engine.getTransport();
  1619. if (engine.isWaitingForInput() || engine.isCountingIn()) // pressed again: cancel
  1620. {
  1621. engine.stop();
  1622. return;
  1623. }
  1624. if (transport.playing.load())
  1625. {
  1626. engine.stop();
  1627. engine.seek (playStartTicks); // back to where playback started
  1628. }
  1629. else
  1630. {
  1631. playStartTicks = transport.positionTicks.load();
  1632. engine.startPlayback();
  1633. }
  1634. }
  1635. void MainComponent::playPause()
  1636. {
  1637. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn())
  1638. engine.stop();
  1639. else
  1640. {
  1641. playStartTicks = engine.getTransport().positionTicks.load();
  1642. engine.startPlayback();
  1643. }
  1644. }
  1645. void MainComponent::playFromStart()
  1646. {
  1647. // FL 2026's Shift+Space (measured in FL, issue #11): playing, recording, waiting or counting in -> stop at the start
  1648. // of the time selection (Song mode) or else of the song / pattern; stopped -> play from the current position, as
  1649. // Space does (a later Space goes back there).
  1650. const auto wasPlaying = engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn();
  1651. if (! wasPlaying)
  1652. {
  1653. playStop();
  1654. return;
  1655. }
  1656. engine.stop();
  1657. const auto& song = engine.getSong();
  1658. const auto target = transportedit::shiftSpaceStopTarget (song.mode == PlayMode::song, song.hasLoop(), song.loopStart);
  1659. if (target > 0)
  1660. engine.seek ((double) target);
  1661. else
  1662. engine.rewind();
  1663. playStartTicks = (double) target;
  1664. }
  1665. void MainComponent::stopAndRewind (bool toStart)
  1666. {
  1667. // Stop while nothing plays (the second press, or a double click) goes back to the very start even when
  1668. // "Remember seek time" sends the first Stop to the ruler mark (round 162, issue #9)
  1669. const auto alreadyStopped = toStart || ! (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn());
  1670. engine.stop();
  1671. // FL: the transport's Stop also ends a Browser sample preview (issue #11)
  1672. browser.stopPreview(); // (the engine's one preview voice: the Sample browser window's preview stops too)
  1673. const auto& globals = EditorGlobals::get();
  1674. const auto back = transportedit::stopTarget (alreadyStopped, globals.rememberSeek && engine.getSong().mode == PlayMode::song, globals.seekMark);
  1675. if (back > 0) // "Remember seek time": back to the position clicked on the Playlist ruler
  1676. engine.seek ((double) back);
  1677. else
  1678. engine.rewind();
  1679. playStartTicks = (double) back;
  1680. }
  1681. void MainComponent::showStopMenu()
  1682. {
  1683. auto& globals = EditorGlobals::get();
  1684. juce::PopupMenu menu;
  1685. menu.addSectionHeader (tr ("Stop"));
  1686. menu.addItem (tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), true, globals.rememberSeek, [this] {
  1687. EditorGlobals::get().rememberSeek = ! EditorGlobals::get().rememberSeek;
  1688. saveUiSettings();
  1689. });
  1690. menu.addSeparator();
  1691. menu.addItem (tr ("All notes off (panic)") + "\t" + tr ("double-click"), [this] { engine.panic(); });
  1692. menu.addItem (tr ("Back to the start"), [this] { stopAndRewind (true); });
  1693. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&stopButton));
  1694. }
  1695. void MainComponent::toggleMode()
  1696. {
  1697. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  1698. }
  1699. // --- panels --------------------------------------------------------------------------------------
  1700. void MainComponent::togglePanel (Panel panel)
  1701. {
  1702. workspace.toggle (panel);
  1703. refreshPanelButtons();
  1704. }
  1705. void MainComponent::fitChannelRack (bool width)
  1706. {
  1707. rack.updateSize();
  1708. const auto scrollbar = rackViewport.getScrollBarThickness();
  1709. // compact like FL's rack: at most two bars of steps are shown, longer patterns scroll sideways, so the
  1710. // rack does not cover the Playlist after a project with long patterns is opened
  1711. const auto maxWidth = juce::jmin (juce::jmax (300, workspace.getWidth() - 2 * 16 - 260), rack.widthForSteps (32));
  1712. const auto contentWidth = juce::jmin (rack.naturalWidth(), maxWidth); // the ghost steps only fill a wider rack
  1713. const auto needsHorizontal = rack.naturalWidth() > contentWidth;
  1714. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  1715. fittedChannelCount = (int) engine.getSong().channels.size();
  1716. }
  1717. void MainComponent::showPanel (Panel panel)
  1718. {
  1719. workspace.show (panel);
  1720. refreshPanelButtons();
  1721. }
  1722. void MainComponent::refreshPanelButtons()
  1723. {
  1724. for (int i = 0; i < workspace::panelCount; ++i)
  1725. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  1726. }
  1727. void MainComponent::openPianoRoll()
  1728. {
  1729. showPanel (Panel::pianoRoll);
  1730. pianoRoll.scrollToNotes();
  1731. }
  1732. void MainComponent::saveLayoutAs()
  1733. {
  1734. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  1735. window->addTextEditor ("name", tr ("My layout"));
  1736. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1737. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1738. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  1739. const auto name = window->getTextEditorContents ("name").trim();
  1740. if (result == 1 && name.isNotEmpty())
  1741. workspace.saveLayoutAs (name);
  1742. }),
  1743. true);
  1744. keepAboveMainWindow (*window);
  1745. }
  1746. juce::PopupMenu MainComponent::layoutsMenu()
  1747. {
  1748. juce::PopupMenu menu;
  1749. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  1750. files.sort();
  1751. for (const auto& file : files)
  1752. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  1753. workspace.loadLayout (file);
  1754. refreshPanelButtons();
  1755. });
  1756. if (files.isEmpty())
  1757. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  1758. menu.addSeparator();
  1759. menu.addItem (tr ("Open layouts folder"), [] {
  1760. Workspace::layoutsFolder().createDirectory();
  1761. Workspace::layoutsFolder().startAsProcess();
  1762. });
  1763. return menu;
  1764. }
  1765. void MainComponent::selectTabForSnapshot (int tab)
  1766. {
  1767. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  1768. const auto panel = panels[juce::jlimit (0, 3, tab)];
  1769. if (panel == Panel::pianoRoll)
  1770. {
  1771. const auto& song = engine.getSong();
  1772. std::vector<int> counts (song.channels.size(), 0);
  1773. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  1774. if (n.channel >= 0 && n.channel < (int) counts.size())
  1775. ++counts[(std::size_t) n.channel];
  1776. if (! counts.empty())
  1777. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  1778. }
  1779. // each view on its own: the panel maximized over the workspace
  1780. workspace.resetLayout();
  1781. workspace.show (panel);
  1782. workspace.toggleMaximised (panel);
  1783. refreshPanelButtons();
  1784. if (panel == Panel::pianoRoll)
  1785. pianoRoll.scrollToNotes();
  1786. if (panel == Panel::playlist)
  1787. playlist.resized(); // update the scrollbars for the loaded song
  1788. if (panel == Panel::mixer)
  1789. mixer.selectFirstTrackWithEffects();
  1790. }
  1791. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  1792. {
  1793. workspace.resetLayout();
  1794. if (auto* stage = dynamic_cast<DanceStage*> (danceStage.get()))
  1795. stage->update(); // (the project's dancers now: no timer runs before the picture)
  1796. if (extraPanels)
  1797. {
  1798. workspace.show (Panel::mixer);
  1799. workspace.show (Panel::pianoRoll);
  1800. pianoRoll.scrollToNotes();
  1801. workspace.show (Panel::channelRack);
  1802. }
  1803. refreshPanelButtons();
  1804. }
  1805. // --- patterns ------------------------------------------------------------------------------------
  1806. void MainComponent::selectPattern (int index)
  1807. {
  1808. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  1809. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  1810. }
  1811. void MainComponent::nextEmptyPattern()
  1812. {
  1813. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  1814. showRenamePattern (engine.getSong().currentPattern);
  1815. }
  1816. void MainComponent::deleteCurrentPattern()
  1817. {
  1818. // FL's Patterns › Delete (Ctrl+Shift+Del); the last pattern stays
  1819. if (engine.getSong().patterns.size() > 1)
  1820. engine.editSong ([] (Song& s) { s.removePattern (s.currentPattern); });
  1821. }
  1822. void MainComponent::insertPatternHere()
  1823. {
  1824. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  1825. }
  1826. // --- window menus ------------------------------------------------------------------------------
  1827. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  1828. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  1829. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  1830. {
  1831. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  1832. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  1833. };
  1834. auto zoomMenu = [&action] (const juce::String& prefix) {
  1835. juce::PopupMenu zoom;
  1836. const std::pair<const char*, const char*> items[] = {
  1837. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  1838. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  1839. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  1840. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  1841. };
  1842. for (const auto& [id, text] : items)
  1843. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  1844. action (zoom, a->id, tr (text));
  1845. return zoom;
  1846. };
  1847. switch (panel)
  1848. {
  1849. case Panel::channelRack:
  1850. {
  1851. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  1852. menu.addSeparator();
  1853. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  1854. action (menu, "rack.pianoRollView", tr ("Piano-roll view of all channels"), true, rack.isPianoRollView());
  1855. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  1856. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  1857. juce::PopupMenu sort;
  1858. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  1859. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  1860. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  1861. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  1862. menu.addSubMenu (tr ("Sort channels"), sort);
  1863. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  1864. action (menu, "rack.groupSelected", tr ("Group selected..."));
  1865. break;
  1866. }
  1867. case Panel::playlist:
  1868. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  1869. workspace.toggleMaximised (Panel::playlist);
  1870. refreshPanelButtons();
  1871. });
  1872. menu.addSeparator();
  1873. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  1874. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  1875. action (menu, "playlist.autoCrossfades", tr ("Automatic crossfades (current project)"), true, engine.getSong().autoCrossfades);
  1876. action (menu, "playlist.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (false));
  1877. action (menu, "playlist.pitchClipsDown", tr ("Pitch selected audio clips one semitone down"));
  1878. action (menu, "playlist.pitchClipsUp", tr ("Pitch selected audio clips one semitone up"));
  1879. action (menu, "playlist.reverseClips", tr ("Reverse selected audio clips"));
  1880. action (menu, "playlist.quantizeStarts", tr ("Quantize the clips' starts"));
  1881. action (menu, "playlist.quantizeHalf", tr ("Quantize the clips' starts 50% (halfway to the grid)"));
  1882. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  1883. menu.addSeparator();
  1884. // FL's Performance mode (round 165m)
  1885. action (menu, "playlist.performanceMode", tr ("Performance mode"), true, engine.getSong().performanceMode);
  1886. action (menu, "playlist.zoomPerformance", tr ("Zoom on performance clips"), engine.getSong().performanceZoneEnd() > 0);
  1887. action (menu, "playlist.perfClipProgress", tr ("Performance clip progress"), true, playlist.clipProgressShown());
  1888. action (menu, "playlist.perfTrackProgress", tr ("Performance track progress"), true, playlist.trackProgressShown());
  1889. break;
  1890. case Panel::pianoRoll:
  1891. {
  1892. juce::PopupMenu tools;
  1893. for (const auto* id : { "pianoRoll.riffMachine", "pianoRoll.chordProgression", "pianoRoll.articulate", "pianoRoll.quantize",
  1894. "pianoRoll.chop", "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flam", "pianoRoll.claw",
  1895. "pianoRoll.limit", "pianoRoll.flip", "pianoRoll.randomise", "pianoRoll.scaleLevels", "pianoRoll.lfo" })
  1896. if (const auto* a = keys::findAction (id))
  1897. action (tools, a->id, tr (a->description));
  1898. menu.addSubMenu (tr ("Tools"), tools);
  1899. action (menu, "pianoRoll.quickQuantize", tr ("Quick quantize (starts and lengths)"));
  1900. action (menu, "pianoRoll.quantizeStarts", tr ("Quantize starts"));
  1901. action (menu, "pianoRoll.quantizeHalf", tr ("Quantize starts 50% (halfway to the grid)"));
  1902. action (menu, "pianoRoll.follow", tr ("Follow the playhead (auto scrolling)"), true, EditorGlobals::get().isFollowing (true));
  1903. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  1904. menu.addItem (tr ("Snap notes to the scale"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  1905. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  1906. break;
  1907. }
  1908. case Panel::mixer:
  1909. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  1910. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  1911. menu.addSeparator();
  1912. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  1913. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  1914. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  1915. break;
  1916. case Panel::browser:
  1917. action (menu, "browser.search", tr ("Search the Browser"));
  1918. browser.addViewItems (menu); // what it lists, which folders it shows (round 163)
  1919. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  1920. action (menu, "view.sampleBrowser", tr ("Sample browser (separate window)"));
  1921. menu.addSeparator();
  1922. // the search index (round 162, issue #9): searches read it; it follows changed folders by itself
  1923. menu.addSectionHeader (browser.searchIndexStatus());
  1924. menu.addItem (tr ("Refresh search index"), [this] { browser.refreshSearchIndex (false); });
  1925. menu.addItem (tr ("Rebuild search index"), [this] { browser.refreshSearchIndex (true); });
  1926. break;
  1927. default:
  1928. break;
  1929. }
  1930. }
  1931. // --- quick-add palette and history -------------------------------------------------------------
  1932. void MainComponent::showQuickAdd()
  1933. {
  1934. QuickAddTargets targets;
  1935. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  1936. targets.addInstrument = [this] (ChannelDef c) {
  1937. rack.addChannel (std::move (c), true);
  1938. showPanel (Panel::channelRack);
  1939. };
  1940. targets.addEffect = [this] (EffectSlot slot) {
  1941. if (! mixer.addEffectToSelected (std::move (slot)))
  1942. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  1943. tr ("The selected insert has no free effect slot."));
  1944. else
  1945. showPanel (Panel::mixer);
  1946. };
  1947. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  1948. }
  1949. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  1950. {
  1951. QuickAddTargets targets;
  1952. targets.addInstrument = [] (ChannelDef) {};
  1953. targets.addEffect = [] (EffectSlot) {};
  1954. return makeQuickAddPalette (engine, std::move (targets));
  1955. }
  1956. void MainComponent::showHistory()
  1957. {
  1958. if (auto* open = findToolWindow ("history"))
  1959. {
  1960. open->toFront (true);
  1961. return;
  1962. }
  1963. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  1964. }
  1965. // --- recording options ---------------------------------------------------------------------------
  1966. void MainComponent::updateRecordQuantise()
  1967. {
  1968. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  1969. std::int64_t ticks = 0;
  1970. // (the grid is kept even with "Note start time" off: "Note end time" uses it too)
  1971. {
  1972. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  1973. if (option.kind == grid::Kind::ticks)
  1974. ticks = option.ticks;
  1975. else if (option.kind == grid::Kind::bar)
  1976. ticks = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  1977. }
  1978. if (engine.getRecordOptions().quantise != ticks || engine.getRecordOptions().quantiseStarts != recordQuantiseOn)
  1979. {
  1980. auto o = engine.getRecordOptions();
  1981. o.quantise = ticks;
  1982. o.quantiseStarts = recordQuantiseOn;
  1983. engine.setRecordOptions (o);
  1984. }
  1985. }
  1986. void MainComponent::addRecordQuantizeItems (juce::PopupMenu& menu)
  1987. {
  1988. const auto o = engine.getRecordOptions();
  1989. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  1990. auto options = engine.getRecordOptions();
  1991. change (options);
  1992. engine.setRecordOptions (options);
  1993. saveUiSettings();
  1994. };
  1995. // FL's record menu "Quantize" items (REA round 139), to the global snap
  1996. menu.addItem (tr ("Note start time"), ! o.toStepSequencer, recordQuantiseOn && ! o.toStepSequencer, [this] {
  1997. recordQuantiseOn = ! recordQuantiseOn;
  1998. updateRecordQuantise();
  1999. saveUiSettings();
  2000. });
  2001. menu.addItem (tr ("Note end time"), ! o.toStepSequencer, o.noteEnd == NoteEnd::quantize && ! o.toStepSequencer, [set] {
  2002. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::quantize ? NoteEnd::keepEnd : NoteEnd::quantize; });
  2003. });
  2004. menu.addItem (tr ("Leave note duration"), ! o.toStepSequencer, o.noteEnd == NoteEnd::keepLength && ! o.toStepSequencer, [set] {
  2005. set ([] (AudioEngine::RecordOptions& r) { r.noteEnd = r.noteEnd == NoteEnd::keepLength ? NoteEnd::keepEnd : NoteEnd::keepLength; });
  2006. });
  2007. menu.addItem (tr ("Record to step sequencer"), true, o.toStepSequencer,
  2008. [set] { set ([] (AudioEngine::RecordOptions& r) { r.toStepSequencer = ! r.toStepSequencer; }); });
  2009. // FL's "Automations" (RecQuantizeAutomationsMenu, setting QuantizeAutomations; REA round 143): recorded automation
  2010. // points go to the snap
  2011. menu.addItem (tr ("Automations"), true, o.quantiseAutomation,
  2012. [set] { set ([] (AudioEngine::RecordOptions& r) { r.quantiseAutomation = ! r.quantiseAutomation; }); });
  2013. }
  2014. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  2015. {
  2016. const auto o = engine.getRecordOptions();
  2017. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2018. auto options = engine.getRecordOptions();
  2019. change (options);
  2020. engine.setRecordOptions (options);
  2021. refreshRecordOptionButtons();
  2022. saveUiSettings();
  2023. };
  2024. juce::PopupMenu countIn;
  2025. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set ([] (AudioEngine::RecordOptions& r) { r.countInBars = 0; }); });
  2026. for (int bars : { 1, 2, 4 })
  2027. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars,
  2028. [set, bars] { set ([bars] (AudioEngine::RecordOptions& r) { r.countInBars = bars; }); });
  2029. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), countIn);
  2030. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  2031. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  2032. // round 163: punch in/out on the loop region, pre-roll and post-roll (bars)
  2033. {
  2034. auto bars = [&set] (juce::PopupMenu& m, int now, std::function<void (AudioEngine::RecordOptions&, int)> apply) {
  2035. m.addItem (tr ("Off"), true, now == 0, [set, apply] { set ([apply] (AudioEngine::RecordOptions& r) { apply (r, 0); }); });
  2036. for (int n : { 1, 2, 4 })
  2037. m.addItem (n == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (n) }), true, now == n,
  2038. [set, apply, n] { set ([apply, n] (AudioEngine::RecordOptions& r) { apply (r, n); }); });
  2039. };
  2040. juce::PopupMenu pre, post;
  2041. bars (pre, o.preRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.preRollBars = n; });
  2042. bars (post, o.postRollBars, [] (AudioEngine::RecordOptions& r, int n) { r.postRollBars = n; });
  2043. menu.addItem (tr ("Audio: punch in/out on the loop region (plays through it, keeps only the region)"), true, o.punchLoopRegion,
  2044. [set] { set ([] (AudioEngine::RecordOptions& r) { r.punchLoopRegion = ! r.punchLoopRegion; }); });
  2045. menu.addSubMenu (tr ("Audio: pre-roll (plays before the punch-in or the start position)"), pre);
  2046. menu.addSubMenu (tr ("Audio: post-roll (plays after the punch-out, then stops)"), post);
  2047. }
  2048. menu.addSeparator();
  2049. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  2050. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  2051. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  2052. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  2053. menu.addSeparator();
  2054. {
  2055. juce::PopupMenu quantize;
  2056. addRecordQuantizeItems (quantize);
  2057. menu.addSubMenu (tr ("Quantize recorded notes to the global snap"), quantize);
  2058. }
  2059. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  2060. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  2061. }
  2062. void MainComponent::toggleRecording()
  2063. {
  2064. if (engine.isRecording())
  2065. {
  2066. engine.setRecording (false);
  2067. return;
  2068. }
  2069. if (! engine.getRecordOptions().askWhatToRecord || ! persistent)
  2070. {
  2071. engine.setRecording (true);
  2072. if (engine.getRecordOptions().startsPlayback && ! engine.getTransport().playing.load()) // FL's "Recording starts playback"
  2073. engine.startPlayback();
  2074. return;
  2075. }
  2076. juce::Component::SafePointer<MainComponent> safe (this);
  2077. showRecordChoiceDialog ([safe] (int choice, bool dontAsk) {
  2078. if (safe == nullptr)
  2079. return;
  2080. if (choice == recordChoiceAudioEditor)
  2081. {
  2082. openAudioEditorRecording (safe->engine);
  2083. if (! safe->engine.getTransport().playing.load())
  2084. safe->engine.play();
  2085. return;
  2086. }
  2087. auto o = safe->engine.getRecordOptions();
  2088. o.recordNotes = choice != recordChoiceAudio;
  2089. o.recordAudio = choice != recordChoiceNotes;
  2090. o.recordAutomation = choice != recordChoiceAudio;
  2091. if (dontAsk)
  2092. o.askWhatToRecord = false;
  2093. safe->engine.setRecordOptions (o);
  2094. if (dontAsk)
  2095. safe->saveUiSettings();
  2096. if (choice == recordChoiceAudio && safe->engine.getArmedInserts().empty())
  2097. safe->armSelectedInsertForAudio();
  2098. safe->engine.setRecording (true);
  2099. if (o.startsPlayback && ! safe->engine.getTransport().playing.load()) // FL's "Recording starts playback"
  2100. safe->engine.startPlayback();
  2101. });
  2102. }
  2103. // Round 163: the fastest way from "press record" to a clip on the Playlist — one key arms the selected insert (or the
  2104. // one with an input), records audio only (no question) and starts playback (count-in / pre-roll as set); pressed
  2105. // again it stops, and the take is on the Playlist.
  2106. void MainComponent::quickRecordAudio()
  2107. {
  2108. auto& transport = engine.getTransport();
  2109. if (engine.isRecording() && (transport.playing.load() || engine.isCountingIn() || engine.isWaitingForInput()))
  2110. {
  2111. engine.stop();
  2112. engine.setRecording (false);
  2113. return;
  2114. }
  2115. if (engine.getArmedInserts().empty())
  2116. armSelectedInsertForAudio();
  2117. if (engine.getArmedInserts().empty()) // no input yet: its menu is open, nothing to record
  2118. return;
  2119. if (auto o = engine.getRecordOptions(); ! o.recordAudio)
  2120. {
  2121. o.recordAudio = true;
  2122. engine.setRecordOptions (o);
  2123. }
  2124. engine.setRecording (true);
  2125. if (! transport.playing.load())
  2126. engine.startPlayback();
  2127. }
  2128. void MainComponent::armSelectedInsertForAudio()
  2129. {
  2130. const auto& mixer = engine.getSong().mixer;
  2131. // the selected insert, else the first one with an input, else a free one
  2132. auto target = this->mixer.getStripsForSnapshot().getSelectedTrack();
  2133. for (int t = 1; target <= 0 && t < (int) mixer.size(); ++t)
  2134. if (mixer[(std::size_t) t].inputChannel >= 0)
  2135. target = t;
  2136. if (target <= 0)
  2137. target = engine.getSong().nextFreeInsert();
  2138. if (target <= 0 || target >= (int) mixer.size())
  2139. return;
  2140. showPanel (Panel::mixer);
  2141. this->mixer.selectTrack (target);
  2142. if (engine.isInsertArmed (target))
  2143. return;
  2144. // this menu item says "(choose its input)": without one, the input menu comes first and arms after the choice
  2145. if (mixer[(std::size_t) target].inputChannel < 0)
  2146. mixerinput::showMenu (engine, target, &this->mixer, [this, target] { engine.setInsertArmed (target, true); });
  2147. else
  2148. mixerinput::toggleArm (engine, target, &this->mixer);
  2149. }
  2150. void MainComponent::showMetronomeMenu()
  2151. {
  2152. // FL 2026's right-click on the metronome button, as it is (REA round 165z-a2): the "Metronome sound" choice only,
  2153. // in FL's order. The volume trim is in Options, the count-in has its own button and the track the click plays
  2154. // through is in Settings › Audio › Mixer.
  2155. auto& transport = engine.getTransport();
  2156. juce::PopupMenu menu;
  2157. menu.addSectionHeader (tr ("Metronome sound"));
  2158. for (int i = 0; i < metronome::soundCount; ++i)
  2159. menu.addItem (tr (metronome::soundName (i)), true, metronome::clampSound (transport.metronomeSound.load()) == i, [this, i] {
  2160. engine.getTransport().metronomeSound.store (i);
  2161. saveUiSettings();
  2162. });
  2163. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&metronomeButton));
  2164. }
  2165. void MainComponent::dumpScoreLog (int minutes)
  2166. {
  2167. const auto& song = engine.getSong();
  2168. scorelog::DumpOptions options;
  2169. options.minutes = minutes;
  2170. options.bpm = song.bpm;
  2171. options.beatsPerBar = song.beatsPerBar;
  2172. auto notes = scorelog::dump (engine.scoreLogSnapshot(), options);
  2173. // (channels deleted since the notes were played are left out)
  2174. notes.erase (std::remove_if (notes.begin(), notes.end(), [&song] (const Note& n) { return n.channel < 0 || n.channel >= (int) song.channels.size(); }),
  2175. notes.end());
  2176. if (notes.empty())
  2177. {
  2178. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Score logger"),
  2179. tr ("The score log is empty: no notes were played on a MIDI keyboard or the typing keyboard in that time."));
  2180. return;
  2181. }
  2182. auto apply = [this] (std::vector<Note> logged, bool replace) {
  2183. const auto count = logged.size();
  2184. engine.editSong ([&logged, replace] (Song& s) {
  2185. if (s.patterns.empty())
  2186. s.patterns.emplace_back();
  2187. s.currentPattern = juce::jlimit (0, (int) s.patterns.size() - 1, s.currentPattern);
  2188. auto& pattern = s.patterns[(std::size_t) s.currentPattern];
  2189. if (replace)
  2190. pattern.notes.clear();
  2191. pattern.notes.insert (pattern.notes.end(), logged.begin(), logged.end());
  2192. pattern.sortNotes();
  2193. });
  2194. ui::postHint ({ tr ("Score log: {0} notes put in the pattern", { juce::String ((int) count) }), {}, false, false }, 4000);
  2195. };
  2196. const auto& patterns = song.patterns;
  2197. const auto current = song.currentPattern;
  2198. if (current < 0 || current >= (int) patterns.size() || patterns[(std::size_t) current].notes.empty())
  2199. {
  2200. apply (std::move (notes), false);
  2201. return;
  2202. }
  2203. auto box = juce::MessageBoxOptions()
  2204. .withIconType (juce::MessageBoxIconType::QuestionIcon)
  2205. .withTitle (tr ("Score logger"))
  2206. .withMessage (tr ("The current pattern isn't empty. Do you want the score log to be merged, or to replace the current content?"))
  2207. .withButton (tr ("Merge"))
  2208. .withButton (tr ("Replace"))
  2209. .withButton (tr ("Cancel"));
  2210. juce::AlertWindow::showAsync (box, [apply, notes] (int result) mutable {
  2211. if (result == 1 || result == 2)
  2212. apply (std::move (notes), result == 2);
  2213. });
  2214. }
  2215. void MainComponent::showMetronomeVolume()
  2216. {
  2217. // a callout with the volume knob; the click plays at the new level at once (Transport::metronomeVolume)
  2218. struct VolumePanel final : public juce::Component
  2219. {
  2220. VolumePanel (MainComponent& m) : owner (m)
  2221. {
  2222. title.setText (tr ("Metronome volume"), juce::dontSendNotification);
  2223. title.setJustificationType (juce::Justification::centred);
  2224. addAndMakeVisible (title);
  2225. knob.setSliderStyle (juce::Slider::RotaryHorizontalVerticalDrag);
  2226. knob.setTextBoxStyle (juce::Slider::TextBoxBelow, false, 120, 18);
  2227. knob.setRange (0.0, controls::maxUtilityVolume, 0.01);
  2228. knob.setDoubleClickReturnValue (true, 1.0);
  2229. knob.textFromValueFunction = [] (double v) { return ui::utilityVolumeText (v); };
  2230. knob.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  2231. knob.setValue (owner.engine.getTransport().metronomeVolume.load(), juce::dontSendNotification);
  2232. knob.onValueChange = [this] { owner.engine.getTransport().metronomeVolume.store ((float) knob.getValue()); };
  2233. knob.onDragEnd = [this] { owner.saveUiSettings(); };
  2234. ui::setHint (knob, tr ("Metronome volume: 100% is the default click level, up to 125% [2xLMB] 100%"));
  2235. addAndMakeVisible (knob);
  2236. setSize (170, 150);
  2237. }
  2238. ~VolumePanel() override { owner.saveUiSettings(); }
  2239. void resized() override
  2240. {
  2241. auto r = getLocalBounds().reduced (8);
  2242. title.setBounds (r.removeFromTop (20));
  2243. knob.setBounds (r);
  2244. }
  2245. MainComponent& owner;
  2246. juce::Label title;
  2247. juce::Slider knob;
  2248. };
  2249. juce::CallOutBox::launchAsynchronously (std::make_unique<VolumePanel> (*this), metronomeButton.getScreenBounds(), nullptr);
  2250. }
  2251. void MainComponent::openAudioEditorForSelection()
  2252. {
  2253. const auto& song = engine.getSong();
  2254. const auto channel = engine.getSelectedChannel();
  2255. if (juce::isPositiveAndBelow (channel, (int) song.channels.size()))
  2256. {
  2257. const auto& c = song.channels[(std::size_t) channel];
  2258. if ((c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && ! c.samplePath.empty())
  2259. {
  2260. openAudioEditorForChannel (engine, channel);
  2261. return;
  2262. }
  2263. }
  2264. openAudioEditor (engine);
  2265. }
  2266. void MainComponent::showRecordMenu()
  2267. {
  2268. const auto o = engine.getRecordOptions();
  2269. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  2270. auto options = engine.getRecordOptions();
  2271. change (options);
  2272. engine.setRecordOptions (options);
  2273. saveUiSettings();
  2274. };
  2275. juce::PopupMenu menu;
  2276. menu.addSectionHeader (tr ("Recording filter"));
  2277. // FL's filter order (RecMenu, REA round 143): Automation, Notes, Audio
  2278. menu.addItem (tr ("Automation (the controls you move: automation clips in song mode, pattern events in pattern mode)"), true,
  2279. o.recordAutomation, [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAutomation = ! r.recordAutomation; }); });
  2280. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), true, o.recordNotes,
  2281. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordNotes = ! r.recordNotes; }); });
  2282. menu.addItem (tr ("Audio of the armed mixer inserts (becomes Playlist clips)"), true, o.recordAudio,
  2283. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordAudio = ! r.recordAudio; }); });
  2284. menu.addItem (tr ("Clips (Performance mode: the launched clips are written into the arrangement)"), true, o.recordClips,
  2285. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordClips = ! r.recordClips; }); });
  2286. menu.addItem (tr ("Ask what to record when recording starts"), true, o.askWhatToRecord,
  2287. [set] { set ([] (AudioEngine::RecordOptions& r) { r.askWhatToRecord = ! r.askWhatToRecord; }); });
  2288. // FL's "Options" section (REA round 134)
  2289. menu.addSectionHeader (tr ("Options"));
  2290. menu.addItem (tr ("Recording starts playback"), true, o.startsPlayback,
  2291. [set] { set ([] (AudioEngine::RecordOptions& r) { r.startsPlayback = ! r.startsPlayback; }); });
  2292. menu.addItem (tr ("Disarm on stop (recording switches off when playback stops)"), true, o.recordOffOnStop,
  2293. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordOffOnStop = ! r.recordOffOnStop; }); });
  2294. // LYNX's own (issue #16; FL has no such option): also in Mixer › Disk recording
  2295. menu.addItem (tr ("Disarm the inserts when recording stops"), true, o.disarmOnStop,
  2296. [set] { set ([] (AudioEngine::RecordOptions& r) { r.disarmOnStop = ! r.disarmOnStop; }); });
  2297. menu.addItem (tr ("Enable recording markers (Start / Stop recording markers in the Playlist)"), true, o.recordingMarkers,
  2298. [set] { set ([] (AudioEngine::RecordOptions& r) { r.recordingMarkers = ! r.recordingMarkers; }); });
  2299. // FL's "Quantize" section (REA round 139): to the global snap
  2300. menu.addSectionHeader (tr ("Quantize"));
  2301. addRecordQuantizeItems (menu);
  2302. menu.addItem (tr ("Record into the audio editor..."), [this] { openAudioEditor (engine); });
  2303. menu.addSeparator();
  2304. menu.addItem (tr ("Arm the selected mixer insert for audio (choose its input)..."), [this] { armSelectedInsertForAudio(); });
  2305. menu.addItem (tr ("Audio settings (input device)..."), [this] { openSettings ((int) SettingsPage::audio); });
  2306. menu.addItem (tr ("Open recordings folder"), [this] {
  2307. const auto folder = engine.getRecordingFolder();
  2308. folder.createDirectory();
  2309. folder.startAsProcess();
  2310. });
  2311. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  2312. menu.addSeparator();
  2313. addRecordOptions (menu);
  2314. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  2315. : (juce::Component*) &recordButton));
  2316. }
  2317. void MainComponent::refreshRecordOptionButtons()
  2318. {
  2319. auto withKey = [this] (const juce::String& text, const char* id) {
  2320. const auto key = shortcutText (id).trim();
  2321. return key.isEmpty() ? text : text + " (" + key + ")";
  2322. };
  2323. const auto o = engine.getRecordOptions();
  2324. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  2325. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  2326. : tr ("Count-in before recording: off"),
  2327. "record.countIn"));
  2328. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  2329. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  2330. "record.waitForInput"));
  2331. }
  2332. void MainComponent::clonePatternNow()
  2333. {
  2334. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  2335. }
  2336. void MainComponent::movePatternNow (int delta)
  2337. {
  2338. engine.editSong ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  2339. }
  2340. void MainComponent::splitPatternByChannelNow()
  2341. {
  2342. int created = 0;
  2343. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  2344. if (created == 0)
  2345. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  2346. }
  2347. void MainComponent::showRenamePattern (int index)
  2348. {
  2349. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  2350. return;
  2351. const auto& p = engine.getSong().patterns[(std::size_t) index];
  2352. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  2353. [this, index] (const juce::String& name, std::uint32_t colour) {
  2354. if (index < (int) engine.getSong().patterns.size())
  2355. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  2356. s.patterns[(std::size_t) index].name = n;
  2357. s.patterns[(std::size_t) index].colour = colour;
  2358. });
  2359. });
  2360. }
  2361. void MainComponent::refreshToolbar()
  2362. {
  2363. const auto& song = engine.getSong();
  2364. patternBox.clear (juce::dontSendNotification);
  2365. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  2366. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  2367. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  2368. swingSlider.setValue (song.swing, juce::dontSendNotification);
  2369. tempoDisplay.repaint();
  2370. refreshModeButton();
  2371. refreshRackPatternSelector();
  2372. refreshRackLengthBox();
  2373. }
  2374. void MainComponent::refreshRackPatternSelector()
  2375. {
  2376. const auto& song = engine.getSong();
  2377. const auto valid = song.currentPattern >= 0 && song.currentPattern < (int) song.patterns.size();
  2378. const auto text = valid ? juce::String::fromUTF8 (song.patterns[(std::size_t) song.currentPattern].name.c_str()) : juce::String();
  2379. const auto colour = valid ? PlaylistComponent::patternColour (song, song.currentPattern) : juce::Colour();
  2380. if (text != rackPatternSelector.text || colour != rackPatternSelector.colour)
  2381. {
  2382. rackPatternSelector.text = text;
  2383. rackPatternSelector.colour = colour;
  2384. rackPatternSelector.repaint();
  2385. }
  2386. }
  2387. void MainComponent::showRackPatternList()
  2388. {
  2389. const auto& song = engine.getSong();
  2390. juce::PopupMenu menu;
  2391. for (int i = 0; i < (int) song.patterns.size(); ++i)
  2392. menu.addItem (juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str()), true, i == song.currentPattern, [this, i] { selectPattern (i); });
  2393. menu.addSeparator();
  2394. menu.addItem (tr ("New pattern"), [this] { newPatternButton.onClick(); });
  2395. menu.addItem (tr ("Rename and color the pattern") + shortcutText ("pattern.rename"), [this] { runAction ("pattern.rename"); });
  2396. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackPatternSelector));
  2397. }
  2398. // --- the Channel Rack's pattern length box (issue #12) ---------------------------------------------------------
  2399. int MainComponent::PatternLengthBox::stepBars (int value, int delta)
  2400. {
  2401. static const int steps[] = { 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 };
  2402. constexpr int count = (int) (sizeof (steps) / sizeof (steps[0]));
  2403. int i = 0;
  2404. while (i + 1 < count && steps[i + 1] <= value)
  2405. ++i;
  2406. if (delta < 0 && steps[i] < value) // between two steps: going down lands on the lower one
  2407. ++delta;
  2408. return steps[juce::jlimit (0, count - 1, i + delta)];
  2409. }
  2410. void MainComponent::PatternLengthBox::paint (juce::Graphics& g)
  2411. {
  2412. using namespace theme;
  2413. const auto area = getLocalBounds().toFloat();
  2414. g.setColour (hovered ? colour::bg3 : colour::bg1);
  2415. g.fillRoundedRectangle (area, radius::sm);
  2416. g.setColour (hovered ? colour::borderStrong : colour::border);
  2417. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  2418. auto r = getLocalBounds().reduced (3, 0);
  2419. g.setFont (font (type::caption - 1.0f, true));
  2420. g.setColour (colour::textSecondary);
  2421. g.drawText (automatic ? "A" : "L", r.removeFromLeft (9), juce::Justification::centred, false);
  2422. g.setFont (font (type::small, true));
  2423. g.setColour (automatic ? colour::textSecondary : colour::textPrimary);
  2424. g.drawText (juce::String (bars), r, juce::Justification::centred, false);
  2425. }
  2426. void MainComponent::PatternLengthBox::mouseDown (const juce::MouseEvent& e)
  2427. {
  2428. dragStartBars = bars;
  2429. if (e.mods.isPopupMenu() && onMenu)
  2430. onMenu();
  2431. }
  2432. void MainComponent::PatternLengthBox::mouseDrag (const juce::MouseEvent& e)
  2433. {
  2434. if (e.mods.isPopupMenu() || onSet == nullptr)
  2435. return;
  2436. // one step of the list per 14 px up (as the rack's insert number box: drag up = more)
  2437. const auto delta = -e.getDistanceFromDragStartY() / 14;
  2438. const auto value = delta == 0 ? dragStartBars : stepBars (dragStartBars, delta);
  2439. if (value != bars || automatic)
  2440. if (delta != 0)
  2441. onSet (value);
  2442. }
  2443. void MainComponent::PatternLengthBox::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  2444. {
  2445. if (onSet != nullptr && wheel.deltaY != 0.0f)
  2446. onSet (stepBars (bars, wheel.deltaY > 0.0f ? 1 : -1));
  2447. }
  2448. void MainComponent::refreshRackLengthBox()
  2449. {
  2450. const auto& song = engine.getSong();
  2451. if (song.currentPattern < 0 || song.currentPattern >= (int) song.patterns.size())
  2452. return;
  2453. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  2454. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  2455. const auto bars = (int) juce::jmax<std::int64_t> (1, (pattern.effectiveLength (song.beatsPerBar) + bar - 1) / bar);
  2456. const auto automatic = pattern.lengthTicks == 0;
  2457. if (bars != rackLengthBox.bars || automatic != rackLengthBox.automatic)
  2458. {
  2459. rackLengthBox.bars = bars;
  2460. rackLengthBox.automatic = automatic;
  2461. rackLengthBox.setTooltip (automatic ? tr ("Pattern length: {0} (automatic, from the notes)", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) })
  2462. : tr ("Pattern length: {0}", { bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }) }));
  2463. rackLengthBox.repaint();
  2464. }
  2465. }
  2466. void MainComponent::showPatternLengthMenu()
  2467. {
  2468. const auto& song = engine.getSong();
  2469. const auto& pattern = song.patterns[(std::size_t) song.currentPattern];
  2470. const auto bar = (std::int64_t) ppq * juce::jmax (1, song.beatsPerBar);
  2471. juce::PopupMenu menu;
  2472. menu.addSectionHeader (tr ("Pattern length"));
  2473. menu.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0, [this] { rackLengthBox.onSet (0); });
  2474. for (int bars : { 1, 2, 4, 8, 16, 32 })
  2475. menu.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == bars * bar,
  2476. [this, bars] { rackLengthBox.onSet (bars); });
  2477. menu.addSeparator();
  2478. menu.addItem (tr ("Type value..."), [this] {
  2479. ui::ValueSpec spec;
  2480. spec.name = tr ("Pattern length (bars, 0 = automatic)");
  2481. spec.minimum = 0.0;
  2482. spec.maximum = 999.0;
  2483. spec.interval = 1.0;
  2484. ui::typeValue (rackLengthBox, spec, rackLengthBox.automatic ? 0.0 : (double) rackLengthBox.bars,
  2485. [this] (double v) { rackLengthBox.onSet (juce::roundToInt (v)); });
  2486. });
  2487. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&rackLengthBox));
  2488. }
  2489. void MainComponent::PatternSelector::paint (juce::Graphics& g)
  2490. {
  2491. using namespace theme;
  2492. auto area = getLocalBounds().toFloat();
  2493. g.setColour (hoveredPart >= 0 ? colour::bg3 : colour::bg1);
  2494. g.fillRoundedRectangle (area, radius::sm);
  2495. g.setColour (hoveredPart >= 0 ? colour::borderStrong : colour::border);
  2496. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  2497. // the pattern's colour as a thin stripe at the left of the name
  2498. if (! colour.isTransparent())
  2499. {
  2500. g.setColour (colour);
  2501. g.fillRect (juce::Rectangle<float> ((float) arrowWidth + 1.0f, 4.0f, 3.0f, (float) getHeight() - 8.0f));
  2502. }
  2503. auto arrow = [&g, this] (int part, bool left) {
  2504. const auto box = juce::Rectangle<float> (left ? 0.0f : (float) (getWidth() - arrowWidth), 0.0f, (float) arrowWidth, (float) getHeight());
  2505. const auto c = box.getCentre();
  2506. juce::Path p;
  2507. if (left)
  2508. p.addTriangle (c.x + 2.5f, c.y - 4.0f, c.x + 2.5f, c.y + 4.0f, c.x - 2.5f, c.y);
  2509. else
  2510. p.addTriangle (c.x - 2.5f, c.y - 4.0f, c.x - 2.5f, c.y + 4.0f, c.x + 2.5f, c.y);
  2511. g.setColour (hoveredPart == part ? colour::textPrimary : colour::textSecondary);
  2512. g.fillPath (p);
  2513. };
  2514. arrow (0, true);
  2515. arrow (2, false);
  2516. g.setColour (colour::textPrimary);
  2517. g.setFont (font (type::small, true));
  2518. const auto name = getLocalBounds().withTrimmedLeft (arrowWidth + 7).withTrimmedRight (arrowWidth + 14);
  2519. g.drawText (text, name, juce::Justification::centredLeft, true);
  2520. icons::draw (g, Icon::chevronDown, juce::Rectangle<float> ((float) (getWidth() - arrowWidth - 14), 0.0f, 12.0f, (float) getHeight()).reduced (1.0f, 4.0f),
  2521. hoveredPart == 1 ? colour::textPrimary : colour::textSecondary);
  2522. g.setColour (colour::border);
  2523. g.fillRect (arrowWidth, 3, 1, getHeight() - 6);
  2524. g.fillRect (getWidth() - arrowWidth - 1, 3, 1, getHeight() - 6);
  2525. }
  2526. void MainComponent::PatternSelector::mouseDown (const juce::MouseEvent& e)
  2527. {
  2528. const auto part = partAt (e.x);
  2529. if (part == 1 || e.mods.isPopupMenu())
  2530. {
  2531. if (onMenu)
  2532. onMenu();
  2533. }
  2534. else if (onStep)
  2535. onStep (part == 0 ? -1 : 1);
  2536. }
  2537. void MainComponent::PatternSelector::mouseWheelMove (const juce::MouseEvent&, const juce::MouseWheelDetails& wheel)
  2538. {
  2539. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  2540. if (delta != 0.0f && onStep)
  2541. onStep (delta > 0.0f ? -1 : 1);
  2542. }
  2543. juce::PopupMenu MainComponent::makePatternMenu()
  2544. {
  2545. const auto& song = engine.getSong();
  2546. const auto index = song.currentPattern;
  2547. const auto& pattern = song.patterns[(std::size_t) index];
  2548. auto colours = ui::colourMenu (pattern.colour, [this, index] (std::uint32_t c) {
  2549. if (index < (int) engine.getSong().patterns.size())
  2550. engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; });
  2551. }, juce::Rectangle<int> (juce::Desktop::getMousePosition().x, juce::Desktop::getMousePosition().y, 1, 1));
  2552. juce::PopupMenu lengths;
  2553. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  2554. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  2555. for (int bars : { 1, 2, 4, 8, 16, 32 })
  2556. {
  2557. const auto ticks = (std::int64_t) bars * ppq * juce::jmax (1, song.beatsPerBar);
  2558. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  2559. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  2560. }
  2561. juce::PopupMenu menu;
  2562. // a double-click on the title renames the pattern (issue #12)
  2563. ui::addItemHeader (menu, tr ("Pattern"), juce::String::fromUTF8 (pattern.name.c_str()), PlaylistComponent::patternColour (song, index),
  2564. [this, index] { showRenamePattern (index); });
  2565. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  2566. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  2567. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  2568. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  2569. menu.addItem (tr ("First empty pattern (and name it)") + shortcutText ("pattern.firstEmpty"), [this] { runAction ("pattern.firstEmpty"); });
  2570. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  2571. menu.addItem (tr ("Next empty pattern (no naming)") + shortcutText ("pattern.nextEmptyNoName"), [this] { runAction ("pattern.nextEmptyNoName"); });
  2572. menu.addSeparator();
  2573. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  2574. menu.addSubMenu (tr ("Color"), colours);
  2575. menu.addSubMenu (tr ("Length"), lengths);
  2576. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  2577. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  2578. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  2579. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  2580. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  2581. juce::PopupMenu signatures;
  2582. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  2583. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats,
  2584. [this, beats] { engine.editSong ([beats] (Song& s) { s.beatsPerBar = beats; }); });
  2585. menu.addSubMenu (tr ("Song time signature"), signatures);
  2586. menu.addSeparator();
  2587. menu.addItem (tr ("Delete pattern") + shortcutText ("pattern.delete"), song.patterns.size() > 1, false,
  2588. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  2589. return menu;
  2590. }
  2591. void MainComponent::showPatternMenu()
  2592. {
  2593. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  2594. }
  2595. void MainComponent::refreshModeButton()
  2596. {
  2597. const auto recording = engine.isRecording();
  2598. recordButton.setToggleState (recording, juce::dontSendNotification);
  2599. const auto inputs = engine.getActiveMidiInputs();
  2600. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  2601. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  2602. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  2603. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  2604. recordMenuButton.setOnColour (theme::colour::accentMuted);
  2605. const auto songMode = engine.getSong().mode == PlayMode::song;
  2606. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  2607. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  2608. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  2609. }
  2610. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  2611. {
  2612. if (const auto notice = engine.takeRecordingNotice(); notice.issue != AudioEngine::InputIssue::none && persistent)
  2613. mixerinput::explain (notice);
  2614. // round 165c: hardware inserts measured for another device setup (the device or its buffer size changed, or the project
  2615. // was measured elsewhere): a prompt that pings them on request, nothing pinged by itself (pings make clicks)
  2616. if (auto stale = engine.takeHardwareInsertNotice(); ! stale.empty() && persistent)
  2617. {
  2618. const auto count = (int) stale.size();
  2619. auto options = juce::MessageBoxOptions()
  2620. .withIconType (juce::MessageBoxIconType::InfoIcon)
  2621. .withTitle (tr ("Hardware Insert"))
  2622. .withMessage ((count == 1 ? tr ("The round trip of a hardware insert was measured for another audio setup (the device or its "
  2623. "buffer size changed), so its return is no longer lined up with the rest of the mix.")
  2624. : tr ("The round trip of {0} hardware inserts was measured for another audio setup (the device or its "
  2625. "buffer size changed), so their returns are no longer lined up with the rest of the mix.",
  2626. { juce::String (count) }))
  2627. + "\n\n" + tr ("Ping now? Each one sends a few clicks out to its gear and listens for them on its return."))
  2628. .withButton (tr ("Ping now"))
  2629. .withButton (tr ("Later"));
  2630. juce::AlertWindow::showAsync (options, [safe = juce::Component::SafePointer<MainComponent> (this), stale = std::move (stale)] (int result) {
  2631. if (result == 1 && safe != nullptr)
  2632. safe->engine.pingHardwareInserts (stale);
  2633. });
  2634. }
  2635. const auto& song = engine.getSong();
  2636. // FL's "Select first channel with notes when the pattern changes" (Settings › General, REA round 167j §5)
  2637. if (song.currentPattern != lastCurrentPattern)
  2638. {
  2639. const auto changedPattern = lastCurrentPattern >= 0;
  2640. lastCurrentPattern = song.currentPattern;
  2641. if (changedPattern && ChannelRackComponent::selectFirstChannelWithNotes)
  2642. if (const auto first = firstChannelWithNotes (song, song.currentPattern); first >= 0 && first != engine.getSelectedChannel())
  2643. engine.setSelectedChannel (first);
  2644. }
  2645. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  2646. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  2647. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  2648. refreshModeButton();
  2649. tempoDisplay.repaint();
  2650. // a project with other filter groups (or none): the rack's filter falls back to "All"
  2651. if (rack.getFilterGroup() >= (int) song.channelGroups.size())
  2652. rack.setFilterGroup (-1);
  2653. if (rackFilterBox.text != rack.filterName())
  2654. {
  2655. rackFilterBox.text = rack.filterName();
  2656. rackFilterBox.repaint();
  2657. }
  2658. if (rackLoopButton.getToggleState() != rack.isLoopingOn()) // (another pattern, undo)
  2659. rackLoopButton.setToggleState (rack.isLoopingOn(), juce::dontSendNotification);
  2660. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  2661. fitChannelRack (false);
  2662. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  2663. refreshToolbar();
  2664. else
  2665. {
  2666. refreshRackPatternSelector(); // a new pattern colour
  2667. refreshRackLengthBox(); // (notes added: the automatic length grows)
  2668. }
  2669. }
  2670. // --- tempo display -------------------------------------------------------------------------------
  2671. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  2672. {
  2673. ui::ValueSpec s;
  2674. s.name = tr ("Tempo");
  2675. s.minimum = minTempo;
  2676. s.maximum = maxTempo;
  2677. s.defaultValue = 130.0;
  2678. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  2679. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  2680. return s;
  2681. }
  2682. void MainComponent::TempoDisplay::setBpm (double bpm)
  2683. {
  2684. bpm = controls::clampTempo (bpm);
  2685. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  2686. engine.editSong ([bpm] (Song& s) { s.bpm = bpm; });
  2687. repaint();
  2688. }
  2689. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  2690. {
  2691. return decimalX > 0 && x > decimalX;
  2692. }
  2693. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  2694. {
  2695. using namespace theme;
  2696. const auto area = getLocalBounds().toFloat();
  2697. g.setColour (colour::bg1);
  2698. g.fillRoundedRectangle (area, radius::md);
  2699. if (dragging)
  2700. {
  2701. g.setColour (colour::accent.withAlpha (0.6f));
  2702. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  2703. }
  2704. const auto bpm = engine.getSong().bpm;
  2705. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  2706. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  2707. const juce::Font big (monoFont (18.0f)), small (monoFont (11.0f)), caption (font (type::caption - 1.0f));
  2708. const auto wholeWidth = juce::GlyphArrangement::getStringWidth (big, whole);
  2709. const auto fracWidth = juce::GlyphArrangement::getStringWidth (small, "." + fraction);
  2710. const auto unitWidth = juce::GlyphArrangement::getStringWidth (caption, "BPM");
  2711. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  2712. const auto baseline = area.getCentreY() + 5.0f;
  2713. g.setColour (colour::textPrimary);
  2714. g.setFont (big);
  2715. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  2716. x += wholeWidth;
  2717. decimalX = juce::roundToInt (x);
  2718. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  2719. g.setFont (small);
  2720. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  2721. x += fracWidth + 6.0f;
  2722. g.setColour (colour::textDisabled);
  2723. g.setFont (caption);
  2724. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  2725. }
  2726. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  2727. {
  2728. if (e.mods.isPopupMenu())
  2729. {
  2730. showMenu();
  2731. return;
  2732. }
  2733. if (ui::isResetClick (e))
  2734. {
  2735. setBpm (spec().defaultValue);
  2736. return;
  2737. }
  2738. startBpm = engine.getSong().bpm;
  2739. dragOnDecimals = isOnDecimals (e.x);
  2740. dragging = true;
  2741. repaint();
  2742. }
  2743. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  2744. {
  2745. if (dragging)
  2746. {
  2747. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  2748. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  2749. }
  2750. }
  2751. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  2752. {
  2753. dragging = false;
  2754. repaint();
  2755. }
  2756. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  2757. {
  2758. if (! e.mods.isPopupMenu())
  2759. ui::typeValue (*this, spec(), engine.getSong().bpm, [this] (double v) { setBpm (v); });
  2760. }
  2761. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  2762. {
  2763. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  2764. if (delta == 0.0f)
  2765. return;
  2766. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  2767. engine.noteTweaked ({ AutomationTargetKind::tempo, 0 });
  2768. setBpm (engine.getSong().bpm + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  2769. }
  2770. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  2771. {
  2772. return ui::valueHint (spec(), engine.getSong().bpm,
  2773. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  2774. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  2775. }
  2776. void MainComponent::TempoDisplay::showMenu()
  2777. {
  2778. const auto bpm = engine.getSong().bpm;
  2779. juce::PopupMenu menu;
  2780. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  2781. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  2782. menu.addItem (tr ("Tempo tapper..."), [this] { showTap(); });
  2783. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  2784. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  2785. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  2786. menu.addSeparator();
  2787. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  2788. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  2789. }
  2790. void MainComponent::TempoDisplay::showTap()
  2791. {
  2792. openTempoTapper (engine); // FL's tempo menu opens its tempo tapper too
  2793. }
  2794. // --- hint bar ------------------------------------------------------------------------------------
  2795. juce::String MainComponent::idleHint() const
  2796. {
  2797. if (engine.isWaitingForInput())
  2798. return tr ("Recording: waiting for the first note ([Space] cancels)");
  2799. if (engine.isCountingIn())
  2800. return tr ("Recording: count-in...");
  2801. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.running)
  2802. return tr ("Scanning for plugins in the background: {0}% {1}", { juce::String (juce::roundToInt (scan.progress * 100.0f)), scan.file });
  2803. return tr ("Point at anything to see what it does here. [F1] shortcuts [F5]-[F9] windows [Space] play/stop "
  2804. "[Ctrl][T] typing piano: {0}", { typingPiano ? tr ("on") : tr ("off") });
  2805. }
  2806. juce::String MainComponent::keyMarkup (const char* actionId) const
  2807. {
  2808. const auto& chords = keyMap.chordsFor (actionId);
  2809. if (chords.empty())
  2810. return {};
  2811. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  2812. const auto text = juce::String (keys::toString (chords.front()));
  2813. juce::String out;
  2814. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  2815. {
  2816. if (! hintmarkup::isToken (part.toStdString()))
  2817. return "(" + text + ")";
  2818. out << "[" << part << "]";
  2819. }
  2820. return out;
  2821. }
  2822. void MainComponent::setControlHints()
  2823. {
  2824. auto with = [this] (const juce::String& text, const char* actionId) {
  2825. const auto key = keyMarkup (actionId);
  2826. return key.isEmpty() ? text : text + " " + key;
  2827. };
  2828. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  2829. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, MIDI)"), "file.open"));
  2830. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  2831. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  2832. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  2833. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  2834. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  2835. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  2836. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  2837. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start (or the remembered position; again: the start) "
  2838. "[2xLMB] back to the start and all notes off (panic) [RMB] remember seek time"),
  2839. true);
  2840. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  2841. true);
  2842. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  2843. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  2844. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  2845. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing [RMB] volume and options"), "transport.metronome"), true);
  2846. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  2847. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  2848. ui::setHint (typingPianoButton, with (tr ("Typing keyboard as a piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  2849. "view.typingPiano"));
  2850. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  2851. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  2852. true);
  2853. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  2854. "[F4] next empty [F2] rename"));
  2855. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  2856. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  2857. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  2858. TR_NOOP ("the instruments and their step sequencer"),
  2859. TR_NOOP ("the notes of the selected channel in the current pattern"),
  2860. TR_NOOP ("inserts, effects and routing"),
  2861. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  2862. for (int i = 0; i < workspace::panelCount; ++i)
  2863. ui::setHint (panelButtons[(std::size_t) i],
  2864. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  2865. panelAction ((Panel) i)));
  2866. setQuickTips();
  2867. }
  2868. std::vector<std::pair<juce::Rectangle<int>, juce::String>> MainComponent::getQuickTipsForSnapshot()
  2869. {
  2870. std::vector<std::pair<juce::Rectangle<int>, juce::String>> tips;
  2871. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  2872. for (auto* child : c.getChildren())
  2873. {
  2874. if (! child->isVisible())
  2875. continue;
  2876. if (const auto tip = ui::quickTipOf (*child); tip.isNotEmpty() && ! child->getBounds().isEmpty())
  2877. tips.emplace_back (getLocalArea (child->getParentComponent(), child->getBounds()), tip);
  2878. visit (*child);
  2879. }
  2880. };
  2881. visit (*this);
  2882. return tips;
  2883. }
  2884. // the small name bubble of every toolbar control (the hint bar keeps the full description)
  2885. void MainComponent::setQuickTips()
  2886. {
  2887. auto tip = [this] (juce::Component& c, const juce::String& name, const char* actionId = nullptr) {
  2888. ui::setQuickTip (c, name, actionId != nullptr ? shortcutText (actionId).trim() : juce::String());
  2889. };
  2890. tip (newButton, tr ("New project"), "file.new");
  2891. tip (openButton, tr ("Open project"), "file.open");
  2892. tip (saveButton, tr ("Save project"), "file.save");
  2893. tip (exportButton, tr ("Export audio"), "file.export");
  2894. tip (undoButton, tr ("Undo"), "edit.undo");
  2895. tip (redoButton, tr ("Redo"), "edit.redo");
  2896. tip (pluginPickerButton, tr ("Plugin picker"), "panel.quickAdd");
  2897. tip (playButton, tr ("Play"), "transport.playStop");
  2898. tip (stopButton, tr ("Stop"));
  2899. tip (recordButton, tr ("Record"), "transport.record");
  2900. tip (recordMenuButton, tr ("Recording options"));
  2901. tip (patternModeButton, tr ("Pattern mode"), "transport.toggleMode");
  2902. tip (songModeButton, tr ("Song mode"), "transport.toggleMode");
  2903. tip (metronomeButton, tr ("Metronome"), "transport.metronome");
  2904. tip (countInButton, tr ("Count-in"), "record.countIn");
  2905. tip (waitInputButton, tr ("Wait for input"), "record.waitForInput");
  2906. tip (typingPianoButton, tr ("Typing keyboard to piano"), "view.typingPiano");
  2907. tip (tempoDisplay, tr ("Tempo (BPM)"));
  2908. tip (timeDisplay, tr ("Song time"));
  2909. tip (songPosition, tr ("Song position"));
  2910. tip (masterVolume, tr ("Master volume"));
  2911. tip (masterPitch, tr ("Master pitch"));
  2912. tip (gridBox, tr ("Snap"));
  2913. tip (patternBox, tr ("Pattern"));
  2914. tip (newPatternButton, tr ("New pattern"));
  2915. tip (patternMenuButton, tr ("Pattern options"));
  2916. tip (perfMeter, tr ("CPU, memory and polyphony"));
  2917. tip (output, tr ("Output monitor"));
  2918. tip (swingSlider, tr ("Swing"));
  2919. tip (rackFilterBox, tr ("Channel filter group"));
  2920. tip (rackGraphButton, tr ("Graph editor"));
  2921. tip (rackPianoRollButton, tr ("Piano-roll view"), "rack.pianoRollView");
  2922. tip (rackLoopButton, tr ("Channel looping"));
  2923. tip (rackLoopStarterButton, tr ("Loop Starter"));
  2924. for (int i = 0; i < workspace::panelCount; ++i)
  2925. tip (panelButtons[(std::size_t) i], tr (panelName ((Panel) i)), panelAction ((Panel) i));
  2926. }
  2927. void MainComponent::timerCallback()
  2928. {
  2929. const uitrace::Scope trace ("MainComponent timer", false);
  2930. {
  2931. const uitrace::Scope part ("timer: toolbar displays", false);
  2932. output.update();
  2933. timeDisplay.update();
  2934. songPosition.update();
  2935. masterVolume.update();
  2936. masterPitch.update();
  2937. updateRecordQuantise();
  2938. }
  2939. if (engine.isModified() != lastModified)
  2940. {
  2941. const uitrace::Scope part ("timer: title", false);
  2942. lastModified = engine.isModified();
  2943. updateTitle();
  2944. }
  2945. // the Browser's "Project folder" follows the project's file (.lynx, or the .flp it was imported from)
  2946. const uitrace::Scope partFolders ("timer: project folder / recording target", false);
  2947. browser.setProjectFile (currentFile != juce::File() ? currentFile : importedFlpFile);
  2948. // and so does where audio is recorded ("<project folder>/Audio/Recorded", FL-like take names)
  2949. engine.setRecordingTarget (recordingFolderFor (currentFile != juce::File() ? currentFile : importedFlpFile),
  2950. projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String());
  2951. // a backup copy every few minutes (Settings › General) when there are changes
  2952. // (not in the middle of a recording: FL also postpones the timed backup until the transport is free)
  2953. if (autosaveMinutes > 0 && ++autosaveTicks >= 30 * 60 * autosaveMinutes && ! engine.isRecording())
  2954. {
  2955. autosaveTicks = 0;
  2956. if (engine.isModified())
  2957. autosave();
  2958. }
  2959. if (const auto scan = engine.getPluginHost().backgroundScan(); scan.finished != scansSeen)
  2960. {
  2961. scansSeen = scan.finished;
  2962. ui::postHint ({ scan.found == 1 ? tr ("Plugin scan finished: 1 new plugin.")
  2963. : tr ("Plugin scan finished: {0} new plugins.", { juce::String (scan.found) }), {}, false, false },
  2964. 6000);
  2965. }
  2966. // a hosted plugin crashed inside a call: it was switched off (bypassed / silent) and LYNX kept running
  2967. if (const auto crashes = pluginCrashCount(); crashes != pluginCrashesSeen)
  2968. {
  2969. pluginCrashesSeen = crashes;
  2970. juce::StringArray names, lines;
  2971. for (const auto& c : pluginCrashes())
  2972. {
  2973. const auto name = juce::String::fromUTF8 (c.plugin.c_str());
  2974. names.addIfNotAlreadyThere (name);
  2975. lines.add (juce::Time::getCurrentTime().toISO8601 (true) + " " + name + " " + crashguard::describe (c.code) + " 0x"
  2976. + juce::String::toHexString ((juce::int64) c.code));
  2977. }
  2978. PluginHost::settingsFolder().getChildFile ("plugin-crashes.log").appendText (lines[lines.size() - 1] + "\n");
  2979. juce::AlertWindow::showMessageBoxAsync (
  2980. juce::MessageBoxIconType::WarningIcon, tr ("Plugin crashed"),
  2981. tr ("The plugin \"{0}\" crashed and was switched off, so LYNX SHARE and your project kept running (the effect is bypassed, an "
  2982. "instrument stays silent). Save your project; the plugin loads again the next time you open it.",
  2983. { names[names.size() - 1] }));
  2984. }
  2985. auto& transport = engine.getTransport();
  2986. if (! heldKeys.empty())
  2987. {
  2988. if (! juce::Process::isForegroundProcess()) // switched to another app with keys down: no key-up will come
  2989. heldKeys.releaseAll();
  2990. else // keys released while another window (a detached panel, a dialog) had the focus
  2991. keyStateChanged (false);
  2992. }
  2993. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  2994. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  2995. // recording states first
  2996. if (! hintsFrozen)
  2997. {
  2998. const uitrace::Scope part ("timer: hint", false);
  2999. ui::Hint hint;
  3000. bool live = false;
  3001. if (engine.isLearningMidi())
  3002. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  3003. else if (engine.isWaitingForInput() || engine.isCountingIn())
  3004. hint.text = idleHint();
  3005. else if (auto posted = ui::postedHint())
  3006. {
  3007. hint = *posted;
  3008. live = true;
  3009. }
  3010. else if (isShowing())
  3011. {
  3012. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  3013. if (auto* under = source.getComponentUnderMouse())
  3014. {
  3015. live = source.isDragging();
  3016. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  3017. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  3018. }
  3019. }
  3020. if (hint.isEmpty())
  3021. {
  3022. hint.text = idleHint();
  3023. live = false;
  3024. }
  3025. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  3026. if (++tweakTicks >= 3) // 10 times a second
  3027. {
  3028. tweakTicks = 0;
  3029. refreshTweakReadout();
  3030. }
  3031. }
  3032. const auto playing = transport.playing.load();
  3033. playButton.setToggleState (playing, juce::dontSendNotification);
  3034. // CPU / memory / polyphony, a few times a second
  3035. if (++meterTicks >= 8 && perfMeter.isVisible() && ! hintsFrozen)
  3036. {
  3037. const uitrace::Scope part ("timer: performance meter", false);
  3038. meterTicks = 0;
  3039. const auto held = (int) heldKeys.size();
  3040. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  3041. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  3042. const auto rt = engine.getRtStats().snapshot();
  3043. juce::StringArray heaviest;
  3044. for (const auto& u : engine.getHeaviestUnits())
  3045. if (heaviest.size() < 3 && u.load >= 0.01)
  3046. heaviest.add (u.name + " " + juce::String (juce::roundToInt (u.load * 100.0)) + "%");
  3047. auto* device = engine.getDeviceManager().getCurrentAudioDevice();
  3048. perfMeter.setRealtime (rt.overBudget, rt.lateCalls, engine.getRtStats().takeWindowMaxLoad(), heaviest,
  3049. device != nullptr ? device->getXRunCount() : -1);
  3050. // dropouts on Windows shared mode: suggest the interface's ASIO driver (round 160), worked out once per device type
  3051. if (device != nullptr && (rt.overBudget > 0 || rt.lateCalls > 0) && device->getTypeName() != driverTipType)
  3052. {
  3053. driverTipType = device->getTypeName();
  3054. std::vector<std::string> asio;
  3055. for (auto* type : engine.getDeviceManager().getAvailableDeviceTypes())
  3056. if (type->getTypeName() == "ASIO")
  3057. for (const auto& name : type->getDeviceNames())
  3058. asio.push_back (name.toStdString());
  3059. perfMeter.setDriverTip (juce::String::fromUTF8 (prefs::suggestedAsioDriver (driverTipType.toStdString(), asio).c_str()));
  3060. }
  3061. // Linux: the first dropouts without real-time priority explain how to get it, once per installation (round 161)
  3062. if (device != nullptr && ! realtimeHintChecked && (rt.overBudget > 0 || device->getXRunCount() > 0)
  3063. && lynx::rt::status() == lynx::rt::Status::denied)
  3064. {
  3065. realtimeHintChecked = true;
  3066. if (lynx::rt::shouldShowHint (PluginHost::settingsFolder().getChildFile ("realtime-hint-shown")))
  3067. juce::AlertWindow::showMessageBoxAsync (
  3068. juce::MessageBoxIconType::InfoIcon, tr ("Real-time priority"),
  3069. 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"
  3070. "- install rtkit (package \"rtkit\"; most desktops already have it), or\n"
  3071. "- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\n"
  3072. "then log out and in again. LYNX SHARE never needs root. Options > Audio settings shows the current state."));
  3073. }
  3074. }
  3075. if (++midiInputTicks % 30 == 1) // the open MIDI inputs, once a second
  3076. midiLightInputs = engine.getActiveMidiInputs();
  3077. midiLight.update (engine.getMidiActivity(), midiLightInputs);
  3078. // If a closed dialog left the main window without a focused component, take it back so the PC keyboard
  3079. // keeps playing. Only while the main window itself is the active one: another LYNX window (Audio editor,
  3080. // Quick-add palette, a plugin's editor, a detached panel) keeps its focus (issue #4: grabbing it here, 30
  3081. // times a second, pulled the main window to the front and closed the plugins' drop-down menus).
  3082. if (shouldReclaimKeyboardFocus())
  3083. grabKeyboardFocus();
  3084. }
  3085. bool MainComponent::shouldReclaimKeyboardFocus()
  3086. {
  3087. auto* peer = getPeer();
  3088. return ! hasKeyboardFocus (true) && isShowing() && peer != nullptr && peer->isFocused() && juce::Process::isForegroundProcess()
  3089. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive();
  3090. }
  3091. void MainComponent::updateTitle()
  3092. {
  3093. repaint (titleArea); // the project name in the toolbar
  3094. if (! engine.isModified()) // what is on disk now: the reference for "unused recordings" after a Discard
  3095. savedSamples = safety::referencedSamples (engine.getSong());
  3096. if (auto* window = getTopLevelComponent())
  3097. window->setName ((engine.isModified() ? "* " : "")
  3098. + (projectName.isNotEmpty() ? "LYNX SHARE - " + projectName : juce::String ("LYNX SHARE")) + importedSuffix);
  3099. }
  3100. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  3101. {
  3102. auto window = std::make_unique<juce::AlertWindow> (tr ("Save changes?"), tr ("The project has unsaved changes."),
  3103. juce::MessageBoxIconType::QuestionIcon);
  3104. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3105. window->addButton (tr ("Discard"), 2);
  3106. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3107. return window;
  3108. }
  3109. void MainComponent::confirmDiscard (std::function<void()> then)
  3110. {
  3111. if (! engine.isModified())
  3112. {
  3113. offerToDeleteUnusedRecordings (true, std::move (then));
  3114. return;
  3115. }
  3116. auto* window = makeConfirmDiscardWindow().release();
  3117. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  3118. if (result == 1)
  3119. {
  3120. save (false);
  3121. if (! engine.isModified()) // saved (did not cancel "save as")
  3122. offerToDeleteUnusedRecordings (true, then);
  3123. }
  3124. else if (result == 2)
  3125. offerToDeleteUnusedRecordings (false, then);
  3126. }),
  3127. true);
  3128. }
  3129. juce::File MainComponent::recordingFolderFor (const juce::File& projectFile) const
  3130. {
  3131. // FL records into the project data folder's "Audio\Recorded" (REA round 134); LYNX's data folder is the folder of
  3132. // the project file. Unsaved projects record into the global recordings folder.
  3133. return projectFile == juce::File() ? AudioEngine::defaultRecordingFolder()
  3134. : projectFile.getParentDirectory().getChildFile (safety::recordedSubfolder);
  3135. }
  3136. namespace
  3137. {
  3138. // FL's Keep / Delete question about recorded files nothing uses (FLEngine FUN_00ed1380, REA round 134)
  3139. void askKeepOrDelete (const juce::String& message, const std::vector<juce::File>& files, std::function<void (bool)> done)
  3140. {
  3141. juce::String list;
  3142. for (std::size_t i = 0; i < files.size() && i < 8; ++i)
  3143. list << "\n " << files[i].getFileName();
  3144. if (files.size() > 8)
  3145. list << "\n " << tr ("...and {0} more", { juce::String ((int) files.size() - 8) });
  3146. auto* w = new juce::AlertWindow (tr ("Unused recordings"), message + list, juce::MessageBoxIconType::QuestionIcon);
  3147. w->addButton (tr ("Keep"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3148. w->addButton (tr ("Delete"), 1);
  3149. w->enterModalState (true, juce::ModalCallbackFunction::create ([done] (int result) { done (result == 1); }), true);
  3150. }
  3151. // to the recycle bin when the system has one (FL's "Delete recorded files to recycle bin")
  3152. int removeFiles (const std::vector<juce::File>& files)
  3153. {
  3154. int removed = 0;
  3155. for (const auto& f : files)
  3156. removed += f.existsAsFile() && (f.moveToTrash() || f.deleteFile());
  3157. return removed;
  3158. }
  3159. } // namespace
  3160. void MainComponent::offerToDeleteUnusedRecordings (bool keepsCurrentState, std::function<void()> then)
  3161. {
  3162. // the takes of this session the project on disk will not use: deleted takes, undone recordings, a project closed
  3163. // without saving (FL: "You created ... sample file(s) that are no longer used if the project isn't saved")
  3164. std::vector<std::string> recorded;
  3165. for (const auto& f : engine.getSessionRecordings())
  3166. if (f.existsAsFile())
  3167. recorded.push_back (f.getFullPathName().toStdString());
  3168. const auto referenced = keepsCurrentState ? safety::referencedSamples (engine.getSong()) : savedSamples;
  3169. std::vector<juce::File> unused;
  3170. for (const auto& path : safety::unusedRecordings (recorded, referenced))
  3171. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  3172. if (unused.empty() || ! askUnusedRecordings || ! persistent)
  3173. {
  3174. then();
  3175. return;
  3176. }
  3177. askKeepOrDelete (unused.size() == 1 ? tr ("You recorded 1 audio file that this project will not use.")
  3178. : tr ("You recorded {0} audio files that this project will not use.", { juce::String ((int) unused.size()) }),
  3179. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused, then] (bool remove) {
  3180. if (safe == nullptr)
  3181. return;
  3182. if (remove)
  3183. removeFiles (unused);
  3184. safe->engine.forgetRecordings (unused); // asked once per file
  3185. then();
  3186. });
  3187. }
  3188. void MainComponent::deleteUnusedRecordingsAndSave()
  3189. {
  3190. // FL's Tools › Macros "Delete unused files and save project", for the files this project recorded: every take in
  3191. // its recording folder (and this session's takes elsewhere) that no channel or clip uses
  3192. if (currentFile == juce::File())
  3193. {
  3194. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Delete unused recordings"),
  3195. tr ("Save the project first: its recordings are kept next to it, in {0}.", { juce::String (safety::recordedSubfolder) }));
  3196. return;
  3197. }
  3198. std::vector<std::string> recorded;
  3199. const auto stem = currentFile.getFileNameWithoutExtension() + "_";
  3200. for (const auto& f : recordingFolderFor (currentFile).findChildFiles (juce::File::findFiles, false, "*.wav"))
  3201. if (f.getFileName().startsWithIgnoreCase (stem)) // other projects in the same folder record there too
  3202. recorded.push_back (f.getFullPathName().toStdString());
  3203. for (const auto& f : engine.getSessionRecordings())
  3204. if (f.existsAsFile())
  3205. recorded.push_back (f.getFullPathName().toStdString());
  3206. std::vector<juce::File> unused;
  3207. for (const auto& path : safety::unusedRecordings (recorded, safety::referencedSamples (engine.getSong())))
  3208. unused.emplace_back (juce::String::fromUTF8 (path.c_str()));
  3209. if (unused.empty())
  3210. {
  3211. save (false);
  3212. ui::postHint ({ tr ("No unused recordings. Project saved."), {}, false, false }, 4000);
  3213. return;
  3214. }
  3215. askKeepOrDelete (tr ("This project has {0} unused recording(s). Deleting them cannot be undone (they go to the recycle bin).",
  3216. { juce::String ((int) unused.size()) }),
  3217. unused, [safe = juce::Component::SafePointer<MainComponent> (this), unused] (bool remove) {
  3218. if (safe == nullptr)
  3219. return;
  3220. if (remove)
  3221. {
  3222. const auto n = removeFiles (unused);
  3223. safe->engine.forgetRecordings (unused);
  3224. ui::postHint ({ tr ("Deleted {0} unused recording(s).", { juce::String (n) }), {}, false, false }, 4000);
  3225. }
  3226. safe->save (false);
  3227. });
  3228. }
  3229. namespace
  3230. {
  3231. juce::String projectStem (const juce::String& projectName)
  3232. {
  3233. return projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  3234. }
  3235. // the backup folder's projects with their modification times (for rotation and "revert to last backup")
  3236. std::vector<safety::BackupFile> backupFiles (const juce::File& folder)
  3237. {
  3238. std::vector<safety::BackupFile> files;
  3239. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, juce::String ("*") + ProjectFile::extension))
  3240. files.push_back ({ f.getFileNameWithoutExtension().toStdString(), f.getLastModificationTime().toMilliseconds() });
  3241. return files;
  3242. }
  3243. // "Song (autosaved on 2026-10-20 at 14h19)" in `folder`, "_2"... when that minute is taken (FL's naming, REA round 118)
  3244. juce::File newBackupFile (const juce::File& folder, const juce::String& stem, safety::BackupKind kind)
  3245. {
  3246. const auto now = juce::Time::getCurrentTime();
  3247. const auto name = safety::backupName (stem.toStdString(), kind, now.getYear(), now.getMonth() + 1, now.getDayOfMonth(), now.getHours(), now.getMinutes());
  3248. const auto unique = safety::uniqueName (name, [&folder] (const std::string& n) {
  3249. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  3250. });
  3251. return folder.getChildFile (juce::String::fromUTF8 (unique.c_str()) + ProjectFile::extension);
  3252. }
  3253. } // namespace
  3254. void MainComponent::autosave()
  3255. {
  3256. // backup copy of the open project, so work isn't lost if something crashes ("Song (autosaved on 2026-10-20 at
  3257. // 14h19).lynx" in the backup folder, like FL's Backup folder); only the newest few of each project are kept
  3258. // The plugins' settings are read here (they answer on the message thread); writing the file (the big part:
  3259. // every plugin's state, encoded) runs on a thread of its own, so the timed backup no longer freezes the screen
  3260. // (round 151: 180 ms every two minutes on a project with 71 plugins). One at a time.
  3261. if (autosaveRunning->load())
  3262. return;
  3263. const auto folder = autosaveFolder();
  3264. folder.createDirectory();
  3265. const auto stem = projectStem (projectName);
  3266. {
  3267. const uitrace::Scope trace ("autosave: plugin states", false);
  3268. engine.capturePluginStates();
  3269. }
  3270. auto copy = std::make_shared<Song> (engine.getSong());
  3271. const auto file = newBackupFile (folder, stem, safety::BackupKind::autosaved);
  3272. autosaveRunning->store (true);
  3273. juce::Thread::launch ([copy, file, running = autosaveRunning, safe = juce::Component::SafePointer<MainComponent> (this), stem] {
  3274. juce::String error;
  3275. const auto ok = ProjectFile::save (*copy, file, error);
  3276. running->store (false);
  3277. juce::MessageManager::callAsync ([safe, ok, error, stem] {
  3278. if (safe == nullptr)
  3279. return;
  3280. if (! ok)
  3281. ui::postHint ({ tr ("Autosave failed: {0}", { error }), {}, false, false }, 6000);
  3282. else
  3283. safe->rotateBackups (stem);
  3284. });
  3285. });
  3286. }
  3287. void MainComponent::rotateBackups (const juce::String& stem)
  3288. {
  3289. const auto folder = autosaveFolder();
  3290. for (const auto& old : safety::backupsToRemove (backupFiles (folder), stem.toStdString(), autosaveKeep))
  3291. {
  3292. const auto f = folder.getChildFile (juce::String::fromUTF8 (old.c_str()) + ProjectFile::extension);
  3293. f.setReadOnly (false); // (FL clears the read-only flag before deleting an old backup too)
  3294. f.deleteFile();
  3295. }
  3296. }
  3297. void MainComponent::keepOverwrittenCopy (const juce::File& file)
  3298. {
  3299. // FL moves the file a save replaces into its Backup folder as "Song (overwritten on ... at ...)"; LYNX copies it
  3300. // (the save itself still goes through a temporary file and a rename)
  3301. const auto folder = autosaveFolder();
  3302. if (! file.existsAsFile() || file.isAChildOf (folder))
  3303. return;
  3304. folder.createDirectory();
  3305. const auto stem = projectStem (file.getFileNameWithoutExtension());
  3306. if (file.copyFileTo (newBackupFile (folder, stem, safety::BackupKind::overwritten)))
  3307. rotateBackups (stem);
  3308. }
  3309. void MainComponent::saveNewVersion()
  3310. {
  3311. // FL's "Save new version": Song.flp -> Song_2.flp -> Song_3.flp, next to the current file
  3312. if (currentFile == juce::File())
  3313. {
  3314. save (true);
  3315. return;
  3316. }
  3317. const auto folder = currentFile.getParentDirectory();
  3318. const auto name = safety::nextVersionName (currentFile.getFileNameWithoutExtension().toStdString(), [&folder] (const std::string& n) {
  3319. return folder.getChildFile (juce::String::fromUTF8 (n.c_str()) + ProjectFile::extension).exists();
  3320. });
  3321. const auto file = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3322. juce::String error;
  3323. engine.capturePluginStates();
  3324. if (! ProjectFile::save (engine.getSong(), file, error))
  3325. {
  3326. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3327. return;
  3328. }
  3329. engine.markSaved();
  3330. rememberRecent (file);
  3331. currentFile = file;
  3332. projectName = file.getFileNameWithoutExtension();
  3333. importedSuffix = {};
  3334. updateTitle();
  3335. ui::postHint ({ tr ("Saved as a new version: {0}", { file.getFileName() }), {}, false, false }, 5000);
  3336. }
  3337. void MainComponent::revertToLastBackup()
  3338. {
  3339. const auto stem = projectStem (projectName);
  3340. const auto name = safety::newestBackup (backupFiles (autosaveFolder()), stem.toStdString());
  3341. if (name.empty())
  3342. {
  3343. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Revert to last backup"),
  3344. tr ("There is no backup of this project yet."));
  3345. return;
  3346. }
  3347. const auto backup = autosaveFolder().getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3348. const auto when = backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M");
  3349. auto* w = new juce::AlertWindow (tr ("Revert to last backup"),
  3350. tr ("Replace the open project with its backup from {0}?\n{1}\n\nThe project file itself only changes when you save.",
  3351. { when, backup.getFileName() }),
  3352. juce::MessageBoxIconType::QuestionIcon);
  3353. w->addButton (tr ("Revert"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3354. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3355. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup] (int result) {
  3356. if (safe == nullptr || result != 1)
  3357. return;
  3358. juce::String error;
  3359. auto song = ProjectFile::load (backup, error);
  3360. if (! song)
  3361. {
  3362. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3363. return;
  3364. }
  3365. safe->engine.getPluginHost().applySubstitutes (*song);
  3366. safe->engine.stop();
  3367. safe->engine.rewind();
  3368. safe->engine.setSong (std::move (*song));
  3369. safe->engine.markModified(); // Save writes it back to the project's own file
  3370. safe->updateTitle();
  3371. safe->playlist.showSongAfterOpen();
  3372. }),
  3373. true);
  3374. }
  3375. void MainComponent::exportPackage()
  3376. {
  3377. // FL's zipped loop package: the project and every sample it uses in one .zip
  3378. const auto stem = projectStem (projectName);
  3379. const auto start = (currentFile != juce::File() ? currentFile.getParentDirectory()
  3380. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory))
  3381. .getChildFile (stem + ".zip");
  3382. fileChooser = std::make_unique<juce::FileChooser> (tr ("Export project with samples"), start, "*.zip");
  3383. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  3384. [safe = juce::Component::SafePointer<MainComponent> (this), stem] (const juce::FileChooser& chooser) {
  3385. auto zip = chooser.getResult();
  3386. if (safe == nullptr || zip == juce::File())
  3387. return;
  3388. zip = zip.withFileExtension (".zip");
  3389. safe->engine.capturePluginStates();
  3390. ProjectPackage::Result result;
  3391. juce::String error;
  3392. if (! ProjectPackage::exportZip (safe->engine.getSong(), stem, zip, result, error))
  3393. {
  3394. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3395. return;
  3396. }
  3397. auto text = tr ("{0} saved with {1} samples.", { zip.getFileName(), juce::String (result.files) });
  3398. if (! result.missing.isEmpty())
  3399. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  3400. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Export project with samples"), text);
  3401. });
  3402. }
  3403. void MainComponent::collectSamples()
  3404. {
  3405. // FL's "Export project data files": copy the samples the project uses into one folder (and use the copies)
  3406. fileChooser = std::make_unique<juce::FileChooser> (tr ("Copy the project's samples to..."),
  3407. currentFile != juce::File() ? currentFile.getParentDirectory()
  3408. : juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  3409. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  3410. [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  3411. const auto folder = chooser.getResult();
  3412. if (safe == nullptr || folder == juce::File())
  3413. return;
  3414. std::map<std::string, std::string> relink;
  3415. ProjectPackage::Result result;
  3416. juce::String error;
  3417. if (! ProjectPackage::collectSamples (safe->engine.getSong(), folder, relink, result, error))
  3418. {
  3419. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not copy"), error);
  3420. return;
  3421. }
  3422. safe->engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  3423. auto text = tr ("{0} samples copied to {1}. The project now uses the copies.", { juce::String (result.files), folder.getFullPathName() });
  3424. if (! result.missing.isEmpty())
  3425. text << "\n\n" << tr ("Not on this PC (left out):") << "\n" << result.missing.joinIntoString ("\n");
  3426. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Collect project samples"), text);
  3427. });
  3428. }
  3429. void MainComponent::saveToNewProjectFolder()
  3430. {
  3431. // FL's "Save to new project folder...": <chosen name>/<name>.lynx, so the project gets its own data folder (its
  3432. // recordings go to <name>/Audio/Recorded). This session's takes still in the global recordings folder move along
  3433. // (copied there, the project uses the copies; the originals are then offered for deletion as unused).
  3434. const auto start = currentFile != juce::File() ? currentFile.getParentDirectory()
  3435. : lynx::platform::documentsFolder().getChildFile ("LYNX/Projects");
  3436. start.createDirectory();
  3437. fileChooser = std::make_unique<juce::FileChooser> (tr ("Save to new project folder"),
  3438. start.getChildFile (projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled")),
  3439. juce::String ("*") + ProjectFile::extension);
  3440. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode, [safe = juce::Component::SafePointer<MainComponent> (this)] (const juce::FileChooser& chooser) {
  3441. const auto chosen = chooser.getResult();
  3442. if (safe == nullptr || chosen == juce::File())
  3443. return;
  3444. const auto name = chosen.getFileNameWithoutExtension();
  3445. auto folder = chosen.getParentDirectory().getChildFile (name);
  3446. if (folder.exists() && ! folder.findChildFiles (juce::File::findFilesAndDirectories, false).isEmpty())
  3447. folder = folder.getNonexistentSibling (false);
  3448. if (! folder.createDirectory())
  3449. {
  3450. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"),
  3451. tr ("Could not create the folder {0}", { folder.getFullPathName() }));
  3452. return;
  3453. }
  3454. auto& self = *safe;
  3455. const auto recorded = folder.getChildFile (safety::recordedSubfolder);
  3456. std::map<std::string, std::string> relink;
  3457. const auto used = safety::referencedSamples (self.engine.getSong());
  3458. for (const auto& take : self.engine.getSessionRecordings())
  3459. if (take.existsAsFile() && take.isAChildOf (AudioEngine::defaultRecordingFolder())
  3460. && std::any_of (used.begin(), used.end(), [&take] (const std::string& p) { return safety::samePath (p, take.getFullPathName().toStdString()); }))
  3461. {
  3462. recorded.createDirectory();
  3463. const auto copy = recorded.getNonexistentChildFile (take.getFileNameWithoutExtension(), take.getFileExtension(), false);
  3464. if (take.copyFileTo (copy))
  3465. relink[take.getFullPathName().toStdString()] = copy.getFullPathName().toStdString();
  3466. }
  3467. if (! relink.empty())
  3468. self.engine.editSong ([&relink] (Song& song) { applyRelocations (song, relink); });
  3469. const auto file = folder.getChildFile (name + ProjectFile::extension);
  3470. juce::String error;
  3471. self.engine.capturePluginStates();
  3472. if (! ProjectFile::save (self.engine.getSong(), file, error))
  3473. {
  3474. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3475. return;
  3476. }
  3477. self.engine.markSaved();
  3478. self.rememberRecent (file);
  3479. self.currentFile = file;
  3480. self.projectName = name;
  3481. self.importedSuffix = {};
  3482. self.updateTitle();
  3483. ui::postHint ({ tr ("Saved in its own folder: {0}", { folder.getFullPathName() }), {}, false, false }, 5000);
  3484. });
  3485. }
  3486. void MainComponent::startSession()
  3487. {
  3488. // Like FL's backup on crash: a marker exists while LYNX runs; finding one at start means the last session
  3489. // ended without closing (crash, power loss), so the newest backup written during it is offered.
  3490. sessionLock = std::make_unique<juce::InterProcessLock> ("LYNX-ui-session");
  3491. if (! sessionLock->enter (0))
  3492. {
  3493. sessionLock.reset(); // another LYNX window is running: it owns the marker
  3494. return;
  3495. }
  3496. sessionMarker = lynx::platform::settingsFile ("session-running.txt");
  3497. if (sessionMarker.existsAsFile())
  3498. {
  3499. const auto previousStart = juce::Time (sessionMarker.loadFileAsString().trim().getLargeIntValue());
  3500. juce::Timer::callAfterDelay (2500, [safe = juce::Component::SafePointer<MainComponent> (this), previousStart] {
  3501. if (safe != nullptr)
  3502. safe->checkPreviousSession (previousStart);
  3503. });
  3504. }
  3505. sessionMarker.getParentDirectory().createDirectory();
  3506. sessionMarker.replaceWithText (juce::String (juce::Time::getCurrentTime().toMilliseconds()));
  3507. // takes that were recording when LYNX stopped (crash, power loss, closed while recording): after the backup offer
  3508. juce::Timer::callAfterDelay (4000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3509. if (safe != nullptr)
  3510. safe->checkInterruptedTakes();
  3511. });
  3512. }
  3513. void MainComponent::checkInterruptedTakes()
  3514. {
  3515. if (juce::Component::getCurrentlyModalComponent() != nullptr) // a dialog is open (the backup offer): ask later
  3516. {
  3517. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3518. if (safe != nullptr)
  3519. safe->checkInterruptedTakes();
  3520. });
  3521. return;
  3522. }
  3523. std::vector<juce::File> folders { engine.getRecordingFolder() };
  3524. const auto takes = engine.recoverInterruptedTakes (folders);
  3525. if (takes.empty())
  3526. return;
  3527. juce::StringArray names;
  3528. for (const auto& j : takes)
  3529. names.add (juce::File (juce::String::fromUTF8 (j.wav.c_str())).getFileName());
  3530. const auto folder = juce::File (juce::String::fromUTF8 (takes.front().wav.c_str())).getParentDirectory();
  3531. auto* w = new juce::AlertWindow (tr ("Recordings recovered"),
  3532. tr ("LYNX SHARE was recording when it stopped. These takes were saved and repaired:\n{0}\n\nPut them on the Playlist "
  3533. "where they were recorded?", { names.joinIntoString ("\n") }),
  3534. juce::MessageBoxIconType::InfoIcon);
  3535. w->addButton (tr ("Put them on the Playlist"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3536. w->addButton (tr ("Show the folder"), 2);
  3537. w->addButton (tr ("Keep the files only"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3538. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), takes, folder] (int result) {
  3539. if (safe == nullptr)
  3540. return;
  3541. if (result == 1)
  3542. {
  3543. const auto placed = safe->engine.placeRecoveredTakes (takes);
  3544. ui::postHint ({ tr ("{0} recovered take(s) placed on the Playlist", { juce::String (placed) }), {}, false, false }, 5000);
  3545. }
  3546. else
  3547. {
  3548. if (result == 2)
  3549. folder.startAsProcess();
  3550. safe->engine.forgetInterruptedTakes (takes);
  3551. }
  3552. }),
  3553. true);
  3554. }
  3555. void MainComponent::checkPreviousSession (juce::Time sessionStart)
  3556. {
  3557. if (juce::Component::getCurrentlyModalComponent() != nullptr) // the setup wizard or another dialog: ask later
  3558. {
  3559. juce::Timer::callAfterDelay (2000, [safe = juce::Component::SafePointer<MainComponent> (this), sessionStart] {
  3560. if (safe != nullptr)
  3561. safe->checkPreviousSession (sessionStart);
  3562. });
  3563. return;
  3564. }
  3565. const auto folder = autosaveFolder();
  3566. const auto name = safety::crashRecoveryCandidate (backupFiles (folder), sessionStart.toMilliseconds());
  3567. if (name.empty())
  3568. return; // nothing was saved in that session
  3569. const auto backup = folder.getChildFile (juce::String::fromUTF8 (name.c_str()) + ProjectFile::extension);
  3570. auto* w = new juce::AlertWindow (tr ("LYNX SHARE did not close properly"),
  3571. tr ("The last session ended unexpectedly. Open the newest backup it saved?\n{0} ({1})",
  3572. { backup.getFileName(), backup.getLastModificationTime().formatted ("%Y-%m-%d %H:%M") }),
  3573. juce::MessageBoxIconType::WarningIcon);
  3574. w->addButton (tr ("Open backup"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3575. w->addButton (tr ("Open backup folder"), 2);
  3576. w->addButton (tr ("Ignore"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3577. w->enterModalState (true, juce::ModalCallbackFunction::create ([safe = juce::Component::SafePointer<MainComponent> (this), backup, folder] (int result) {
  3578. if (safe == nullptr)
  3579. return;
  3580. if (result == 1)
  3581. safe->confirmDiscard ([safe, backup] {
  3582. if (safe != nullptr)
  3583. safe->openLynxProject (backup);
  3584. });
  3585. else if (result == 2)
  3586. folder.startAsProcess();
  3587. }),
  3588. true);
  3589. }
  3590. void MainComponent::newProject (bool askAlways)
  3591. {
  3592. confirmDiscard ([this, askAlways] {
  3593. if (! askAlways && ! newProjectDialogEnabled())
  3594. {
  3595. startNewProject (makeNewProject(), {});
  3596. return;
  3597. }
  3598. showNewProjectDialog ([safe = juce::Component::SafePointer<MainComponent> (this)] (Song song, juce::File file) {
  3599. if (safe != nullptr)
  3600. safe->startNewProject (std::move (song), file);
  3601. });
  3602. });
  3603. }
  3604. void MainComponent::startNewProject (Song song, const juce::File& file)
  3605. {
  3606. engine.stop();
  3607. engine.rewind();
  3608. engine.setSong (std::move (song));
  3609. engine.markCreatedNow(); // Project info › created (a template's own date is kept, as FL does)
  3610. currentFile = juce::File();
  3611. projectName = {};
  3612. importedSuffix = {};
  3613. if (file != juce::File())
  3614. {
  3615. juce::String error;
  3616. file.getParentDirectory().createDirectory();
  3617. if (ProjectFile::save (engine.getSong(), file, error))
  3618. {
  3619. engine.markSaved();
  3620. rememberRecent (file);
  3621. currentFile = file;
  3622. projectName = file.getFileNameWithoutExtension();
  3623. }
  3624. else
  3625. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3626. }
  3627. updateTitle();
  3628. }
  3629. void MainComponent::saveAsTemplate()
  3630. {
  3631. auto* w = new juce::AlertWindow (tr ("Save as template"), tr ("The template appears in File › New project... (saved in {0})", { userTemplatesFolder().getFullPathName() }),
  3632. juce::MessageBoxIconType::NoIcon);
  3633. w->addTextEditor ("name", projectName.isNotEmpty() ? projectName : tr ("My template"));
  3634. w->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  3635. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  3636. w->enterModalState (true, juce::ModalCallbackFunction::create ([w, safe = juce::Component::SafePointer<MainComponent> (this)] (int result) {
  3637. if (result != 1 || safe == nullptr)
  3638. return;
  3639. safe->engine.capturePluginStates();
  3640. juce::String error;
  3641. if (! saveUserTemplate (safe->engine.getSong(), w->getTextEditorContents ("name"), error))
  3642. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  3643. }), true);
  3644. }
  3645. void MainComponent::chooseFileToOpen()
  3646. {
  3647. confirmDiscard ([this] { chooseFileToOpenNow(); });
  3648. }
  3649. void MainComponent::chooseFileToOpenNow()
  3650. {
  3651. fileChooser = std::make_unique<juce::FileChooser> (tr ("Open project"), currentFile.getParentDirectory(),
  3652. juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.zip;*.mid;*.midi");
  3653. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  3654. [this] (const juce::FileChooser& chooser) {
  3655. if (chooser.getResult().existsAsFile())
  3656. openFile (chooser.getResult());
  3657. });
  3658. }
  3659. void MainComponent::openFile (const juce::File& file)
  3660. {
  3661. juce::String error;
  3662. crashguard::note (("opening project " + file.getFileName()).toStdString()); // session breadcrumb (round 111)
  3663. if (file.hasFileExtension ("zip"))
  3664. {
  3665. // a project package (File › Export project with samples, or FL's zipped loop package): extracted into a
  3666. // folder of its own, then the project inside is opened (its samples are found next to it)
  3667. const auto project = ProjectPackage::extractZip (file, ProjectPackage::defaultExtractRoot(), error);
  3668. if (project == juce::File())
  3669. {
  3670. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3671. return;
  3672. }
  3673. openFile (project);
  3674. return;
  3675. }
  3676. if (file.hasFileExtension ("mid;midi"))
  3677. {
  3678. auto song = MidiFileIo::loadSong (file, error);
  3679. if (! song)
  3680. {
  3681. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3682. return;
  3683. }
  3684. engine.stop();
  3685. engine.rewind();
  3686. engine.setSong (std::move (*song));
  3687. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  3688. projectName = file.getFileNameWithoutExtension();
  3689. rememberRecent (file);
  3690. importedSuffix = " " + tr ("(imported from MIDI)");
  3691. updateTitle();
  3692. return;
  3693. }
  3694. if (file.hasFileExtension ("flp"))
  3695. {
  3696. if (! persistent) // (command-line modes open synchronously, without scanning)
  3697. {
  3698. importFlp (file);
  3699. return;
  3700. }
  3701. // behind a progress panel (round 112): the project's unknown plugins get a targeted scan of just their files,
  3702. // the samples are decoded off the message thread, the hosted plugins are created one by one with their names
  3703. // shown; the panel's bar never sits still at 0 %
  3704. if (projectLoadRunning())
  3705. return;
  3706. openFlpWithProgress (*this, engine, file, [safe = juce::Component::SafePointer<MainComponent> (this), file] (bool ok, const juce::String& error) {
  3707. if (safe == nullptr)
  3708. return;
  3709. if (! ok)
  3710. {
  3711. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3712. return;
  3713. }
  3714. safe->flpImported (file);
  3715. });
  3716. return;
  3717. }
  3718. openLynxProject (file);
  3719. }
  3720. void MainComponent::importFlp (const juce::File& file)
  3721. {
  3722. juce::String error;
  3723. loadtrace::begin (file.getFullPathName().toStdString());
  3724. const auto ok = engine.importFlpFile (file, error);
  3725. loadtrace::end();
  3726. if (! ok)
  3727. {
  3728. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3729. return;
  3730. }
  3731. flpImported (file);
  3732. }
  3733. void MainComponent::flpImported (const juce::File& file)
  3734. {
  3735. {
  3736. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  3737. importedFlpFile = file;
  3738. projectName = file.getFileNameWithoutExtension();
  3739. rememberRecent (file);
  3740. importedSuffix = " " + tr ("(imported from FL Studio)");
  3741. updateTitle();
  3742. playlist.showSongAfterOpen();
  3743. showMissingFiles (true);
  3744. // FL opens Project info when the project's "Show on opening" box is on (event 0x0A, REA round 167g)
  3745. if (engine.getSong().info.showOnOpen && platform::testMode())
  3746. platform::testModeLog ("project info shown on open");
  3747. else if (engine.getSong().info.showOnOpen)
  3748. openSettings ((int) SettingsPage::info);
  3749. }
  3750. }
  3751. void MainComponent::openLynxProject (const juce::File& file)
  3752. {
  3753. juce::String error;
  3754. auto song = ProjectFile::load (file, error);
  3755. if (! song)
  3756. {
  3757. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3758. return;
  3759. }
  3760. // missing plugins get their LYNX substitute; substitutes whose original is installed now go back to it
  3761. engine.getPluginHost().applySubstitutes (*song);
  3762. engine.stop();
  3763. engine.rewind();
  3764. engine.setSong (std::move (*song));
  3765. currentFile = file;
  3766. importedFlpFile = juce::File();
  3767. projectName = file.getFileNameWithoutExtension();
  3768. importedSuffix = {};
  3769. rememberRecent (file);
  3770. updateTitle();
  3771. playlist.showSongAfterOpen();
  3772. if (persistent)
  3773. {
  3774. showMissingFiles (true);
  3775. if (engine.getSong().info.showOnOpen && platform::testMode())
  3776. platform::testModeLog ("project info shown on open");
  3777. else if (engine.getSong().info.showOnOpen)
  3778. openSettings (1);
  3779. }
  3780. }
  3781. void MainComponent::openSettings (int page)
  3782. {
  3783. const juce::Component::SafePointer<MainComponent> safe (this);
  3784. SettingsHooks hooks;
  3785. hooks.browserFoldersChanged = [safe] {
  3786. if (safe != nullptr)
  3787. safe->browser.reloadUserFolders();
  3788. };
  3789. hooks.getGeneral = [safe] {
  3790. GeneralOptions o;
  3791. if (safe == nullptr)
  3792. return o;
  3793. o.language = i18n::saved();
  3794. o.uiScale = safe->toolbarLayout.uiScale;
  3795. o.compactMenus = theme::menus::compact();
  3796. o.waveSpectral = ui::WaveformCache::spectral;
  3797. o.waveStereo = ui::WaveformCache::stereo;
  3798. o.noteNames = notenames::currentStyle.load();
  3799. o.noteFlats = notenames::currentFlats.load();
  3800. o.reducedEffects = skin::reducedEffects();
  3801. o.gpuRendering = gpuRenderingEnabled();
  3802. o.pluginStyle = skin::forcedStyle();
  3803. o.splash = safe->startup.splash;
  3804. o.startupSound = safe->startup.sound;
  3805. o.scanAtStart = backgroundScanAtStart();
  3806. o.typingPiano = safe->typingPiano;
  3807. o.keepEditorsOpen = ChannelRackComponent::keepEditorsOpen;
  3808. o.selectFirstChannelWithNotes = ChannelRackComponent::selectFirstChannelWithNotes;
  3809. o.alternateUndo = safe->alternateUndo;
  3810. o.rememberSeek = EditorGlobals::get().rememberSeek;
  3811. o.editPatternsIn = PlaylistComponent::editPatternsIn;
  3812. o.undoLevels = safe->engine.getUndoLevels();
  3813. o.autosaveMinutes = safe->autosaveMinutes;
  3814. o.autosaveKeep = safe->autosaveKeep;
  3815. o.askUnusedRecordings = safe->askUnusedRecordings;
  3816. o.crossfadesInNewProjects = newProjectDefaults().autoCrossfades;
  3817. o.pluginSandbox = pluginSandboxEnabled();
  3818. o.menuEntry = appImageMenuEntryInstalled();
  3819. o.pluginSubstitutes = pluginSubstitutesEnabled();
  3820. o.crashReports = (int) crashreporter::consent();
  3821. o.checkUpdates = updater::automatic();
  3822. return o;
  3823. };
  3824. hooks.setGeneral = [safe] (const GeneralOptions& o) {
  3825. if (safe == nullptr)
  3826. return;
  3827. auto& self = *safe;
  3828. if (o.uiScale != self.toolbarLayout.uiScale)
  3829. {
  3830. auto layout = self.toolbarLayout;
  3831. layout.uiScale = toolbarlayout::clampScale (o.uiScale);
  3832. self.setToolbarLayout (layout, true);
  3833. }
  3834. theme::menus::setCompact (o.compactMenus);
  3835. if (o.reducedEffects != skin::reducedEffects() || o.pluginStyle != skin::forcedStyle())
  3836. {
  3837. skin::setReducedEffects (o.reducedEffects);
  3838. skin::setForcedStyle (o.pluginStyle);
  3839. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // open editors redraw at once
  3840. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  3841. }
  3842. if (o.noteNames != notenames::currentStyle.load() || o.noteFlats != notenames::currentFlats.load())
  3843. {
  3844. notenames::currentStyle.store (juce::jlimit (0, 2, o.noteNames));
  3845. notenames::currentFlats.store (o.noteFlats);
  3846. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i) // the keyboards redraw with the new names
  3847. if (auto* c = juce::Desktop::getInstance().getComponent (i)) c->repaint();
  3848. }
  3849. if (o.gpuRendering != gpuRenderingEnabled())
  3850. setGpuRenderingEnabled (o.gpuRendering);
  3851. if (o.waveSpectral != ui::WaveformCache::spectral || o.waveStereo != ui::WaveformCache::stereo)
  3852. {
  3853. ui::WaveformCache::spectral = o.waveSpectral;
  3854. ui::WaveformCache::stereo = o.waveStereo;
  3855. ui::WaveformCache::getInstance()->settingsChanged();
  3856. }
  3857. if (o.typingPiano != self.typingPiano)
  3858. self.setTypingPiano (o.typingPiano);
  3859. if (o.scanAtStart != backgroundScanAtStart())
  3860. setBackgroundScanAtStart (o.scanAtStart);
  3861. if (o.pluginSandbox != pluginSandboxEnabled())
  3862. setPluginSandboxEnabled (o.pluginSandbox);
  3863. if (runningAsAppImage() && o.menuEntry != appImageMenuEntryInstalled())
  3864. setAppImageMenuEntry (o.menuEntry);
  3865. if (o.pluginSubstitutes != pluginSubstitutesEnabled())
  3866. setPluginSubstitutesEnabled (o.pluginSubstitutes);
  3867. if (o.crashReports != (int) crashreporter::consent())
  3868. crashreporter::setConsent ((crashreport::Consent) juce::jlimit (0, 2, o.crashReports));
  3869. updater::setAutomatic (o.checkUpdates);
  3870. ChannelRackComponent::keepEditorsOpen = o.keepEditorsOpen;
  3871. ChannelRackComponent::selectFirstChannelWithNotes = o.selectFirstChannelWithNotes;
  3872. self.alternateUndo = o.alternateUndo;
  3873. EditorGlobals::get().rememberSeek = o.rememberSeek;
  3874. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, o.editPatternsIn);
  3875. self.startup.splash = o.splash;
  3876. self.startup.sound = o.startupSound;
  3877. self.engine.setUndoLevels (o.undoLevels);
  3878. self.autosaveMinutes = prefs::clampAutosaveMinutes (o.autosaveMinutes);
  3879. self.autosaveKeep = prefs::clampAutosaveKeep (o.autosaveKeep);
  3880. self.askUnusedRecordings = o.askUnusedRecordings;
  3881. newProjectDefaults().autoCrossfades = o.crossfadesInNewProjects;
  3882. self.autosaveTicks = 0;
  3883. self.saveUiSettings();
  3884. if (o.language != i18n::saved())
  3885. self.showLanguageChoice (o.language);
  3886. };
  3887. hooks.manageShortcuts = [safe] {
  3888. if (safe != nullptr)
  3889. safe->showShortcutManager();
  3890. };
  3891. hooks.managePlugins = [safe] {
  3892. if (safe != nullptr)
  3893. safe->showPluginManager();
  3894. };
  3895. showSettings (engine, (SettingsPage) juce::jlimit (0, (int) SettingsPage::theme, page), std::move (hooks)); // (Theme was clamped to MIDI)
  3896. }
  3897. void MainComponent::showPluginManager()
  3898. {
  3899. lynx::showPluginManager (engine, [safe = juce::Component::SafePointer<MainComponent> (this)] {
  3900. if (safe != nullptr)
  3901. safe->openSettings ((int) SettingsPage::files);
  3902. });
  3903. }
  3904. void MainComponent::showShortcutManager()
  3905. {
  3906. lynx::showShortcutManager ([safe = juce::Component::SafePointer<MainComponent> (this)] {
  3907. if (safe == nullptr)
  3908. return;
  3909. safe->loadKeyMap();
  3910. safe->setControlHints();
  3911. safe->menuItemsChanged();
  3912. });
  3913. }
  3914. void MainComponent::showMissingFiles (bool afterOpening)
  3915. {
  3916. if (afterOpening && platform::testMode()) // (LYNX_TEST_MODE: nothing waits for a click)
  3917. {
  3918. platform::testModeLog ("Missing files dialog after opening " + projectName);
  3919. return;
  3920. }
  3921. MissingFilesInfo info;
  3922. info.projectName = projectName;
  3923. const auto fromFlp = importedFlpFile.existsAsFile() && currentFile == juce::File();
  3924. 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(); };
  3925. if (fromFlp)
  3926. {
  3927. // the import dropped the samples it couldn't find: its report keeps them (minus the ones located since)
  3928. const auto& report = engine.getImportReport();
  3929. for (const auto& m : report.missingFiles)
  3930. info.files.push_back (m);
  3931. info.plugins = engine.getMissingPluginDetails();
  3932. info.autoRelocated = report.relocatedFiles;
  3933. info.searchFolders.add (importedFlpFile.getParentDirectory().getFullPathName());
  3934. }
  3935. else
  3936. {
  3937. const auto& song = engine.getSong();
  3938. info.files = findMissingSamples (song, exists);
  3939. auto& host = engine.getPluginHost();
  3940. auto addPlugin = [&info] (const PluginRef& ref, const std::string& user, const char* replacement) {
  3941. const auto name = ref.name.empty() ? ref.id : ref.name;
  3942. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  3943. if (it == info.plugins.end())
  3944. it = info.plugins.insert (info.plugins.end(), MissingPlugin { name, {}, replacement });
  3945. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  3946. it->usedBy.push_back (user);
  3947. };
  3948. for (const auto& c : song.channels)
  3949. if (c.instrument == InstrumentKind::plugin && ! c.plugin.id.empty() && host.find (juce::String::fromUTF8 (c.plugin.id.c_str())) == nullptr)
  3950. addPlugin (c.plugin, c.name, "Silence: the channel keeps the plugin's settings until it is installed");
  3951. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  3952. for (const auto& fx : song.mixer[t].effects)
  3953. if (fx.kind == EffectKind::plugin && ! fx.plugin.id.empty() && host.find (juce::String::fromUTF8 (fx.plugin.id.c_str())) == nullptr)
  3954. addPlugin (fx.plugin, song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name,
  3955. "Bypassed: the slot keeps the plugin's settings until it is installed");
  3956. // played by a LYNX substitute until the original is installed
  3957. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  3958. for (const auto& fx : song.mixer[t].effects)
  3959. if (fx.isSubstitute())
  3960. {
  3961. const auto name = substituteOriginalName (fx);
  3962. auto it = std::find_if (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == name; });
  3963. if (it == info.plugins.end())
  3964. it = info.plugins.insert (info.plugins.end(),
  3965. 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"),
  3966. effectInfo (fx.kind).name });
  3967. const auto user = song.mixer[t].name.empty() ? (t == 0 ? std::string ("Master") : "Insert " + std::to_string (t)) : song.mixer[t].name;
  3968. if (std::find (it->usedBy.begin(), it->usedBy.end(), user) == it->usedBy.end())
  3969. it->usedBy.push_back (user);
  3970. }
  3971. // installed, but failed to load: they play silence / are bypassed
  3972. for (const auto& line : host.getLoadFailures())
  3973. if (std::none_of (info.plugins.begin(), info.plugins.end(), [&] (const MissingPlugin& p) { return p.name == line.toStdString(); }))
  3974. info.plugins.push_back ({ line.toStdString(), {}, "Silence: the plugin is installed but did not load" });
  3975. if (currentFile.existsAsFile())
  3976. info.searchFolders.add (currentFile.getParentDirectory().getFullPathName());
  3977. }
  3978. if (afterOpening && info.files.empty() && info.plugins.empty())
  3979. {
  3980. if (fromFlp)
  3981. showImportReport();
  3982. return;
  3983. }
  3984. auto safe = juce::Component::SafePointer<MainComponent> (this);
  3985. const auto flp = fromFlp ? importedFlpFile : juce::File();
  3986. showMissingFilesDialog (
  3987. std::move (info),
  3988. [safe, flp] (const std::map<std::string, std::string>& relocations) {
  3989. if (safe == nullptr)
  3990. return;
  3991. if (flp != juce::File())
  3992. {
  3993. // FL import: imported again with the located samples (the channels become samplers, slices are read...)
  3994. juce::String error;
  3995. if (! safe->engine.importFlpFile (flp, error, relocations, true))
  3996. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  3997. }
  3998. else
  3999. safe->engine.editSong ([&relocations] (Song& s) { applyRelocations (s, relocations); });
  4000. safe->updateTitle();
  4001. },
  4002. [safe, afterOpening, fromFlp] {
  4003. if (safe != nullptr && afterOpening && fromFlp)
  4004. safe->showImportReport();
  4005. });
  4006. }
  4007. void MainComponent::switchSmartDisableForAll()
  4008. {
  4009. // FL's Tools › Macros › "Switch smart disable for all plugins" (FLEngine FUN_0124d430, REA round 139): every
  4010. // effect slot of every insert is set to smart disable
  4011. engine.editSong ([] (Song& s) {
  4012. for (auto& track : s.mixer)
  4013. for (auto& slot : track.effects)
  4014. slot.smartDisable = true;
  4015. });
  4016. }
  4017. void MainComponent::exportAudio (int format)
  4018. {
  4019. showExportDialog (engine, currentFile.getParentDirectory(), projectName, format);
  4020. }
  4021. void MainComponent::importMidiFile()
  4022. {
  4023. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  4024. fileChooser = std::make_unique<juce::FileChooser> (tr ("Import MIDI file"), folder, "*.mid;*.midi");
  4025. juce::Component::SafePointer<MainComponent> safe (this);
  4026. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe] (const juce::FileChooser& fc) {
  4027. const auto file = fc.getResult();
  4028. if (safe == nullptr || file == juce::File())
  4029. return;
  4030. juce::String error;
  4031. const auto midi = MidiFileIo::parseFile (file, error);
  4032. if (! midi)
  4033. {
  4034. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  4035. return;
  4036. }
  4037. static MidiFileIo::ImportOptions remembered; // FL keeps the window's choices
  4038. showMidiImportDialog (file.getFileName(), *midi, remembered, false, [safe, file] (const MidiFileIo::ImportOptions& o) {
  4039. remembered = o;
  4040. if (safe != nullptr)
  4041. safe->importMidiFile (file, o);
  4042. });
  4043. });
  4044. }
  4045. void MainComponent::importMidiFile (const juce::File& file, const MidiFileIo::ImportOptions& o)
  4046. {
  4047. juce::String error;
  4048. if (o.newProject)
  4049. {
  4050. confirmDiscard ([this, file, o] {
  4051. Song song;
  4052. juce::String err;
  4053. if (! MidiFileIo::importInto (song, file, o, err))
  4054. {
  4055. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), err);
  4056. return;
  4057. }
  4058. engine.stop();
  4059. engine.rewind();
  4060. engine.setSong (std::move (song));
  4061. currentFile = juce::File();
  4062. projectName = file.getFileNameWithoutExtension();
  4063. importedSuffix = " " + tr ("(imported from MIDI)");
  4064. updateTitle();
  4065. });
  4066. return;
  4067. }
  4068. auto song = engine.getSong();
  4069. if (! MidiFileIo::importInto (song, file, o, error))
  4070. {
  4071. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not import"), error);
  4072. return;
  4073. }
  4074. engine.editSong ([&song] (Song& s) { s = std::move (song); });
  4075. showPanel (Panel::channelRack);
  4076. }
  4077. void MainComponent::exportMidiFile()
  4078. {
  4079. // FL's File › Export › "MIDI file...": the arrangement's notes (or the current pattern's) as a Standard MIDI File
  4080. const auto folder = currentFile.existsAsFile() ? currentFile.getParentDirectory() : juce::File::getSpecialLocation (juce::File::userMusicDirectory);
  4081. const auto name = projectName.isNotEmpty() ? projectName : juce::String ("LYNX SHARE");
  4082. fileChooser = std::make_unique<juce::FileChooser> (tr ("Export MIDI file"), folder.getChildFile (name + ".mid"), "*.mid");
  4083. juce::Component::SafePointer<MainComponent> safe (this);
  4084. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  4085. [safe] (const juce::FileChooser& fc) {
  4086. auto file = fc.getResult();
  4087. if (safe == nullptr || file == juce::File())
  4088. return;
  4089. if (! file.hasFileExtension (".mid;.midi"))
  4090. file = file.withFileExtension (".mid");
  4091. juce::String error;
  4092. if (! MidiFileIo::saveSong (safe->engine.getSong(), file, error))
  4093. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not export"), error);
  4094. else
  4095. file.revealToUser();
  4096. });
  4097. }
  4098. void MainComponent::save (bool askForFile)
  4099. {
  4100. auto write = [this] (juce::File file) {
  4101. if (! file.hasFileExtension (ProjectFile::extension))
  4102. file = file.withFileExtension (ProjectFile::extension);
  4103. juce::String error;
  4104. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  4105. keepOverwrittenCopy (file); // the version this save replaces goes to the backup folder (like FL)
  4106. if (ProjectFile::save (engine.getSong(), file, error))
  4107. {
  4108. engine.markSaved();
  4109. rememberRecent (file);
  4110. currentFile = file;
  4111. projectName = file.getFileNameWithoutExtension();
  4112. importedSuffix = {};
  4113. updateTitle();
  4114. }
  4115. else
  4116. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  4117. };
  4118. // a project opened from the backup folder is saved somewhere else (old backups there are deleted)
  4119. if (! askForFile && currentFile != juce::File() && ! currentFile.isAChildOf (autosaveFolder()))
  4120. {
  4121. write (currentFile);
  4122. return;
  4123. }
  4124. const auto startFolder = currentFile.isAChildOf (autosaveFolder()) ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory)
  4125. : currentFile.getParentDirectory();
  4126. fileChooser = std::make_unique<juce::FileChooser> (tr ("Save project"), startFolder, juce::String ("*") + ProjectFile::extension);
  4127. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  4128. [write] (const juce::FileChooser& chooser) {
  4129. const auto file = chooser.getResult();
  4130. if (file == juce::File())
  4131. return;
  4132. if (! file.isAChildOf (autosaveFolder()))
  4133. {
  4134. write (file);
  4135. return;
  4136. }
  4137. // FL warns the same way: the backup folder is cleaned up as new backups arrive
  4138. auto* w = new juce::AlertWindow (tr ("Save in the backup folder?"),
  4139. tr ("This folder keeps LYNX SHARE's automatic backups and old ones are deleted as new "
  4140. "ones arrive, so a project saved here can be lost. If you opened a backup, save it "
  4141. "somewhere else."),
  4142. juce::MessageBoxIconType::WarningIcon);
  4143. w->addButton (tr ("Save anyway"), 1);
  4144. w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4145. w->enterModalState (true, juce::ModalCallbackFunction::create ([write, file] (int r) {
  4146. if (r == 1)
  4147. write (file);
  4148. }),
  4149. true);
  4150. });
  4151. }
  4152. void MainComponent::placeHintBar (juce::Rectangle<int> row)
  4153. {
  4154. // the read-out takes the right part of the hint row once something was tweaked (2/5 of it, 170..280 px), and
  4155. // only when the hint keeps at least 220 px
  4156. const auto readoutWidth = juce::jlimit (170, 280, row.getWidth() * 2 / 5);
  4157. if (tweakReadout.hasContent() && row.getWidth() - readoutWidth - 6 >= 220)
  4158. {
  4159. tweakReadout.setBounds (row.removeFromRight (readoutWidth));
  4160. tweakReadout.setVisible (true);
  4161. row.removeFromRight (6);
  4162. }
  4163. else
  4164. {
  4165. tweakReadout.setVisible (false);
  4166. tweakReadout.setBounds ({});
  4167. }
  4168. hintBar.setVisible (true);
  4169. hintBar.setBounds (row);
  4170. }
  4171. void MainComponent::refreshTweakReadout()
  4172. {
  4173. const auto had = tweakReadout.hasContent();
  4174. if (const auto t = engine.getLastTweaked (0))
  4175. tweakReadout.setContent (describeAutomationTarget (engine, *t), describeTargetValue (engine, *t));
  4176. else
  4177. tweakReadout.setContent ({}, {});
  4178. if (had != tweakReadout.hasContent())
  4179. resized(); // the read-out appears (or goes, with its target)
  4180. }
  4181. juce::PopupMenu MainComponent::makeLastTweakedMenu (int which)
  4182. {
  4183. juce::PopupMenu menu;
  4184. const auto target = engine.getLastTweaked (which);
  4185. if (! target)
  4186. {
  4187. menu.addItem (tr ("No parameter"), false, false, [] {});
  4188. return menu;
  4189. }
  4190. // as FL: the parameter's name, then the items of its own menu (events, automation clip, remote control, value)
  4191. const auto valueNow = describeTargetValue (engine, *target); // (round 162d: with its value, as the read-out shows it)
  4192. ui::addItemHeader (menu, tr ("Parameter"), describeAutomationTarget (engine, *target) + (valueNow.isNotEmpty() ? ": " + valueNow : juce::String()),
  4193. juce::Colours::transparentBlack);
  4194. const auto& song = engine.getSong();
  4195. int clip = -1;
  4196. for (int a = 0; a < (int) song.automations.size(); ++a)
  4197. if (song.automations[(std::size_t) a].target == *target)
  4198. clip = a;
  4199. juce::ignoreUnused (clip);
  4200. addAutomationItem (menu, engine, *target, true);
  4201. menu.addSectionHeader (tr ("Value"));
  4202. const auto value = engine.currentTargetValue (*target);
  4203. menu.addItem (tr ("Copy value"), value >= 0.0f, false, [value] { lastTweakedClipboard() = value; });
  4204. menu.addItem (tr ("Paste value"), lastTweakedClipboard() >= 0.0f, false, [this, t = *target] { setTweakedValue (t, lastTweakedClipboard()); });
  4205. menu.addItem (tr ("Type in value..."), value >= 0.0f, false, [this, t = *target, value] {
  4206. auto spec = ui::percentSpec (describeAutomationTarget (engine, t), value);
  4207. ui::typeValue (*this, spec, value, [this, t] (double v) { setTweakedValue (t, (float) v); });
  4208. });
  4209. return menu;
  4210. }
  4211. float& MainComponent::lastTweakedClipboard()
  4212. {
  4213. static float copied = -1.0f;
  4214. return copied;
  4215. }
  4216. void MainComponent::setTweakedValue (const AutomationTarget& target, float value)
  4217. {
  4218. value = juce::jlimit (0.0f, 1.0f, value);
  4219. auto plugin = false;
  4220. engine.editSong ([&] (Song& s) { plugin = ! s.setTargetValue (target, value); });
  4221. if (plugin)
  4222. {
  4223. if (target.kind == AutomationTargetKind::channelParam)
  4224. if (auto* p = dynamic_cast<PluginInstrument*> (engine.getChannelInstrument (target.index).get()))
  4225. p->setParameterFromUi (target.param, value);
  4226. if (target.kind == AutomationTargetKind::effectParam)
  4227. if (auto* p = dynamic_cast<PluginEffect*> (engine.getEffect (target.index, target.slot).get()))
  4228. p->setParameterFromUi (target.param, value);
  4229. }
  4230. engine.noteTweaked (target);
  4231. }
  4232. juce::StringArray MainComponent::getMenuBarNames()
  4233. {
  4234. // FL's menu bar order (REA round 139): FILE EDIT ADD PATTERNS VIEW OPTIONS TOOLS HELP
  4235. return { tr ("File"), tr ("Edit"), tr ("Add"), tr ("Patterns"), tr ("View"), tr ("Options"), tr ("Tools"), tr ("Help") };
  4236. }
  4237. juce::PopupMenu MainComponent::getMenuForIndex (int barIndex, const juce::String&)
  4238. {
  4239. juce::PopupMenu menu;
  4240. // the bar's position → the menu built below (0 File, 1 Edit, 2 View, 3 Patterns, 4 Options, 5 Help, 10 Add, 11 Tools)
  4241. static constexpr int menus[] = { 0, 1, 10, 3, 2, 4, 11, 5 };
  4242. const auto index = juce::isPositiveAndBelow (barIndex, (int) std::size (menus)) ? menus[barIndex] : 5;
  4243. if (index == 10)
  4244. {
  4245. // FL's ADD menu: a channel (LYNX's instruments and the installed plugins), a pattern, the plugin tools
  4246. menu.addSectionHeader (tr ("Channel"));
  4247. rack.addInstrumentItems (menu, -1);
  4248. menu.addSectionHeader (tr ("Other"));
  4249. // FL's "Automation for last tweaked parameter" (Add_AutoLastMenu → FUN_01231100, REA round 143)
  4250. const auto last = engine.getLastTweaked (0);
  4251. menu.addItem (last ? tr ("Automation for last tweaked parameter ({0})", { describeAutomationTarget (engine, *last) })
  4252. : tr ("Automation for last tweaked parameter"),
  4253. last.has_value(), false, [this] {
  4254. if (const auto t = engine.getLastTweaked (0))
  4255. createAutomationClip (engine, *t);
  4256. });
  4257. menu.addItem (tr ("Pattern"), [this] { newPatternButton.onClick(); });
  4258. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  4259. return menu;
  4260. }
  4261. if (index == 11)
  4262. {
  4263. // FL's TOOLS menu, with the tools LYNX has (REA round 139)
  4264. menu.addItem (tr ("Browser find") + shortcutText ("browser.search"), [this] {
  4265. showPanel (Panel::browser);
  4266. browser.focusSearch();
  4267. });
  4268. menu.addItem (tr ("One-click audio recording: arm the selected insert..."), [this] { armSelectedInsertForAudio(); });
  4269. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  4270. // FL's "Last tweaked parameters" section (LastTweaked1Menu / LastTweaked2Menu → FUN_0123d1d0, REA round 143):
  4271. // the parameter's own menu for the last two moved controls
  4272. menu.addSectionHeader (tr ("Last tweaked parameters"));
  4273. menu.addSubMenu (tr ("Last tweaked"), makeLastTweakedMenu (0), engine.getLastTweaked (0).has_value());
  4274. menu.addSubMenu (tr ("Next to last tweaked"), makeLastTweakedMenu (1), engine.getLastTweaked (1).has_value());
  4275. menu.addSectionHeader (tr ("Macros"));
  4276. menu.addItem (tr ("Stop sound (all notes off)"), [this] { engine.panic(); });
  4277. menu.addItem (tr ("Select unused channels"), [this] {
  4278. showPanel (Panel::channelRack);
  4279. rack.selectUnused();
  4280. });
  4281. menu.addItem (tr ("Switch smart disable for all plugins"), [this] { switchSmartDisableForAll(); });
  4282. menu.addItem (tr ("Prepare for performance mode..."), [this] { prepareForPerformance(); });
  4283. menu.addItem (tr ("Delete unused recordings and save project..."), [this] { deleteUnusedRecordingsAndSave(); });
  4284. menu.addItem (tr ("Collect project samples into a folder..."), [this] { collectSamples(); });
  4285. return menu;
  4286. }
  4287. if (index == 0)
  4288. {
  4289. menu.addItem (tr ("New") + shortcutText ("file.new"), [this] { newProject(); });
  4290. menu.addItem (tr ("New project..."), [this] { newProject (true); });
  4291. juce::PopupMenu templates;
  4292. const auto names = templateNames();
  4293. for (int i = 0; i < (int) names.size(); ++i)
  4294. templates.addItem (juce::String::fromUTF8 (names[(std::size_t) i].c_str()), [this, i] {
  4295. confirmDiscard ([this, i] {
  4296. engine.stop();
  4297. engine.rewind();
  4298. engine.setSong (makeNewProject (i));
  4299. currentFile = juce::File();
  4300. projectName = {};
  4301. importedSuffix = {};
  4302. updateTitle();
  4303. });
  4304. });
  4305. menu.addSubMenu (tr ("New from template"), templates);
  4306. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  4307. menu.addSeparator();
  4308. // FL's order (REA round 139): saving, then Export, then the recent projects listed in the menu itself
  4309. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  4310. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  4311. menu.addItem (tr ("Save new version") + shortcutText ("file.saveNewVersion"), [this] { saveNewVersion(); });
  4312. menu.addItem (tr ("Save to new project folder..."), [this] { saveToNewProjectFolder(); });
  4313. menu.addItem (tr ("Save as template..."), [this] { saveAsTemplate(); });
  4314. menu.addItem (tr ("Delete unused recordings and save..."), [this] { deleteUnusedRecordingsAndSave(); });
  4315. menu.addSeparator();
  4316. {
  4317. // FL's File › Import (ImportMenu › ImportMIDIMenu → FileImportMIDIFileAction, REA round 143)
  4318. juce::PopupMenu imports;
  4319. imports.addItem (tr ("MIDI file..."), [this] { importMidiFile(); });
  4320. menu.addSubMenu (tr ("Import"), imports);
  4321. }
  4322. {
  4323. // FL's File › Export (REA round 139): one entry per format, then the formats of the last export
  4324. juce::PopupMenu exports;
  4325. exports.addItem (tr ("Wave file..."), [this] { exportAudio (0); });
  4326. exports.addItem (tr ("MP3 file...") + shortcutText ("file.exportMp3"), [this] { exportAudio (1); });
  4327. exports.addItem (tr ("OGG file..."), [this] { exportAudio (2); });
  4328. exports.addItem (tr ("FLAC file..."), [this] { exportAudio (3); });
  4329. exports.addItem (tr ("MIDI file...") + shortcutText ("file.exportMidi"), [this] { exportMidiFile(); });
  4330. exports.addItem (tr ("Last exported format(s)...") + shortcutText ("file.export"), [this] { exportAudio(); });
  4331. exports.addSeparator();
  4332. exports.addItem (tr ("Project with samples (.zip)..."), [this] { exportPackage(); });
  4333. exports.addItem (tr ("Project data files (collect the samples into a folder)..."), [this] { collectSamples(); });
  4334. menu.addSubMenu (tr ("Export"), exports);
  4335. }
  4336. menu.addSectionHeader (tr ("Recent projects"));
  4337. const auto shown = juce::jmin (recent.getNumFiles(), 10);
  4338. for (int i = 0; i < shown; ++i)
  4339. {
  4340. const auto file = recent.getFile (i);
  4341. juce::PopupMenu::Item item (file.getFileName());
  4342. item.shortcutKeyDescription = file.getParentDirectory().getFileName(); // its folder on the right
  4343. item.setEnabled (file.existsAsFile()).setAction ([this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  4344. menu.addItem (std::move (item));
  4345. }
  4346. if (recent.getNumFiles() > shown)
  4347. {
  4348. juce::PopupMenu more;
  4349. for (int i = shown; i < recent.getNumFiles(); ++i)
  4350. {
  4351. const auto file = recent.getFile (i);
  4352. more.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  4353. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  4354. }
  4355. menu.addSubMenu (tr ("More recent projects"), more);
  4356. }
  4357. if (recent.getNumFiles() == 0)
  4358. menu.addItem (tr ("(none)"), false, false, [] {});
  4359. menu.addSeparator();
  4360. menu.addItem (tr ("Revert to last backup..."), [this] { revertToLastBackup(); });
  4361. menu.addItem (tr ("Open autosave folder"), [] {
  4362. autosaveFolder().createDirectory();
  4363. autosaveFolder().startAsProcess();
  4364. });
  4365. menu.addSeparator();
  4366. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  4367. }
  4368. else if (index == 1)
  4369. {
  4370. // FL's Edit menu: "Undo backwards" (Ctrl+Alt+Z) above "Undo" (Ctrl+Z: undo, or redo after an undo)
  4371. menu.addItem (tr ("Undo backwards") + shortcutText ("edit.undoBackwards"), engine.canUndo(), false, [this] { undoRedo (false); });
  4372. menu.addItem ((alternateUndo || ! engine.canRedo() ? tr ("Undo") : tr ("Undo (redo)")) + shortcutText ("edit.undo"),
  4373. engine.canUndo() || engine.canRedo(), false, [this] { flUndo(); });
  4374. menu.addItem (tr ("Redo") + shortcutText ("edit.redo"), engine.canRedo(), false, [this] { undoRedo (true); });
  4375. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  4376. menu.addItem (tr ("Audio editor..."), [this] { openAudioEditor (engine); });
  4377. menu.addSeparator();
  4378. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  4379. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  4380. showPanel (Panel::browser);
  4381. browser.focusSearch();
  4382. });
  4383. }
  4384. else if (index == 2)
  4385. {
  4386. for (auto panel : panelOrder)
  4387. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  4388. menu.addSeparator();
  4389. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  4390. workspace.toggleMaximised (Panel::playlist);
  4391. refreshPanelButtons();
  4392. });
  4393. {
  4394. juce::PopupMenu detach;
  4395. for (auto panel : panelOrder)
  4396. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  4397. workspace.setDetached (panel, ! workspace.isDetached (panel));
  4398. refreshPanelButtons();
  4399. });
  4400. menu.addSubMenu (tr ("Detached panels (own window)"), detach);
  4401. }
  4402. menu.addSeparator();
  4403. menu.addItem (tr ("Reset layout"), [this] {
  4404. workspace.resetLayout();
  4405. refreshPanelButtons();
  4406. });
  4407. menu.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  4408. menu.addSubMenu (tr ("Load layout"), layoutsMenu());
  4409. menu.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  4410. menu.addItem (tr ("Close all windows (plugins, channel settings, tools)") + shortcutText ("view.closeWindows"), [this] { runAction ("view.closeWindows"); });
  4411. menu.addItem (tr ("Close all plugin windows") + shortcutText ("view.closePluginWindows"), [this] { runAction ("view.closePluginWindows"); });
  4412. menu.addItem (tr ("Close all windows except the focused one") + shortcutText ("view.closeUnfocusedWindows"), [this] { runAction ("view.closeUnfocusedWindows"); });
  4413. menu.addSeparator();
  4414. menu.addItem (tr ("Plugin database (in the Browser)") + shortcutText ("view.pluginDatabase"), [this] { runAction ("view.pluginDatabase"); });
  4415. menu.addItem (tr ("Audio editor") + shortcutText ("view.audioEditor"), [this] { openAudioEditorForSelection(); });
  4416. menu.addItem (tr ("Tempo tapper") + shortcutText ("view.tempoTapper"), [this] { openTempoTapper (engine); });
  4417. menu.addItem (tr ("Sample browser (separate window)") + shortcutText ("view.sampleBrowser"), true, findToolWindow ("sampleBrowser") != nullptr,
  4418. [this] { toggleSampleBrowser(); });
  4419. menu.addSeparator();
  4420. menu.addItem (tr ("Typing keyboard as a piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { setTypingPiano (! typingPiano); });
  4421. menu.addItem (tr ("Touch keyboard") + shortcutText ("view.touchKeyboard"), true, isTouchKeyboardOpen(), [this] { toggleTouchKeyboard (engine); });
  4422. {
  4423. // FL's View › Background (audit round 165z-a): the workspace image and colour of Options › Theme
  4424. juce::PopupMenu background;
  4425. background.addItem (tr ("Set image wallpaper..."), [] { themeui::setImageWallpaper(); });
  4426. background.addItem (tr ("Remove image wallpaper"), ! themeui::current().image.empty(), false, [] { themeui::removeImageWallpaper(); });
  4427. background.addItem (tr ("Set background color..."), [this] { openSettings ((int) SettingsPage::theme); });
  4428. menu.addSubMenu (tr ("Background"), background);
  4429. }
  4430. menu.addSeparator();
  4431. // FL's "Auto scrolling" (round 162, issue #9)
  4432. menu.addItem (tr ("Playlist follows the playhead (auto scrolling)") + shortcutText ("playlist.follow"), true,
  4433. EditorGlobals::get().isFollowing (false), [this] { runAction ("playlist.follow"); });
  4434. menu.addItem (tr ("Piano Roll follows the playhead (auto scrolling)") + shortcutText ("pianoRoll.follow"), true,
  4435. EditorGlobals::get().isFollowing (true), [this] { runAction ("pianoRoll.follow"); });
  4436. }
  4437. else if (index == 3)
  4438. {
  4439. menu = makePatternMenu();
  4440. }
  4441. else if (index == 4)
  4442. {
  4443. // the Settings window's pages (Settings › General gathers the app options that were menu items here)
  4444. menu.addItem (tr ("Audio settings..."), [this] { openSettings ((int) SettingsPage::audio); });
  4445. menu.addItem (tr ("MIDI settings...") + shortcutText ("view.midiSettings"), [this] { openSettings ((int) SettingsPage::midi); });
  4446. menu.addItem (tr ("General settings..."), [this] { openSettings ((int) SettingsPage::general); });
  4447. menu.addItem (tr ("Theme (colors, background)..."), [this] { openSettings ((int) SettingsPage::theme); });
  4448. menu.addItem (tr ("File settings (search folders)..."), [this] { openSettings ((int) SettingsPage::files); });
  4449. menu.addItem (tr ("Project settings (tempo, time signature)..."), [this] { openSettings ((int) SettingsPage::project); });
  4450. menu.addItem (tr ("Project info...") + shortcutText ("view.projectInfo"), [this] { openSettings ((int) SettingsPage::info); });
  4451. {
  4452. juce::PopupMenu mixerMenu; // round 163: clean mixer, inserts and Master chain of new projects
  4453. mixeroptions::addItems (mixerMenu, engine, true);
  4454. menu.addSubMenu (tr ("Mixer"), mixerMenu);
  4455. }
  4456. menu.addSeparator();
  4457. menu.addItem (tr ("Plugin manager..."), [this] { showPluginManager(); });
  4458. const auto scanning = engine.getPluginHost().backgroundScan().running;
  4459. menu.addItem (scanning ? tr ("Stop the plugin scan") : tr ("Scan for plugins ({0})", { platform::pluginFormatNames() }), [this, scanning] {
  4460. if (scanning)
  4461. engine.getPluginHost().cancelBackgroundScan();
  4462. else
  4463. engine.getPluginHost().startBackgroundScan(); // progress in the hint bar; LYNX stays usable
  4464. });
  4465. menu.addItem (tr ("Manage shortcuts..."), [this] { showShortcutManager(); });
  4466. menu.addItem (tr ("Plugin performance monitor..."), [this] { showPluginMonitor (engine); });
  4467. menu.addSeparator();
  4468. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  4469. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  4470. });
  4471. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  4472. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  4473. });
  4474. menu.addItem (tr ("Metronome volume ({0})...", { ui::utilityVolumeText (engine.getTransport().metronomeVolume.load()) }),
  4475. [this] { showMetronomeVolume(); });
  4476. {
  4477. // FL's Options › "Auto scrolling" (audit round 165z-a): one switch for every editor's Follow (Playlist,
  4478. // Piano roll, Channel rack, Audio editor); each window's own Follow button still sets just that window
  4479. auto& globals = EditorGlobals::get();
  4480. const auto on = globals.isFollowing (false) && globals.isFollowing (true);
  4481. menu.addItem (tr ("Auto scrolling"), true, on, [on] {
  4482. auto& g = EditorGlobals::get();
  4483. for (auto v : { EditorGlobals::FollowView::playlist, EditorGlobals::FollowView::pianoRoll,
  4484. EditorGlobals::FollowView::channelRack, EditorGlobals::FollowView::audioEditor })
  4485. g.setFollowingView (v, ! on);
  4486. });
  4487. }
  4488. {
  4489. juce::PopupMenu recording;
  4490. addRecordOptions (recording);
  4491. menu.addSubMenu (tr ("Recording"), recording);
  4492. }
  4493. {
  4494. // FL 2026's Audio Logger (REA round 153): everything the Master plays goes to a WAV in the background
  4495. auto& logger = engine.getAudioLogger();
  4496. menu.addItem (tr ("Audio logger (record everything the Master plays)"), true, logger.isLogging(), [this] {
  4497. auto& log = engine.getAudioLogger();
  4498. if (log.isLogging())
  4499. {
  4500. const auto file = log.currentFile();
  4501. const auto seconds = log.secondsWritten();
  4502. log.stop();
  4503. ui::postHint ({ tr ("Audio logger: saved {0} ({1} s)", { file.getFileName(), juce::String (seconds, 1) }), {}, false, false }, 5000);
  4504. }
  4505. else if (! log.start (AudioLogger::defaultFolder(), engine.getTransport().sampleRate.load()))
  4506. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio logger"),
  4507. tr ("Could not create a file in {0}", { AudioLogger::defaultFolder().getFullPathName() }));
  4508. else
  4509. ui::postHint ({ tr ("Audio logger: recording the Master to {0}", { log.currentFile().getFileName() }), {}, false, false }, 5000);
  4510. });
  4511. menu.addItem (tr ("Show the audio logger's files"), [] {
  4512. const auto folder = AudioLogger::defaultFolder();
  4513. folder.createDirectory();
  4514. folder.startAsProcess();
  4515. });
  4516. }
  4517. {
  4518. // FL's score logger (REA round 165f): the notes played lately, recording or not, into the current pattern
  4519. juce::PopupMenu dumpMenu;
  4520. for (const auto minutes : { 2, 5, 10, 20, 30 })
  4521. dumpMenu.addItem (tr ("Last {0} minutes", { juce::String (minutes) }), [this, minutes] { dumpScoreLog (minutes); });
  4522. menu.addSubMenu (tr ("Dump score log to selected pattern"), dumpMenu);
  4523. menu.addItem (tr ("Clear score log"), ! engine.scoreLogEmpty(), false, [this] {
  4524. auto options = juce::MessageBoxOptions()
  4525. .withIconType (juce::MessageBoxIconType::WarningIcon)
  4526. .withTitle (tr ("Score logger"))
  4527. .withMessage (tr ("This will clear all logged notes!"))
  4528. .withButton (tr ("Clear log"))
  4529. .withButton (tr ("Cancel"));
  4530. juce::AlertWindow::showAsync (options, [this] (int result) {
  4531. if (result == 1)
  4532. engine.clearScoreLog();
  4533. });
  4534. });
  4535. }
  4536. menu.addSubMenu (tr ("Toolbar"), makeToolbarMenu());
  4537. menu.addSeparator();
  4538. menu.addItem (tr ("Setup wizard (language, audio, plugin folders)..."), [this] { showSetupWizard(); });
  4539. }
  4540. else
  4541. {
  4542. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  4543. menu.addItem (tr ("Missing files..."), [this] { showMissingFiles (false); });
  4544. menu.addItem (tr ("Last FL Studio import report"), [this] {
  4545. const auto& r = engine.getImportReport();
  4546. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.partialEffects.empty() && r.missingSamples == 0
  4547. && engine.getMissingPlugins().isEmpty() && engine.getMatchedPlugins().isEmpty() && engine.getPluginsWithoutState().isEmpty()
  4548. && engine.getPluginHost().getLoadFailures().isEmpty())
  4549. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"),
  4550. tr ("Nothing to report (no .flp imported in this session, or everything was converted)."));
  4551. else
  4552. showImportReport();
  4553. });
  4554. menu.addItem (tr ("Built-in plugins (online list)..."), [] {
  4555. juce::URL ("https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/PLUGINS.md").launchInDefaultBrowser();
  4556. });
  4557. menu.addItem (tr ("Report a problem..."), [this] { crashreporter::showManualReport (&engine.getDeviceManager()); });
  4558. if (updater::offered()) // (not in the Store build: the Store updates it)
  4559. menu.addItem (tr ("Check for updates..."), [] { updater::checkNow(); });
  4560. menu.addItem (tr ("About LYNX SHARE"), [] {
  4561. auto* window = makeAboutWindow().release();
  4562. window->enterModalState (true, nullptr, true);
  4563. keepAboveMainWindow (*window);
  4564. });
  4565. }
  4566. return menu;
  4567. }
  4568. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  4569. {
  4570. struct Logo final : juce::Component
  4571. {
  4572. Logo() { setSize (300, 150); }
  4573. void paint (juce::Graphics& g) override
  4574. {
  4575. g.drawImageWithin (logoImage(), 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred);
  4576. }
  4577. };
  4578. struct About final : juce::AlertWindow
  4579. {
  4580. About()
  4581. : juce::AlertWindow ("LYNX SHARE " JUCE_APPLICATION_VERSION_STRING,
  4582. tr ("Lightweight C++/JUCE DAW with the FL Studio workflow.\n"
  4583. "Independent implementation: no Image-Line code was copied."),
  4584. juce::MessageBoxIconType::NoIcon)
  4585. {
  4586. addCustomComponent (&logo);
  4587. }
  4588. Logo logo;
  4589. };
  4590. auto window = std::make_unique<About>();
  4591. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4592. return std::unique_ptr<juce::AlertWindow> (window.release());
  4593. }
  4594. void MainComponent::showLanguageChoice (const juce::String& id)
  4595. {
  4596. if (id == i18n::saved())
  4597. return;
  4598. i18n::save (id);
  4599. const auto restart = [this] {
  4600. confirmDiscard ([] {
  4601. lynx::platform::relaunchApp(); // through the package in the Store build (platform/Package.h)
  4602. juce::JUCEApplication::quit();
  4603. });
  4604. };
  4605. // the message is shown in the language just chosen
  4606. const auto table = i18n::tableText (id);
  4607. const juce::LocalisedStrings strings (table, false);
  4608. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  4609. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX SHARE restarts.")),
  4610. juce::MessageBoxIconType::InfoIcon);
  4611. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4612. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4613. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  4614. if (result == 1)
  4615. restart();
  4616. }),
  4617. true);
  4618. }
  4619. void MainComponent::rememberRecent (const juce::File& file)
  4620. {
  4621. recent.addFile (file);
  4622. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  4623. menuItemsChanged();
  4624. }
  4625. std::unique_ptr<juce::Component> MainComponent::makeHelpContent (const keys::KeyMap* keyMapIn)
  4626. {
  4627. // shortcut sheet: sections of "keys - action" rows, in two columns
  4628. struct Row
  4629. {
  4630. const char* keys;
  4631. const char* action;
  4632. };
  4633. struct Section
  4634. {
  4635. const char* title;
  4636. std::vector<Row> rows;
  4637. };
  4638. static const std::vector<Section> sections {
  4639. { TR_NOOP ("General"),
  4640. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  4641. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  4642. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  4643. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  4644. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  4645. { "Ctrl+R", TR_NOOP ("Export audio") },
  4646. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  4647. { "L", TR_NOOP ("Pattern / song mode") },
  4648. { "Ctrl+T", TR_NOOP ("Typing keyboard as a piano on/off") },
  4649. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  4650. { "Numpad +/-", TR_NOOP ("Next / previous pattern") },
  4651. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  4652. { TR_NOOP ("Workspace"),
  4653. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  4654. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  4655. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  4656. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  4657. { TR_NOOP ("Channel Rack and Mixer"),
  4658. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  4659. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  4660. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  4661. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  4662. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  4663. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  4664. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  4665. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  4666. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  4667. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  4668. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  4669. { "Piano Roll",
  4670. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  4671. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  4672. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  4673. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  4674. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  4675. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  4676. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  4677. { "Alt+M / Shift+Alt+M", TR_NOOP ("Mute / unmute") },
  4678. { "Ctrl+P / Ctrl+D", TR_NOOP ("Portamento / deselect") },
  4679. { TR_NOOP ("Shift+arrows"), TR_NOOP ("Transpose a semitone / move by the grid (Ctrl+Up/Down: an octave)") },
  4680. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  4681. { "Playlist",
  4682. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  4683. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  4684. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  4685. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  4686. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  4687. };
  4688. // the fourth column: every F-key of the live key map (issue #23: the sheet listed no F-keys), custom keys included
  4689. const keys::KeyMap defaults;
  4690. const auto& map = keyMapIn != nullptr ? *keyMapIn : defaults;
  4691. std::vector<std::pair<juce::String, juce::String>> functionKeys;
  4692. for (const auto& b : map.functionKeyBindings())
  4693. if (const auto* action = keys::findAction (b.actionId))
  4694. {
  4695. auto text = tr (action->description);
  4696. if (b.context != keys::Context::global)
  4697. text << " (" << tr (b.context == keys::Context::browser ? "Browser"
  4698. : b.context == keys::Context::mixer ? "Mixer"
  4699. : b.context == keys::Context::playlist ? "Playlist"
  4700. : b.context == keys::Context::pianoRoll ? "Piano Roll"
  4701. : "Channel Rack")
  4702. << ")";
  4703. functionKeys.push_back ({ juce::String (keys::toString (b.chord)), text });
  4704. }
  4705. struct Sheet final : juce::Component
  4706. {
  4707. explicit Sheet (std::vector<std::pair<juce::String, juce::String>> f) : fkeys (std::move (f))
  4708. {
  4709. setSize (1500, juce::jmax (520, 20 + 28 + (int) fkeys.size() * 22 + 20));
  4710. }
  4711. void paint (juce::Graphics& g) override
  4712. {
  4713. using namespace theme;
  4714. g.fillAll (colour::bg2);
  4715. const auto columnWidth = (getWidth() - 5 * 24) / 4;
  4716. int column = 0, y = 20;
  4717. for (std::size_t i = 0; i < sections.size(); ++i)
  4718. {
  4719. if (i == 2 || i == 3) // next column
  4720. {
  4721. ++column;
  4722. y = 20;
  4723. }
  4724. const auto x = 24 + column * (columnWidth + 24);
  4725. const auto& section = sections[i];
  4726. g.setColour (colour::accent);
  4727. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  4728. g.setColour (colour::textPrimary);
  4729. g.setFont (font (type::title, true));
  4730. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  4731. y += 28;
  4732. for (const auto& row : section.rows)
  4733. {
  4734. const auto keys = tr (row.keys);
  4735. g.setFont (font (type::small, true));
  4736. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  4737. g.setColour (colour::bg4);
  4738. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  4739. g.setColour (colour::textPrimary);
  4740. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  4741. g.setColour (colour::textSecondary);
  4742. g.setFont (font (type::body));
  4743. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  4744. y += 24;
  4745. }
  4746. y += 14;
  4747. }
  4748. // Function keys
  4749. const auto x = 24 + 3 * (columnWidth + 24);
  4750. y = 20;
  4751. g.setColour (colour::accent);
  4752. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  4753. g.setColour (colour::textPrimary);
  4754. g.setFont (font (type::title, true));
  4755. g.drawText (tr ("Function keys"), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  4756. y += 28;
  4757. g.setFont (font (type::small, true));
  4758. int keyWidth = 0;
  4759. for (const auto& [keys, text] : fkeys)
  4760. keyWidth = juce::jmax (keyWidth, juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14);
  4761. for (const auto& [keys, text] : fkeys)
  4762. {
  4763. g.setFont (font (type::small, true));
  4764. g.setColour (colour::bg4);
  4765. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  4766. g.setColour (colour::textPrimary);
  4767. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  4768. g.setColour (colour::textSecondary);
  4769. g.setFont (font (type::body));
  4770. g.drawFittedText (text, x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.8f);
  4771. y += 22;
  4772. }
  4773. }
  4774. std::vector<std::pair<juce::String, juce::String>> fkeys;
  4775. };
  4776. return std::make_unique<Sheet> (std::move (functionKeys));
  4777. }
  4778. void MainComponent::showHelp()
  4779. {
  4780. juce::DialogWindow::LaunchOptions options;
  4781. options.content.setOwned (makeHelpContent (&keyMap).release());
  4782. options.dialogTitle = tr ("LYNX SHARE shortcuts");
  4783. options.dialogBackgroundColour = theme::colour::bg2;
  4784. options.useNativeTitleBar = true;
  4785. options.resizable = true;
  4786. options.escapeKeyTriggersCloseButton = true;
  4787. if (auto* dialog = options.launchAsync())
  4788. {
  4789. keepAboveMainWindow (*dialog);
  4790. helpWindow = dialog;
  4791. }
  4792. }
  4793. void MainComponent::closeHelp()
  4794. {
  4795. // (the key may come from the sheet itself: delete it after this call stack)
  4796. if (helpWindow == nullptr)
  4797. return;
  4798. helpWindow->setVisible (false);
  4799. juce::MessageManager::callAsync ([w = helpWindow] { delete w.getComponent(); });
  4800. helpWindow = nullptr;
  4801. }
  4802. void MainComponent::closeUnfocusedWindows()
  4803. {
  4804. // FL's Ctrl+F12 (CloseAllUnfocusedWindowsAction, round 167o): every window but the focused one closes. LYNX's
  4805. // docked or detached panels and dialogs that wait for an answer stay, as for F12.
  4806. auto* focused = juce::TopLevelWindow::getActiveTopLevelWindow();
  4807. auto* main = getTopLevelComponent();
  4808. juce::Array<juce::Component::SafePointer<juce::DocumentWindow>> close;
  4809. for (int i = 0; i < juce::TopLevelWindow::getNumTopLevelWindows(); ++i)
  4810. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (i)))
  4811. if (w != focused && w != main && w->isVisible() && ! w->isCurrentlyModal() && ! (bool) w->getProperties()["lynxPanel"])
  4812. close.add (w);
  4813. for (auto& w : close)
  4814. if (w != nullptr)
  4815. w->closeButtonPressed();
  4816. }
  4817. void MainComponent::showSetupWizard()
  4818. {
  4819. // on top of the main window (round 140), so the DAW is visible behind it from the first start on
  4820. if (setupOverlay != nullptr)
  4821. return;
  4822. auto safe = juce::Component::SafePointer<MainComponent> (this);
  4823. setupOverlay = lynx::makeSetupWizardOverlay (
  4824. engine,
  4825. [safe] (const juce::String& language) {
  4826. if (safe != nullptr)
  4827. safe->showLanguageChoice (language);
  4828. },
  4829. [safe] {
  4830. juce::MessageManager::callAsync ([safe] { // the overlay's own button is still running
  4831. if (safe != nullptr)
  4832. safe->setupOverlay.reset();
  4833. });
  4834. });
  4835. addAndMakeVisible (*setupOverlay);
  4836. setupOverlay->setBounds (getLocalBounds());
  4837. setupOverlay->toFront (true);
  4838. }
  4839. void MainComponent::showImportReport()
  4840. {
  4841. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  4842. const auto& r = engine.getImportReport();
  4843. const auto& missing = engine.getMissingPlugins();
  4844. auto list = [] (const std::map<std::string, int>& items) {
  4845. std::vector<std::pair<int, std::string>> sorted;
  4846. for (const auto& [name, count] : items)
  4847. sorted.push_back ({ count, name });
  4848. std::sort (sorted.rbegin(), sorted.rend());
  4849. juce::StringArray lines;
  4850. for (const auto& [count, name] : sorted)
  4851. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  4852. return lines.joinIntoString ("\n");
  4853. };
  4854. juce::String text;
  4855. if (! r.approximated.empty())
  4856. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  4857. if (! r.unsupported.empty())
  4858. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  4859. if (const auto& matched = engine.getMatchedPlugins(); ! matched.isEmpty())
  4860. text << tr ("Plugins found on this PC:") << "\n " << matched.joinIntoString ("\n ") << "\n\n";
  4861. if (! missing.isEmpty())
  4862. text << tr ("Plugins not installed on this PC (or in a folder LYNX SHARE doesn't scan; Options > Setup wizard):") << "\n "
  4863. << missing.joinIntoString ("\n ") << "\n\n";
  4864. if (const auto& lost = engine.getPluginsWithoutState(); ! lost.isEmpty())
  4865. text << tr ("Plugins found but playing their default settings (the project saved them for the other format, VST2/VST3):") << "\n "
  4866. << lost.joinIntoString ("\n ") << "\n\n";
  4867. if (const auto failed = engine.getPluginHost().getLoadFailures(); ! failed.isEmpty())
  4868. text << tr ("Plugins installed but not loaded (silent):") << "\n " << failed.joinIntoString ("\n ") << "\n\n";
  4869. if (! r.droppedEffects.empty())
  4870. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  4871. if (! r.partialEffects.empty())
  4872. text << tr ("Effects kept but approximated or partly reproduced:") << "\n" << list (r.partialEffects) << "\n\n";
  4873. if (r.missingSamples > 0)
  4874. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  4875. if (r.relocatedSamples > 0)
  4876. text << tr ("Samples found in another folder than the project says (FL Studio's folders or next to the project): {0}",
  4877. { juce::String (r.relocatedSamples) }) << "\n";
  4878. if (text.isNotEmpty())
  4879. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"), text.trimEnd());
  4880. }
  4881. void MainComponent::showAudioSettings()
  4882. {
  4883. openSettings ((int) SettingsPage::audio);
  4884. }
  4885. // --- the Channel Rack's filter box ---------------------------------------------------------------
  4886. void MainComponent::FilterBox::paint (juce::Graphics& g)
  4887. {
  4888. using namespace theme;
  4889. auto area = getLocalBounds().toFloat();
  4890. g.setColour (hovered ? colour::bg3 : colour::bg1);
  4891. g.fillRoundedRectangle (area, radius::sm);
  4892. g.setColour (hovered ? colour::borderStrong : colour::border);
  4893. g.drawRoundedRectangle (area.reduced (0.5f), radius::sm, 1.0f);
  4894. g.setColour (colour::textPrimary);
  4895. g.setFont (font (type::small));
  4896. g.drawText (text, getLocalBounds().withTrimmedLeft (7).withTrimmedRight (16), juce::Justification::centredLeft, true);
  4897. icons::draw (g, Icon::chevronDown, area.removeFromRight (16.0f).reduced (3.0f).translated (-2.0f, 0.0f), colour::textSecondary);
  4898. }
  4899. // FL's Tools › Macros › Prepare for performance mode ([DECOMP] FUN_0122d010, its "Marker settings" dialog: marker count
  4900. // 4 / 8 / 16 / 32 / 64, default 16; spacing 1…128 steps, default 16 = a bar): room for a launch grid before the song,
  4901. // a marker per column, a Start marker, Performance mode on, the zone in view. FL warns it can't be undone; in LYNX it
  4902. // is one undo step.
  4903. void MainComponent::prepareForPerformance()
  4904. {
  4905. auto* window = new juce::AlertWindow (tr ("Prepare for performance mode"),
  4906. tr ("Inserts empty columns before the song for the clips to launch, a marker on each, and a Start "
  4907. "marker where the song begins; Performance mode is turned on."),
  4908. juce::MessageBoxIconType::NoIcon);
  4909. window->addComboBox ("count", { "4", "8", "16", "32", "64" }, tr ("Marker count"));
  4910. 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") },
  4911. tr ("Spacing"));
  4912. if (auto* c = window->getComboBoxComponent ("count"))
  4913. c->setSelectedItemIndex (2, juce::dontSendNotification);
  4914. if (auto* c = window->getComboBoxComponent ("spacing"))
  4915. c->setSelectedItemIndex (4, juce::dontSendNotification);
  4916. window->addButton (tr ("Accept"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  4917. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  4918. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  4919. if (result != 1)
  4920. return;
  4921. const auto count = 4 << juce::jlimit (0, 4, window->getComboBoxComponent ("count")->getSelectedItemIndex());
  4922. const auto steps = 1 << juce::jlimit (0, 7, window->getComboBoxComponent ("spacing")->getSelectedItemIndex());
  4923. engine.editSong ([count, steps] (Song& s) { perf::prepareForPerformance (s, count, (std::int64_t) steps * (ppq / 4)); });
  4924. showPanel (Panel::playlist);
  4925. playlist.runAction ("playlist.zoomPerformance");
  4926. }),
  4927. true);
  4928. keepAboveMainWindow (*window);
  4929. }
  4930. } // namespace lynx