SoundFontEditor.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. #include "ui/SoundFontEditor.h"
  2. #include <algorithm>
  3. #include <atomic>
  4. #include <thread>
  5. #include "core/SoundFont.h"
  6. #include "ui/ExternalDrag.h"
  7. #include "core/SoundFontIndex.h"
  8. #include "engine/PluginHost.h"
  9. #include "core/SearchQuery.h"
  10. #include "ui/FileChoosers.h"
  11. #include "ui/HintBar.h"
  12. #include "ui/I18n.h"
  13. #include "ui/PluginSkin.h"
  14. #include "ui/Theme.h"
  15. #include "ui/ValueControl.h"
  16. namespace lynx
  17. {
  18. namespace
  19. {
  20. constexpr const char* dragPrefix = "lynx-sf-preset|";
  21. juce::String u8 (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); }
  22. std::string std8 (const juce::String& s) { return s.toStdString(); }
  23. // a parameter's shown value, translated (the numbers kept)
  24. juce::String shownValue (int index, float v)
  25. {
  26. if (index == sf::pPolyphony)
  27. return tr ("{0} voices", { juce::String ((int) v) });
  28. if ((index == sf::pReverbTrack || index == sf::pChorusTrack) && v >= 1.0f)
  29. return tr ("Insert {0}", { juce::String ((int) v) });
  30. return tr (u8 (sf::displayValue (index, v)));
  31. }
  32. // a preset category, translated ("Bass" is the EQ band in the shared table: the instrument family is "Baixo")
  33. juce::String categoryText (const std::string& c)
  34. {
  35. if (c == "Bass")
  36. return i18n::current() == "en" ? juce::String ("Bass") : tr ("Bass guitar");
  37. return tr (u8 (c));
  38. }
  39. // round 170j: the page has art of its own ("a sound library", ui/PluginArtGenerators.inc): Themed unless a style is forced
  40. skin::Style pageStyle() { return skin::resolve (skin::Style::themed, skin::Art::soundFont); }
  41. juce::Colour accentColour() // (sampler-like generators: azure; the art's own light when Themed)
  42. {
  43. return pageStyle() == skin::Style::themed ? skin::artAccent (skin::Art::soundFont) : skin::colour::azure;
  44. }
  45. // every part of the page paints in the page's style (the knobs, toggles and selectors are child components)
  46. struct PageScope
  47. {
  48. skin::StyleScope scope { pageStyle(), skin::Art::soundFont };
  49. };
  50. // What the editor edits: a Channel Rack channel, or a LYNX Soundfont node inside a Patcher (round 165c: found through
  51. // `locate`, channel −1 — no automation target, the preview note is rendered off-line instead of played on a channel)
  52. struct SfTarget
  53. {
  54. std::function<ChannelDef* (Song&)> locate;
  55. int channel = -1;
  56. static SfTarget rack (int c)
  57. {
  58. return { [c] (Song& s) -> ChannelDef* { return c >= 0 && c < (int) s.channels.size() ? &s.channels[(std::size_t) c] : nullptr; }, c };
  59. }
  60. };
  61. const ChannelDef* channelOf (AudioEngine& engine, const SfTarget& target)
  62. {
  63. const auto* c = target.locate ? target.locate (const_cast<Song&> (engine.getSong())) : nullptr;
  64. return c != nullptr && c->instrument == InstrumentKind::soundfont ? c : nullptr;
  65. }
  66. float paramOf (AudioEngine& engine, const SfTarget& target, int index)
  67. {
  68. if (const auto* c = channelOf (engine, target))
  69. return sf::readParams (c->modelParams)[(std::size_t) index];
  70. return sf::paramInfo (index).def;
  71. }
  72. void editTarget (AudioEngine& engine, const SfTarget& target, std::function<void (ChannelDef&)> change, bool undoable = true)
  73. {
  74. engine.editSong ([locate = target.locate, change = std::move (change)] (Song& s) {
  75. auto* c = locate ? locate (s) : nullptr;
  76. if (c != nullptr && c->instrument == InstrumentKind::soundfont)
  77. change (*c);
  78. }, undoable);
  79. }
  80. void setParam (AudioEngine& engine, const SfTarget& target, int index, float value, bool undoable = true)
  81. {
  82. editTarget (engine, target, [index, value] (ChannelDef& c) {
  83. auto params = sf::readParams (c.modelParams);
  84. params[(std::size_t) index] = value;
  85. c.modelParams.assign (params.begin(), params.end());
  86. }, undoable);
  87. }
  88. void loadInto (AudioEngine& engine, const SfTarget& target, const std::string& path, int bank, int program)
  89. {
  90. editTarget (engine, target, [path, bank, program] (ChannelDef& c) {
  91. c.samplePath = path;
  92. auto params = sf::readParams (c.modelParams);
  93. params[sf::pBank] = (float) juce::jlimit (0, 128, bank);
  94. params[sf::pProgram] = (float) juce::jlimit (0, 127, program);
  95. c.modelParams.assign (params.begin(), params.end());
  96. });
  97. }
  98. ui::ValueSpec specFor (const SfTarget& target, int index, const juce::String& channelName)
  99. {
  100. const auto& info = sf::paramInfo (index);
  101. ui::ValueSpec spec;
  102. spec.name = channelName + " - " + tr (info.name);
  103. spec.minimum = info.min;
  104. spec.maximum = info.max;
  105. spec.defaultValue = info.def;
  106. spec.interval = info.integer ? 1.0 : 0.0;
  107. spec.pixelsForRange = info.integer ? juce::jlimit (60.0, 300.0, 6.0 * (info.max - info.min)) : 150.0;
  108. spec.toText = [index] (double v) { return shownValue (index, (float) v); };
  109. spec.fromText = ui::inverseOf (spec.toText, info.min, info.max);
  110. if (target.channel >= 0 && sf::automatable (index))
  111. spec.target = AutomationTarget { AutomationTargetKind::channelParam, target.channel, 0, index };
  112. return spec;
  113. }
  114. juce::String channelLabel (AudioEngine& engine, const SfTarget& target)
  115. {
  116. if (const auto* c = channelOf (engine, target); c != nullptr && ! c->name.empty())
  117. return u8 (c->name);
  118. return "LYNX Soundfont";
  119. }
  120. // --- controls ----------------------------------------------------------------------------------------------------------
  121. // A knob of one parameter, drawn with the plugin skin; LYNX's control contract (drag, wheel, reset, value menu)
  122. class SfKnob final : public juce::Component, public ui::HintSource
  123. {
  124. public:
  125. SfKnob (AudioEngine& e, SfTarget c, int p, juce::String caption) : engine (e), channel (c), param (p), label (std::move (caption))
  126. {
  127. setRepaintsOnMouseActivity (true);
  128. }
  129. ui::ValueSpec spec() const { return specFor (channel, param, channelLabel (engine, channel)); }
  130. // the Song's value, or (issue #152) the automation's while the song plays it, as the Sampler's knobs show
  131. double value() const
  132. {
  133. if (channel.channel >= 0 && sf::automatable (param))
  134. if (const auto v = engine.getAutomationDisplay().valueOf ({ AutomationTargetKind::channelParam, channel.channel, 0, param }))
  135. return sf::denormalise (param, *v);
  136. return paramOf (engine, channel, param);
  137. }
  138. void set (double v) { setParam (engine, channel, param, (float) v); repaint(); }
  139. ui::Hint hintAt (juce::Point<int>) override { return ui::valueHint (spec(), value(), ui::valueGestures()); }
  140. void paint (juce::Graphics& g) override
  141. {
  142. const PageScope pageScope;
  143. const auto s = spec();
  144. auto area = getLocalBounds().toFloat();
  145. const auto caption = area.removeFromBottom (13.0f);
  146. const auto valueArea = area.removeFromBottom (12.0f);
  147. const auto size = juce::jmin (area.getWidth(), area.getHeight());
  148. skin::KnobLook look;
  149. look.value = (float) juce::jlimit (0.0, 1.0, (value() - s.minimum) / juce::jmax (1e-9, s.maximum - s.minimum));
  150. look.bipolar = param == sf::pLfoAmount && value() > 0.0;
  151. look.accent = accentColour();
  152. look.hover = isMouseOver() ? 1.0f : 0.0f;
  153. look.active = drag.isActive();
  154. skin::knob (g, juce::Rectangle<float> (size, size).withCentre (area.getCentre()), look);
  155. g.setFont (theme::font (10.0f));
  156. g.setColour (skin::valueColour (isMouseOverOrDragging()));
  157. g.drawFittedText (s.text (value()), valueArea.toNearestInt(), juce::Justification::centred, 1, 0.7f);
  158. g.setColour (skin::captionColour());
  159. g.setFont (theme::font (9.5f, true));
  160. g.drawFittedText (theme::caps (label), caption.toNearestInt(), juce::Justification::centred, 1, 0.7f);
  161. }
  162. void mouseDown (const juce::MouseEvent& e) override
  163. {
  164. if (e.mods.isPopupMenu())
  165. {
  166. ui::showValueMenu (*this, &engine, spec(), value(), [this] (double v) { set (v); });
  167. return;
  168. }
  169. if (ui::isResetClick (e))
  170. {
  171. set (spec().defaultValue);
  172. return;
  173. }
  174. drag.begin (e, value());
  175. }
  176. void mouseDrag (const juce::MouseEvent& e) override
  177. {
  178. if (! drag.isActive())
  179. return;
  180. const auto s = spec();
  181. set (drag.update (e, s));
  182. ui::reportTweak (s);
  183. ui::showValueTip (*this, getLocalBounds(), s.text (value()));
  184. }
  185. void mouseUp (const juce::MouseEvent&) override
  186. {
  187. drag.end();
  188. ui::hideValueTip();
  189. }
  190. void mouseDoubleClick (const juce::MouseEvent&) override { set (spec().defaultValue); }
  191. void mouseWheelMove (const juce::MouseEvent& e, const juce::MouseWheelDetails& w) override
  192. {
  193. if (const auto v = ui::wheelValue (value(), e, w, spec()))
  194. {
  195. set (*v);
  196. ui::flashValueTip (*this, getLocalBounds(), spec().text (value()));
  197. }
  198. }
  199. private:
  200. AudioEngine& engine;
  201. SfTarget channel;
  202. int param;
  203. juce::String label;
  204. ui::ValueDrag drag;
  205. };
  206. // An on / off switch of one parameter
  207. class SfToggle final : public juce::Component, public juce::SettableTooltipClient
  208. {
  209. public:
  210. SfToggle (AudioEngine& e, SfTarget c, int p, juce::String caption, juce::String tip) : engine (e), channel (c), param (p), label (std::move (caption))
  211. {
  212. setTooltip (tip);
  213. setRepaintsOnMouseActivity (true);
  214. }
  215. void paint (juce::Graphics& g) override
  216. {
  217. const PageScope pageScope;
  218. const auto on = paramOf (engine, channel, param) >= 0.5f;
  219. auto r = getLocalBounds().toFloat();
  220. skin::switchPill (g, r.removeFromLeft (26.0f).withSizeKeepingCentre (24.0f, 13.0f), on, accentColour(), true);
  221. r.removeFromLeft (5.0f);
  222. g.setColour (on ? theme::colour::textPrimary : theme::colour::textSecondary);
  223. g.setFont (theme::font (11.0f));
  224. g.drawFittedText (label, r.toNearestInt(), juce::Justification::centredLeft, 1, 0.7f);
  225. }
  226. void mouseDown (const juce::MouseEvent&) override
  227. {
  228. setParam (engine, channel, param, paramOf (engine, channel, param) >= 0.5f ? 0.0f : 1.0f);
  229. repaint();
  230. }
  231. private:
  232. AudioEngine& engine;
  233. SfTarget channel;
  234. int param;
  235. juce::String label;
  236. };
  237. // A selector of one integer parameter (a menu of its values)
  238. class SfChoice final : public juce::Component, public juce::SettableTooltipClient
  239. {
  240. public:
  241. SfChoice (AudioEngine& e, SfTarget c, int p, juce::String caption, std::function<juce::PopupMenu (std::function<void (int)>)> custom = {})
  242. : engine (e), channel (c), param (p), label (std::move (caption)), customMenu (std::move (custom))
  243. {
  244. setRepaintsOnMouseActivity (true);
  245. }
  246. void paint (juce::Graphics& g) override
  247. {
  248. const PageScope pageScope;
  249. auto r = getLocalBounds().toFloat();
  250. const auto cap = r.removeFromTop (12.0f);
  251. g.setColour (skin::captionColour());
  252. g.setFont (theme::font (9.5f, true));
  253. g.drawFittedText (theme::caps (label), cap.toNearestInt(), juce::Justification::centredLeft, 1, 0.7f);
  254. skin::selector (g, r.reduced (0.0f, 1.0f), isMouseOver());
  255. g.setColour (theme::colour::textPrimary);
  256. g.setFont (theme::font (11.0f));
  257. g.drawFittedText (shownValue (param, paramOf (engine, channel, param)) + juce::String::fromUTF8 (" \xe2\x96\xbe"),
  258. r.reduced (6.0f, 0.0f).toNearestInt(), juce::Justification::centredLeft, 1, 0.7f);
  259. }
  260. void mouseDown (const juce::MouseEvent&) override
  261. {
  262. const auto pick = [this] (int v) {
  263. setParam (engine, channel, param, (float) v);
  264. repaint();
  265. };
  266. juce::PopupMenu menu;
  267. if (customMenu)
  268. menu = customMenu (pick);
  269. else
  270. {
  271. const auto& info = sf::paramInfo (param);
  272. const auto current = (int) paramOf (engine, channel, param);
  273. for (int v = (int) info.min; v <= (int) info.max; ++v)
  274. menu.addItem (shownValue (param, (float) v), true, v == current, [pick, v] { pick (v); });
  275. }
  276. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this));
  277. }
  278. private:
  279. AudioEngine& engine;
  280. SfTarget channel;
  281. int param;
  282. juce::String label;
  283. std::function<juce::PopupMenu (std::function<void (int)>)> customMenu;
  284. };
  285. // --- the preset lists --------------------------------------------------------------------------------------------------
  286. struct Row
  287. {
  288. std::string path, font, name, category;
  289. int bank = 0, program = 0;
  290. };
  291. class PresetList final : public juce::ListBox, private juce::ListBoxModel
  292. {
  293. public:
  294. std::function<void (const Row&)> onPreview, onLoad;
  295. std::function<void (const Row&)> onMenu;
  296. bool showFont = false;
  297. PresetList()
  298. {
  299. setModel (this);
  300. setRowHeight (20);
  301. setColour (juce::ListBox::backgroundColourId, skin::colour::wellTop);
  302. setColour (juce::ListBox::outlineColourId, theme::colour::border);
  303. setOutlineThickness (1);
  304. setMultipleSelectionEnabled (false);
  305. }
  306. void setRows (std::vector<Row> r, const std::string& currentPath, int bank, int program)
  307. {
  308. rows = std::move (r);
  309. updateContent();
  310. int select = -1;
  311. for (std::size_t i = 0; i < rows.size(); ++i)
  312. if (rows[i].path == currentPath && rows[i].bank == bank && rows[i].program == program)
  313. select = (int) i;
  314. if (select >= 0)
  315. selectRow (select, true, true);
  316. else
  317. deselectAllRows();
  318. repaint();
  319. }
  320. const std::vector<Row>& all() const { return rows; }
  321. int rowCount() const { return (int) rows.size(); }
  322. private:
  323. // issue #182: typing jumps to the preset whose name starts with it (JUCE fix 37 reads the names)
  324. juce::String getNameForRow (int row) override
  325. {
  326. return juce::isPositiveAndBelow (row, (int) rows.size()) ? juce::String::fromUTF8 (rows[(std::size_t) row].name.c_str()) : juce::String();
  327. }
  328. int getNumRows() override { return (int) rows.size(); }
  329. void paintListBoxItem (int row, juce::Graphics& g, int width, int height, bool selected) override
  330. {
  331. if (row < 0 || row >= (int) rows.size())
  332. return;
  333. const auto& r = rows[(std::size_t) row];
  334. if (selected)
  335. g.fillAll (accentColour().withAlpha (0.28f));
  336. else if (row % 2 == 1)
  337. g.fillAll (juce::Colours::white.withAlpha (0.02f));
  338. auto area = juce::Rectangle<int> (0, 0, width, height).reduced (6, 0);
  339. g.setFont (theme::monoFont (11.0f));
  340. g.setColour (theme::colour::textSecondary);
  341. g.drawText (juce::String::formatted ("%03d:%03d", r.bank, r.program), area.removeFromLeft (58), juce::Justification::centredLeft, false);
  342. const auto catWidth = juce::jmin (110, width / 4);
  343. auto cat = area.removeFromRight (catWidth);
  344. g.setFont (theme::font (10.5f));
  345. g.setColour (theme::colour::textDisabled);
  346. g.drawFittedText (categoryText (r.category), cat, juce::Justification::centredRight, 1, 0.7f);
  347. g.setColour (selected ? theme::colour::textPrimary : skin::valueColour (false));
  348. g.setFont (theme::font (12.0f));
  349. if (showFont)
  350. {
  351. const auto nameWidth = area.getWidth() * 3 / 5;
  352. g.drawFittedText (u8 (r.name), area.removeFromLeft (nameWidth), juce::Justification::centredLeft, 1, 0.75f);
  353. g.setColour (theme::colour::textDisabled);
  354. g.setFont (theme::font (10.5f));
  355. g.drawFittedText (u8 (r.font), area.reduced (4, 0), juce::Justification::centredLeft, 1, 0.7f);
  356. }
  357. else
  358. g.drawFittedText (u8 (r.name), area, juce::Justification::centredLeft, 1, 0.75f);
  359. }
  360. void listBoxItemClicked (int row, const juce::MouseEvent& e) override
  361. {
  362. if (row < 0 || row >= (int) rows.size())
  363. return;
  364. if (e.mods.isPopupMenu())
  365. {
  366. if (onMenu)
  367. onMenu (rows[(std::size_t) row]);
  368. return;
  369. }
  370. if (onPreview)
  371. onPreview (rows[(std::size_t) row]);
  372. }
  373. void load (int row)
  374. {
  375. if (row >= 0 && row < (int) rows.size() && onLoad)
  376. onLoad (rows[(std::size_t) row]);
  377. }
  378. void listBoxItemDoubleClicked (int row, const juce::MouseEvent&) override { load (row); }
  379. void returnKeyPressed (int row) override { load (row); }
  380. juce::var getDragSourceDescription (const juce::SparseSet<int>& selected) override
  381. {
  382. if (selected.size() == 0 || selected[0] >= (int) rows.size())
  383. return {};
  384. const auto& r = rows[(std::size_t) selected[0]];
  385. return soundFontDragDescription (r.path, r.bank, r.program);
  386. }
  387. juce::String getTooltipForRow (int row) override
  388. {
  389. if (row < 0 || row >= (int) rows.size())
  390. return {};
  391. const auto& r = rows[(std::size_t) row];
  392. return u8 (r.name) + " (" + u8 (r.font) + ", " + juce::String (r.bank) + ":" + juce::String (r.program) + ")\n"
  393. + tr ("Click: preview. Double-click: load into this channel. Drag onto the Channel rack: a new channel.");
  394. }
  395. std::vector<Row> rows;
  396. };
  397. // --- the editor ----------------------------------------------------------------------------------------------------
  398. class SoundFontEditor final : public juce::Component,
  399. public juce::DragAndDropContainer,
  400. private juce::ChangeListener,
  401. private juce::Timer
  402. {
  403. public:
  404. // issue #174: Edison's drag button may start its drag from this container (the first one it finds): its sample goes
  405. // on as a file drag over a plugin's editor or out of LYNX
  406. bool shouldDropFilesWhenDraggedExternally (const juce::DragAndDropTarget::SourceDetails& details, juce::StringArray& files,
  407. bool& canMoveFiles) override
  408. {
  409. return externaldrag::shouldDropFiles (details, nullptr, files, canMoveFiles);
  410. }
  411. SoundFontEditor (AudioEngine& e, SfTarget c) : engine (e), channel (std::move (c))
  412. {
  413. ensureSoundFontIndex();
  414. load.setButtonText (tr ("Load SoundFont..."));
  415. load.setTooltip (tr ("Open a .sf2 / .sf3 / .sfz file"));
  416. load.onClick = [this] { chooseFont(); };
  417. addAndMakeVisible (load);
  418. for (auto* b : { &prev, &next })
  419. {
  420. b->setTooltip (b == &prev ? tr ("Previous preset") : tr ("Next preset"));
  421. b->onClick = [this, b] { stepPreset (b == &prev ? -1 : 1); };
  422. addAndMakeVisible (*b);
  423. }
  424. prev.setButtonText (juce::String::fromUTF8 ("\xe2\x97\x80"));
  425. next.setButtonText (juce::String::fromUTF8 ("\xe2\x96\xb6"));
  426. patch.setTooltip (tr ("The preset (bank:patch): click for the list of this SoundFont's presets"));
  427. patch.onClick = [this] { showPatchMenu(); };
  428. addAndMakeVisible (patch);
  429. const auto knob = [this] (int p, const char* caption) {
  430. knobs.push_back (std::make_unique<SfKnob> (engine, channel, p, tr (caption)));
  431. addAndMakeVisible (*knobs.back());
  432. return knobs.back().get();
  433. };
  434. attack = knob (sf::pAttack, TR_NOOP ("Attack"));
  435. decay = knob (sf::pDecay, TR_NOOP ("Decay"));
  436. sustain = knob (sf::pSustain, TR_NOOP ("Sustain"));
  437. release = knob (sf::pRelease, TR_NOOP ("Release"));
  438. lfoDelay = knob (sf::pLfoDelay, TR_NOOP ("Delay"));
  439. lfoAmount = knob (sf::pLfoAmount, TR_NOOP ("Amount"));
  440. lfoSpeed = knob (sf::pLfoSpeed, TR_NOOP ("Speed"));
  441. cutoff = knob (sf::pCutoff, TR_NOOP ("Cutoff"));
  442. cutMod = knob (sf::pCutoffMod, TR_NOOP ("Env mod"));
  443. resonance = knob (sf::pResonance, TR_NOOP ("Resonance"));
  444. reverbSend = knob (sf::pReverbAmount, TR_NOOP ("Level"));
  445. chorusSend = knob (sf::pChorusAmount, TR_NOOP ("Level"));
  446. volume = knob (sf::pVolume, TR_NOOP ("Volume"));
  447. bend = knob (sf::pBendRange, TR_NOOP ("Bend range"));
  448. poly = knob (sf::pPolyphony, TR_NOOP ("Polyphony"));
  449. transpose = knob (sf::pTranspose, TR_NOOP ("Transpose"));
  450. modWheel = knob (sf::pModWheel, TR_NOOP ("Mod wheel"));
  451. const auto toggle = [this] (int p, const char* caption, const char* tip) {
  452. toggles.push_back (std::make_unique<SfToggle> (engine, channel, p, tr (caption), tr (tip)));
  453. addAndMakeVisible (*toggles.back());
  454. return toggles.back().get();
  455. };
  456. reverbOverride = toggle (sf::pReverbOverride, TR_NOOP ("Level"), TR_NOOP ("On: the knob scales the preset's send (100 % = as the preset); off: the preset's own send"));
  457. reverbBuiltIn = toggle (sf::pReverbBuiltIn, TR_NOOP ("Built-in"), TR_NOOP ("Use the built-in reverb"));
  458. chorusOverride = toggle (sf::pChorusOverride, TR_NOOP ("Level"), TR_NOOP ("On: the knob scales the preset's send (100 % = as the preset); off: the preset's own send"));
  459. chorusBuiltIn = toggle (sf::pChorusBuiltIn, TR_NOOP ("Built-in"), TR_NOOP ("Use the built-in chorus"));
  460. velFilter = toggle (sf::pVelocityToCutoff, TR_NOOP ("Velocity to cutoff"), TR_NOOP ("Softer notes are darker (the SoundFont default modulator)"));
  461. emu = toggle (sf::pEmuEnvelope, TR_NOOP ("EMU volume envelope"), TR_NOOP ("The attack of EMU sound cards (curved in decibels)"));
  462. loops = toggle (sf::pUseLoops, TR_NOOP ("Use loops"), TR_NOOP ("Play the samples' loops (off: every sample plays once)"));
  463. const auto choice = [this] (int p, const char* caption) {
  464. choices.push_back (std::make_unique<SfChoice> (engine, channel, p, tr (caption)));
  465. addAndMakeVisible (*choices.back());
  466. return choices.back().get();
  467. };
  468. resampling = choice (sf::pResampling, TR_NOOP ("Resampling"));
  469. // "send to" a mixer insert (FL: SEND TO): the dry send into that insert, for a reverb of the user's own
  470. const auto sendMenu = [this] (int p) {
  471. return [this, p] (std::function<void (int)> pick) {
  472. juce::PopupMenu menu;
  473. const auto current = (int) paramOf (engine, channel, p);
  474. menu.addItem (tr ("None"), true, current < 0, [pick] { pick (-1); });
  475. const auto& song = engine.getSong();
  476. for (int t = 0; t < juce::jmin (126, (int) song.mixer.size()); ++t)
  477. {
  478. const auto name = t == 0 ? tr ("Master")
  479. : song.mixer[(std::size_t) t].name.empty() ? tr ("Insert {0}", { juce::String (t) })
  480. : juce::String (t) + ": " + juce::String::fromUTF8 (song.mixer[(std::size_t) t].name.c_str());
  481. menu.addItem (name, true, current == t, [pick, t] { pick (t); });
  482. }
  483. return menu;
  484. };
  485. };
  486. for (auto [p, slot] : { std::pair { sf::pReverbTrack, &reverbTrack }, std::pair { sf::pChorusTrack, &chorusTrack } })
  487. {
  488. choices.push_back (std::make_unique<SfChoice> (engine, channel, p, tr ("Send to"), sendMenu (p)));
  489. choices.back()->setTooltip (tr ("Also send the effect's input to a mixer insert (put your own reverb or chorus there)"));
  490. addAndMakeVisible (*choices.back());
  491. *slot = choices.back().get();
  492. }
  493. mode = choice (sf::pProgramMode, TR_NOOP ("Program mode"));
  494. curve = choice (sf::pVelocityCurve, TR_NOOP ("Velocity curve"));
  495. resampling->setTooltip (tr ("How transposed samples are interpolated: linear (crunchy) to 16-point sinc (extreme HQ)"));
  496. mode->setTooltip (tr ("Automatic: drum kits (bank 128) play their samples out; Instrument: notes stop at the note-off; Drums: one-shot"));
  497. curve->setTooltip (tr ("How velocity sets the level (SoundFont: the standard curve)"));
  498. // presets: this SoundFont / search everything
  499. for (auto* b : { &fontTab, &searchTab })
  500. {
  501. b->setClickingTogglesState (true);
  502. b->setRadioGroupId (158);
  503. b->onClick = [this] { showList (searchTab.getToggleState()); };
  504. addAndMakeVisible (*b);
  505. }
  506. fontTab.setButtonText (tr ("This SoundFont"));
  507. searchTab.setButtonText (tr ("Search all"));
  508. searchTab.setTooltip (tr ("Every preset of every SoundFont in your folders"));
  509. search.setTextToShowWhenEmpty (tr ("Search presets: piano, 808, pad..."), theme::colour::textDisabled);
  510. search.onTextChange = [this] {
  511. if (! searchTab.getToggleState() && search.getText().isNotEmpty())
  512. searchTab.setToggleState (true, juce::sendNotificationSync);
  513. refreshLists();
  514. };
  515. search.onReturnKey = [this] {
  516. if (list.rowCount() > 0)
  517. {
  518. list.selectRow (0);
  519. list.grabKeyboardFocus();
  520. }
  521. };
  522. addAndMakeVisible (search);
  523. folders.setButtonText (tr ("Folders..."));
  524. folders.setTooltip (tr ("The folders searched for SoundFonts (and a rescan)"));
  525. folders.onClick = [this] { showFoldersMenu(); };
  526. addAndMakeVisible (folders);
  527. status.setFont (theme::font (10.5f));
  528. status.setColour (juce::Label::textColourId, theme::colour::textDisabled);
  529. addAndMakeVisible (status);
  530. list.onPreview = [this] (const Row& r) {
  531. if (r.path == currentPath())
  532. {
  533. // this font: the channel takes the preset (as FL's patch selector), and a short note plays
  534. loadInto (engine, channel, r.path, r.bank, r.program);
  535. juce::Timer::callAfterDelay (60, [safe = juce::Component::SafePointer<SoundFontEditor> (this)] {
  536. if (safe != nullptr)
  537. safe->playNote();
  538. });
  539. }
  540. else
  541. previewSoundFontPreset (engine, r.path, r.bank, r.program);
  542. refreshHeader();
  543. };
  544. list.onLoad = [this] (const Row& r) {
  545. loadInto (engine, channel, r.path, r.bank, r.program);
  546. refreshAll();
  547. };
  548. list.onMenu = [this] (const Row& r) {
  549. juce::PopupMenu m;
  550. m.addItem (channel.channel >= 0 ? tr ("Load into this channel") : tr ("Load into this node"), [this, r] {
  551. loadInto (engine, channel, r.path, r.bank, r.program);
  552. refreshAll();
  553. });
  554. m.addItem (tr ("Load into a new channel"), [this, r] { addSoundFontChannel (engine, r.path, r.bank, r.program); });
  555. m.addItem (tr ("Preview"), [this, r] { previewSoundFontPreset (engine, r.path, r.bank, r.program); });
  556. m.addSeparator();
  557. m.addItem (tr ("Show in folder"), [r] { juce::File (u8 (r.path)).revealToUser(); });
  558. m.showMenuAsync (juce::PopupMenu::Options().withMousePosition());
  559. };
  560. addAndMakeVisible (list);
  561. fontTab.setToggleState (true, juce::dontSendNotification);
  562. setSize (800, 500);
  563. refreshAll();
  564. if (const auto* c = channelOf (engine, channel))
  565. seenParams = c->modelParams;
  566. engine.addChangeListener (this);
  567. startTimerHz (30); // (the knobs follow their automation; the rest of the timer's work runs 5 times a second)
  568. }
  569. ~SoundFontEditor() override
  570. {
  571. engine.removeChangeListener (this);
  572. stopTimer();
  573. if (noteKey >= 0)
  574. noteOff();
  575. }
  576. void paint (juce::Graphics& g) override
  577. {
  578. const PageScope pageScope;
  579. const auto accent = accentColour();
  580. skin::canvas (g, getLocalBounds().toFloat(), accent);
  581. // title + description line
  582. auto top = getLocalBounds().reduced (12, 0).removeFromTop (descriptionBottom).toFloat();
  583. top.removeFromTop (headerHeight);
  584. g.setColour (theme::colour::textSecondary);
  585. g.setFont (theme::font (11.0f));
  586. g.drawFittedText (tr ("LYNX Soundfont: plays SoundFont 2 / 3 banks and SFZ instruments. Search presets across all your SoundFonts, click to preview, double-click to load."),
  587. top.toNearestInt(), juce::Justification::centredLeft, 1, 0.75f);
  588. // the font's name next to the load button
  589. g.setColour (theme::colour::textPrimary);
  590. g.setFont (theme::font (13.0f, true));
  591. g.drawFittedText (fontTitle, fontNameArea, juce::Justification::centredLeft, 1, 0.7f);
  592. for (const auto& [area, title] : sections)
  593. {
  594. skin::section (g, area, theme::radius::lg, false, accent);
  595. skin::sectionTitle (g, area.withHeight (16.0f).translated (0.0f, 1.0f), theme::caps (title), accent);
  596. }
  597. skin::well (g, listArea.toFloat().expanded (2.0f), theme::radius::lg, accent);
  598. }
  599. void resized() override
  600. {
  601. sections.clear();
  602. auto area = getLocalBounds().reduced (12, 8);
  603. auto header = area.removeFromTop (headerHeight - 8);
  604. load.setBounds (header.removeFromLeft (130).reduced (0, 4));
  605. header.removeFromLeft (8);
  606. next.setBounds (header.removeFromRight (26).reduced (0, 4));
  607. patch.setBounds (header.removeFromRight (juce::jmin (260, header.getWidth() / 2)).reduced (2, 4));
  608. prev.setBounds (header.removeFromRight (26).reduced (0, 4));
  609. fontNameArea = header.reduced (4, 0);
  610. area.removeFromTop (descriptionBottom - headerHeight);
  611. area.removeFromTop (4);
  612. // controls on the left, presets on the right (below each other when narrow)
  613. const auto narrow = getWidth() < 700;
  614. auto controls = narrow ? area.removeFromTop (juce::jmin (area.getHeight() / 2 + 120, 380)) : area.removeFromLeft (juce::jmin (470, area.getWidth() * 3 / 5));
  615. if (! narrow)
  616. area.removeFromLeft (10);
  617. else
  618. area.removeFromTop (8);
  619. layoutControls (controls);
  620. layoutPresets (area);
  621. }
  622. private:
  623. static constexpr int headerHeight = 40, descriptionBottom = 58;
  624. void layoutControls (juce::Rectangle<int> r)
  625. {
  626. const auto rowH = juce::jlimit (70, 96, (r.getHeight() - 70) / 3);
  627. const auto half = [] (juce::Rectangle<int>& row) {
  628. auto left = row.removeFromLeft (row.getWidth() / 2 - 4);
  629. row.removeFromLeft (8);
  630. return left;
  631. };
  632. const auto place = [this] (juce::Rectangle<int> box, const juce::String& title, std::initializer_list<juce::Component*> items) {
  633. sections.push_back ({ box.toFloat(), title });
  634. auto inner = box.reduced (6, 0).withTrimmedTop (18).withTrimmedBottom (4);
  635. const auto n = (int) items.size();
  636. const auto w = inner.getWidth() / juce::jmax (1, n);
  637. for (auto* c : items)
  638. c->setBounds (inner.removeFromLeft (w).reduced (2, 0));
  639. };
  640. auto row1 = r.removeFromTop (rowH);
  641. place (half (row1), tr ("Envelope"), { attack, decay, sustain, release });
  642. place (row1, tr ("Pitch LFO"), { lfoDelay, lfoAmount, lfoSpeed, modWheel });
  643. r.removeFromTop (6);
  644. auto row2 = r.removeFromTop (rowH);
  645. place (half (row2), tr ("Filter"), { cutoff, cutMod, resonance });
  646. place (row2, tr ("Voice"), { volume, bend, poly, transpose });
  647. r.removeFromTop (6);
  648. auto row3 = r.removeFromTop (rowH);
  649. const auto fx = [this] (juce::Rectangle<int> box, const juce::String& title, juce::Component* send, juce::Component* over, juce::Component* builtIn, juce::Component* track) {
  650. sections.push_back ({ box.toFloat(), title });
  651. auto inner = box.reduced (6, 0).withTrimmedTop (18).withTrimmedBottom (4);
  652. send->setBounds (inner.removeFromLeft (juce::jmin (64, inner.getWidth() / 3)));
  653. inner.removeFromLeft (4);
  654. auto boxes = inner.removeFromLeft (inner.getWidth() / 2);
  655. const auto h = juce::jmin (22, boxes.getHeight() / 2);
  656. over->setBounds (boxes.removeFromTop (h));
  657. builtIn->setBounds (boxes.removeFromTop (h));
  658. inner.removeFromLeft (4);
  659. track->setBounds (inner.withSizeKeepingCentre (inner.getWidth(), juce::jmin (34, inner.getHeight())));
  660. };
  661. fx (half (row3), tr ("Reverb"), reverbSend, reverbOverride, reverbBuiltIn, reverbTrack);
  662. fx (row3, tr ("Chorus"), chorusSend, chorusOverride, chorusBuiltIn, chorusTrack);
  663. r.removeFromTop (6);
  664. // options
  665. sections.push_back ({ r.toFloat(), tr ("Options") });
  666. auto inner = r.reduced (8, 0).withTrimmedTop (18).withTrimmedBottom (4);
  667. auto line = inner.removeFromTop (juce::jmin (34, inner.getHeight() / 2));
  668. const auto w = line.getWidth() / 3;
  669. resampling->setBounds (line.removeFromLeft (w).reduced (3, 0));
  670. mode->setBounds (line.removeFromLeft (w).reduced (3, 0));
  671. curve->setBounds (line.reduced (3, 0));
  672. inner.removeFromTop (2);
  673. const auto tw = inner.getWidth() / 3;
  674. const auto th = juce::jmin (20, inner.getHeight());
  675. velFilter->setBounds (inner.removeFromLeft (tw).withHeight (th).reduced (3, 0));
  676. emu->setBounds (inner.removeFromLeft (tw).withHeight (th).reduced (3, 0));
  677. loops->setBounds (inner.withHeight (th).reduced (3, 0));
  678. }
  679. void layoutPresets (juce::Rectangle<int> r)
  680. {
  681. auto tabs = r.removeFromTop (24);
  682. fontTab.setBounds (tabs.removeFromLeft (tabs.getWidth() / 2).reduced (1, 0));
  683. searchTab.setBounds (tabs.reduced (1, 0));
  684. r.removeFromTop (6);
  685. auto bar = r.removeFromTop (24);
  686. folders.setBounds (bar.removeFromRight (80));
  687. bar.removeFromRight (4);
  688. search.setBounds (bar);
  689. r.removeFromTop (6);
  690. status.setBounds (r.removeFromBottom (18));
  691. r.removeFromBottom (4);
  692. listArea = r;
  693. list.setBounds (r);
  694. }
  695. void noteOff()
  696. {
  697. if (noteKey >= 0 && channel.channel >= 0)
  698. engine.sendLiveNote (channel.channel, noteKey, 0.0f, false);
  699. }
  700. std::string currentPath() const
  701. {
  702. if (const auto* c = channelOf (engine, channel))
  703. return c->samplePath;
  704. return {};
  705. }
  706. void chooseFont()
  707. {
  708. const auto start = currentPath().empty() ? juce::File::getSpecialLocation (juce::File::userDocumentsDirectory) : juce::File (u8 (currentPath()));
  709. chooser = lynx::ui::makeFileChooser (tr ("Load SoundFont"), start, "*.sf2;*.sf3;*.sfz");
  710. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  711. [safe = juce::Component::SafePointer<SoundFontEditor> (this)] (const juce::FileChooser& fc) {
  712. if (safe == nullptr || fc.getResult() == juce::File())
  713. return;
  714. const auto path = std8 (fc.getResult().getFullPathName());
  715. int bank = 0, program = 0;
  716. if (! firstSoundFontPreset (path, bank, program))
  717. {
  718. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Load SoundFont"),
  719. tr ("This file is not a SoundFont LYNX SHARE can read."));
  720. return;
  721. }
  722. loadInto (safe->engine, safe->channel, path, bank, program);
  723. sf::PresetIndex::shared().addFont (path);
  724. safe->refreshAll();
  725. });
  726. }
  727. void stepPreset (int delta)
  728. {
  729. if (fontRows.empty())
  730. return;
  731. const auto bank = (int) paramOf (engine, channel, sf::pBank), program = (int) paramOf (engine, channel, sf::pProgram);
  732. int at = 0;
  733. for (std::size_t i = 0; i < fontRows.size(); ++i)
  734. if (fontRows[i].bank == bank && fontRows[i].program == program)
  735. at = (int) i;
  736. at = (at + delta + (int) fontRows.size()) % (int) fontRows.size();
  737. loadInto (engine, channel, currentPath(), fontRows[(std::size_t) at].bank, fontRows[(std::size_t) at].program);
  738. refreshAll();
  739. }
  740. void showPatchMenu()
  741. {
  742. juce::PopupMenu menu;
  743. const auto bank = (int) paramOf (engine, channel, sf::pBank), program = (int) paramOf (engine, channel, sf::pProgram);
  744. if (fontRows.empty())
  745. menu.addItem (tr ("(no SoundFont loaded)"), false, false, nullptr);
  746. for (const auto& r : fontRows)
  747. menu.addItem (juce::String::formatted ("%03d:%03d ", r.bank, r.program) + u8 (r.name), true, r.bank == bank && r.program == program,
  748. [this, r] {
  749. loadInto (engine, channel, r.path, r.bank, r.program);
  750. refreshAll();
  751. });
  752. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&patch).withMaximumNumColumns (3));
  753. }
  754. void showFoldersMenu()
  755. {
  756. juce::PopupMenu menu;
  757. menu.addSectionHeader (tr ("SoundFont folders"));
  758. for (const auto& f : soundFontFolders())
  759. menu.addItem (u8 (f), false, false, nullptr);
  760. menu.addSeparator();
  761. menu.addItem (tr ("Add folder..."), [this] {
  762. chooser = lynx::ui::makeFileChooser (tr ("Add a SoundFont folder"), juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  763. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectDirectories,
  764. [] (const juce::FileChooser& fc) {
  765. if (fc.getResult() == juce::File())
  766. return;
  767. auto lines = juce::StringArray::fromLines (soundFontFoldersFile().loadFileAsString());
  768. lines.removeEmptyStrings();
  769. lines.addIfNotAlreadyThere (fc.getResult().getFullPathName());
  770. soundFontFoldersFile().getParentDirectory().createDirectory();
  771. soundFontFoldersFile().replaceWithText (lines.joinIntoString ("\n") + "\n");
  772. ensureSoundFontIndex (true);
  773. });
  774. });
  775. juce::PopupMenu remove;
  776. for (const auto& line : juce::StringArray::fromLines (soundFontFoldersFile().loadFileAsString()))
  777. if (line.trim().isNotEmpty())
  778. remove.addItem (line.trim(), [line] {
  779. auto lines = juce::StringArray::fromLines (soundFontFoldersFile().loadFileAsString());
  780. lines.removeString (line);
  781. lines.removeEmptyStrings();
  782. soundFontFoldersFile().replaceWithText (lines.joinIntoString ("\n") + "\n");
  783. ensureSoundFontIndex (true);
  784. });
  785. menu.addSubMenu (tr ("Remove folder"), remove, remove.getNumItems() > 0);
  786. menu.addItem (tr ("Rescan now"), [] { ensureSoundFontIndex (true); });
  787. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&folders));
  788. }
  789. void playNote()
  790. {
  791. const auto drums = (int) paramOf (engine, channel, sf::pBank) == 128;
  792. if (noteKey >= 0)
  793. noteOff();
  794. if (channel.channel < 0) // a Patcher node: the note is rendered off-line (the node plays only what is cabled to it)
  795. {
  796. previewSoundFontPreset (engine, currentPath(), (int) paramOf (engine, channel, sf::pBank), (int) paramOf (engine, channel, sf::pProgram));
  797. return;
  798. }
  799. noteKey = drums ? 38 : 60;
  800. engine.sendLiveNote (channel.channel, noteKey, 0.8f, true);
  801. noteOffAt = juce::Time::getMillisecondCounter() + 450;
  802. }
  803. void showList (bool all)
  804. {
  805. searchMode = all;
  806. list.showFont = all;
  807. refreshLists();
  808. }
  809. void refreshHeader()
  810. {
  811. const auto path = currentPath();
  812. const auto bank = (int) paramOf (engine, channel, sf::pBank), program = (int) paramOf (engine, channel, sf::pProgram);
  813. juce::String name;
  814. for (const auto& r : fontRows)
  815. if (r.bank == bank && r.program == program)
  816. name = u8 (r.name);
  817. patch.setButtonText (juce::String::formatted ("%03d:%03d ", bank, program) + (name.isEmpty() ? juce::String ("--") : name));
  818. if (path.empty())
  819. fontTitle = tr ("No SoundFont loaded");
  820. else if (handle != nullptr && handle->finished() && handle->font() == nullptr)
  821. fontTitle = tr ("{0} (could not be loaded: {1})", { juce::File (u8 (path)).getFileName(), tr (u8 (handle->error())) });
  822. else if (handle != nullptr && ! handle->finished())
  823. fontTitle = tr ("{0} (loading...)", { juce::File (u8 (path)).getFileName() });
  824. else
  825. fontTitle = handle != nullptr && handle->font() != nullptr && ! handle->font()->name.empty()
  826. ? u8 (handle->font()->name) + " (" + juce::File (u8 (path)).getFileName() + ")"
  827. : juce::File (u8 (path)).getFileName();
  828. repaint (fontNameArea);
  829. }
  830. void refreshLists()
  831. {
  832. const auto path = currentPath();
  833. const auto bank = (int) paramOf (engine, channel, sf::pBank), program = (int) paramOf (engine, channel, sf::pProgram);
  834. if (! searchMode)
  835. {
  836. auto rows = fontRows;
  837. const auto query = std8 (search.getText());
  838. if (! query.empty())
  839. {
  840. std::vector<Row> kept;
  841. const auto q = search::parse (query);
  842. for (const auto& r : rows)
  843. if (search::matches (q, r.name + " | " + r.category))
  844. kept.push_back (r);
  845. rows = std::move (kept);
  846. }
  847. list.setRows (std::move (rows), path, bank, program);
  848. }
  849. else
  850. {
  851. std::vector<Row> rows;
  852. for (const auto& h : sf::PresetIndex::shared().search (std8 (search.getText()), 2000))
  853. rows.push_back ({ h.path, h.fontName, h.presetName, h.category, h.bank, h.program });
  854. list.setRows (std::move (rows), path, bank, program);
  855. }
  856. const auto& index = sf::PresetIndex::shared();
  857. const auto fonts = index.fonts().size();
  858. status.setText (searchMode ? tr ("{0} presets in {1} SoundFonts", { juce::String ((int) index.presetCount()), juce::String ((int) fonts) })
  859. + (index.busy() ? tr (" (indexing...)") : juce::String()) + " - "
  860. + tr ("{0} shown", { juce::String (list.rowCount()) })
  861. : tr ("{0} presets", { juce::String ((int) fontRows.size()) }),
  862. juce::dontSendNotification);
  863. }
  864. void refreshAll()
  865. {
  866. const auto path = currentPath();
  867. if (path != loadedPath)
  868. {
  869. loadedPath = path;
  870. handle = path.empty() ? nullptr : sf::FontLibrary::instance().get (path);
  871. fontRows.clear();
  872. rowsFromFont = false;
  873. }
  874. if (! rowsFromFont && handle != nullptr && handle->font() != nullptr)
  875. {
  876. fontRows.clear();
  877. for (const auto& p : handle->font()->presets)
  878. fontRows.push_back ({ path, handle->font()->name, p.name, sf::category (p.bank, p.program, p.name), p.bank, p.program });
  879. rowsFromFont = true;
  880. }
  881. refreshHeader();
  882. refreshLists();
  883. for (auto* c : getChildren())
  884. c->repaint();
  885. }
  886. // issue #152 (round 190he): a linked controller, an Init song value or an undo moves the knobs (they read the Song)
  887. void changeListenerCallback (juce::ChangeBroadcaster*) override
  888. {
  889. const auto* c = channelOf (engine, channel);
  890. if (c == nullptr || c->modelParams == seenParams)
  891. return;
  892. seenParams = c->modelParams;
  893. for (auto& k : knobs)
  894. k->repaint();
  895. }
  896. void timerCallback() override
  897. {
  898. if (channel.channel >= 0 && isShowing())
  899. if (const auto& shown = engine.getAutomationDisplay(); shown.getGeneration() != automationShown)
  900. {
  901. automationShown = shown.getGeneration();
  902. for (auto& k : knobs)
  903. k->repaint();
  904. }
  905. if (++slowTicks < 6)
  906. return;
  907. slowTicks = 0;
  908. if (noteKey >= 0 && juce::Time::getMillisecondCounter() >= noteOffAt)
  909. {
  910. noteOff();
  911. noteKey = -1;
  912. }
  913. if (channelOf (engine, channel) == nullptr)
  914. return;
  915. const auto gen = sf::PresetIndex::shared().generation();
  916. const auto loading = handle != nullptr && ! rowsFromFont && handle->finished();
  917. const auto busy = sf::PresetIndex::shared().busy();
  918. if (gen != lastGeneration || loading || currentPath() != loadedPath || busy != wasBusy
  919. || (paramOf (engine, channel, sf::pBank) != lastBank || paramOf (engine, channel, sf::pProgram) != lastProgram))
  920. {
  921. lastGeneration = gen;
  922. wasBusy = busy;
  923. lastBank = paramOf (engine, channel, sf::pBank), lastProgram = paramOf (engine, channel, sf::pProgram);
  924. refreshAll();
  925. }
  926. }
  927. AudioEngine& engine;
  928. SfTarget channel;
  929. juce::TextButton load, prev, next, patch, fontTab, searchTab, folders;
  930. juce::TextEditor search;
  931. juce::Label status;
  932. PresetList list;
  933. std::vector<std::unique_ptr<SfKnob>> knobs;
  934. std::vector<float> seenParams; // the settings the knobs last drew (issue #152)
  935. std::uint32_t automationShown = 0;
  936. int slowTicks = 0;
  937. std::vector<std::unique_ptr<SfToggle>> toggles;
  938. std::vector<std::unique_ptr<SfChoice>> choices;
  939. SfKnob *attack {}, *decay {}, *sustain {}, *release {}, *lfoDelay {}, *lfoAmount {}, *lfoSpeed {}, *cutoff {}, *cutMod {}, *resonance {},
  940. *reverbSend {}, *chorusSend {}, *volume {}, *bend {}, *poly {}, *transpose {}, *modWheel {};
  941. SfChoice *reverbTrack {}, *chorusTrack {};
  942. SfToggle *reverbOverride {}, *reverbBuiltIn {}, *chorusOverride {}, *chorusBuiltIn {}, *velFilter {}, *emu {}, *loops {};
  943. SfChoice *resampling {}, *mode {}, *curve {};
  944. std::vector<std::pair<juce::Rectangle<float>, juce::String>> sections;
  945. juce::Rectangle<int> fontNameArea, listArea;
  946. juce::String fontTitle;
  947. std::unique_ptr<juce::FileChooser> chooser;
  948. std::shared_ptr<sf::FontHandle> handle;
  949. std::string loadedPath;
  950. std::vector<Row> fontRows;
  951. bool rowsFromFont = false, searchMode = false, wasBusy = false;
  952. int lastGeneration = -1, noteKey = -1;
  953. float lastBank = -1, lastProgram = -1;
  954. juce::uint32 noteOffAt = 0;
  955. };
  956. } // namespace
  957. std::unique_ptr<juce::Component> makeSoundFontEditor (AudioEngine& engine, int channel)
  958. {
  959. return std::make_unique<SoundFontEditor> (engine, SfTarget::rack (channel));
  960. }
  961. std::unique_ptr<juce::Component> makeSoundFontEditor (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate)
  962. {
  963. return std::make_unique<SoundFontEditor> (engine, SfTarget { std::move (locate), -1 });
  964. }
  965. juce::File soundFontFoldersFile()
  966. {
  967. return PluginHost::settingsFolder().getChildFile ("soundfont-folders.txt");
  968. }
  969. std::vector<std::string> soundFontFolders()
  970. {
  971. std::vector<std::string> out;
  972. const auto add = [&out] (const juce::File& f) {
  973. if (f.isDirectory())
  974. {
  975. const auto p = std8 (f.getFullPathName());
  976. if (std::find (out.begin(), out.end(), p) == out.end())
  977. out.push_back (p);
  978. }
  979. };
  980. const auto& roots = flStudioAccess().roots;
  981. if (! roots.data.empty())
  982. add (juce::File (u8 (roots.data)).getChildFile ("Patches").getChildFile ("Soundfonts"));
  983. if (! roots.userData.empty())
  984. add (juce::File (u8 (roots.userData)));
  985. for (const auto& line : juce::StringArray::fromLines (soundFontFoldersFile().loadFileAsString()))
  986. if (line.trim().isNotEmpty())
  987. add (juce::File (line.trim()));
  988. add (juce::File::getSpecialLocation (juce::File::userDocumentsDirectory));
  989. add (juce::File::getSpecialLocation (juce::File::userMusicDirectory));
  990. add (juce::File::getSpecialLocation (juce::File::userDesktopDirectory));
  991. add (juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads"));
  992. for (const auto& line : juce::StringArray::fromLines (PluginHost::settingsFolder().getChildFile ("browser-folders.txt").loadFileAsString()))
  993. if (line.trim().isNotEmpty())
  994. add (juce::File (line.trim()));
  995. return out;
  996. }
  997. void ensureSoundFontIndex (bool force)
  998. {
  999. static bool cacheSet = false;
  1000. auto& index = sf::PresetIndex::shared();
  1001. if (! cacheSet)
  1002. {
  1003. index.setCacheFile (std8 (PluginHost::settingsFolder().getChildFile ("soundfont-index.txt").getFullPathName()));
  1004. cacheSet = true;
  1005. }
  1006. index.setFolders (soundFontFolders(), force);
  1007. }
  1008. void previewSoundFontPreset (AudioEngine& engine, const std::string& path, int bank, int program)
  1009. {
  1010. static std::atomic<int> latest { 0 };
  1011. const auto ticket = ++latest;
  1012. std::thread ([&engine, path, bank, program, ticket] {
  1013. auto handle = sf::FontLibrary::instance().getNow (path);
  1014. if (handle->font() == nullptr || ticket != latest.load())
  1015. return;
  1016. constexpr double rate = 48000.0;
  1017. auto inst = sf::makeInstrument (handle);
  1018. inst->prepare (rate);
  1019. inst->configure (sf::makeChannel (path, bank, program), 120.0);
  1020. auto sample = std::make_shared<SampleData>();
  1021. sample->sampleRate = rate;
  1022. const auto total = (int) (rate * 1.6), held = (int) (rate * 0.7);
  1023. sample->left.assign ((std::size_t) total, 0.0f);
  1024. sample->right.assign ((std::size_t) total, 0.0f);
  1025. const auto key = bank == 128 ? 38 : 60;
  1026. inst->noteOn (key, 0.8f);
  1027. for (int at = 0; at < total; at += 256)
  1028. {
  1029. if (at >= held && at - 256 < held)
  1030. inst->noteOff (key);
  1031. inst->render (sample->left.data() + at, sample->right.data() + at, std::min (256, total - at), 1.0f, 1.0f);
  1032. }
  1033. juce::MessageManager::callAsync ([&engine, sample, ticket] {
  1034. if (ticket == latest.load())
  1035. engine.previewSample (sample);
  1036. });
  1037. }).detach();
  1038. }
  1039. int addSoundFontChannel (AudioEngine& engine, const std::string& path, int bank, int program, int insertAt)
  1040. {
  1041. auto c = sf::makeChannel (path, bank, program);
  1042. if (! path.empty())
  1043. {
  1044. // the channel is named after the preset
  1045. const auto info = sf::scanFontFile (path);
  1046. for (const auto& p : info.presets)
  1047. if (p.bank == bank && p.program == program && ! p.name.empty())
  1048. c.name = p.name;
  1049. }
  1050. int index = 0;
  1051. engine.editSong ([&] (Song& s) {
  1052. c.mixerTrack = s.claimFreeInsert();
  1053. if (insertAt < 0 || insertAt > (int) s.channels.size())
  1054. {
  1055. s.channels.push_back (c);
  1056. index = (int) s.channels.size() - 1;
  1057. }
  1058. else
  1059. {
  1060. s.channels.insert (s.channels.begin() + insertAt, c);
  1061. index = insertAt;
  1062. }
  1063. });
  1064. engine.setSelectedChannel (index);
  1065. if (! path.empty())
  1066. sf::PresetIndex::shared().addFont (path);
  1067. return index;
  1068. }
  1069. void loadSoundFontInto (AudioEngine& engine, int channel, const std::string& path, int bank, int program)
  1070. {
  1071. loadInto (engine, SfTarget::rack (channel), path, bank, program);
  1072. }
  1073. bool firstSoundFontPreset (const std::string& path, int& bank, int& program)
  1074. {
  1075. const auto info = sf::scanFontFile (path);
  1076. if (! info.valid)
  1077. return false;
  1078. bank = 0, program = 0;
  1079. bool first = true;
  1080. for (const auto& p : info.presets)
  1081. if (first || p.bank < bank || (p.bank == bank && p.program < program))
  1082. bank = p.bank, program = p.program, first = false;
  1083. return true;
  1084. }
  1085. bool openSoundFontFile (AudioEngine& engine, const juce::File& file, int channel)
  1086. {
  1087. const auto path = std8 (file.getFullPathName());
  1088. int bank = 0, program = 0;
  1089. if (! firstSoundFontPreset (path, bank, program))
  1090. return false;
  1091. if (channelOf (engine, SfTarget::rack (channel)) != nullptr)
  1092. {
  1093. loadInto (engine, SfTarget::rack (channel), path, bank, program);
  1094. sf::PresetIndex::shared().addFont (path);
  1095. }
  1096. else
  1097. addSoundFontChannel (engine, path, bank, program);
  1098. return true;
  1099. }
  1100. juce::String soundFontDragDescription (const std::string& path, int bank, int program)
  1101. {
  1102. return juce::String (dragPrefix) + juce::String (bank) + "|" + juce::String (program) + "|" + u8 (path);
  1103. }
  1104. bool parseSoundFontDrag (const juce::String& description, std::string& path, int& bank, int& program)
  1105. {
  1106. if (! description.startsWith (dragPrefix))
  1107. return false;
  1108. const auto rest = description.substring ((int) std::strlen (dragPrefix));
  1109. bank = rest.upToFirstOccurrenceOf ("|", false, false).getIntValue();
  1110. const auto rest2 = rest.fromFirstOccurrenceOf ("|", false, false);
  1111. program = rest2.upToFirstOccurrenceOf ("|", false, false).getIntValue();
  1112. path = std8 (rest2.fromFirstOccurrenceOf ("|", false, false));
  1113. return ! path.empty();
  1114. }
  1115. } // namespace lynx