MainComponent.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  1. #include "ui/MainComponent.h"
  2. #include "ui/HistoryPanel.h"
  3. #include "ui/QuickAddPalette.h"
  4. #include "ui/ToolWindow.h"
  5. #include "ui/WindowOwner.h"
  6. #include "engine/PluginSandbox.h"
  7. #include "engine/Text.h"
  8. #include "core/RackOps.h"
  9. #include "core/Templates.h"
  10. #include "engine/MidiFileIo.h"
  11. #include "engine/ProjectFile.h"
  12. #include "ui/AutomationUi.h"
  13. #include "ui/ChannelSettings.h"
  14. #include "ui/Dialogs.h"
  15. #include "ui/EditorTools.h"
  16. #include "ui/ExportDialog.h"
  17. #include "ui/ParametricEqEditor.h"
  18. #include "ui/PluginWindow.h"
  19. #include "ui/I18n.h"
  20. #include "ui/Theme.h"
  21. #include "core/HintMarkup.h"
  22. #include "core/SongStats.h"
  23. namespace lynx
  24. {
  25. namespace
  26. {
  27. using workspace::Panel;
  28. constexpr Panel panelOrder[] = { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser };
  29. const char* panelAction (Panel p)
  30. {
  31. switch (p)
  32. {
  33. case Panel::playlist: return "panel.playlist";
  34. case Panel::channelRack: return "panel.channelRack";
  35. case Panel::pianoRoll: return "panel.pianoRoll";
  36. case Panel::mixer: return "panel.mixer";
  37. case Panel::browser: return "panel.browser";
  38. }
  39. return "";
  40. }
  41. // JUCE key event -> LYNX key map chord
  42. keys::Chord toChord (const juce::KeyPress& key)
  43. {
  44. keys::Chord c;
  45. const auto code = key.getKeyCode();
  46. const auto mods = key.getModifiers();
  47. c.mods = (std::uint8_t) ((mods.isCommandDown() ? keys::ctrl : 0) | (mods.isShiftDown() ? keys::shift : 0) | (mods.isAltDown() ? keys::alt : 0));
  48. struct Pair
  49. {
  50. int juceCode, key;
  51. };
  52. const Pair specials[] = {
  53. { juce::KeyPress::spaceKey, keys::space }, { juce::KeyPress::returnKey, keys::enter }, { juce::KeyPress::escapeKey, keys::escape },
  54. { juce::KeyPress::tabKey, keys::tab }, { juce::KeyPress::backspaceKey, keys::backspace }, { juce::KeyPress::deleteKey, keys::del },
  55. { juce::KeyPress::insertKey, keys::insert }, { juce::KeyPress::upKey, keys::up }, { juce::KeyPress::downKey, keys::down },
  56. { juce::KeyPress::leftKey, keys::left }, { juce::KeyPress::rightKey, keys::right }, { juce::KeyPress::pageUpKey, keys::pageUp },
  57. { juce::KeyPress::pageDownKey, keys::pageDown }, { juce::KeyPress::homeKey, keys::home }, { juce::KeyPress::endKey, keys::end },
  58. { juce::KeyPress::numberPadAdd, keys::numpadPlus }, { juce::KeyPress::numberPadSubtract, keys::numpadMinus },
  59. { juce::KeyPress::F1Key, keys::f1 }, { juce::KeyPress::F2Key, keys::f2 }, { juce::KeyPress::F3Key, keys::f3 },
  60. { juce::KeyPress::F4Key, keys::f4 }, { juce::KeyPress::F5Key, keys::f5 }, { juce::KeyPress::F6Key, keys::f6 },
  61. { juce::KeyPress::F7Key, keys::f7 }, { juce::KeyPress::F8Key, keys::f8 }, { juce::KeyPress::F9Key, keys::f9 },
  62. { juce::KeyPress::F10Key, keys::f10 }, { juce::KeyPress::F11Key, keys::f11 }, { juce::KeyPress::F12Key, keys::f12 },
  63. };
  64. for (const auto& p : specials)
  65. if (code == p.juceCode)
  66. {
  67. c.key = p.key;
  68. return c;
  69. }
  70. if (code > ' ' && code < 0x7f)
  71. c.key = (int) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) code);
  72. return c;
  73. }
  74. juce::String panelName (Panel p)
  75. {
  76. switch (p)
  77. {
  78. case Panel::playlist: return "Playlist";
  79. case Panel::channelRack: return "Channel Rack";
  80. case Panel::pianoRoll: return "Piano Roll";
  81. case Panel::mixer: return "Mixer";
  82. case Panel::browser: return "Browser";
  83. }
  84. return {};
  85. }
  86. } // namespace
  87. MainComponent::MainComponent (AudioEngine& e, bool restoreUserSettings)
  88. : persistent (restoreUserSettings),
  89. engine (e),
  90. rack (e),
  91. pianoRoll (e),
  92. playlist (e),
  93. mixer (e),
  94. browser (e)
  95. {
  96. browser.onOpenProject = [this] (const juce::File& file) { confirmDiscard ([this, file] { openFile (file); }); };
  97. browser.onLoadIntoChannel = [this] (const juce::File& file) { return rack.loadSampleIntoSelected (file); };
  98. if (persistent)
  99. {
  100. loadUiSettings();
  101. loadKeyMap();
  102. }
  103. newButton.setTooltip (tr ("New project") + " (Ctrl+N)");
  104. newButton.onClick = [this] { newProject(); };
  105. openButton.setTooltip (tr ("Open project") + " (Ctrl+O)");
  106. openButton.onClick = [this] { chooseFileToOpen(); };
  107. saveButton.setTooltip (tr ("Save project") + " (Ctrl+S)");
  108. saveButton.onClick = [this] { save (false); };
  109. exportButton.setTooltip (tr ("Export audio: WAV, FLAC or OGG") + " (Ctrl+R)");
  110. exportButton.onClick = [this] { exportAudio(); };
  111. auto withKey = [this] (const juce::String& text, const char* id) {
  112. const auto key = shortcutText (id).trim();
  113. return key.isEmpty() ? text : text + " (" + key + ")";
  114. };
  115. undoButton.setTooltip (withKey (tr ("Undo"), "edit.undo"));
  116. undoButton.onClick = [this] { engine.undo(); };
  117. undoButton.onRightClick = [this] { showHistory(); };
  118. redoButton.setTooltip (withKey (tr ("Redo"), "edit.redo"));
  119. redoButton.onClick = [this] { engine.redo(); };
  120. redoButton.onRightClick = [this] { showHistory(); };
  121. pluginPickerButton.setTooltip (withKey (tr ("Plugin picker: add an instrument or plugin as a new channel"), "panel.quickAdd"));
  122. pluginPickerButton.onClick = [this] { showQuickAdd(); };
  123. // transport: Play toggles play / stop-and-back; Stop returns to the start; double-click Stop = all notes off
  124. playButton.setTooltip (tr ("Play; pressed again, stops and goes back to where it started") + " (Space; Ctrl+Space pauses)");
  125. playButton.onClick = [this] { playStop(); };
  126. stopButton.setTooltip (tr ("Stop and return to the start (double-click: all notes off)"));
  127. stopButton.onClick = [this] { stopAndRewind(); };
  128. stopButton.onDoubleClick = [this] { engine.panic(); };
  129. recordButton.setOnColour (theme::colour::record);
  130. recordButton.setIconColour (theme::colour::record.withMultipliedSaturation (0.8f));
  131. recordButton.onClick = [this] { engine.setRecording (! engine.isRecording()); };
  132. recordMenuButton.setTooltip (tr ("Recording options: what to record"));
  133. recordMenuButton.onClick = [this] { showRecordMenu(); };
  134. recordButton.onRightClick = [this] { showRecordMenu(); };
  135. // Pattern / Song: a two-segment switch (L toggles); right-click shows the matching panel
  136. // as in FL, a two-line switch in front of the transport buttons: pattern on top, song below
  137. patternModeButton.setText (tr ("Pattern"));
  138. songModeButton.setText (tr ("Song"));
  139. for (auto* b : { &patternModeButton, &songModeButton })
  140. {
  141. b->setOnColour (theme::colour::bg6);
  142. b->setIconColourWhenOn (theme::colour::textPrimary);
  143. }
  144. patternModeButton.setTooltip (tr ("Pattern mode: plays the current pattern in a loop") + " (L)\n" + tr ("Right-click: show the Channel Rack"));
  145. songModeButton.setTooltip (tr ("Song mode: plays the Playlist arrangement") + " (L)\n" + tr ("Right-click: show the Playlist"));
  146. patternModeButton.onClick = [this] {
  147. if (engine.getSong().mode != PlayMode::pattern)
  148. toggleMode();
  149. };
  150. songModeButton.onClick = [this] {
  151. if (engine.getSong().mode != PlayMode::song)
  152. toggleMode();
  153. };
  154. patternModeButton.onRightClick = [this] { showPanel (Panel::channelRack); };
  155. songModeButton.onRightClick = [this] { showPanel (Panel::playlist); };
  156. metronomeButton.setClickingTogglesState (true);
  157. metronomeButton.setOnColour (theme::colour::bg6);
  158. metronomeButton.setIconColourWhenOn (theme::colour::accent);
  159. metronomeButton.setTooltip (tr ("Metronome"));
  160. metronomeButton.onClick = [this] { engine.getTransport().metronome.store (metronomeButton.getToggleState()); };
  161. typingPianoButton.setOnColour (theme::colour::bg6);
  162. typingPianoButton.setIconColourWhenOn (theme::colour::accent);
  163. typingPianoButton.onClick = [this] { setTypingPiano (! typingPiano); };
  164. // count-in and wait-for-input switches next to the metronome, as in FL's recording panel
  165. for (auto* b : { &countInButton, &waitInputButton })
  166. {
  167. b->setOnColour (theme::colour::bg6);
  168. b->setIconColourWhenOn (theme::colour::accent);
  169. }
  170. countInButton.onClick = [this] { runAction ("record.countIn"); };
  171. waitInputButton.onClick = [this] { runAction ("record.waitForInput"); };
  172. for (int i = 0; i < workspace::panelCount; ++i)
  173. {
  174. const auto panel = (Panel) i;
  175. auto& b = panelButtons[(std::size_t) i];
  176. b.setFlat (true);
  177. b.setOnColour (theme::colour::bg5);
  178. b.setIconColourWhenOn (theme::colour::textPrimary);
  179. b.setTooltip (panelName (panel) + " (" + keys::toString (keyMap.chordsFor (panelAction (panel)).empty() ? keys::Chord {}
  180. : keyMap.chordsFor (panelAction (panel)).front()) + ")\n"
  181. + tr ("Click: show, focus or hide. Right-click: show maximized"));
  182. b.onClick = [this, panel] { togglePanel (panel); };
  183. b.onRightClick = [this, panel] {
  184. showPanel (panel);
  185. if (! workspace.isMaximised (panel) && ! workspace.isDetached (panel))
  186. workspace.toggleMaximised (panel);
  187. refreshPanelButtons();
  188. };
  189. }
  190. patternBox.setTooltip (tr ("Current pattern (Numpad +/-: next/previous, F4: next empty, F2: rename)"));
  191. patternBox.setScrollWheelEnabled (true);
  192. gridBox.setScrollWheelEnabled (true);
  193. patternBox.onChange = [this]
  194. {
  195. const auto index = patternBox.getSelectedItemIndex();
  196. if (index >= 0 && index != engine.getSong().currentPattern)
  197. selectPattern (index);
  198. };
  199. newPatternButton.setTooltip (tr ("New pattern"));
  200. newPatternButton.onClick = [this]
  201. {
  202. engine.editSong ([] (Song& s) {
  203. Pattern p;
  204. p.name = newPatternName (s);
  205. s.patterns.push_back (std::move (p));
  206. s.currentPattern = (int) s.patterns.size() - 1;
  207. });
  208. };
  209. swingSlider.setRange (0.0, 1.0, 0.01);
  210. swingSlider.setDoubleClickReturnValue (true, 0.0);
  211. swingSlider.setValue (engine.getSong().swing, juce::dontSendNotification);
  212. swingSlider.textFromValueFunction = [] (double v) { return juce::String (juce::roundToInt (v * 100.0)) + "%"; };
  213. swingSlider.valueFromTextFunction = [] (const juce::String& t) { return t.retainCharacters ("0123456789.").getDoubleValue() / 100.0; };
  214. swingSlider.onValueChange = [this] { engine.editSong ([v = (float) swingSlider.getValue()] (Song& s) { s.swing = v; }); };
  215. swingSlider.setTooltip (tr ("Swing of the Channel Rack (all channels)"));
  216. swingSlider.setMouseClickGrabsKeyboardFocus (false);
  217. swingSlider.setWantsKeyboardFocus (false);
  218. patternMenuButton.setTooltip (tr ("Pattern: rename, color, clone, insert, split, length, delete"));
  219. patternMenuButton.onClick = [this] { showPatternMenu(); };
  220. // the workspace panels
  221. rack.onOpenPianoRoll = [this] { openPianoRoll(); };
  222. rackViewport.setViewedComponent (&rack, false);
  223. rackViewport.setScrollBarsShown (true, true);
  224. workspace.setContent (Panel::playlist, playlistArea, "Playlist", Icon::playlist);
  225. workspace.setContent (Panel::channelRack, rackViewport, "Channel Rack", Icon::channelRack);
  226. workspace.setContent (Panel::pianoRoll, pianoRoll, "Piano Roll", Icon::pianoRoll);
  227. workspace.setContent (Panel::mixer, mixer, "Mixer", Icon::mixer);
  228. workspace.setContent (Panel::browser, browser, "Browser", Icon::browser);
  229. workspace.setTitleTooltip (Panel::channelRack, tr ("Shift+wheel here changes the pattern"));
  230. workspace.setTitleAccessory (Panel::channelRack, &swingSlider, 26); // FL keeps the global swing in the rack's title bar
  231. workspace.onPanelMenu = [this] (Panel panel, juce::PopupMenu& menu) { addPanelMenuItems (panel, menu); };
  232. workspace.onFocusChanged = [this] (Panel) { refreshPanelButtons(); };
  233. workspace.onKeyInDetachedWindow = [this] (const juce::KeyPress& key) { return keyPressed (key); };
  234. workspace.onTitleWheel = [this] (Panel panel, const juce::MouseEvent& ev, const juce::MouseWheelDetails& wheel) {
  235. if (panel == Panel::channelRack && ev.mods.isShiftDown())
  236. selectPattern (stepPattern (engine.getSong(), (wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX) > 0.0f ? -1 : 1));
  237. };
  238. workspace.onTitleRightClick = [this] (Panel panel, const juce::MouseEvent&) {
  239. if (panel == Panel::channelRack)
  240. showPatternMenu();
  241. };
  242. workspace.onDefaultLayout = [this] { fitChannelRack (true); };
  243. workspace.setPersistent (persistent);
  244. playlist.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  245. playlist.onOpenPianoRoll = [this] {
  246. // edit a channel that plays in this pattern
  247. const auto& song = engine.getSong();
  248. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  249. const auto channel = engine.getSelectedChannel();
  250. if (! notes.empty() && std::none_of (notes.begin(), notes.end(), [channel] (const Note& n) { return n.channel == channel; }))
  251. engine.setSelectedChannel (notes.front().channel);
  252. openPianoRoll();
  253. };
  254. picker.onOpenPattern = [this] { showPanel (Panel::channelRack); };
  255. ui::setHint (pianoRoll, tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  256. ui::setHint (playlist, tr ("Playlist: [LMB] paint the current pattern [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"));
  257. // recent files (stored in %APPDATA%\LYNX)
  258. recent.setMaxNumberOfItems (12);
  259. recent.restoreFromString (PluginHost::settingsFolder().getChildFile ("recentes.txt").loadFileAsString());
  260. addAndMakeVisible (menuBar);
  261. for (auto* c : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  262. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  263. &tempoDisplay, &patternBox, &newPatternButton, &patternMenuButton, &pluginPickerButton, &timeDisplay,
  264. &songPosition, &masterVolume, &masterPitch, &perfMeter, &output, &hintBar, &workspace })
  265. {
  266. addAndMakeVisible (c);
  267. c->setMouseClickGrabsKeyboardFocus (false); // the PC keyboard stays with the main window
  268. }
  269. for (auto& b : panelButtons)
  270. {
  271. addAndMakeVisible (b);
  272. b.setMouseClickGrabsKeyboardFocus (false);
  273. b.setWantsKeyboardFocus (false);
  274. }
  275. for (auto* b : std::initializer_list<juce::Component*> { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &playButton, &stopButton,
  276. &recordButton, &recordMenuButton, &patternModeButton, &songModeButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton,
  277. &newPatternButton, &patternMenuButton, &pluginPickerButton })
  278. b->setWantsKeyboardFocus (false);
  279. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton, &recordMenuButton, &newPatternButton, &patternMenuButton,
  280. &pluginPickerButton, &metronomeButton, &typingPianoButton, &countInButton, &waitInputButton })
  281. b->setFlat (true);
  282. ui::installSliderContract();
  283. addAndMakeVisible (gridBox); // global grid (editors)
  284. engine.addChangeListener (this);
  285. setTypingPiano (typingPiano);
  286. refreshRecordOptionButtons();
  287. refreshToolbar();
  288. refreshPanelButtons();
  289. setControlHints();
  290. fittedChannelCount = (int) engine.getSong().channels.size();
  291. hintBar.setHint ({ idleHint(), {}, false, false });
  292. setWantsKeyboardFocus (true);
  293. setSize (1180, 642);
  294. startTimerHz (30);
  295. }
  296. MainComponent::~MainComponent()
  297. {
  298. saveUiSettings();
  299. workspace.saveState();
  300. ui::uninstallSliderContract();
  301. PluginWindows::closeAll(); // plugin UIs before the engine
  302. ParametricEqWindows::closeAll();
  303. closeAutomationEditors();
  304. closeChannelSettings();
  305. closeAllToolWindows(); // note tools, history, quick-add (they edit the song)
  306. engine.removeChangeListener (this);
  307. stopTimer();
  308. }
  309. void MainComponent::paint (juce::Graphics& g)
  310. {
  311. using namespace theme;
  312. g.fillAll (colour::bg1);
  313. // the toolbar: one band, its panels separated by hairlines
  314. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  315. g.setColour (colour::bg3);
  316. g.fillRect (bar);
  317. g.setColour (colour::border);
  318. g.fillRect (bar.withHeight (1).withY (bar.getBottom() - 1));
  319. for (auto x : dividers)
  320. g.fillRect (x, bar.getY() + 8, 1, bar.getHeight() - 16);
  321. // the hint bar sits in an inset well under the menu
  322. if (! hintBar.getBounds().isEmpty())
  323. {
  324. g.setColour (colour::bg1);
  325. g.fillRoundedRectangle (hintBar.getBounds().toFloat(), radius::md);
  326. }
  327. // the project name, beside the menus (FL's title/hint panel: the title above the hint bar)
  328. if (! titleArea.isEmpty())
  329. {
  330. const auto name = projectName.isNotEmpty() ? projectName : tr ("Untitled");
  331. g.setFont (font (type::small, true));
  332. g.setColour (colour::textSecondary);
  333. g.drawFittedText ((engine.isModified() ? juce::String ("* ") : juce::String()) + name, titleArea, juce::Justification::centredRight, 1, 0.8f);
  334. }
  335. // captions that name the snap and pattern selectors
  336. g.setFont (font (type::caption - 1.0f, true));
  337. g.setColour (colour::textDisabled);
  338. if (! snapLabelArea.isEmpty())
  339. g.drawText (tr ("SNAP"), snapLabelArea, juce::Justification::centredLeft, true);
  340. if (! patternLabelArea.isEmpty())
  341. g.drawText (tr ("PATTERN"), patternLabelArea, juce::Justification::centredLeft, true);
  342. }
  343. void MainComponent::resized()
  344. {
  345. dividers.clear();
  346. const auto bar = juce::Rectangle<int> (0, 0, getWidth(), toolbarHeight);
  347. auto toolbar = bar.reduced (8, 4);
  348. const auto row1 = toolbar.getY(), row2 = toolbar.getY() + rowHeight + 2, h = rowHeight;
  349. const auto big = toolbar.getHeight() - 8; // transport buttons: both rows
  350. const auto bigWidth = 44;
  351. constexpr int gap = 17; // a divider and the space around it
  352. // panel widths
  353. auto& lf = getLookAndFeel();
  354. int menuWidth = 0;
  355. for (const auto& name : getMenuBarNames())
  356. menuWidth += lf.getMenuBarItemWidth (menuBar, 0, name);
  357. const auto modeWidth = juce::jmax (patternModeButton.getIdealWidth (h - 2), songModeButton.getIdealWidth (h - 2));
  358. constexpr int tempoWidth = 94, timeWidth = 116, captionWidth = 58, gridWidth = 168;
  359. enum Section { transport, master, record, snap, shortcuts, meters, monitor, sectionCount };
  360. struct Info
  361. {
  362. int width, priority; // the lowest priority drops first when the window is narrow
  363. bool shown = true;
  364. };
  365. std::array<Info, sectionCount> sections { {
  366. { modeWidth + 8 + 3 * (bigWidth + 4) + 4 + tempoWidth + 6 + timeWidth, 100 },
  367. { 100, 80 },
  368. { 3 * h + 4, 60 },
  369. { captionWidth + gridWidth, 90 },
  370. { 6 * h, 70 },
  371. { 118, 55 },
  372. { 116, 50 },
  373. } };
  374. const auto room = toolbar.getWidth();
  375. const auto minHint = juce::jmax (menuWidth + 8, 300), maxHint = 620;
  376. auto used = [&sections] {
  377. int total = 0;
  378. for (const auto& s : sections)
  379. total += s.shown ? s.width + gap : 0;
  380. return total;
  381. };
  382. while (used() + minHint > room)
  383. {
  384. Info* lowest = nullptr;
  385. for (auto& s : sections)
  386. if (s.shown && s.priority < 100 && (lowest == nullptr || s.priority < lowest->priority))
  387. lowest = &s;
  388. if (lowest == nullptr)
  389. break;
  390. lowest->shown = false;
  391. }
  392. const auto hintWidth = juce::jlimit (juce::jmin (minHint, juce::jmax (160, room - used())), maxHint, room - used());
  393. const auto spare = juce::jmax (0, room - used() - hintWidth); // goes before the meters, which sit on the right
  394. auto take = [&toolbar] (int width) { return toolbar.removeFromLeft (juce::jmin (width, toolbar.getWidth())); };
  395. auto divide = [&] {
  396. take (8);
  397. dividers.push_back (toolbar.getX());
  398. take (9);
  399. };
  400. auto hide = [] (std::initializer_list<juce::Component*> components) {
  401. for (auto* c : components)
  402. {
  403. c->setVisible (false);
  404. c->setBounds ({});
  405. }
  406. };
  407. auto put = [] (juce::Component& c, juce::Rectangle<int> r) {
  408. c.setVisible (true);
  409. c.setBounds (r);
  410. };
  411. // 1. the menu (and the project name beside it) over the hint bar
  412. {
  413. auto column = take (hintWidth);
  414. const auto menu = column.withY (row1).withHeight (h).removeFromLeft (juce::jmin (menuWidth + 8, column.getWidth()));
  415. put (menuBar, menu);
  416. titleArea = column.withY (row1).withHeight (h).withTrimmedLeft (menu.getWidth() + 12).withTrimmedRight (4);
  417. if (titleArea.getWidth() < 60)
  418. titleArea = {};
  419. put (hintBar, column.withY (row2).withHeight (h).reduced (0, 1));
  420. }
  421. // 2. transport: Pattern/Song switch, play, stop, record, tempo, time display with the song position under it
  422. divide();
  423. {
  424. auto panel = take (sections[transport].width);
  425. auto mode = panel.removeFromLeft (modeWidth);
  426. put (patternModeButton, mode.withY (row1).withHeight (h).reduced (0, 1));
  427. put (songModeButton, mode.withY (row2).withHeight (h).reduced (0, 1));
  428. panel.removeFromLeft (8);
  429. const auto y = panel.getCentreY() - big / 2;
  430. for (auto* b : { &playButton, &stopButton, &recordButton })
  431. {
  432. put (*b, juce::Rectangle<int> (panel.getX(), y, bigWidth, big));
  433. panel.removeFromLeft (bigWidth + 4);
  434. }
  435. panel.removeFromLeft (4);
  436. const auto displays = panel.withY (y).withHeight (big);
  437. const auto displayHeight = big - 12;
  438. put (tempoDisplay, displays.withWidth (tempoWidth).withHeight (displayHeight));
  439. put (timeDisplay, displays.withTrimmedLeft (tempoWidth + 6).withWidth (timeWidth).withHeight (displayHeight));
  440. put (songPosition, displays.withTop (displays.getY() + displayHeight + 1).withWidth (tempoWidth + 6 + timeWidth));
  441. }
  442. // 3. master volume over master pitch
  443. if (sections[master].shown)
  444. {
  445. divide();
  446. auto panel = take (sections[master].width);
  447. put (masterVolume, panel.withY (row1).withHeight (h).reduced (0, 1));
  448. put (masterPitch, panel.withY (row2).withHeight (h).reduced (0, 1));
  449. }
  450. else
  451. hide ({ &masterVolume, &masterPitch });
  452. // 4. recording options: metronome, count-in and wait for input over "what to record" and typing piano
  453. if (sections[record].shown)
  454. {
  455. divide();
  456. auto panel = take (sections[record].width);
  457. put (metronomeButton, juce::Rectangle<int> (panel.getX(), row1, h, h));
  458. put (countInButton, juce::Rectangle<int> (panel.getX() + h + 2, row1, h, h));
  459. put (waitInputButton, juce::Rectangle<int> (panel.getX() + 2 * (h + 2), row1, h, h));
  460. put (recordMenuButton, juce::Rectangle<int> (panel.getX(), row2, h, h));
  461. put (typingPianoButton, juce::Rectangle<int> (panel.getX() + h + 2, row2, h, h));
  462. }
  463. else
  464. hide ({ &metronomeButton, &typingPianoButton, &recordMenuButton, &countInButton, &waitInputButton });
  465. // 5. global snap over the pattern selector, each with its name
  466. if (sections[snap].shown)
  467. {
  468. divide();
  469. auto panel = take (sections[snap].width);
  470. auto first = juce::Rectangle<int> (panel.getX(), row1, panel.getWidth(), h);
  471. snapLabelArea = first.removeFromLeft (captionWidth);
  472. put (gridBox, first.reduced (0, 1));
  473. auto second = juce::Rectangle<int> (panel.getX(), row2, panel.getWidth(), h);
  474. patternLabelArea = second.removeFromLeft (captionWidth);
  475. put (patternMenuButton, second.removeFromRight (h));
  476. put (newPatternButton, second.removeFromRight (h));
  477. second.removeFromRight (2);
  478. put (patternBox, second.reduced (0, 1));
  479. }
  480. else
  481. {
  482. snapLabelArea = patternLabelArea = {};
  483. hide ({ &gridBox, &patternBox, &newPatternButton, &patternMenuButton });
  484. }
  485. // 6. shortcuts: the windows over the file actions
  486. if (sections[shortcuts].shown)
  487. {
  488. divide();
  489. auto panel = take (sections[shortcuts].width);
  490. auto first = panel.withY (row1).withHeight (h);
  491. for (auto p : { Panel::playlist, Panel::channelRack, Panel::pianoRoll, Panel::mixer, Panel::browser })
  492. put (panelButtons[(std::size_t) p], first.removeFromLeft (h));
  493. put (pluginPickerButton, first.removeFromLeft (h));
  494. auto second = panel.withY (row2).withHeight (h);
  495. for (auto* b : { &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton })
  496. put (*b, second.removeFromLeft (h));
  497. }
  498. else
  499. {
  500. for (auto& b : panelButtons)
  501. hide ({ &b });
  502. hide ({ &pluginPickerButton, &newButton, &openButton, &saveButton, &exportButton, &undoButton, &redoButton });
  503. }
  504. // 7. on the right: CPU / memory / polyphony, then the output monitor
  505. take (spare);
  506. for (auto [section, component] : { std::pair<Section, juce::Component*> { meters, &perfMeter }, { monitor, &output } })
  507. {
  508. if (sections[section].shown)
  509. {
  510. divide();
  511. put (*component, take (sections[section].width).withY (row1).withHeight (2 * h + 2));
  512. }
  513. else
  514. hide ({ component });
  515. }
  516. workspace.setBounds (getLocalBounds().withTrimmedTop (toolbarHeight));
  517. }
  518. // --- keys --------------------------------------------------------------------------------------
  519. keys::Context MainComponent::focusContext() const
  520. {
  521. switch (workspace.getFocused())
  522. {
  523. case Panel::playlist: return keys::Context::playlist;
  524. case Panel::channelRack: return keys::Context::channelRack;
  525. case Panel::pianoRoll: return keys::Context::pianoRoll;
  526. case Panel::mixer: return keys::Context::mixer;
  527. case Panel::browser: return keys::Context::browser;
  528. }
  529. return keys::Context::global;
  530. }
  531. bool MainComponent::keyPressed (const juce::KeyPress& key)
  532. {
  533. const auto chord = toChord (key);
  534. // 1. the typing piano (its keys win over plain-letter shortcuts while it is on)
  535. if (keys::KeyMap::playsNote (chord, typingPiano))
  536. {
  537. const auto note = keys::typingPianoNote (chord.key);
  538. if (heldKeys.find (key.getKeyCode()) == heldKeys.end())
  539. {
  540. const auto channels = engine.getSelectedChannels();
  541. heldKeys[key.getKeyCode()] = channels;
  542. for (auto c : channels)
  543. engine.sendLiveNote (c, note, 0.8f, true, true);
  544. }
  545. return true;
  546. }
  547. // 2. the focused panel's own keys
  548. const auto focused = workspace.getFocused();
  549. const auto panelShown = workspace.isPanelVisible (focused);
  550. if (panelShown && focused == Panel::pianoRoll && pianoRoll.handleKey (key))
  551. return true;
  552. if (panelShown && focused == Panel::playlist && playlist.handleKey (key))
  553. return true;
  554. // 3. the key map
  555. const auto action = keyMap.find (chord, focusContext(), typingPiano);
  556. return ! action.empty() && runAction (action);
  557. }
  558. bool MainComponent::runAction (const std::string& id)
  559. {
  560. auto is = [&id] (const char* name) { return id == name; };
  561. if (is ("transport.playStop")) playStop();
  562. else if (is ("transport.pause")) playPause();
  563. else if (is ("transport.toggleMode")) toggleMode();
  564. else if (is ("view.typingPiano")) setTypingPiano (! typingPiano);
  565. else if (is ("panel.playlist")) togglePanel (Panel::playlist);
  566. else if (is ("panel.channelRack")) togglePanel (Panel::channelRack);
  567. else if (is ("panel.pianoRoll"))
  568. {
  569. togglePanel (Panel::pianoRoll);
  570. if (workspace.isPanelVisible (Panel::pianoRoll))
  571. pianoRoll.scrollToNotes();
  572. }
  573. else if (is ("panel.browser")) togglePanel (Panel::browser);
  574. else if (is ("panel.mixer")) togglePanel (Panel::mixer);
  575. else if (is ("panel.maximisePlaylist"))
  576. {
  577. workspace.toggleMaximised (Panel::playlist);
  578. refreshPanelButtons();
  579. }
  580. else if (is ("pattern.next")) selectPattern (stepPattern (engine.getSong(), 1));
  581. else if (is ("pattern.previous")) selectPattern (stepPattern (engine.getSong(), -1));
  582. else if (is ("pattern.nextEmpty")) nextEmptyPattern();
  583. else if (is ("pattern.rename")) showRenamePattern (engine.getSong().currentPattern);
  584. else if (is ("pattern.insert")) insertPatternHere();
  585. else if (is ("pattern.clone")) clonePatternNow();
  586. else if (is ("pattern.moveUp")) movePatternNow (-1);
  587. else if (is ("pattern.moveDown")) movePatternNow (1);
  588. else if (id.rfind ("pattern.select", 0) == 0) selectPattern (std::stoi (id.substr (14)) - 1);
  589. else if (is ("panel.quickAdd")) showQuickAdd();
  590. else if (is ("edit.history")) showHistory();
  591. else if (is ("browser.search"))
  592. {
  593. showPanel (Panel::browser);
  594. browser.focusSearch();
  595. }
  596. else if (is ("transport.record")) engine.setRecording (! engine.isRecording());
  597. else if (is ("transport.metronome"))
  598. {
  599. engine.getTransport().metronome.store (! engine.getTransport().metronome.load());
  600. refreshModeButton();
  601. }
  602. else if (is ("record.countIn"))
  603. {
  604. auto o = engine.getRecordOptions();
  605. o.countInBars = o.countInBars > 0 ? 0 : 1;
  606. engine.setRecordOptions (o);
  607. refreshRecordOptionButtons();
  608. }
  609. else if (is ("record.waitForInput"))
  610. {
  611. auto o = engine.getRecordOptions();
  612. o.waitForInput = ! o.waitForInput;
  613. engine.setRecordOptions (o);
  614. refreshRecordOptionButtons();
  615. }
  616. else if (is ("rack.graphEditor")) rack.toggleGraphLanes();
  617. else if (is ("rack.rotateLeft")) rack.rotateSelected (-1);
  618. else if (is ("rack.rotateRight")) rack.rotateSelected (1);
  619. else if (is ("browser.previous")) browser.step (-1, false);
  620. else if (is ("browser.next")) browser.step (1, false);
  621. else if (is ("browser.swapPrevious")) browser.step (-1, true);
  622. else if (is ("browser.swapNext")) browser.step (1, true);
  623. else if (is ("browser.load")) browser.loadSelected();
  624. else if (id.rfind ("pianoRoll.", 0) == 0) return pianoRoll.runAction (id);
  625. else if (id.rfind ("playlist.", 0) == 0) return playlist.runAction (id);
  626. else if (id.rfind ("mixer.", 0) == 0) return mixer.runAction (id);
  627. else if (is ("file.new")) newProject();
  628. else if (is ("file.open")) chooseFileToOpen();
  629. else if (is ("file.save")) save (false);
  630. else if (is ("file.saveAs")) save (true);
  631. else if (is ("file.export")) exportAudio();
  632. else if (is ("edit.undo")) engine.undo();
  633. else if (is ("edit.redo")) engine.redo();
  634. else if (is ("help.shortcuts")) showHelp();
  635. else if (is ("rack.selectPrevious")) rack.selectRelative (-1, false);
  636. else if (is ("rack.selectNext")) rack.selectRelative (1, false);
  637. else if (is ("rack.extendUp")) rack.selectRelative (-1, true);
  638. else if (is ("rack.extendDown")) rack.selectRelative (1, true);
  639. else if (is ("rack.moveUp")) rack.moveSelected (-1);
  640. else if (is ("rack.moveDown")) rack.moveSelected (1);
  641. else if (is ("rack.selectAll")) rack.selectAll();
  642. else if (is ("rack.clone")) rack.cloneSelected();
  643. else if (is ("rack.deleteSelected")) rack.deleteSelected();
  644. else if (is ("rack.sendToInserts")) rack.sendSelectedToInserts();
  645. else if (id.rfind ("rack.mute", 0) == 0) rack.toggleMute (std::stoi (id.substr (9)) - 1);
  646. else if (id.rfind ("rack.solo", 0) == 0) rack.solo (std::stoi (id.substr (9)) - 1);
  647. else
  648. return false;
  649. return true;
  650. }
  651. bool MainComponent::keyStateChanged (bool)
  652. {
  653. // JUCE has no per-key "keyReleased"; check which held keys were released.
  654. for (auto it = heldKeys.begin(); it != heldKeys.end();)
  655. {
  656. if (! juce::KeyPress::isKeyCurrentlyDown (it->first))
  657. {
  658. const auto note = keys::typingPianoNote ((int) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) it->first));
  659. for (auto c : it->second)
  660. engine.sendLiveNote (c, note, 0.0f, false, true);
  661. it = heldKeys.erase (it);
  662. }
  663. else
  664. ++it;
  665. }
  666. return false;
  667. }
  668. juce::String MainComponent::shortcutText (const char* actionId) const
  669. {
  670. const auto& chords = keyMap.chordsFor (actionId);
  671. return chords.empty() ? juce::String() : "\t" + juce::String (keys::toString (chords.front()));
  672. }
  673. void MainComponent::setTypingPiano (bool on)
  674. {
  675. typingPiano = on;
  676. EditorGlobals::get().typingPiano = on; // the editors' single-letter tool keys only work while it is off
  677. typingPianoButton.setToggleState (on, juce::dontSendNotification);
  678. typingPianoButton.setTooltip ((on ? tr ("Typing keyboard as a piano: on (Z..M and Q..P play the selected channels)")
  679. : tr ("Typing keyboard as a piano: off (letter and number keys are shortcuts)"))
  680. + juce::String (" (") + juce::String (keys::toString (keyMap.chordsFor ("view.typingPiano").empty() ? keys::Chord {}
  681. : keyMap.chordsFor ("view.typingPiano").front()))
  682. + ")");
  683. // release anything still sounding from the keyboard
  684. for (const auto& [code, channels] : heldKeys)
  685. for (auto c : channels)
  686. engine.sendLiveNote (c, keys::typingPianoNote ((int) juce::CharacterFunctions::toUpperCase ((juce::juce_wchar) code)), 0.0f, false);
  687. heldKeys.clear();
  688. }
  689. void MainComponent::loadKeyMap()
  690. {
  691. keyMap.resetToDefaults();
  692. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  693. if (file.existsAsFile())
  694. {
  695. std::vector<std::string> errors;
  696. if (! keyMap.loadJson (file.loadFileAsString().toStdString(), &errors))
  697. juce::Logger::writeToLog ("keys.json is not a JSON object; using the default keys");
  698. for (const auto& e : errors)
  699. juce::Logger::writeToLog ("keys.json: " + juce::String (e));
  700. }
  701. }
  702. void MainComponent::editKeyMap()
  703. {
  704. const auto file = PluginHost::settingsFolder().getChildFile ("keys.json");
  705. if (! file.existsAsFile())
  706. file.replaceWithText (juce::String (keys::KeyMap().toJson()));
  707. file.startAsProcess();
  708. }
  709. // --- UI options ----------------------------------------------------------------------------------
  710. juce::File MainComponent::uiSettingsFile() const
  711. {
  712. return PluginHost::settingsFolder().getChildFile ("ui-options.txt");
  713. }
  714. void MainComponent::loadUiSettings()
  715. {
  716. juce::StringArray lines;
  717. lines.addLines (uiSettingsFile().loadFileAsString());
  718. for (const auto& line : lines)
  719. {
  720. const auto key = line.upToFirstOccurrenceOf ("=", false, false).trim();
  721. const auto on = line.fromFirstOccurrenceOf ("=", false, false).trim() == "1";
  722. if (key == "typingPiano")
  723. typingPiano = on;
  724. else if (key == "keepEditorsOpen")
  725. ChannelRackComponent::keepEditorsOpen = on;
  726. else if (key == "editPatternsIn")
  727. PlaylistComponent::editPatternsIn = juce::jlimit (0, 2, line.fromFirstOccurrenceOf ("=", false, false).trim().getIntValue());
  728. }
  729. startup = StartupOptions::load();
  730. }
  731. void MainComponent::saveUiSettings()
  732. {
  733. if (! persistent)
  734. return;
  735. uiSettingsFile().replaceWithText ("typingPiano=" + juce::String (typingPiano ? 1 : 0) + "\nkeepEditorsOpen="
  736. + juce::String (ChannelRackComponent::keepEditorsOpen ? 1 : 0) + "\neditPatternsIn="
  737. + juce::String (PlaylistComponent::editPatternsIn) + "\nsplash=" + juce::String (startup.splash ? 1 : 0)
  738. + "\nstartupSound=" + juce::String (startup.sound ? 1 : 0) + "\n");
  739. }
  740. // --- transport -----------------------------------------------------------------------------------
  741. void MainComponent::playStop()
  742. {
  743. auto& transport = engine.getTransport();
  744. if (engine.isWaitingForInput() || engine.isCountingIn()) // pressed again: cancel
  745. {
  746. engine.stop();
  747. return;
  748. }
  749. if (transport.playing.load())
  750. {
  751. engine.stop();
  752. engine.seek (playStartTicks); // back to where playback started
  753. }
  754. else
  755. {
  756. playStartTicks = transport.positionTicks.load();
  757. engine.startPlayback();
  758. }
  759. }
  760. void MainComponent::playPause()
  761. {
  762. if (engine.getTransport().playing.load() || engine.isWaitingForInput() || engine.isCountingIn())
  763. engine.stop();
  764. else
  765. {
  766. playStartTicks = engine.getTransport().positionTicks.load();
  767. engine.startPlayback();
  768. }
  769. }
  770. void MainComponent::stopAndRewind()
  771. {
  772. engine.stop();
  773. engine.rewind();
  774. playStartTicks = 0.0;
  775. }
  776. void MainComponent::toggleMode()
  777. {
  778. engine.editSong ([] (Song& s) { s.mode = s.mode == PlayMode::song ? PlayMode::pattern : PlayMode::song; }, false);
  779. }
  780. // --- panels --------------------------------------------------------------------------------------
  781. void MainComponent::togglePanel (Panel panel)
  782. {
  783. workspace.toggle (panel);
  784. refreshPanelButtons();
  785. }
  786. void MainComponent::fitChannelRack (bool width)
  787. {
  788. rack.updateSize();
  789. const auto scrollbar = rackViewport.getScrollBarThickness();
  790. const auto maxWidth = juce::jmax (300, workspace.getWidth() - 2 * 16 - 260);
  791. const auto contentWidth = juce::jmin (rack.getWidth(), maxWidth);
  792. const auto needsHorizontal = rack.getWidth() > contentWidth;
  793. workspace.fitPanelContent (Panel::channelRack, width ? contentWidth + scrollbar : 0, rack.getHeight() + (needsHorizontal ? scrollbar : 0));
  794. fittedChannelCount = (int) engine.getSong().channels.size();
  795. }
  796. void MainComponent::showPanel (Panel panel)
  797. {
  798. workspace.show (panel);
  799. refreshPanelButtons();
  800. }
  801. void MainComponent::refreshPanelButtons()
  802. {
  803. for (int i = 0; i < workspace::panelCount; ++i)
  804. panelButtons[(std::size_t) i].setToggleState (workspace.isPanelVisible ((Panel) i), juce::dontSendNotification);
  805. }
  806. void MainComponent::openPianoRoll()
  807. {
  808. showPanel (Panel::pianoRoll);
  809. pianoRoll.scrollToNotes();
  810. }
  811. void MainComponent::saveLayoutAs()
  812. {
  813. auto* window = new juce::AlertWindow (tr ("Save layout as"), tr ("Name of the layout:"), juce::MessageBoxIconType::NoIcon);
  814. window->addTextEditor ("name", tr ("My layout"));
  815. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  816. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  817. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, window] (int result) {
  818. const auto name = window->getTextEditorContents ("name").trim();
  819. if (result == 1 && name.isNotEmpty())
  820. workspace.saveLayoutAs (name);
  821. }),
  822. true);
  823. keepAboveMainWindow (*window);
  824. }
  825. juce::PopupMenu MainComponent::layoutsMenu()
  826. {
  827. juce::PopupMenu menu;
  828. auto files = Workspace::layoutsFolder().findChildFiles (juce::File::findFiles, false, "*.txt");
  829. files.sort();
  830. for (const auto& file : files)
  831. menu.addItem (file.getFileNameWithoutExtension(), [this, file] {
  832. workspace.loadLayout (file);
  833. refreshPanelButtons();
  834. });
  835. if (files.isEmpty())
  836. menu.addItem (tr ("(none saved yet)"), false, false, [] {});
  837. menu.addSeparator();
  838. menu.addItem (tr ("Open layouts folder"), [] {
  839. Workspace::layoutsFolder().createDirectory();
  840. Workspace::layoutsFolder().startAsProcess();
  841. });
  842. return menu;
  843. }
  844. void MainComponent::selectTabForSnapshot (int tab)
  845. {
  846. const Panel panels[] = { Panel::channelRack, Panel::pianoRoll, Panel::playlist, Panel::mixer };
  847. const auto panel = panels[juce::jlimit (0, 3, tab)];
  848. if (panel == Panel::pianoRoll)
  849. {
  850. const auto& song = engine.getSong();
  851. std::vector<int> counts (song.channels.size(), 0);
  852. for (const auto& n : song.patterns[(std::size_t) song.currentPattern].notes)
  853. if (n.channel >= 0 && n.channel < (int) counts.size())
  854. ++counts[(std::size_t) n.channel];
  855. if (! counts.empty())
  856. engine.setSelectedChannel ((int) (std::max_element (counts.begin(), counts.end()) - counts.begin()));
  857. }
  858. // each view on its own: the panel maximized over the workspace
  859. workspace.resetLayout();
  860. workspace.show (panel);
  861. workspace.toggleMaximised (panel);
  862. refreshPanelButtons();
  863. if (panel == Panel::pianoRoll)
  864. pianoRoll.scrollToNotes();
  865. if (panel == Panel::playlist)
  866. playlist.resized(); // update the scrollbars for the loaded song
  867. if (panel == Panel::mixer)
  868. mixer.selectFirstTrackWithEffects();
  869. }
  870. void MainComponent::showDesktopForSnapshot (bool extraPanels)
  871. {
  872. workspace.resetLayout();
  873. if (extraPanels)
  874. {
  875. workspace.show (Panel::mixer);
  876. workspace.show (Panel::pianoRoll);
  877. pianoRoll.scrollToNotes();
  878. workspace.show (Panel::channelRack);
  879. }
  880. refreshPanelButtons();
  881. }
  882. // --- patterns ------------------------------------------------------------------------------------
  883. void MainComponent::selectPattern (int index)
  884. {
  885. if (index >= 0 && index < (int) engine.getSong().patterns.size() && index != engine.getSong().currentPattern)
  886. engine.editSong ([index] (Song& s) { s.currentPattern = index; }, false);
  887. }
  888. void MainComponent::nextEmptyPattern()
  889. {
  890. engine.editSong ([] (Song& s) { gotoNextEmptyPattern (s); });
  891. showRenamePattern (engine.getSong().currentPattern);
  892. }
  893. void MainComponent::insertPatternHere()
  894. {
  895. engine.editSong ([] (Song& s) { insertPattern (s, s.currentPattern, newPatternName (s)); });
  896. }
  897. // --- window menus ------------------------------------------------------------------------------
  898. // Each window's own items, at the top of the menu in its title bar (FL keeps an editor's options in the
  899. // small menu at the left of its title bar). Items run the key map's actions, so they show their keys.
  900. void MainComponent::addPanelMenuItems (Panel panel, juce::PopupMenu& menu)
  901. {
  902. auto action = [this] (juce::PopupMenu& m, const char* id, const juce::String& text, bool enabled = true, bool ticked = false) {
  903. m.addItem (text + shortcutText (id), enabled, ticked, [this, id] { runAction (id); });
  904. };
  905. auto zoomMenu = [&action] (const juce::String& prefix) {
  906. juce::PopupMenu zoom;
  907. const std::pair<const char*, const char*> items[] = {
  908. { "zoomIn", TR_NOOP ("Zoom in") }, { "zoomOut", TR_NOOP ("Zoom out") }, { "zoom1", TR_NOOP ("Zoom: one bar") },
  909. { "zoom2", TR_NOOP ("Zoom: four bars") }, { "zoom3", TR_NOOP ("Zoom: sixteen bars") },
  910. { "zoomAll", TR_NOOP ("Zoom to show everything") }, { "zoomSelection", TR_NOOP ("Zoom to the selection") },
  911. { "centrePlayhead", TR_NOOP ("Centre the view on the playhead") }
  912. };
  913. for (const auto& [id, text] : items)
  914. if (const auto* a = keys::findAction ((prefix + id).toStdString())) // the key map holds the id strings
  915. action (zoom, a->id, tr (text));
  916. return zoom;
  917. };
  918. switch (panel)
  919. {
  920. case Panel::channelRack:
  921. {
  922. menu.addSubMenu (tr ("Pattern"), makePatternMenu());
  923. menu.addSeparator();
  924. action (menu, "rack.graphEditor", tr ("Graph lanes (velocity, pan, pitch...)"), true, rack.areGraphLanesShown());
  925. action (menu, "rack.rotateLeft", tr ("Rotate the selected channels' steps left"));
  926. action (menu, "rack.rotateRight", tr ("Rotate the selected channels' steps right"));
  927. juce::PopupMenu sort;
  928. sort.addItem (tr ("By name"), [this] { rack.sortChannels (ChannelSort::name); });
  929. sort.addItem (tr ("By color"), [this] { rack.sortChannels (ChannelSort::colour); });
  930. sort.addItem (tr ("By mixer insert"), [this] { rack.sortChannels (ChannelSort::insert); });
  931. sort.addItem (tr ("By type"), [this] { rack.sortChannels (ChannelSort::type); });
  932. menu.addSubMenu (tr ("Sort channels"), sort);
  933. menu.addItem (tr ("Select unused channels"), [this] { rack.selectUnused(); });
  934. break;
  935. }
  936. case Panel::playlist:
  937. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  938. workspace.toggleMaximised (Panel::playlist);
  939. refreshPanelButtons();
  940. });
  941. menu.addSeparator();
  942. action (menu, "playlist.ripple", tr ("Ripple editing (resizing and deleting move the later clips)"), true, playlist.isRippleOn());
  943. action (menu, "playlist.rippleDelete", tr ("Delete the selected clips and close the gaps"));
  944. menu.addSubMenu (tr ("Zoom"), zoomMenu ("playlist."));
  945. break;
  946. case Panel::pianoRoll:
  947. {
  948. juce::PopupMenu tools;
  949. for (const auto* id : { "pianoRoll.arpeggiate", "pianoRoll.strum", "pianoRoll.flip", "pianoRoll.randomise",
  950. "pianoRoll.scaleLevels", "pianoRoll.limit" })
  951. if (const auto* a = keys::findAction (id))
  952. action (tools, a->id, tr (a->description));
  953. menu.addSubMenu (tr ("Tools"), tools);
  954. menu.addSubMenu (tr ("Zoom"), zoomMenu ("pianoRoll."));
  955. menu.addItem (tr ("Snap notes to the scale"), pianoRoll.hasScale(), pianoRoll.isScaleSnapOn(),
  956. [this] { pianoRoll.setScaleSnap (! pianoRoll.isScaleSnapOn()); });
  957. break;
  958. }
  959. case Panel::mixer:
  960. action (menu, "mixer.moveLeft", tr ("Move the selected inserts left"));
  961. action (menu, "mixer.moveRight", tr ("Move the selected inserts right"));
  962. menu.addSeparator();
  963. action (menu, "mixer.linkChannels", tr ("Link the selected channels to the selected insert"));
  964. action (menu, "mixer.linkChannelsFrom", tr ("Link the selected channels to inserts starting from the selected one"));
  965. action (menu, "mixer.selectLinkedChannels", tr ("Select the channels linked to the selected insert"));
  966. break;
  967. case Panel::browser:
  968. action (menu, "browser.search", tr ("Search the Browser"));
  969. menu.addItem (tr ("Add folder..."), [this] { browser.addUserFolder(); });
  970. break;
  971. default:
  972. break;
  973. }
  974. }
  975. // --- quick-add palette and history -------------------------------------------------------------
  976. void MainComponent::showQuickAdd()
  977. {
  978. QuickAddTargets targets;
  979. targets.effectsFirst = workspace.getFocused() == Panel::mixer;
  980. targets.addInstrument = [this] (ChannelDef c) {
  981. rack.addChannel (std::move (c), true);
  982. showPanel (Panel::channelRack);
  983. };
  984. targets.addEffect = [this] (EffectSlot slot) {
  985. if (! mixer.addEffectToSelected (std::move (slot)))
  986. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Quick-add palette"),
  987. tr ("The selected insert has no free effect slot."));
  988. else
  989. showPanel (Panel::mixer);
  990. };
  991. openToolWindow (makeQuickAddPalette (engine, std::move (targets)), tr ("Quick-add palette"), "quickadd");
  992. }
  993. std::unique_ptr<juce::Component> MainComponent::makeQuickAddForSnapshot()
  994. {
  995. QuickAddTargets targets;
  996. targets.addInstrument = [] (ChannelDef) {};
  997. targets.addEffect = [] (EffectSlot) {};
  998. return makeQuickAddPalette (engine, std::move (targets));
  999. }
  1000. void MainComponent::showHistory()
  1001. {
  1002. if (auto* open = findToolWindow ("history"))
  1003. {
  1004. open->toFront (true);
  1005. return;
  1006. }
  1007. openToolWindow (makeHistoryPanel (engine), tr ("Undo history"), "history");
  1008. }
  1009. // --- recording options ---------------------------------------------------------------------------
  1010. void MainComponent::updateRecordQuantise()
  1011. {
  1012. // the global grid sets the record quantise; "none" and the zoom-dependent grids record as played
  1013. std::int64_t ticks = 0;
  1014. if (recordQuantiseOn)
  1015. {
  1016. const auto& option = grid::options()[(std::size_t) juce::jlimit (0, (int) grid::options().size() - 1, EditorGlobals::get().getGridOption())];
  1017. if (option.kind == grid::Kind::ticks)
  1018. ticks = option.ticks;
  1019. else if (option.kind == grid::Kind::bar)
  1020. ticks = (std::int64_t) ppq * juce::jmax (1, engine.getSong().beatsPerBar);
  1021. }
  1022. if (engine.getRecordOptions().quantise != ticks)
  1023. {
  1024. auto o = engine.getRecordOptions();
  1025. o.quantise = ticks;
  1026. engine.setRecordOptions (o);
  1027. }
  1028. }
  1029. void MainComponent::addRecordOptions (juce::PopupMenu& menu)
  1030. {
  1031. const auto o = engine.getRecordOptions();
  1032. auto set = [this] (std::function<void (AudioEngine::RecordOptions&)> change) {
  1033. auto options = engine.getRecordOptions();
  1034. change (options);
  1035. engine.setRecordOptions (options);
  1036. refreshRecordOptionButtons();
  1037. };
  1038. juce::PopupMenu countIn;
  1039. countIn.addItem (tr ("Off"), true, o.countInBars == 0, [set] { set ([] (AudioEngine::RecordOptions& r) { r.countInBars = 0; }); });
  1040. for (int bars : { 1, 2, 4 })
  1041. countIn.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, o.countInBars == bars,
  1042. [set, bars] { set ([bars] (AudioEngine::RecordOptions& r) { r.countInBars = bars; }); });
  1043. menu.addSubMenu (tr ("Count-in") + shortcutText ("record.countIn"), countIn);
  1044. menu.addItem (tr ("Wait for the first note to start") + shortcutText ("record.waitForInput"), true, o.waitForInput,
  1045. [set] { set ([] (AudioEngine::RecordOptions& r) { r.waitForInput = ! r.waitForInput; }); });
  1046. menu.addSeparator();
  1047. menu.addItem (tr ("Overdub: add to the pattern"), true, o.mode == RecordMode::overdub,
  1048. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::overdub; }); });
  1049. menu.addItem (tr ("Replace: a recorded channel's old notes are cleared"), true, o.mode == RecordMode::replace,
  1050. [set] { set ([] (AudioEngine::RecordOptions& r) { r.mode = RecordMode::replace; }); });
  1051. menu.addSeparator();
  1052. menu.addItem (tr ("Quantise recorded notes to the global grid"), true, recordQuantiseOn, [this] {
  1053. recordQuantiseOn = ! recordQuantiseOn;
  1054. updateRecordQuantise();
  1055. });
  1056. menu.addItem (tr ("Song mode: place a pattern clip where recording starts"), true, o.placeSongClip,
  1057. [set] { set ([] (AudioEngine::RecordOptions& r) { r.placeSongClip = ! r.placeSongClip; }); });
  1058. }
  1059. void MainComponent::showRecordMenu()
  1060. {
  1061. juce::PopupMenu menu;
  1062. menu.addItem (tr ("Notes (MIDI and PC keyboard) into the current pattern"), false, true, [] {});
  1063. menu.addItem (tr ("Audio from the sound card input (becomes a Playlist clip)"), true, engine.isAudioRecordingArmed(), [this] {
  1064. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  1065. if (engine.getLastRecordingError().isNotEmpty())
  1066. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Audio input"), engine.getLastRecordingError());
  1067. });
  1068. menu.addSeparator();
  1069. menu.addItem (tr ("Open recordings folder"), [] {
  1070. juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings").createDirectory();
  1071. juce::File::getSpecialLocation (juce::File::userMusicDirectory).getChildFile ("LYNX/Recordings").startAsProcess();
  1072. });
  1073. menu.addSeparator();
  1074. addRecordOptions (menu);
  1075. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (recordMenuButton.isVisible() ? (juce::Component*) &recordMenuButton
  1076. : (juce::Component*) &recordButton));
  1077. }
  1078. void MainComponent::refreshRecordOptionButtons()
  1079. {
  1080. auto withKey = [this] (const juce::String& text, const char* id) {
  1081. const auto key = shortcutText (id).trim();
  1082. return key.isEmpty() ? text : text + " (" + key + ")";
  1083. };
  1084. const auto o = engine.getRecordOptions();
  1085. countInButton.setToggleState (o.countInBars > 0, juce::dontSendNotification);
  1086. countInButton.setTooltip (withKey (o.countInBars > 0 ? tr ("Count-in before recording: {0} bar(s)", { juce::String (o.countInBars) })
  1087. : tr ("Count-in before recording: off"),
  1088. "record.countIn"));
  1089. waitInputButton.setToggleState (o.waitForInput, juce::dontSendNotification);
  1090. waitInputButton.setTooltip (withKey (o.waitForInput ? tr ("Recording waits for the first note: on") : tr ("Recording waits for the first note: off"),
  1091. "record.waitForInput"));
  1092. }
  1093. void MainComponent::clonePatternNow()
  1094. {
  1095. engine.editSong ([] (Song& s) { clonePattern (s, s.currentPattern); });
  1096. }
  1097. void MainComponent::movePatternNow (int delta)
  1098. {
  1099. engine.editSong ([delta] (Song& s) { movePattern (s, s.currentPattern, delta); });
  1100. }
  1101. void MainComponent::splitPatternByChannelNow()
  1102. {
  1103. int created = 0;
  1104. engine.editSong ([&created] (Song& s) { created = splitPatternByChannel (s, s.currentPattern); });
  1105. if (created == 0)
  1106. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Split by channel"), tr ("This pattern has no notes."));
  1107. }
  1108. void MainComponent::showRenamePattern (int index)
  1109. {
  1110. if (index < 0 || index >= (int) engine.getSong().patterns.size())
  1111. return;
  1112. const auto& p = engine.getSong().patterns[(std::size_t) index];
  1113. showNameAndColourDialog (tr ("Rename pattern"), juce::String::fromUTF8 (p.name.c_str()), p.colour,
  1114. [this, index] (const juce::String& name, std::uint32_t colour) {
  1115. if (index < (int) engine.getSong().patterns.size())
  1116. engine.editSong ([index, n = name.toStdString(), colour] (Song& s) {
  1117. s.patterns[(std::size_t) index].name = n;
  1118. s.patterns[(std::size_t) index].colour = colour;
  1119. });
  1120. });
  1121. }
  1122. void MainComponent::refreshToolbar()
  1123. {
  1124. const auto& song = engine.getSong();
  1125. patternBox.clear (juce::dontSendNotification);
  1126. for (std::size_t i = 0; i < song.patterns.size(); ++i)
  1127. patternBox.addItem (juce::String::fromUTF8 (song.patterns[i].name.c_str()), (int) i + 1);
  1128. patternBox.setSelectedItemIndex (song.currentPattern, juce::dontSendNotification);
  1129. swingSlider.setValue (song.swing, juce::dontSendNotification);
  1130. tempoDisplay.repaint();
  1131. refreshModeButton();
  1132. if (! song.patterns.empty())
  1133. workspace.setTitle (Panel::channelRack, "Channel Rack - " + juce::String::fromUTF8 (song.patterns[(std::size_t) song.currentPattern].name.c_str()));
  1134. }
  1135. juce::PopupMenu MainComponent::makePatternMenu()
  1136. {
  1137. const auto& song = engine.getSong();
  1138. const auto index = song.currentPattern;
  1139. const auto& pattern = song.patterns[(std::size_t) index];
  1140. juce::PopupMenu colours;
  1141. colours.addItem (tr ("Automatic"), true, pattern.colour == 0,
  1142. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].colour = 0; }); });
  1143. colours.addSeparator();
  1144. for (auto c : lynxPalette())
  1145. {
  1146. juce::Image swatch (juce::Image::ARGB, 16, 16, true);
  1147. juce::Graphics (swatch).fillAll (juce::Colour (c));
  1148. juce::PopupMenu::Item item;
  1149. item.text = "#" + juce::String::toHexString ((juce::int64) (c & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase();
  1150. item.image = std::make_unique<juce::DrawableImage> (swatch);
  1151. item.isTicked = pattern.colour == c;
  1152. item.action = [this, index, c] { engine.editSong ([index, c] (Song& s) { s.patterns[(std::size_t) index].colour = c; }); };
  1153. colours.addItem (std::move (item));
  1154. }
  1155. juce::PopupMenu lengths;
  1156. lengths.addItem (tr ("Automatic (from notes)"), true, pattern.lengthTicks == 0,
  1157. [this, index] { engine.editSong ([index] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = 0; }); });
  1158. for (int bars : { 1, 2, 4, 8, 16, 32 })
  1159. {
  1160. const auto ticks = (std::int64_t) bars * ppq * juce::jmax (1, song.beatsPerBar);
  1161. lengths.addItem (bars == 1 ? tr ("1 bar") : tr ("{0} bars", { juce::String (bars) }), true, pattern.lengthTicks == ticks,
  1162. [this, index, ticks] { engine.editSong ([index, ticks] (Song& s) { s.patterns[(std::size_t) index].lengthTicks = ticks; }); });
  1163. }
  1164. juce::PopupMenu menu;
  1165. menu.addSectionHeader (juce::String::fromUTF8 (pattern.name.c_str()));
  1166. menu.addItem (tr ("Next pattern") + shortcutText ("pattern.next"), index + 1 < (int) song.patterns.size(), false,
  1167. [this] { selectPattern (stepPattern (engine.getSong(), 1)); });
  1168. menu.addItem (tr ("Previous pattern") + shortcutText ("pattern.previous"), index > 0, false,
  1169. [this] { selectPattern (stepPattern (engine.getSong(), -1)); });
  1170. menu.addItem (tr ("Next empty pattern (and name it)") + shortcutText ("pattern.nextEmpty"), [this] { nextEmptyPattern(); });
  1171. menu.addSeparator();
  1172. menu.addItem (tr ("Rename and color...") + shortcutText ("pattern.rename"), [this, index] { showRenamePattern (index); });
  1173. menu.addSubMenu (tr ("Color"), colours);
  1174. menu.addSubMenu (tr ("Length"), lengths);
  1175. menu.addItem (tr ("Insert an empty pattern before this one") + shortcutText ("pattern.insert"), [this] { insertPatternHere(); });
  1176. menu.addItem (tr ("Clone") + shortcutText ("pattern.clone"), [this] { clonePatternNow(); });
  1177. menu.addItem (tr ("Move up") + shortcutText ("pattern.moveUp"), index > 0, false, [this] { movePatternNow (-1); });
  1178. menu.addItem (tr ("Move down") + shortcutText ("pattern.moveDown"), index + 1 < (int) song.patterns.size(), false, [this] { movePatternNow (1); });
  1179. menu.addItem (tr ("Split by channel (one new pattern per channel)"), ! pattern.notes.empty(), false, [this] { splitPatternByChannelNow(); });
  1180. juce::PopupMenu signatures;
  1181. for (int beats : { 2, 3, 4, 5, 6, 7, 8, 9, 12 })
  1182. signatures.addItem (juce::String (beats) + "/4", true, song.beatsPerBar == beats,
  1183. [this, beats] { engine.editSong ([beats] (Song& s) { s.beatsPerBar = beats; }); });
  1184. menu.addSubMenu (tr ("Song time signature"), signatures);
  1185. menu.addSeparator();
  1186. menu.addItem (tr ("Delete pattern"), song.patterns.size() > 1, false,
  1187. [this, index] { engine.editSong ([index] (Song& s) { s.removePattern (index); }); });
  1188. return menu;
  1189. }
  1190. void MainComponent::showPatternMenu()
  1191. {
  1192. makePatternMenu().showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patternMenuButton));
  1193. }
  1194. void MainComponent::refreshModeButton()
  1195. {
  1196. const auto recording = engine.isRecording();
  1197. recordButton.setToggleState (recording, juce::dontSendNotification);
  1198. const auto inputs = engine.getActiveMidiInputs();
  1199. recordButton.setTooltip ((engine.isAudioRecordingArmed() ? tr ("Record while playing: notes (PC keyboard and MIDI) and input audio")
  1200. : tr ("Record while playing: notes (PC keyboard and MIDI)"))
  1201. + "\n" + tr ("MIDI inputs: {0}", { inputs.isEmpty() ? tr ("none") : inputs.joinIntoString (", ") }));
  1202. recordMenuButton.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  1203. recordMenuButton.setOnColour (theme::colour::accentMuted);
  1204. const auto songMode = engine.getSong().mode == PlayMode::song;
  1205. patternModeButton.setToggleState (! songMode, juce::dontSendNotification);
  1206. songModeButton.setToggleState (songMode, juce::dontSendNotification);
  1207. metronomeButton.setToggleState (engine.getTransport().metronome.load(), juce::dontSendNotification);
  1208. }
  1209. void MainComponent::changeListenerCallback (juce::ChangeBroadcaster*)
  1210. {
  1211. const auto& song = engine.getSong();
  1212. bool namesChanged = patternBox.getNumItems() != (int) song.patterns.size();
  1213. for (int i = 0; ! namesChanged && i < patternBox.getNumItems(); ++i)
  1214. namesChanged = patternBox.getItemText (i) != juce::String::fromUTF8 (song.patterns[(std::size_t) i].name.c_str());
  1215. refreshModeButton();
  1216. tempoDisplay.repaint();
  1217. if ((int) song.channels.size() != fittedChannelCount && fittedChannelCount >= 0) // a row was added or removed
  1218. fitChannelRack (false);
  1219. if (namesChanged || patternBox.getSelectedItemIndex() != song.currentPattern || std::abs (swingSlider.getValue() - song.swing) > 1e-6)
  1220. refreshToolbar();
  1221. }
  1222. // --- tempo display -------------------------------------------------------------------------------
  1223. ui::ValueSpec MainComponent::TempoDisplay::spec() const
  1224. {
  1225. ui::ValueSpec s;
  1226. s.name = tr ("Tempo");
  1227. s.minimum = minTempo;
  1228. s.maximum = maxTempo;
  1229. s.defaultValue = 130.0;
  1230. s.toText = [] (double v) { return juce::String (v, 3) + " BPM"; };
  1231. s.target = AutomationTarget { AutomationTargetKind::tempo, 0 };
  1232. return s;
  1233. }
  1234. void MainComponent::TempoDisplay::setBpm (double bpm)
  1235. {
  1236. bpm = controls::clampTempo (bpm);
  1237. if (std::abs (bpm - engine.getSong().bpm) > 1e-9)
  1238. engine.editSong ([bpm] (Song& s) { s.bpm = bpm; });
  1239. repaint();
  1240. }
  1241. bool MainComponent::TempoDisplay::isOnDecimals (int x) const
  1242. {
  1243. return decimalX > 0 && x > decimalX;
  1244. }
  1245. void MainComponent::TempoDisplay::paint (juce::Graphics& g)
  1246. {
  1247. using namespace theme;
  1248. const auto area = getLocalBounds().toFloat();
  1249. g.setColour (colour::bg0);
  1250. g.fillRoundedRectangle (area, radius::md);
  1251. if (dragging)
  1252. {
  1253. g.setColour (colour::accent.withAlpha (0.6f));
  1254. g.drawRoundedRectangle (area.reduced (0.5f), radius::md, 1.0f);
  1255. }
  1256. const auto bpm = engine.getSong().bpm;
  1257. const auto whole = juce::String ((int) std::floor (bpm + 1e-9));
  1258. const auto fraction = juce::String (bpm - std::floor (bpm + 1e-9), 3).fromFirstOccurrenceOf (".", false, false).paddedRight ('0', 3).substring (0, 3);
  1259. const juce::Font big (monoFont (22.0f)), small (monoFont (13.0f)), caption (font (type::caption, true));
  1260. const auto wholeWidth = juce::GlyphArrangement::getStringWidth (big, whole);
  1261. const auto fracWidth = juce::GlyphArrangement::getStringWidth (small, "." + fraction);
  1262. const auto unitWidth = juce::GlyphArrangement::getStringWidth (caption, "BPM");
  1263. auto x = area.getCentreX() - (wholeWidth + fracWidth + 6.0f + unitWidth) / 2.0f;
  1264. const auto baseline = area.getCentreY() + 6.0f;
  1265. g.setColour (colour::textPrimary);
  1266. g.setFont (big);
  1267. g.drawSingleLineText (whole, juce::roundToInt (x), juce::roundToInt (baseline));
  1268. x += wholeWidth;
  1269. decimalX = juce::roundToInt (x);
  1270. g.setColour (dragOnDecimals && dragging ? colour::textPrimary : colour::textSecondary);
  1271. g.setFont (small);
  1272. g.drawSingleLineText ("." + fraction, juce::roundToInt (x), juce::roundToInt (baseline));
  1273. x += fracWidth + 6.0f;
  1274. g.setColour (colour::textDisabled);
  1275. g.setFont (caption);
  1276. g.drawSingleLineText ("BPM", juce::roundToInt (x), juce::roundToInt (baseline));
  1277. }
  1278. void MainComponent::TempoDisplay::mouseDown (const juce::MouseEvent& e)
  1279. {
  1280. if (e.mods.isPopupMenu())
  1281. {
  1282. showMenu();
  1283. return;
  1284. }
  1285. if (ui::isResetClick (e))
  1286. {
  1287. setBpm (spec().defaultValue);
  1288. return;
  1289. }
  1290. startBpm = engine.getSong().bpm;
  1291. dragOnDecimals = isOnDecimals (e.x);
  1292. dragging = true;
  1293. repaint();
  1294. }
  1295. void MainComponent::TempoDisplay::mouseDrag (const juce::MouseEvent& e)
  1296. {
  1297. if (dragging)
  1298. setBpm (controls::tempoDrag (startBpm, -e.getDistanceFromDragStartY(), dragOnDecimals, e.mods.isCtrlDown()));
  1299. }
  1300. void MainComponent::TempoDisplay::mouseUp (const juce::MouseEvent&)
  1301. {
  1302. dragging = false;
  1303. repaint();
  1304. }
  1305. void MainComponent::TempoDisplay::mouseDoubleClick (const juce::MouseEvent& e)
  1306. {
  1307. if (! e.mods.isPopupMenu())
  1308. ui::typeValue (*this, spec(), engine.getSong().bpm, [this] (double v) { setBpm (v); });
  1309. }
  1310. void MainComponent::TempoDisplay::mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& wheel)
  1311. {
  1312. const auto delta = wheel.deltaY != 0.0f ? wheel.deltaY : -wheel.deltaX;
  1313. if (delta == 0.0f)
  1314. return;
  1315. const auto step = isOnDecimals (e.x) ? 0.01 : 1.0;
  1316. setBpm (engine.getSong().bpm + (delta > 0.0f ? 1.0 : -1.0) * step * (e.mods.isCtrlDown() ? 0.1 : 1.0));
  1317. }
  1318. ui::Hint MainComponent::TempoDisplay::hintAt (juce::Point<int> p)
  1319. {
  1320. return ui::valueHint (spec(), engine.getSong().bpm,
  1321. isOnDecimals (p.x) ? tr ("[LMB] drag the decimals for fine changes [Wheel] 0.01 [2xLMB] type [RMB] tap tempo, half, double")
  1322. : tr ("[LMB] drag the whole number [Ctrl] fine [Wheel] 1 BPM [2xLMB] type [RMB] tap tempo, half, double"));
  1323. }
  1324. void MainComponent::TempoDisplay::showMenu()
  1325. {
  1326. const auto bpm = engine.getSong().bpm;
  1327. juce::PopupMenu menu;
  1328. menu.addSectionHeader (tr ("Tempo") + ": " + juce::String (bpm, 3) + " BPM");
  1329. menu.addItem (tr ("Type value..."), [this, bpm] { ui::typeValue (*this, spec(), bpm, [this] (double v) { setBpm (v); }); });
  1330. menu.addItem (tr ("Tap tempo..."), [this] { showTap(); });
  1331. menu.addItem (tr ("Half ({0} BPM)", { juce::String (controls::halfTempo (bpm), 2) }), [this, bpm] { setBpm (controls::halfTempo (bpm)); });
  1332. menu.addItem (tr ("Double ({0} BPM)", { juce::String (controls::doubleTempo (bpm), 2) }), [this, bpm] { setBpm (controls::doubleTempo (bpm)); });
  1333. menu.addItem (tr ("Reset ({0})", { "130 BPM" }), [this] { setBpm (130.0); });
  1334. menu.addSeparator();
  1335. addAutomationItem (menu, engine, { AutomationTargetKind::tempo, 0 });
  1336. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  1337. }
  1338. void MainComponent::TempoDisplay::showTap()
  1339. {
  1340. // a callout with a big Tap pad: the tempo follows from the second tap on
  1341. struct TapPad final : juce::Component
  1342. {
  1343. explicit TapPad (TempoDisplay& d) : display (d)
  1344. {
  1345. setSize (220, 120);
  1346. setWantsKeyboardFocus (true);
  1347. }
  1348. void paint (juce::Graphics& g) override
  1349. {
  1350. using namespace theme;
  1351. auto r = getLocalBounds().reduced (10);
  1352. const auto pad = r.removeFromTop (70).toFloat();
  1353. g.setColour (flash > 0 ? colour::accent : colour::bg4);
  1354. g.fillRoundedRectangle (pad, radius::lg);
  1355. icons::draw (g, Icon::tap, pad.withSizeKeepingCentre (26.0f, 26.0f).translated (-34.0f, 0.0f), colour::textPrimary);
  1356. g.setColour (colour::textPrimary);
  1357. g.setFont (font (type::title, true));
  1358. g.drawText (tr ("Tap"), pad.withTrimmedLeft (40.0f), juce::Justification::centred);
  1359. g.setColour (colour::textSecondary);
  1360. g.setFont (font (type::small));
  1361. g.drawFittedText (taps.count() < 2 ? tr ("Click (or press T) on each beat")
  1362. : tr ("{0} taps: {1} BPM", { juce::String (taps.count()), juce::String (lastBpm, 2) }),
  1363. r, juce::Justification::centred, 2);
  1364. }
  1365. void tap()
  1366. {
  1367. if (const auto bpm = taps.tap (juce::Time::getMillisecondCounterHiRes()))
  1368. {
  1369. lastBpm = *bpm;
  1370. display.setBpm (*bpm);
  1371. }
  1372. flash = 1;
  1373. repaint();
  1374. juce::Timer::callAfterDelay (90, [safe = juce::Component::SafePointer<TapPad> (this)] {
  1375. if (safe != nullptr)
  1376. {
  1377. safe->flash = 0;
  1378. safe->repaint();
  1379. }
  1380. });
  1381. }
  1382. void mouseDown (const juce::MouseEvent&) override { tap(); }
  1383. bool keyPressed (const juce::KeyPress& key) override
  1384. {
  1385. if (key.getKeyCode() == 'T' || key.getKeyCode() == 't' || key == juce::KeyPress::spaceKey)
  1386. {
  1387. tap();
  1388. return true;
  1389. }
  1390. return false;
  1391. }
  1392. TempoDisplay& display;
  1393. controls::TapTempo taps;
  1394. double lastBpm = 0.0;
  1395. int flash = 0;
  1396. };
  1397. auto pad = std::make_unique<TapPad> (*this);
  1398. auto* raw = pad.get();
  1399. juce::CallOutBox::launchAsynchronously (std::move (pad), getScreenBounds(), nullptr);
  1400. raw->grabKeyboardFocus();
  1401. }
  1402. // --- hint bar ------------------------------------------------------------------------------------
  1403. juce::String MainComponent::idleHint() const
  1404. {
  1405. if (engine.isWaitingForInput())
  1406. return tr ("Recording: waiting for the first note ([Space] cancels)");
  1407. if (engine.isCountingIn())
  1408. return tr ("Recording: count-in...");
  1409. return tr ("Point at anything to see what it does here. [F1] shortcuts [F5]-[F9] windows [Space] play/stop "
  1410. "[Ctrl][T] typing piano: {0}", { typingPiano ? tr ("on") : tr ("off") });
  1411. }
  1412. juce::String MainComponent::keyMarkup (const char* actionId) const
  1413. {
  1414. const auto& chords = keyMap.chordsFor (actionId);
  1415. if (chords.empty())
  1416. return {};
  1417. // "Ctrl+Shift+S" -> "[Ctrl][Shift][S]"; a key name that is not markup stays as text
  1418. const auto text = juce::String (keys::toString (chords.front()));
  1419. juce::String out;
  1420. for (const auto& part : juce::StringArray::fromTokens (text, "+", ""))
  1421. {
  1422. if (! hintmarkup::isToken (part.toStdString()))
  1423. return "(" + text + ")";
  1424. out << "[" << part << "]";
  1425. }
  1426. return out;
  1427. }
  1428. void MainComponent::setControlHints()
  1429. {
  1430. auto with = [this] (const juce::String& text, const char* actionId) {
  1431. const auto key = keyMarkup (actionId);
  1432. return key.isEmpty() ? text : text + " " + key;
  1433. };
  1434. ui::setHint (newButton, with (tr ("New project"), "file.new"));
  1435. ui::setHint (openButton, with (tr ("Open a project (.lynx, FL Studio .flp, MIDI)"), "file.open"));
  1436. ui::setHint (saveButton, with (tr ("Save the project"), "file.save") + " " + tr ("save as:") + " " + keyMarkup ("file.saveAs"));
  1437. ui::setHint (exportButton, with (tr ("Export audio: WAV, FLAC or OGG"), "file.export"));
  1438. ui::setHint (undoButton, with (tr ("Undo the last edit"), "edit.undo") + " " + tr ("[RMB] undo history"), true);
  1439. ui::setHint (redoButton, with (tr ("Redo"), "edit.redo") + " " + tr ("[RMB] undo history"), true);
  1440. ui::setHint (pluginPickerButton, with (tr ("Plugin picker: add an instrument or an effect by name"), "panel.quickAdd"));
  1441. ui::setHint (playButton, with (tr ("Play: [LMB] play; again: stop and go back to where it started"), "transport.playStop")
  1442. + " " + keyMarkup ("transport.pause") + " " + tr ("pause"));
  1443. ui::setHint (stopButton, tr ("Stop: [LMB] stop and go back to the start [2xLMB] all notes off (panic)"));
  1444. ui::setHint (recordButton, with (tr ("Record: [LMB] arm, then play to record notes (and audio, when armed) [RMB] what to record"), "transport.record"),
  1445. true);
  1446. ui::setHint (recordMenuButton, tr ("What to record: notes, input audio, count-in, overdub or replace, quantise [LMB] menu"), true);
  1447. ui::setHint (patternModeButton, with (tr ("Pattern mode: plays the current pattern in a loop [RMB] show the Channel Rack"), "transport.toggleMode"));
  1448. ui::setHint (songModeButton, with (tr ("Song mode: plays the Playlist arrangement [RMB] show the Playlist"), "transport.toggleMode"));
  1449. ui::setHint (metronomeButton, with (tr ("Metronome: clicks on every beat while playing"), "transport.metronome"));
  1450. ui::setHint (countInButton, with (tr ("Count-in: one bar of clicks before recording starts (the menu has more lengths)"), "record.countIn"));
  1451. ui::setHint (waitInputButton, with (tr ("Wait for input: recording starts with the first note you play"), "record.waitForInput"));
  1452. ui::setHint (typingPianoButton, with (tr ("Typing keyboard as a piano: Z..M and Q..P play the selected channels; letter shortcuts pause"),
  1453. "view.typingPiano"));
  1454. ui::setHint (gridBox, tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  1455. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"),
  1456. true);
  1457. ui::setHint (patternBox, tr ("Current pattern: what the Channel Rack and Piano Roll edit and Pattern mode plays [LMB] choose [Wheel] step "
  1458. "[F4] next empty [F2] rename"));
  1459. ui::setHint (newPatternButton, tr ("New pattern: an empty pattern after the last one"));
  1460. ui::setHint (patternMenuButton, tr ("Pattern menu: rename, color, length, clone, insert, split by channel, delete"), true);
  1461. const char* panelHelp[] = { TR_NOOP ("the arrangement: clips of patterns, audio and automation on tracks"),
  1462. TR_NOOP ("the instruments and their step sequencer"),
  1463. TR_NOOP ("the notes of the selected channel in the current pattern"),
  1464. TR_NOOP ("inserts, effects and routing"),
  1465. TR_NOOP ("samples, presets, plugins and projects to drag in") };
  1466. for (int i = 0; i < workspace::panelCount; ++i)
  1467. ui::setHint (panelButtons[(std::size_t) i],
  1468. with (panelName ((Panel) i) + ": " + tr (panelHelp[i]) + " " + tr ("[LMB] show, focus or hide [RMB] maximized"),
  1469. panelAction ((Panel) i)));
  1470. }
  1471. void MainComponent::timerCallback()
  1472. {
  1473. output.update();
  1474. timeDisplay.update();
  1475. songPosition.update();
  1476. masterVolume.update();
  1477. masterPitch.update();
  1478. updateRecordQuantise();
  1479. if (engine.isModified() != lastModified)
  1480. {
  1481. lastModified = engine.isModified();
  1482. updateTitle();
  1483. }
  1484. // autosave every 2 minutes when there are changes
  1485. if (++autosaveTicks >= 30 * 120)
  1486. {
  1487. autosaveTicks = 0;
  1488. if (engine.isModified())
  1489. autosave();
  1490. }
  1491. auto& transport = engine.getTransport();
  1492. if (! heldKeys.empty()) // keys released while a detached panel window had the focus
  1493. keyStateChanged (false);
  1494. // hint bar: a gesture's own posted hint, else the control under the mouse (while it is dragged, the
  1495. // control that was pressed, at the point it was pressed, so its value updates live); MIDI learn and
  1496. // recording states first
  1497. if (! hintsFrozen)
  1498. {
  1499. ui::Hint hint;
  1500. bool live = false;
  1501. if (engine.isLearningMidi())
  1502. hint.text = tr ("Move a knob/fader on the MIDI controller to link it to the parameter...");
  1503. else if (engine.isWaitingForInput() || engine.isCountingIn())
  1504. hint.text = idleHint();
  1505. else if (auto posted = ui::postedHint())
  1506. {
  1507. hint = *posted;
  1508. live = true;
  1509. }
  1510. else if (isShowing())
  1511. {
  1512. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  1513. if (auto* under = source.getComponentUnderMouse())
  1514. {
  1515. live = source.isDragging();
  1516. const auto at = live ? source.getLastMouseDownPosition() : source.getScreenPosition();
  1517. hint = ui::hintFor (under, under->getLocalPoint (nullptr, at).roundToInt());
  1518. }
  1519. }
  1520. if (hint.isEmpty())
  1521. {
  1522. hint.text = idleHint();
  1523. live = false;
  1524. }
  1525. hintBar.setHint (hint, live && hint.value.isNotEmpty());
  1526. }
  1527. const auto playing = transport.playing.load();
  1528. playButton.setToggleState (playing, juce::dontSendNotification);
  1529. // CPU / memory / polyphony, a few times a second
  1530. if (++meterTicks >= 8 && perfMeter.isVisible() && ! hintsFrozen)
  1531. {
  1532. meterTicks = 0;
  1533. int held = 0;
  1534. for (const auto& [code, channels] : heldKeys)
  1535. held += (int) channels.size();
  1536. const auto notes = playing ? songstats::soundingNotes (engine.getSong(), transport.positionTicks.load()) : 0;
  1537. perfMeter.setValues (engine.getDeviceManager().getCpuUsage(), toolbar::PerformanceMeter::processMemoryBytes(), notes + held);
  1538. }
  1539. // If a dialog stole focus, give it back so the PC keyboard keeps playing (unless a detached panel has it).
  1540. if (! hasKeyboardFocus (true) && isShowing() && juce::Process::isForegroundProcess()
  1541. && juce::Component::getCurrentlyModalComponent() == nullptr && ! workspace.isDetachedWindowActive())
  1542. grabKeyboardFocus();
  1543. }
  1544. void MainComponent::updateTitle()
  1545. {
  1546. repaint (titleArea); // the project name in the toolbar
  1547. if (auto* window = getTopLevelComponent())
  1548. window->setName ((engine.isModified() ? "* " : "")
  1549. + (projectName.isNotEmpty() ? "LYNX - " + projectName : juce::String ("LYNX")) + importedSuffix);
  1550. }
  1551. std::unique_ptr<juce::AlertWindow> MainComponent::makeConfirmDiscardWindow()
  1552. {
  1553. auto window = std::make_unique<juce::AlertWindow> (tr ("Save changes?"), tr ("The project has unsaved changes."),
  1554. juce::MessageBoxIconType::QuestionIcon);
  1555. window->addButton (tr ("Save"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1556. window->addButton (tr ("Discard"), 2);
  1557. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1558. return window;
  1559. }
  1560. void MainComponent::confirmDiscard (std::function<void()> then)
  1561. {
  1562. if (! engine.isModified())
  1563. {
  1564. then();
  1565. return;
  1566. }
  1567. auto* window = makeConfirmDiscardWindow().release();
  1568. window->enterModalState (true, juce::ModalCallbackFunction::create ([this, then] (int result) {
  1569. if (result == 1)
  1570. {
  1571. save (false);
  1572. if (! engine.isModified()) // saved (did not cancel "save as")
  1573. then();
  1574. }
  1575. else if (result == 2)
  1576. then();
  1577. }),
  1578. true);
  1579. }
  1580. void MainComponent::autosave()
  1581. {
  1582. // backup copy of the open project, so work isn't lost if something crashes
  1583. const auto folder = juce::File::getSpecialLocation (juce::File::userApplicationDataDirectory).getChildFile ("LYNX/autosave");
  1584. folder.createDirectory();
  1585. const auto name = projectName.isNotEmpty() ? juce::File::createLegalFileName (projectName) : juce::String ("untitled");
  1586. juce::String error;
  1587. engine.capturePluginStates();
  1588. ProjectFile::save (engine.getSong(), folder.getChildFile (name + ProjectFile::extension), error);
  1589. }
  1590. void MainComponent::newProject()
  1591. {
  1592. confirmDiscard ([this] {
  1593. engine.stop();
  1594. engine.rewind();
  1595. engine.setSong (Song::makeDefault());
  1596. currentFile = juce::File();
  1597. projectName = {};
  1598. importedSuffix = {};
  1599. updateTitle();
  1600. });
  1601. }
  1602. void MainComponent::chooseFileToOpen()
  1603. {
  1604. confirmDiscard ([this] { chooseFileToOpenNow(); });
  1605. }
  1606. void MainComponent::chooseFileToOpenNow()
  1607. {
  1608. fileChooser = std::make_unique<juce::FileChooser> (tr ("Open project"), currentFile.getParentDirectory(),
  1609. juce::String ("*") + ProjectFile::extension + ";*.dawproj;*.flp;*.mid;*.midi");
  1610. fileChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  1611. [this] (const juce::FileChooser& chooser) {
  1612. if (chooser.getResult().existsAsFile())
  1613. openFile (chooser.getResult());
  1614. });
  1615. }
  1616. void MainComponent::openFile (const juce::File& file)
  1617. {
  1618. juce::String error;
  1619. if (file.hasFileExtension ("mid;midi"))
  1620. {
  1621. auto song = MidiFileIo::loadSong (file, error);
  1622. if (! song)
  1623. {
  1624. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  1625. return;
  1626. }
  1627. engine.stop();
  1628. engine.rewind();
  1629. engine.setSong (std::move (*song));
  1630. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  1631. projectName = file.getFileNameWithoutExtension();
  1632. rememberRecent (file);
  1633. importedSuffix = " " + tr ("(imported from MIDI)");
  1634. updateTitle();
  1635. return;
  1636. }
  1637. if (file.hasFileExtension ("flp"))
  1638. {
  1639. if (! engine.importFlpFile (file, error))
  1640. {
  1641. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  1642. return;
  1643. }
  1644. currentFile = juce::File(); // imported: "Save" asks where to write the .lynx
  1645. projectName = file.getFileNameWithoutExtension();
  1646. rememberRecent (file);
  1647. importedSuffix = " " + tr ("(imported from FL Studio)");
  1648. updateTitle();
  1649. showImportReport();
  1650. return;
  1651. }
  1652. auto song = ProjectFile::load (file, error);
  1653. if (! song)
  1654. {
  1655. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not open"), error);
  1656. return;
  1657. }
  1658. engine.stop();
  1659. engine.rewind();
  1660. engine.setSong (std::move (*song));
  1661. currentFile = file;
  1662. projectName = file.getFileNameWithoutExtension();
  1663. importedSuffix = {};
  1664. rememberRecent (file);
  1665. updateTitle();
  1666. }
  1667. void MainComponent::exportAudio()
  1668. {
  1669. showExportDialog (engine, currentFile.getParentDirectory(), projectName);
  1670. }
  1671. void MainComponent::save (bool askForFile)
  1672. {
  1673. auto write = [this] (juce::File file) {
  1674. if (! file.hasFileExtension (ProjectFile::extension))
  1675. file = file.withFileExtension (ProjectFile::extension);
  1676. juce::String error;
  1677. engine.capturePluginStates(); // plugin state lives in the plugins; copy it before saving
  1678. if (ProjectFile::save (engine.getSong(), file, error))
  1679. {
  1680. engine.markSaved();
  1681. rememberRecent (file);
  1682. currentFile = file;
  1683. projectName = file.getFileNameWithoutExtension();
  1684. importedSuffix = {};
  1685. updateTitle();
  1686. }
  1687. else
  1688. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Could not save"), error);
  1689. };
  1690. if (! askForFile && currentFile != juce::File())
  1691. {
  1692. write (currentFile);
  1693. return;
  1694. }
  1695. fileChooser = std::make_unique<juce::FileChooser> (tr ("Save project"), currentFile.getParentDirectory(),
  1696. juce::String ("*") + ProjectFile::extension);
  1697. fileChooser->launchAsync (juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::warnAboutOverwriting,
  1698. [write] (const juce::FileChooser& chooser) {
  1699. if (chooser.getResult() != juce::File())
  1700. write (chooser.getResult());
  1701. });
  1702. }
  1703. juce::StringArray MainComponent::getMenuBarNames()
  1704. {
  1705. return { tr ("File"), tr ("Edit"), tr ("View"), tr ("Patterns"), tr ("Options"), tr ("Help") };
  1706. }
  1707. juce::PopupMenu MainComponent::getMenuForIndex (int index, const juce::String&)
  1708. {
  1709. juce::PopupMenu menu;
  1710. if (index == 0)
  1711. {
  1712. menu.addItem (tr ("New") + shortcutText ("file.new"), [this] { newProject(); });
  1713. juce::PopupMenu templates;
  1714. const auto names = templateNames();
  1715. for (int i = 0; i < (int) names.size(); ++i)
  1716. templates.addItem (juce::String::fromUTF8 (names[(std::size_t) i].c_str()), [this, i] {
  1717. confirmDiscard ([this, i] {
  1718. engine.stop();
  1719. engine.rewind();
  1720. engine.setSong (makeTemplate (i));
  1721. currentFile = juce::File();
  1722. projectName = {};
  1723. importedSuffix = {};
  1724. updateTitle();
  1725. });
  1726. });
  1727. menu.addSubMenu (tr ("New from template"), templates);
  1728. menu.addItem (tr ("Open...") + shortcutText ("file.open"), [this] { chooseFileToOpen(); });
  1729. juce::PopupMenu recentMenu;
  1730. for (int i = 0; i < recent.getNumFiles(); ++i)
  1731. {
  1732. const auto file = recent.getFile (i);
  1733. recentMenu.addItem (file.getFileName() + " (" + file.getParentDirectory().getFullPathName() + ")", file.existsAsFile(),
  1734. false, [this, file] { confirmDiscard ([this, file] { openFile (file); }); });
  1735. }
  1736. if (recent.getNumFiles() == 0)
  1737. recentMenu.addItem (tr ("(none)"), false, false, [] {});
  1738. menu.addSubMenu (tr ("Open recent"), recentMenu);
  1739. menu.addItem (tr ("Save") + shortcutText ("file.save"), [this] { save (false); });
  1740. menu.addItem (tr ("Save as...") + shortcutText ("file.saveAs"), [this] { save (true); });
  1741. menu.addSeparator();
  1742. menu.addItem (tr ("Export audio...") + shortcutText ("file.export"), [this] { exportAudio(); });
  1743. menu.addItem (tr ("Open autosave folder"), [] {
  1744. juce::File::getSpecialLocation (juce::File::userApplicationDataDirectory).getChildFile ("LYNX/autosave").startAsProcess();
  1745. });
  1746. menu.addSeparator();
  1747. menu.addItem (tr ("Exit"), [] { juce::JUCEApplication::getInstance()->systemRequestedQuit(); });
  1748. }
  1749. else if (index == 1)
  1750. {
  1751. menu.addItem (tr ("Undo") + shortcutText ("edit.undo"), engine.canUndo(), false, [this] { engine.undo(); });
  1752. menu.addItem (tr ("Redo") + shortcutText ("edit.redo"), engine.canRedo(), false, [this] { engine.redo(); });
  1753. menu.addItem (tr ("Undo history...") + shortcutText ("edit.history"), [this] { showHistory(); });
  1754. menu.addSeparator();
  1755. menu.addItem (tr ("Quick-add palette...") + shortcutText ("panel.quickAdd"), [this] { showQuickAdd(); });
  1756. menu.addItem (tr ("Search the Browser") + shortcutText ("browser.search"), [this] {
  1757. showPanel (Panel::browser);
  1758. browser.focusSearch();
  1759. });
  1760. }
  1761. else if (index == 2)
  1762. {
  1763. for (auto panel : panelOrder)
  1764. menu.addItem (panelName (panel) + shortcutText (panelAction (panel)), true, workspace.isPanelVisible (panel), [this, panel] { togglePanel (panel); });
  1765. menu.addSeparator();
  1766. menu.addItem (tr ("Maximize or restore the Playlist") + shortcutText ("panel.maximisePlaylist"), [this] {
  1767. workspace.toggleMaximised (Panel::playlist);
  1768. refreshPanelButtons();
  1769. });
  1770. {
  1771. juce::PopupMenu detach;
  1772. for (auto panel : panelOrder)
  1773. detach.addItem (panelName (panel), true, workspace.isDetached (panel), [this, panel] {
  1774. workspace.setDetached (panel, ! workspace.isDetached (panel));
  1775. refreshPanelButtons();
  1776. });
  1777. menu.addSubMenu (tr ("Detached panels (own window)"), detach);
  1778. }
  1779. menu.addSeparator();
  1780. menu.addItem (tr ("Reset layout"), [this] {
  1781. workspace.resetLayout();
  1782. refreshPanelButtons();
  1783. });
  1784. menu.addItem (tr ("Save layout as..."), [this] { saveLayoutAs(); });
  1785. menu.addSubMenu (tr ("Load layout"), layoutsMenu());
  1786. menu.addItem (tr ("Bring back off-screen panels"), [this] { workspace.bringBackOffscreen(); });
  1787. menu.addSeparator();
  1788. menu.addItem (tr ("Typing keyboard as a piano") + shortcutText ("view.typingPiano"), true, typingPiano, [this] { setTypingPiano (! typingPiano); });
  1789. }
  1790. else if (index == 3)
  1791. {
  1792. menu = makePatternMenu();
  1793. }
  1794. else if (index == 4)
  1795. {
  1796. menu.addItem (tr ("Audio settings..."), [this] { showAudioSettings(); });
  1797. menu.addItem (tr ("Scan for plugins (VST3 and CLAP)..."), [this] {
  1798. scanPluginsWithProgress (engine, [] (int found) {
  1799. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugins"),
  1800. found == 1 ? tr ("1 new plugin found.") : tr ("{0} new plugins found.", { juce::String (found) }));
  1801. });
  1802. });
  1803. menu.addItem (tr ("Run plugins in a separate process (protects LYNX from crashes)"), true, pluginSandboxEnabled(), [] {
  1804. setPluginSandboxEnabled (! pluginSandboxEnabled());
  1805. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Plugins"),
  1806. pluginSandboxEnabled()
  1807. ? tr ("On: plugins opened from now on run in a separate process. "
  1808. "If one crashes, it goes silent and LYNX keeps running. Reopen the project to apply this to plugins already open.")
  1809. : tr ("Off: plugins opened from now on run inside LYNX."));
  1810. });
  1811. menu.addItem (tr ("Record input audio"), true, engine.isAudioRecordingArmed(), [this] {
  1812. engine.setAudioRecordingArmed (! engine.isAudioRecordingArmed());
  1813. });
  1814. menu.addItem (tr ("Metronome") + shortcutText ("transport.metronome"), true, engine.getTransport().metronome.load(), [this] {
  1815. metronomeButton.setToggleState (! metronomeButton.getToggleState(), juce::sendNotification);
  1816. });
  1817. {
  1818. juce::PopupMenu recording;
  1819. addRecordOptions (recording);
  1820. menu.addSubMenu (tr ("Recording"), recording);
  1821. }
  1822. {
  1823. juce::PopupMenu editIn;
  1824. const char* choices[] = { TR_NOOP ("Piano Roll when it has piano-roll notes, else Channel Rack"), TR_NOOP ("Channel Rack"), TR_NOOP ("Piano Roll") };
  1825. for (int i = 0; i < 3; ++i)
  1826. editIn.addItem (tr (choices[i]), true, PlaylistComponent::editPatternsIn == i, [this, i] {
  1827. PlaylistComponent::editPatternsIn = i;
  1828. saveUiSettings();
  1829. });
  1830. menu.addSubMenu (tr ("Double-click on a pattern clip opens"), editIn);
  1831. }
  1832. menu.addItem (tr ("Keep channel editors open (a channel button click doesn't close the previous editor)"), true,
  1833. ChannelRackComponent::keepEditorsOpen, [this] {
  1834. ChannelRackComponent::keepEditorsOpen = ! ChannelRackComponent::keepEditorsOpen;
  1835. saveUiSettings();
  1836. });
  1837. menu.addItem (tr ("Show the splash screen at startup"), true, startup.splash, [this] {
  1838. startup.splash = ! startup.splash;
  1839. saveUiSettings();
  1840. });
  1841. menu.addItem (tr ("Play the startup sound"), true, startup.sound, [this] {
  1842. startup.sound = ! startup.sound;
  1843. saveUiSettings();
  1844. });
  1845. menu.addSeparator();
  1846. menu.addItem (tr ("Edit keyboard shortcuts (keys.json)..."), [this] { editKeyMap(); });
  1847. menu.addItem (tr ("Reload keyboard shortcuts"), [this] {
  1848. loadKeyMap();
  1849. setControlHints();
  1850. });
  1851. menu.addSeparator();
  1852. juce::PopupMenu languages;
  1853. for (const auto& language : i18n::languages())
  1854. {
  1855. const juce::String id (language.id);
  1856. languages.addItem (juce::String::fromUTF8 (language.nativeName), true, i18n::saved() == id, [this, id] { showLanguageChoice (id); });
  1857. }
  1858. menu.addSubMenu (tr ("Language"), languages);
  1859. }
  1860. else
  1861. {
  1862. menu.addItem (tr ("Shortcuts") + shortcutText ("help.shortcuts"), [this] { showHelp(); });
  1863. menu.addItem (tr ("Last FL Studio import report"), [this] {
  1864. const auto& r = engine.getImportReport();
  1865. if (r.converted.empty() && r.approximated.empty() && r.unsupported.empty() && r.droppedEffects.empty() && r.missingSamples == 0
  1866. && engine.getMissingPlugins().isEmpty())
  1867. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"),
  1868. tr ("Nothing to report (no .flp imported in this session, or everything was converted)."));
  1869. else
  1870. showImportReport();
  1871. });
  1872. menu.addItem (tr ("About LYNX"), [] {
  1873. auto* window = makeAboutWindow().release();
  1874. window->enterModalState (true, nullptr, true);
  1875. keepAboveMainWindow (*window);
  1876. });
  1877. }
  1878. return menu;
  1879. }
  1880. std::unique_ptr<juce::AlertWindow> MainComponent::makeAboutWindow()
  1881. {
  1882. struct Logo final : juce::Component
  1883. {
  1884. Logo() { setSize (300, 150); }
  1885. void paint (juce::Graphics& g) override
  1886. {
  1887. g.drawImageWithin (logoImage(), 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred);
  1888. }
  1889. };
  1890. struct About final : juce::AlertWindow
  1891. {
  1892. About()
  1893. : juce::AlertWindow ("LYNX " JUCE_APPLICATION_VERSION_STRING,
  1894. tr ("Lightweight C++/JUCE DAW with the FL Studio workflow.\n"
  1895. "Independent implementation: no Image-Line code was copied."),
  1896. juce::MessageBoxIconType::NoIcon)
  1897. {
  1898. addCustomComponent (&logo);
  1899. }
  1900. Logo logo;
  1901. };
  1902. auto window = std::make_unique<About>();
  1903. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1904. return std::unique_ptr<juce::AlertWindow> (window.release());
  1905. }
  1906. void MainComponent::showLanguageChoice (const juce::String& id)
  1907. {
  1908. if (id == i18n::saved())
  1909. return;
  1910. i18n::save (id);
  1911. const auto restart = [this] {
  1912. confirmDiscard ([] {
  1913. juce::File::getSpecialLocation (juce::File::currentExecutableFile).startAsProcess();
  1914. juce::JUCEApplication::quit();
  1915. });
  1916. };
  1917. // the message is shown in the language just chosen
  1918. const auto table = i18n::tableText (id);
  1919. const juce::LocalisedStrings strings (table, false);
  1920. auto say = [&] (const char* text) { return table.isEmpty() ? juce::String::fromUTF8 (text) : strings.translate (juce::String::fromUTF8 (text)); };
  1921. auto* window = new juce::AlertWindow (say (TR_NOOP ("Language")), say (TR_NOOP ("The new language is applied when LYNX restarts.")),
  1922. juce::MessageBoxIconType::InfoIcon);
  1923. window->addButton (say (TR_NOOP ("Restart now")), 1, juce::KeyPress (juce::KeyPress::returnKey));
  1924. window->addButton (say (TR_NOOP ("Later")), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  1925. window->enterModalState (true, juce::ModalCallbackFunction::create ([restart] (int result) {
  1926. if (result == 1)
  1927. restart();
  1928. }),
  1929. true);
  1930. }
  1931. void MainComponent::rememberRecent (const juce::File& file)
  1932. {
  1933. recent.addFile (file);
  1934. PluginHost::settingsFolder().getChildFile ("recentes.txt").replaceWithText (recent.toString());
  1935. menuItemsChanged();
  1936. }
  1937. std::unique_ptr<juce::Component> MainComponent::makeHelpContent()
  1938. {
  1939. // shortcut sheet: sections of "keys - action" rows, in two columns
  1940. struct Row
  1941. {
  1942. const char* keys;
  1943. const char* action;
  1944. };
  1945. struct Section
  1946. {
  1947. const char* title;
  1948. std::vector<Row> rows;
  1949. };
  1950. static const std::vector<Section> sections {
  1951. { TR_NOOP ("General"),
  1952. { { TR_NOOP ("Space"), TR_NOOP ("Play / stop (back to where playback started)") },
  1953. { "Ctrl+Space", TR_NOOP ("Play / pause") },
  1954. { "Ctrl+Z / Ctrl+Y", TR_NOOP ("Undo / redo") },
  1955. { "Ctrl+N / Ctrl+O", TR_NOOP ("New project / open") },
  1956. { "Ctrl+S / Ctrl+Shift+S", TR_NOOP ("Save / save as") },
  1957. { "Ctrl+R", TR_NOOP ("Export audio") },
  1958. { "F5 F6 F7 F9 F8", TR_NOOP ("Panels: Playlist, Channel Rack, Piano Roll, Mixer, Browser") },
  1959. { "Enter", TR_NOOP ("Maximize or restore the Playlist") },
  1960. { "L", TR_NOOP ("Pattern / song mode") },
  1961. { "Ctrl+T", TR_NOOP ("Typing keyboard as a piano on/off") },
  1962. { "Z..M Q..P", TR_NOOP ("PC keyboard as a piano (selected channels)") },
  1963. { TR_NOOP ("Numpad +/- F4 F2"), TR_NOOP ("Next/previous pattern, next empty, rename and color") },
  1964. { "Ctrl+Shift+Ins", TR_NOOP ("Insert an empty pattern before the current one") } } },
  1965. { TR_NOOP ("Workspace"),
  1966. { { TR_NOOP ("Drag a panel title"), TR_NOOP ("Move (snaps; Alt: free)") },
  1967. { TR_NOOP ("Double-click a title"), TR_NOOP ("Maximize / restore") },
  1968. { TR_NOOP ("Title buttons"), TR_NOOP ("Detach into a window, maximize, close") },
  1969. { TR_NOOP ("View menu"), TR_NOOP ("Reset, save and load layouts") } } },
  1970. { TR_NOOP ("Channel Rack and Mixer"),
  1971. { { TR_NOOP ("Click the name"), TR_NOOP ("Open/close the editor (Alt keeps others open)") },
  1972. { TR_NOOP ("Ctrl+click the name"), TR_NOOP ("Audition the channel") },
  1973. { TR_NOOP ("Selector / Up, Down"), TR_NOOP ("Select (Ctrl: add, Shift: range)") },
  1974. { "Alt+Up / Alt+Down", TR_NOOP ("Move the selected channels") },
  1975. { "Alt+C / Alt+Del", TR_NOOP ("Clone / delete the selected channels") },
  1976. { "Ctrl+L", TR_NOOP ("Send the selected channels to free mixer inserts") },
  1977. { TR_NOOP ("1..0 / Ctrl+1..0"), TR_NOOP ("Mute / solo channels 1-10 (typing piano off)") },
  1978. { TR_NOOP ("Knobs and faders"), TR_NOOP ("Drag (Ctrl: fine), wheel, Alt+click or middle-click resets") },
  1979. { TR_NOOP ("Right-click a knob/fader"), TR_NOOP ("Type value, reset, automation, MIDI link") },
  1980. { TR_NOOP ("Right-click Pattern / Song"), TR_NOOP ("Show the Channel Rack / Playlist") },
  1981. { TR_NOOP ("Double-click Stop"), TR_NOOP ("All notes off") } } },
  1982. { "Piano Roll",
  1983. { { TR_NOOP ("Click"), TR_NOOP ("Create a note (or chord, via the selector)") },
  1984. { TR_NOOP ("Drag"), TR_NOOP ("Move; the right edge changes the length") },
  1985. { TR_NOOP ("Right-click"), TR_NOOP ("Delete") },
  1986. { TR_NOOP ("Ctrl+drag"), TR_NOOP ("Select (Ctrl+click adds to the selection)") },
  1987. { TR_NOOP ("Shift+drag"), TR_NOOP ("Copy") },
  1988. { "Ctrl+A/C/X/V", TR_NOOP ("Select all, copy, cut, paste") },
  1989. { "Ctrl+B / Ctrl+Q", TR_NOOP ("Duplicate / quantize") },
  1990. { "Ctrl+M / Ctrl+P", TR_NOOP ("Mute / portamento") },
  1991. { TR_NOOP ("Arrows"), TR_NOOP ("Move (Shift = octave/bar)") },
  1992. { TR_NOOP ("Alt / Ctrl+wheel"), TR_NOOP ("Disable snap / zoom") } } },
  1993. { "Playlist",
  1994. { { TR_NOOP ("Click"), TR_NOOP ("Paint the current pattern") },
  1995. { TR_NOOP ("Drag on the ruler"), TR_NOOP ("Set the loop (right-click clears)") },
  1996. { TR_NOOP ("Right-click a clip name"), TR_NOOP ("Split, make unique...") },
  1997. { TR_NOOP ("Track LED"), TR_NOOP ("Mute the track") },
  1998. { "Ctrl+A/C/X/V Ctrl+B", TR_NOOP ("Edit and duplicate") } } },
  1999. };
  2000. struct Sheet final : juce::Component
  2001. {
  2002. Sheet() { setSize (1180, 520); }
  2003. void paint (juce::Graphics& g) override
  2004. {
  2005. using namespace theme;
  2006. g.fillAll (colour::bg2);
  2007. const auto columnWidth = (getWidth() - 4 * 24) / 3;
  2008. int column = 0, y = 20;
  2009. for (std::size_t i = 0; i < sections.size(); ++i)
  2010. {
  2011. if (i == 2 || i == 3) // next column
  2012. {
  2013. ++column;
  2014. y = 20;
  2015. }
  2016. const auto x = 24 + column * (columnWidth + 24);
  2017. const auto& section = sections[i];
  2018. g.setColour (colour::accent);
  2019. g.fillRoundedRectangle ((float) x, (float) y + 4.0f, 3.0f, 12.0f, 1.5f);
  2020. g.setColour (colour::textPrimary);
  2021. g.setFont (font (type::title, true));
  2022. g.drawText (tr (section.title), x + 10, y, columnWidth - 10, 20, juce::Justification::centredLeft);
  2023. y += 28;
  2024. for (const auto& row : section.rows)
  2025. {
  2026. const auto keys = tr (row.keys);
  2027. g.setFont (font (type::small, true));
  2028. const auto keyWidth = juce::roundToInt (juce::GlyphArrangement::getStringWidth (g.getCurrentFont(), keys)) + 14;
  2029. g.setColour (colour::bg4);
  2030. g.fillRoundedRectangle ((float) x, (float) y + 1.0f, (float) keyWidth, 18.0f, radius::sm);
  2031. g.setColour (colour::textPrimary);
  2032. g.drawText (keys, x, y + 1, keyWidth, 18, juce::Justification::centred);
  2033. g.setColour (colour::textSecondary);
  2034. g.setFont (font (type::body));
  2035. g.drawFittedText (tr (row.action), x + keyWidth + 10, y, columnWidth - keyWidth - 10, 20, juce::Justification::centredLeft, 1, 0.85f);
  2036. y += 24;
  2037. }
  2038. y += 14;
  2039. }
  2040. }
  2041. };
  2042. return std::make_unique<Sheet>();
  2043. }
  2044. void MainComponent::showHelp()
  2045. {
  2046. juce::DialogWindow::LaunchOptions options;
  2047. options.content.setOwned (makeHelpContent().release());
  2048. options.dialogTitle = tr ("LYNX shortcuts");
  2049. options.dialogBackgroundColour = theme::colour::bg2;
  2050. options.useNativeTitleBar = true;
  2051. options.resizable = true;
  2052. options.escapeKeyTriggersCloseButton = true;
  2053. if (auto* dialog = options.launchAsync())
  2054. keepAboveMainWindow (*dialog);
  2055. }
  2056. void MainComponent::showImportReport()
  2057. {
  2058. // summary of what the .flp had that LYNX doesn't reproduce exactly (only when there is something to say)
  2059. const auto& r = engine.getImportReport();
  2060. const auto& missing = engine.getMissingPlugins();
  2061. auto list = [] (const std::map<std::string, int>& items) {
  2062. std::vector<std::pair<int, std::string>> sorted;
  2063. for (const auto& [name, count] : items)
  2064. sorted.push_back ({ count, name });
  2065. std::sort (sorted.rbegin(), sorted.rend());
  2066. juce::StringArray lines;
  2067. for (const auto& [count, name] : sorted)
  2068. lines.add (" " + juce::String::fromUTF8 (name.c_str()) + (count > 1 ? " (" + juce::String (count) + ")" : juce::String()));
  2069. return lines.joinIntoString ("\n");
  2070. };
  2071. juce::String text;
  2072. if (! r.approximated.empty())
  2073. text << tr ("Approximated by the built-in synth:") << "\n" << list (r.approximated) << "\n\n";
  2074. if (! r.unsupported.empty())
  2075. text << tr ("No equivalent (played with a synth preset):") << "\n" << list (r.unsupported) << "\n\n";
  2076. if (! missing.isEmpty())
  2077. text << tr ("Plugins not found (Options > Scan for plugins):") << "\n " << missing.joinIntoString ("\n ") << "\n\n";
  2078. if (! r.droppedEffects.empty())
  2079. text << tr ("Effects with no equivalent (left out):") << "\n" << list (r.droppedEffects) << "\n\n";
  2080. if (r.missingSamples > 0)
  2081. text << tr ("Samples missing on this machine: {0}", { juce::String (r.missingSamples) }) << "\n";
  2082. if (text.isNotEmpty())
  2083. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("FL Studio import"), text.trimEnd());
  2084. }
  2085. void MainComponent::showAudioSettings()
  2086. {
  2087. auto selector = std::make_unique<juce::AudioDeviceSelectorComponent> (
  2088. engine.getDeviceManager(), 0, 0, 2, 2, false, false, true, false);
  2089. selector->setSize (500, 400);
  2090. juce::DialogWindow::LaunchOptions options;
  2091. options.content.setOwned (selector.release());
  2092. options.dialogTitle = tr ("Audio settings");
  2093. options.dialogBackgroundColour = theme::colour::bg2;
  2094. options.useNativeTitleBar = true;
  2095. options.resizable = false;
  2096. if (auto* dialog = options.launchAsync())
  2097. keepAboveMainWindow (*dialog);
  2098. }
  2099. } // namespace lynx