MainComponent.cpp 227 KB

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