SoundFontEditor.cpp 50 KB

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