SettingsPages.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. #include "ui/SettingsPages.h"
  2. #include "platform/Paths.h"
  3. #include "core/ToolbarLayout.h"
  4. #include "engine/AudioEngine.h"
  5. #include "engine/PluginHost.h"
  6. #include "ui/AutomationUi.h"
  7. #include "ui/I18n.h"
  8. namespace lynx
  9. {
  10. using namespace settingsui;
  11. juce::File autosaveFolder()
  12. {
  13. return lynx::platform::settingsFile ("autosave");
  14. }
  15. namespace
  16. {
  17. constexpr int labelWidth = 190;
  18. constexpr int rowHeight = 28;
  19. constexpr int rowGap = 8;
  20. constexpr int sectionHeight = 28;
  21. void styleCombo (juce::ComboBox& box)
  22. {
  23. box.setColour (juce::ComboBox::outlineColourId, theme::colour::borderStrong);
  24. }
  25. void styleToggle (juce::ToggleButton& t, const juce::String& text)
  26. {
  27. t.setButtonText (text);
  28. }
  29. // Lays out rows top to bottom inside a page of a given width.
  30. struct Rows
  31. {
  32. juce::Rectangle<int> area;
  33. int y = 0;
  34. explicit Rows (int width) : area (20, 14, width - 40, 100000), y (14) {}
  35. void section (juce::Component& title, bool first = false)
  36. {
  37. if (! first)
  38. y += 10;
  39. title.setBounds (area.getX(), y, area.getWidth(), sectionHeight);
  40. y += sectionHeight + rowGap;
  41. }
  42. // label + control (control width 0 = to the right edge)
  43. juce::Rectangle<int> row (juce::Label& label, int controlWidth = 260, int height = rowHeight)
  44. {
  45. label.setBounds (area.getX(), y, labelWidth, height);
  46. auto r = juce::Rectangle<int> (area.getX() + labelWidth, y, controlWidth > 0 ? controlWidth : area.getWidth() - labelWidth, height);
  47. y += height + rowGap;
  48. return r;
  49. }
  50. juce::Rectangle<int> full (int height = rowHeight)
  51. {
  52. auto r = juce::Rectangle<int> (area.getX(), y, area.getWidth(), height);
  53. y += height + rowGap;
  54. return r;
  55. }
  56. juce::Rectangle<int> indented (int height = rowHeight)
  57. {
  58. auto r = juce::Rectangle<int> (area.getX() + labelWidth, y, area.getWidth() - labelWidth, height);
  59. y += height + rowGap;
  60. return r;
  61. }
  62. int bottom() const { return y + 14; }
  63. };
  64. // ================================================================================================================
  65. // General
  66. // ================================================================================================================
  67. class GeneralPage final : public ScrollingPage
  68. {
  69. public:
  70. GeneralPage (AudioEngine& e, SettingsHooks h, bool keep) : engine (e), hooks (std::move (h)), persistent (keep)
  71. {
  72. if (hooks.getGeneral)
  73. options = hooks.getGeneral();
  74. else
  75. options.language = "en";
  76. for (auto* c : std::initializer_list<juce::Component*> { &languageTitle, &displayTitle, &startupTitle, &editingTitle, &backupTitle,
  77. &pluginsTitle, &languageLabel, &languageBox, &languageNote, &scaleLabel, &scaleBox,
  78. &wavesLabel, &wavesBox, &stereoWaves, &splash, &startupSound, &scanAtStart,
  79. &typingPiano, &keepEditors, &rememberSeek, &editInLabel, &editInBox, &undoLabel,
  80. &undoBox, &autosaveLabel, &autosaveBox, &keepLabel, &keepBox, &openBackups,
  81. &sandbox, &sandboxNote, &substitutes, &substitutesNote, &managePlugins, &manageShortcuts, &shortcutsNote })
  82. add (*c);
  83. styleLabel (languageLabel, tr ("Language"));
  84. styleNote (languageNote, tr ("A new language is applied when LYNX restarts."));
  85. int id = 1;
  86. for (const auto& l : i18n::languages())
  87. {
  88. languageBox.addItem (juce::String::fromUTF8 (l.nativeName), id);
  89. if (options.language == l.id)
  90. languageBox.setSelectedId (id, juce::dontSendNotification);
  91. ++id;
  92. }
  93. languageBox.onChange = [this] {
  94. const auto index = languageBox.getSelectedId() - 1;
  95. if (juce::isPositiveAndBelow (index, (int) i18n::languages().size()))
  96. change ([&] { options.language = i18n::languages()[(std::size_t) index].id; });
  97. };
  98. styleLabel (scaleLabel, tr ("Interface size"));
  99. for (auto percent : toolbarlayout::uiScales)
  100. scaleBox.addItem (juce::String (percent) + "%", percent);
  101. scaleBox.setSelectedId (options.uiScale, juce::dontSendNotification);
  102. scaleBox.onChange = [this] { change ([&] { options.uiScale = scaleBox.getSelectedId(); }); };
  103. styleLabel (wavesLabel, tr ("Waveforms"));
  104. wavesBox.addItem (tr ("Clean (the clip colour)"), 1);
  105. wavesBox.addItem (tr ("Spectral colours (warm = bass, cool = treble)"), 2);
  106. wavesBox.setSelectedId (options.waveSpectral ? 2 : 1, juce::dontSendNotification);
  107. wavesBox.onChange = [this] { change ([&] { options.waveSpectral = wavesBox.getSelectedId() == 2; }); };
  108. toggle (stereoWaves, tr ("Stereo (left and right channels apart)"), options.waveStereo, [this] (bool on) { options.waveStereo = on; });
  109. toggle (splash, tr ("Show the splash screen at startup"), options.splash, [this] (bool on) { options.splash = on; });
  110. toggle (startupSound, tr ("Play the startup sound"), options.startupSound, [this] (bool on) { options.startupSound = on; });
  111. toggle (scanAtStart, tr ("Look for new plugins in the background at every start"), options.scanAtStart,
  112. [this] (bool on) { options.scanAtStart = on; });
  113. toggle (typingPiano, tr ("Typing keyboard as a piano"), options.typingPiano, [this] (bool on) { options.typingPiano = on; });
  114. toggle (keepEditors, tr ("Keep channel editors open (a channel button click doesn't close the previous editor)"), options.keepEditorsOpen,
  115. [this] (bool on) { options.keepEditorsOpen = on; });
  116. toggle (rememberSeek, tr ("Remember seek time: Stop goes back to the position clicked on the Playlist ruler"), options.rememberSeek,
  117. [this] (bool on) { options.rememberSeek = on; });
  118. styleLabel (editInLabel, tr ("Double-click on a pattern clip opens"));
  119. const char* choices[] = { TR_NOOP ("Piano Roll when it has piano-roll notes, else Channel Rack"), TR_NOOP ("Channel Rack"), TR_NOOP ("Piano Roll") };
  120. for (int i = 0; i < 3; ++i)
  121. editInBox.addItem (tr (choices[i]), i + 1);
  122. editInBox.setSelectedId (options.editPatternsIn + 1, juce::dontSendNotification);
  123. editInBox.onChange = [this] { change ([&] { options.editPatternsIn = editInBox.getSelectedId() - 1; }); };
  124. styleLabel (undoLabel, tr ("Maximum undo levels"));
  125. for (auto n : { 25, 50, 100, 200, 500, 1000 })
  126. undoBox.addItem (juce::String (n), n);
  127. selectNearest (undoBox, options.undoLevels);
  128. undoBox.onChange = [this] { change ([&] { options.undoLevels = undoBox.getSelectedId(); }); };
  129. styleLabel (autosaveLabel, tr ("Save a backup copy"));
  130. for (auto minutes : prefs::autosaveIntervals())
  131. autosaveBox.addItem (minutes == 0 ? tr ("Never")
  132. : minutes == 1 ? tr ("Every minute")
  133. : tr ("Every {0} minutes", { juce::String (minutes) }),
  134. minutes + 1);
  135. autosaveBox.setSelectedId (prefs::clampAutosaveMinutes (options.autosaveMinutes) + 1, juce::dontSendNotification);
  136. autosaveBox.onChange = [this] {
  137. change ([&] { options.autosaveMinutes = autosaveBox.getSelectedId() - 1; });
  138. keepBox.setEnabled (options.autosaveMinutes > 0);
  139. };
  140. styleLabel (keepLabel, tr ("Backups kept per project"));
  141. for (auto n : { 1, 3, 5, 10, 20, 50 })
  142. keepBox.addItem (juce::String (n), n);
  143. selectNearest (keepBox, options.autosaveKeep);
  144. keepBox.setEnabled (options.autosaveMinutes > 0);
  145. keepBox.onChange = [this] { change ([&] { options.autosaveKeep = keepBox.getSelectedId(); }); };
  146. openBackups.onClick = [] {
  147. autosaveFolder().createDirectory();
  148. autosaveFolder().startAsProcess();
  149. };
  150. toggle (sandbox, tr ("Run plugins in a separate process (protects LYNX from crashes)"), options.pluginSandbox,
  151. [this] (bool on) { options.pluginSandbox = on; });
  152. styleNote (sandboxNote, tr ("Applies to plugins opened from now on; reopen the project to move the others."));
  153. toggle (substitutes, tr ("Substitute missing plugins with LYNX equivalents"), options.pluginSubstitutes,
  154. [this] (bool on) { options.pluginSubstitutes = on; });
  155. styleNote (substitutesNote, tr ("A project keeps the original plugin and uses it again once it is installed."));
  156. managePlugins.onClick = [this] {
  157. if (hooks.managePlugins)
  158. hooks.managePlugins();
  159. };
  160. manageShortcuts.onClick = [this] {
  161. if (hooks.manageShortcuts)
  162. hooks.manageShortcuts();
  163. };
  164. styleNote (shortcutsNote, tr ("See, search and change every keyboard shortcut."));
  165. for (auto* b : { &languageBox, &scaleBox, &wavesBox, &editInBox, &undoBox, &autosaveBox, &keepBox })
  166. styleCombo (*b);
  167. juce::ignoreUnused (engine, persistent);
  168. }
  169. private:
  170. int layout (int width) override
  171. {
  172. Rows r (width);
  173. r.section (languageTitle, true);
  174. languageBox.setBounds (r.row (languageLabel, 220));
  175. languageNote.setBounds (r.indented (16).translated (0, -6));
  176. scaleBox.setBounds (r.row (scaleLabel, 120));
  177. wavesBox.setBounds (r.row (wavesLabel, 0));
  178. stereoWaves.setBounds (r.indented (24));
  179. r.section (startupTitle);
  180. for (auto* t : { &splash, &startupSound, &scanAtStart })
  181. t->setBounds (r.full (24));
  182. r.section (editingTitle);
  183. for (auto* t : { &typingPiano, &keepEditors, &rememberSeek })
  184. t->setBounds (r.full (24));
  185. editInBox.setBounds (r.row (editInLabel, 0));
  186. undoBox.setBounds (r.row (undoLabel, 120));
  187. r.section (backupTitle);
  188. {
  189. auto row = r.row (autosaveLabel, 0);
  190. autosaveBox.setBounds (row.removeFromLeft (220));
  191. row.removeFromLeft (8);
  192. openBackups.setBounds (row.removeFromLeft (juce::jmin (row.getWidth(), 170)));
  193. }
  194. keepBox.setBounds (r.row (keepLabel, 120));
  195. r.section (pluginsTitle);
  196. sandbox.setBounds (r.full (24));
  197. sandboxNote.setBounds (r.full (16).translated (0, -6));
  198. substitutes.setBounds (r.full (24));
  199. substitutesNote.setBounds (r.full (16).translated (0, -6));
  200. {
  201. auto row = r.full();
  202. managePlugins.setBounds (row.removeFromLeft (180));
  203. row.removeFromLeft (8);
  204. manageShortcuts.setBounds (row.removeFromLeft (180));
  205. row.removeFromLeft (12);
  206. shortcutsNote.setBounds (row.withTrimmedTop (6));
  207. }
  208. displayTitle.setVisible (false);
  209. return r.bottom();
  210. }
  211. void toggle (juce::ToggleButton& t, const juce::String& text, bool value, std::function<void (bool)> set)
  212. {
  213. styleToggle (t, text);
  214. t.setToggleState (value, juce::dontSendNotification);
  215. t.onClick = [this, &t, set = std::move (set)] { change ([&] { set (t.getToggleState()); }); };
  216. }
  217. static void selectNearest (juce::ComboBox& box, int value)
  218. {
  219. auto best = box.getItemId (0);
  220. for (int i = 0; i < box.getNumItems(); ++i)
  221. if (std::abs (box.getItemId (i) - value) < std::abs (best - value))
  222. best = box.getItemId (i);
  223. box.setSelectedId (best, juce::dontSendNotification);
  224. }
  225. void change (const std::function<void()>& fn)
  226. {
  227. fn();
  228. if (hooks.setGeneral)
  229. hooks.setGeneral (options);
  230. }
  231. AudioEngine& engine;
  232. SettingsHooks hooks;
  233. bool persistent;
  234. GeneralOptions options;
  235. SectionTitle languageTitle { tr ("Language and display") }, displayTitle, startupTitle { tr ("Startup") }, editingTitle { tr ("Editing") },
  236. backupTitle { tr ("Backup") }, pluginsTitle { tr ("Plugins and shortcuts") };
  237. juce::Label languageLabel, languageNote, scaleLabel, wavesLabel, editInLabel, undoLabel, autosaveLabel, keepLabel, sandboxNote, substitutesNote, shortcutsNote;
  238. juce::ComboBox languageBox, scaleBox, wavesBox, editInBox, undoBox, autosaveBox, keepBox;
  239. juce::ToggleButton stereoWaves, splash, startupSound, scanAtStart, typingPiano, keepEditors, rememberSeek, sandbox, substitutes;
  240. juce::TextButton openBackups { tr ("Open backup folder") }, managePlugins { tr ("Plugin manager...") }, manageShortcuts { tr ("Manage shortcuts...") };
  241. };
  242. // ================================================================================================================
  243. // Audio
  244. // ================================================================================================================
  245. class AudioPage final : public ScrollingPage,
  246. private juce::ChangeListener,
  247. private juce::Timer
  248. {
  249. public:
  250. AudioPage (AudioEngine& e) : engine (e), devices (e.getDeviceManager())
  251. {
  252. for (auto* c : std::initializer_list<juce::Component*> { &deviceTitle, &statusTitle, &recordTitle, &driverLabel, &driverBox, &driverNote, &outputLabel,
  253. &outputBox, &inputLabel, &inputBox, &rateLabel, &rateBox, &bufferLabel, &bufferBox,
  254. &bufferNote, &panelButton, &testButton, &status, &load, &recordInput, &recordNote, &inputChannels })
  255. add (*c);
  256. styleLabel (driverLabel, tr ("Driver"));
  257. styleLabel (outputLabel, tr ("Output device"));
  258. styleLabel (inputLabel, tr ("Input device"));
  259. styleLabel (rateLabel, tr ("Sample rate"));
  260. styleLabel (bufferLabel, tr ("Buffer size"));
  261. styleNote (driverNote, {});
  262. styleNote (bufferNote, tr ("Smaller buffers answer faster when you play; larger ones give the CPU more room (fewer clicks)."));
  263. for (auto* l : { &status, &load })
  264. {
  265. styleLabel (*l, {}, false);
  266. l->setJustificationType (juce::Justification::centredLeft);
  267. }
  268. for (auto* b : { &driverBox, &outputBox, &inputBox, &rateBox, &bufferBox })
  269. {
  270. styleCombo (*b);
  271. b->setTextWhenNoChoicesAvailable (tr ("(open an output device first)"));
  272. b->setTextWhenNothingSelected (tr ("(choose)"));
  273. }
  274. driverBox.onChange = [this] {
  275. if (updating)
  276. return;
  277. auto& types = devices.getAvailableDeviceTypes();
  278. const auto index = driverBox.getSelectedId() - 1;
  279. if (juce::isPositiveAndBelow (index, types.size()))
  280. devices.setCurrentAudioDeviceType (types[index]->getTypeName(), true);
  281. refresh();
  282. };
  283. outputBox.onChange = [this] {
  284. apply ([this] (juce::AudioDeviceManager::AudioDeviceSetup& s) { s.outputDeviceName = outputBox.getText(); });
  285. };
  286. inputBox.onChange = [this] {
  287. if (updating)
  288. return;
  289. if (inputBox.getSelectedId() <= 1)
  290. apply ([] (juce::AudioDeviceManager::AudioDeviceSetup& s) {
  291. s.inputDeviceName = {};
  292. s.useDefaultInputChannels = false;
  293. s.inputChannels.clear();
  294. });
  295. else
  296. {
  297. // every channel of the device opens: each mixer insert picks its own (pair or single channel)
  298. const auto result = engine.openAudioInput (inputBox.getText());
  299. error = result.issue == AudioEngine::InputIssue::failed ? result.detail : juce::String();
  300. refresh();
  301. }
  302. };
  303. rateBox.onChange = [this] {
  304. apply ([this] (juce::AudioDeviceManager::AudioDeviceSetup& s) { s.sampleRate = (double) rateBox.getSelectedId(); });
  305. };
  306. bufferBox.onChange = [this] {
  307. apply ([this] (juce::AudioDeviceManager::AudioDeviceSetup& s) { s.bufferSize = bufferBox.getSelectedId(); });
  308. };
  309. panelButton.onClick = [this] {
  310. if (auto* device = devices.getCurrentAudioDevice(); device != nullptr && device->hasControlPanel())
  311. {
  312. // the driver's own window (ASIO): the device is reopened afterwards with what was set there
  313. devices.closeAudioDevice();
  314. device->showControlPanel();
  315. devices.restartLastAudioDevice();
  316. refresh();
  317. }
  318. };
  319. testButton.onClick = [this] { devices.playTestSound(); };
  320. styleToggle (recordInput, tr ("Record input audio"));
  321. styleNote (recordNote, tr ("Choose each mixer insert's input in the Mixer (the input box above its effect slots), arm it, then Rec + Play. "
  322. "This switch records the first two input channels into a new insert when nothing is armed."));
  323. recordInput.onClick = [this] { engine.setAudioRecordingArmed (recordInput.getToggleState()); };
  324. devices.addChangeListener (this);
  325. refresh();
  326. startTimerHz (2);
  327. }
  328. ~AudioPage() override { devices.removeChangeListener (this); }
  329. private:
  330. int layout (int width) override
  331. {
  332. Rows r (width);
  333. r.section (deviceTitle, true);
  334. driverBox.setBounds (r.row (driverLabel, 320));
  335. driverNote.setBounds (r.indented (46).translated (0, -6));
  336. outputBox.setBounds (r.row (outputLabel, 0));
  337. inputBox.setBounds (r.row (inputLabel, 0));
  338. rateBox.setBounds (r.row (rateLabel, 160));
  339. bufferBox.setBounds (r.row (bufferLabel, 260));
  340. bufferNote.setBounds (r.indented (18).translated (0, -6));
  341. {
  342. auto row = r.indented();
  343. panelButton.setBounds (row.removeFromLeft (170));
  344. row.removeFromLeft (8);
  345. testButton.setBounds (row.removeFromLeft (150));
  346. }
  347. r.section (statusTitle);
  348. status.setBounds (r.full (22));
  349. load.setBounds (r.full (22));
  350. r.section (recordTitle);
  351. inputChannels.setBounds (r.full (34));
  352. recordInput.setBounds (r.full (24));
  353. recordNote.setBounds (r.full (32).translated (0, -6));
  354. return r.bottom();
  355. }
  356. void apply (const std::function<void (juce::AudioDeviceManager::AudioDeviceSetup&)>& change)
  357. {
  358. if (updating)
  359. return;
  360. auto setup = devices.getAudioDeviceSetup();
  361. change (setup);
  362. error = devices.setAudioDeviceSetup (setup, true);
  363. refresh();
  364. }
  365. void refresh()
  366. {
  367. const juce::ScopedValueSetter<bool> guard (updating, true);
  368. auto* type = devices.getCurrentDeviceTypeObject();
  369. auto* device = devices.getCurrentAudioDevice();
  370. const auto setup = devices.getAudioDeviceSetup();
  371. driverBox.clear (juce::dontSendNotification);
  372. auto& types = devices.getAvailableDeviceTypes();
  373. for (int i = 0; i < types.size(); ++i)
  374. {
  375. driverBox.addItem (driverDisplayName (types[i]->getTypeName()), i + 1);
  376. if (types[i] == type)
  377. driverBox.setSelectedId (i + 1, juce::dontSendNotification);
  378. }
  379. outputBox.clear (juce::dontSendNotification);
  380. inputBox.clear (juce::dontSendNotification);
  381. inputBox.addItem (tr ("(none)"), 1);
  382. inputBox.setSelectedId (1, juce::dontSendNotification);
  383. if (type != nullptr)
  384. {
  385. if (type->getDeviceNames (false).isEmpty())
  386. type->scanForDevices(); // (a driver type not opened yet this session)
  387. const auto outs = type->getDeviceNames (false);
  388. for (int i = 0; i < outs.size(); ++i)
  389. {
  390. outputBox.addItem (outs[i], i + 1);
  391. if (outs[i] == setup.outputDeviceName)
  392. outputBox.setSelectedId (i + 1, juce::dontSendNotification);
  393. }
  394. if (type->hasSeparateInputsAndOutputs())
  395. {
  396. const auto ins = type->getDeviceNames (true);
  397. for (int i = 0; i < ins.size(); ++i)
  398. {
  399. inputBox.addItem (ins[i], i + 2);
  400. if (ins[i] == setup.inputDeviceName && ! setup.inputChannels.isZero())
  401. inputBox.setSelectedId (i + 2, juce::dontSendNotification);
  402. }
  403. }
  404. else if (setup.outputDeviceName.isNotEmpty())
  405. {
  406. // ASIO: one device does both
  407. inputBox.addItem (setup.outputDeviceName, 2);
  408. if (! setup.inputChannels.isZero())
  409. inputBox.setSelectedId (2, juce::dontSendNotification);
  410. }
  411. }
  412. rateBox.clear (juce::dontSendNotification);
  413. bufferBox.clear (juce::dontSendNotification);
  414. if (device != nullptr)
  415. {
  416. const auto rate = device->getCurrentSampleRate();
  417. for (auto r : device->getAvailableSampleRates())
  418. rateBox.addItem (juce::String ((int) r) + " Hz", (int) r);
  419. rateBox.setSelectedId ((int) rate, juce::dontSendNotification);
  420. const auto kind = prefs::driverKind (device->getTypeName().toStdString());
  421. std::vector<int> offered;
  422. for (auto b : device->getAvailableBufferSizes())
  423. offered.push_back (b);
  424. for (auto b : prefs::usableBufferSizes (kind, offered, device->getDefaultBufferSize()))
  425. bufferBox.addItem (tr ("{0} samples ({1} ms)", { juce::String (b), juce::String (prefs::bufferLatencyMs (b, rate), 1) }), b);
  426. bufferBox.setSelectedId (device->getCurrentBufferSizeSamples(), juce::dontSendNotification);
  427. }
  428. for (auto* b : { &outputBox, &inputBox, &rateBox, &bufferBox })
  429. b->setEnabled (b->getNumItems() > 0);
  430. driverNote.setText (driverExplanation (type != nullptr ? type->getTypeName() : juce::String(), device), juce::dontSendNotification);
  431. panelButton.setEnabled (device != nullptr && device->hasControlPanel());
  432. testButton.setEnabled (device != nullptr);
  433. recordInput.setToggleState (engine.isAudioRecordingArmed(), juce::dontSendNotification);
  434. {
  435. // what the mixer inserts can take their input from
  436. const auto names = engine.getInputChannelNames();
  437. juce::StringArray list;
  438. for (const auto& n : names)
  439. list.add (juce::String::fromUTF8 (n.c_str()));
  440. styleNote (inputChannels, names.empty() ? tr ("Input channels: none open. Choose an input device above to record a microphone or an instrument.")
  441. : tr ("Input channels ({0}): {1}", { juce::String ((int) names.size()), list.joinIntoString (", ") }));
  442. }
  443. updateStatus();
  444. }
  445. void updateStatus()
  446. {
  447. auto* device = devices.getCurrentAudioDevice();
  448. if (device == nullptr)
  449. {
  450. status.setText (error.isNotEmpty() ? error : tr ("No audio device is open: choose an output device."), juce::dontSendNotification);
  451. status.setColour (juce::Label::textColourId, theme::colour::warning);
  452. load.setText ({}, juce::dontSendNotification);
  453. return;
  454. }
  455. const auto rate = device->getCurrentSampleRate();
  456. const auto latency = prefs::bufferLatencyMs (device->getOutputLatencyInSamples() + device->getCurrentBufferSizeSamples(), rate);
  457. status.setText (tr ("{0} is running: {1} Hz, output latency {2} ms",
  458. { device->getName(), juce::String ((int) rate), juce::String (latency, 1) }),
  459. juce::dontSendNotification);
  460. status.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  461. const auto xruns = device->getXRunCount();
  462. const auto rt = engine.getRtStats().snapshot();
  463. const auto dot = juce::String::fromUTF8 (" \xc2\xb7 ");
  464. load.setText (tr ("Audio CPU load: {0}%", { juce::String (juce::roundToInt (devices.getCpuUsage() * 100.0)) })
  465. + (xruns > 0 ? dot + tr ("{0} dropouts (buffer underruns) so far", { juce::String (xruns) }) : juce::String())
  466. + (rt.overBudget > 0 ? dot + tr ("{0} blocks over the deadline (max {1}%)", { juce::String ((juce::int64) rt.overBudget), juce::String (juce::roundToInt (rt.maxLoad * 100.0)) })
  467. : juce::String()),
  468. juce::dontSendNotification);
  469. load.setColour (juce::Label::textColourId, xruns > 0 || rt.overBudget > 0 ? theme::colour::warning : theme::colour::textSecondary);
  470. }
  471. void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
  472. void timerCallback() override { updateStatus(); }
  473. // The driver types with what they mean (JUCE's type names stay the identity in the saved setup).
  474. static juce::String driverDisplayName (const juce::String& typeName)
  475. {
  476. switch (prefs::driverKind (typeName.toStdString()))
  477. {
  478. case prefs::DriverKind::wasapiShared: return tr ("Windows Audio (shared)");
  479. case prefs::DriverKind::wasapiLowLatency: return tr ("Windows Audio (shared, low-latency period)");
  480. case prefs::DriverKind::wasapiExclusive: return tr ("Windows Audio (exclusive, lowest latency)");
  481. case prefs::DriverKind::directSound: return tr ("DirectSound (legacy)");
  482. case prefs::DriverKind::asio: return "ASIO";
  483. case prefs::DriverKind::lynxAsio: return tr ("LYNX ASIO (built in)");
  484. case prefs::DriverKind::coreAudio: return "Core Audio";
  485. case prefs::DriverKind::alsa: return "ALSA";
  486. case prefs::DriverKind::jack: return tr ("JACK / PipeWire");
  487. case prefs::DriverKind::other: break;
  488. }
  489. return typeName;
  490. }
  491. // What the selected driver type does, and for shared mode the period this device mixes at (REA round 97).
  492. static juce::String driverExplanation (const juce::String& typeName, juce::AudioIODevice* device)
  493. {
  494. const auto rate = device != nullptr && device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate() : 48000.0;
  495. const auto period = device != nullptr ? device->getDefaultBufferSize() : 0;
  496. switch (prefs::driverKind (typeName.toStdString()))
  497. {
  498. case prefs::DriverKind::wasapiShared:
  499. return tr ("Other programs keep their sound. Windows mixes every program in steps of {0} ms on this device, so the buffer cannot go below that. "
  500. "For lower latency choose the exclusive mode or an ASIO driver.",
  501. { juce::String (prefs::bufferLatencyMs (period > 0 ? period : 480, rate), 1) });
  502. case prefs::DriverKind::wasapiLowLatency:
  503. return period > 0 && device != nullptr && device->getAvailableBufferSizes().size() <= 1
  504. ? tr ("This device does not support a shorter period in shared mode (it stays at {0} ms). Use the exclusive mode or an ASIO driver for lower latency.",
  505. { juce::String (prefs::bufferLatencyMs (period, rate), 1) })
  506. : tr ("Shared like the normal mode, but asks Windows for a shorter mixing period. Only some drivers support it.");
  507. case prefs::DriverKind::wasapiExclusive:
  508. return tr ("LYNX uses the device alone: the lowest latency without ASIO, but other programs go silent while LYNX plays.");
  509. case prefs::DriverKind::directSound:
  510. return tr ("Old Windows audio path with high latency. Use it only when the others fail.");
  511. case prefs::DriverKind::asio:
  512. return tr ("Low-latency drivers. LYNX ASIO, FL Studio ASIO and ASIO4ALL work with any device; a manufacturer's ASIO driver works with its own device.");
  513. case prefs::DriverKind::lynxAsio:
  514. return tr ("LYNX's own ASIO driver, with any device: playback and recording (microphone) at low latency. \"Driver settings...\" chooses shared or exclusive mode, the output and input devices and shows the latency. "
  515. "For other programs, run \"Register LYNX ASIO\" in LYNX's folder once.");
  516. case prefs::DriverKind::coreAudio:
  517. return tr ("macOS's own audio system: low latency with any device, shared with other programs.");
  518. case prefs::DriverKind::alsa:
  519. return tr ("Talks to the sound card directly. Choose \"default\" or \"pipewire\" to share the device with other programs; a \"hw:\" device gives the lowest latency but takes the card for LYNX alone.");
  520. case prefs::DriverKind::jack:
  521. return tr ("Low latency, shared with other programs and routable. On current distributions PipeWire answers as JACK (package pipewire-jack); otherwise start a JACK server first.");
  522. case prefs::DriverKind::other:
  523. break;
  524. }
  525. return {};
  526. }
  527. AudioEngine& engine;
  528. juce::AudioDeviceManager& devices;
  529. bool updating = false;
  530. juce::String error;
  531. SectionTitle deviceTitle { tr ("Audio device") }, statusTitle { tr ("Status") }, recordTitle { tr ("Recording") };
  532. juce::Label driverLabel, driverNote, outputLabel, inputLabel, rateLabel, bufferLabel, bufferNote, status, load, recordNote, inputChannels;
  533. juce::ComboBox driverBox, outputBox, inputBox, rateBox, bufferBox;
  534. juce::TextButton panelButton { tr ("Driver settings...") }, testButton { tr ("Play a test sound") };
  535. juce::ToggleButton recordInput;
  536. };
  537. // ================================================================================================================
  538. // MIDI
  539. // ================================================================================================================
  540. // One input device: on/off, which MIDI channel it listens to and what it plays.
  541. class MidiInputRow final : public juce::Component
  542. {
  543. public:
  544. MidiInputRow (const juce::String& deviceName, const prefs::MidiInputPrefs& p, const std::vector<std::string>& channels,
  545. std::function<void (const prefs::MidiInputPrefs&)> changed)
  546. : prefsNow (p), onChange (std::move (changed))
  547. {
  548. enabled.setButtonText (deviceName);
  549. enabled.setToggleState (p.enabled, juce::dontSendNotification);
  550. enabled.onClick = [this] {
  551. prefsNow.enabled = enabled.getToggleState();
  552. update();
  553. };
  554. addAndMakeVisible (enabled);
  555. channel.addItem (tr ("Any MIDI channel"), 1);
  556. for (int c = 1; c <= 16; ++c)
  557. channel.addItem (tr ("MIDI channel {0}", { juce::String (c) }), c + 1);
  558. channel.setSelectedId (p.midiChannel + 1, juce::dontSendNotification);
  559. channel.onChange = [this] {
  560. prefsNow.midiChannel = channel.getSelectedId() - 1;
  561. update();
  562. };
  563. plays.addItem (tr ("Plays the selected channels"), 1);
  564. for (int i = 0; i < (int) channels.size(); ++i)
  565. plays.addItem (tr ("Plays {0}", { juce::String (i + 1) + " " + juce::String::fromUTF8 (channels[(std::size_t) i].c_str()) }), i + 2);
  566. if (p.target >= (int) channels.size()) // a channel this project doesn't have (kept)
  567. plays.addItem (tr ("Plays channel {0}", { juce::String (p.target + 1) }), p.target + 2);
  568. plays.setSelectedId (p.target + 2, juce::dontSendNotification);
  569. plays.onChange = [this] {
  570. prefsNow.target = plays.getSelectedId() - 2;
  571. update();
  572. };
  573. for (auto* b : { &channel, &plays })
  574. {
  575. styleCombo (*b);
  576. addAndMakeVisible (b);
  577. }
  578. update (false);
  579. }
  580. void resized() override
  581. {
  582. auto r = getLocalBounds().reduced (8, 4);
  583. plays.setBounds (r.removeFromRight (230));
  584. r.removeFromRight (8);
  585. channel.setBounds (r.removeFromRight (150));
  586. r.removeFromRight (8);
  587. enabled.setBounds (r);
  588. }
  589. void paint (juce::Graphics& g) override
  590. {
  591. g.setColour (theme::colour::bg1);
  592. g.fillRoundedRectangle (getLocalBounds().toFloat(), theme::radius::md);
  593. }
  594. private:
  595. void update (bool notify = true)
  596. {
  597. channel.setEnabled (prefsNow.enabled);
  598. plays.setEnabled (prefsNow.enabled);
  599. if (notify && onChange)
  600. onChange (prefsNow);
  601. }
  602. prefs::MidiInputPrefs prefsNow;
  603. std::function<void (const prefs::MidiInputPrefs&)> onChange;
  604. juce::ToggleButton enabled;
  605. juce::ComboBox channel, plays;
  606. };
  607. class MidiPage final : public ScrollingPage,
  608. private juce::ChangeListener,
  609. private juce::ListBoxModel
  610. {
  611. public:
  612. MidiPage (AudioEngine& e, SettingsHooks h, bool keep) : engine (e), hooks (std::move (h)), persistent (keep)
  613. {
  614. for (auto* c : std::initializer_list<juce::Component*> { &inputsTitle, &notesTitle, &controllersTitle, &inputsNote, &refresh, &noDevices,
  615. &velocityLabel, &velocityBox, &velocityNote, &typeLabel, &typeValue, &pickup,
  616. &pickupNote, &linksLabel, &links, &removeLink, &removeAll })
  617. add (*c);
  618. styleNote (inputsNote, tr ("Each input device can be turned off, listen to one MIDI channel only and play a fixed channel of the "
  619. "Channel Rack instead of the selected ones."));
  620. styleLabel (noDevices, tr ("No MIDI input devices found. Connect one and refresh the list."));
  621. refresh.onClick = [this] { rebuildInputs(); };
  622. styleLabel (velocityLabel, tr ("Velocity"));
  623. velocityBox.addItem (tr ("As played"), 1);
  624. velocityBox.addItem (tr ("Soft (light playing sounds louder)"), 2);
  625. velocityBox.addItem (tr ("Hard (needs harder playing)"), 3);
  626. velocityBox.addItem (tr ("Fixed (every note at full velocity)"), 4);
  627. velocityBox.onChange = [this] {
  628. auto p = engine.getMidiPrefs();
  629. p.velocity = (prefs::VelocityCurve) (velocityBox.getSelectedId() - 1);
  630. set (p);
  631. };
  632. styleCombo (velocityBox);
  633. styleNote (velocityNote, tr ("For notes from MIDI devices (the typing keyboard always plays at the Piano Roll's velocity)."));
  634. styleLabel (typeLabel, tr ("Controller type"));
  635. typeLabel.setJustificationType (juce::Justification::topLeft);
  636. styleLabel (typeValue, tr ("Generic controller: link a knob or fader with a control's right-click menu > Link to MIDI controller."), false);
  637. typeValue.setMinimumHorizontalScale (1.0f);
  638. typeValue.setJustificationType (juce::Justification::topLeft);
  639. styleToggle (pickup, tr ("Pickup (takeover mode)"));
  640. pickup.onClick = [this] {
  641. auto p = engine.getMidiPrefs();
  642. p.pickup = pickup.getToggleState();
  643. set (p);
  644. };
  645. styleNote (pickupNote, tr ("A controller moves a parameter only after reaching its current value, so nothing jumps."));
  646. styleLabel (linksLabel, tr ("Links in this project"));
  647. linksLabel.setJustificationType (juce::Justification::topLeft);
  648. links.setModel (this);
  649. links.setRowHeight (24);
  650. links.setColour (juce::ListBox::backgroundColourId, theme::colour::bg0);
  651. links.setColour (juce::ListBox::outlineColourId, theme::colour::border);
  652. links.setOutlineThickness (1);
  653. removeLink.onClick = [this] {
  654. const auto row = links.getSelectedRow();
  655. if (juce::isPositiveAndBelow (row, (int) engine.getSong().midiLinks.size()))
  656. engine.editSong ([row] (Song& s) { s.midiLinks.erase (s.midiLinks.begin() + row); });
  657. };
  658. removeAll.onClick = [this] { engine.editSong ([] (Song& s) { s.midiLinks.clear(); }); };
  659. if (! persistent)
  660. {
  661. // --snapshot: devices of a typical setup, and two links
  662. sampleDevices = { "Arturia KeyLab 49", "Akai MPD218" };
  663. engine.editSong ([] (Song& s) {
  664. AutomationTarget volume;
  665. volume.kind = AutomationTargetKind::mixerVolume;
  666. volume.index = 0;
  667. AutomationTarget pan;
  668. pan.kind = AutomationTargetKind::channelPan;
  669. pan.index = 0;
  670. s.midiLinks = { { 7, -1, volume }, { 10, 0, pan } };
  671. }, false);
  672. }
  673. engine.addChangeListener (this);
  674. rebuildInputs();
  675. load();
  676. }
  677. ~MidiPage() override { engine.removeChangeListener (this); }
  678. private:
  679. int layout (int width) override
  680. {
  681. Rows r (width);
  682. r.section (inputsTitle, true);
  683. inputsNote.setBounds (r.full (32).translated (0, -4));
  684. if (rows.empty())
  685. noDevices.setBounds (r.full (24));
  686. for (auto& row : rows)
  687. row->setBounds (r.full (34).translated (0, -4));
  688. refresh.setBounds (r.full().removeFromLeft (150));
  689. r.section (notesTitle);
  690. velocityBox.setBounds (r.row (velocityLabel, 300));
  691. velocityNote.setBounds (r.indented (16).translated (0, -6));
  692. r.section (controllersTitle);
  693. {
  694. auto row = r.row (typeLabel, 0, 36);
  695. typeLabel.setBounds (typeLabel.getBounds().withTrimmedTop (6));
  696. typeValue.setBounds (row.withTrimmedTop (6));
  697. }
  698. pickup.setBounds (r.full (24));
  699. pickupNote.setBounds (r.full (16).translated (0, -6));
  700. {
  701. auto row = r.row (linksLabel, 0, 110);
  702. linksLabel.setBounds (linksLabel.getBounds().withTrimmedTop (4));
  703. auto buttons = row.removeFromRight (120);
  704. row.removeFromRight (8);
  705. links.setBounds (row);
  706. removeLink.setBounds (buttons.removeFromTop (26));
  707. buttons.removeFromTop (6);
  708. removeAll.setBounds (buttons.removeFromTop (26));
  709. }
  710. return r.bottom();
  711. }
  712. void set (const prefs::MidiPrefs& p)
  713. {
  714. if (loading)
  715. return;
  716. engine.setMidiPrefs (p, persistent);
  717. if (hooks.midiChanged)
  718. hooks.midiChanged();
  719. }
  720. void load()
  721. {
  722. const juce::ScopedValueSetter<bool> guard (loading, true);
  723. const auto& p = engine.getMidiPrefs();
  724. velocityBox.setSelectedId ((int) p.velocity + 1, juce::dontSendNotification);
  725. pickup.setToggleState (p.pickup, juce::dontSendNotification);
  726. links.updateContent();
  727. links.repaint();
  728. removeLink.setEnabled (links.getSelectedRow() >= 0);
  729. removeAll.setEnabled (! engine.getSong().midiLinks.empty());
  730. }
  731. void rebuildInputs()
  732. {
  733. rows.clear();
  734. juce::StringArray names;
  735. if (persistent)
  736. for (const auto& d : juce::MidiInput::getAvailableDevices())
  737. names.add (d.name);
  738. else
  739. names = sampleDevices;
  740. std::vector<std::string> channels;
  741. for (const auto& c : engine.getSong().channels)
  742. channels.push_back (c.name);
  743. for (const auto& name : names)
  744. {
  745. auto row = std::make_unique<MidiInputRow> (name, engine.getMidiPrefs().input (name.toStdString()), channels,
  746. [this] (const prefs::MidiInputPrefs& in) {
  747. auto p = engine.getMidiPrefs();
  748. p.setInput (in);
  749. set (p);
  750. });
  751. add (*row);
  752. rows.push_back (std::move (row));
  753. }
  754. noDevices.setVisible (rows.empty());
  755. resized();
  756. }
  757. // links list
  758. int getNumRows() override { return juce::jmax (1, (int) engine.getSong().midiLinks.size()); }
  759. void paintListBoxItem (int row, juce::Graphics& g, int width, int height, bool selected) override
  760. {
  761. const auto& list = engine.getSong().midiLinks;
  762. if (list.empty())
  763. {
  764. g.setFont (theme::font (theme::type::small));
  765. g.setColour (theme::colour::textDisabled);
  766. g.drawText (tr ("(none yet)"), 10, 0, width - 20, height, juce::Justification::centredLeft);
  767. return;
  768. }
  769. if (selected)
  770. {
  771. g.setColour (theme::colour::accentMuted);
  772. g.fillRect (0, 0, width, height);
  773. }
  774. const auto& link = list[(std::size_t) row];
  775. g.setFont (theme::font (theme::type::body));
  776. g.setColour (theme::colour::info);
  777. const auto source = "CC " + juce::String (link.cc) + (link.channel >= 0 ? juce::String::fromUTF8 (" \xc2\xb7 ") + tr ("ch. {0}", { juce::String (link.channel + 1) }) : juce::String());
  778. g.drawText (source, 10, 0, 110, height, juce::Justification::centredLeft);
  779. g.setColour (theme::colour::textPrimary);
  780. g.drawText (describeAutomationTarget (engine, link.target), 124, 0, width - 134, height, juce::Justification::centredLeft, true);
  781. }
  782. void selectedRowsChanged (int) override { removeLink.setEnabled (links.getSelectedRow() >= 0 && ! engine.getSong().midiLinks.empty()); }
  783. void changeListenerCallback (juce::ChangeBroadcaster*) override
  784. {
  785. if (engine.getSong().channels.size() != channelCount)
  786. {
  787. channelCount = engine.getSong().channels.size();
  788. rebuildInputs();
  789. }
  790. load();
  791. }
  792. AudioEngine& engine;
  793. SettingsHooks hooks;
  794. bool persistent;
  795. bool loading = false;
  796. std::size_t channelCount = 0;
  797. juce::StringArray sampleDevices;
  798. std::vector<std::unique_ptr<MidiInputRow>> rows;
  799. SectionTitle inputsTitle { tr ("Input devices") }, notesTitle { tr ("Notes") }, controllersTitle { tr ("Controllers") };
  800. juce::Label inputsNote, noDevices, velocityLabel, velocityNote, typeLabel, typeValue, pickupNote, linksLabel;
  801. juce::TextButton refresh { tr ("Refresh device list") }, removeLink { tr ("Remove link") }, removeAll { tr ("Remove all") };
  802. juce::ComboBox velocityBox;
  803. juce::ToggleButton pickup;
  804. juce::ListBox links;
  805. };
  806. } // namespace
  807. std::unique_ptr<juce::Component> makeGeneralPage (AudioEngine& engine, const SettingsHooks& hooks, bool persistent)
  808. {
  809. return std::make_unique<GeneralPage> (engine, hooks, persistent);
  810. }
  811. std::unique_ptr<juce::Component> makeAudioPage (AudioEngine& engine, bool persistent)
  812. {
  813. juce::ignoreUnused (persistent);
  814. return std::make_unique<AudioPage> (engine);
  815. }
  816. std::unique_ptr<juce::Component> makeMidiPage (AudioEngine& engine, const SettingsHooks& hooks, bool persistent)
  817. {
  818. return std::make_unique<MidiPage> (engine, hooks, persistent);
  819. }
  820. } // namespace lynx