PluginWindow.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. #include "ui/WindowOwner.h"
  2. #include "ui/PluginWindow.h"
  3. #include "ui/PluginPicker.h"
  4. #include "ui/PluginPresetMenu.h"
  5. #include <algorithm>
  6. #include <map>
  7. #include "core/FlWrapper.h"
  8. #include "core/LastTweaked.h"
  9. #include "engine/PluginSandbox.h"
  10. #include "engine/Text.h"
  11. #include "platform/CrashGuard.h"
  12. #include "ui/I18n.h"
  13. #include "platform/Paths.h"
  14. #include "ui/Theme.h"
  15. namespace lynx
  16. {
  17. namespace
  18. {
  19. void toggleWrapperOption (AudioEngine& engine, const std::function<PluginRef* (Song&)>& find, juce::AudioPluginInstance* instance,
  20. bool PluginRef::*option, bool recreates);
  21. // FL's plugin wrapper settings page (REA rounds 146a / 149), in LYNX's style with the tabs and groups of FL's wrapper
  22. // form (Fruity Wrapper's DFM [DATA], FL 2026's page [EXEC]): Settings (Info with the latency, MIDI ports), Processing
  23. // (Options) and Troubleshooting (Compatibility: the fixed buffers; Location). Options that re-create the plugin keep
  24. // its state and close this window (open it again from the channel or the slot).
  25. class WrapperSettingsPage final : public juce::Component, private juce::ChangeListener
  26. {
  27. public:
  28. WrapperSettingsPage (AudioEngine& e, std::function<PluginRef* (Song&)> f, juce::AudioPluginInstance& p, bool channel)
  29. : engine (e), find (std::move (f)), plugin (p)
  30. {
  31. const char* tabNames[] = { TR_NOOP ("Settings"), TR_NOOP ("Processing"), TR_NOOP ("Troubleshooting") };
  32. for (int t = 0; t < 3; ++t)
  33. {
  34. auto* b = tabs.add (new juce::TextButton (tr (tabNames[t])));
  35. b->setClickingTogglesState (false); // LYNX's tab look (as the channel window's): the shown one filled
  36. b->onClick = [this, t] { showTab (t); };
  37. addAndMakeVisible (b);
  38. }
  39. const auto& options = wrapperOptions();
  40. for (std::size_t i = 0; i < options.size(); ++i)
  41. {
  42. auto* t = toggles.add (new juce::ToggleButton (tr (options[i].label)));
  43. t->setTooltip (tr (options[i].hint));
  44. t->setColour (juce::ToggleButton::textColourId, theme::colour::textPrimary);
  45. t->setColour (juce::ToggleButton::tickColourId, theme::colour::accent);
  46. t->onClick = [this, i] {
  47. auto* en = &engine;
  48. auto fn = find;
  49. auto* inst = &plugin;
  50. const auto& o = wrapperOptions()[i];
  51. juce::MessageManager::callAsync ([en, fn, inst, member = o.member, re = o.recreates] { toggleWrapperOption (*en, fn, inst, member, re); });
  52. };
  53. addChildComponent (t);
  54. }
  55. for (auto* box : { &inPort, &outPort })
  56. {
  57. box->addItem (juce::String::fromUTF8 ("\xe2\x80\x94"), 1);
  58. for (int i = 0; i < 256; ++i)
  59. box->addItem (juce::String (i), i + 2);
  60. addChildComponent (box);
  61. }
  62. for (int st = 1; st <= 48; ++st)
  63. bendRange.addItem (juce::String (st), st);
  64. bendRange.setTooltip (tr ("The pitch bend range sent to the plugin (semitones)"));
  65. bendRange.onChange = [this] {
  66. engine.editSong ([fn = find, v = bendRange.getSelectedId()] (Song& song) {
  67. if (auto* ref = fn (song); ref != nullptr && v > 0)
  68. ref->bendRange = v;
  69. });
  70. };
  71. addChildComponent (bendRange);
  72. inPort.setTooltip (tr ("MIDI input port number"));
  73. inPort.onChange = [this] { setPort (inPort.getSelectedId() - 2, false); };
  74. // FL's Output port: the notes the plugin sends out play the plugins on that input port (instruments in the
  75. // Channel rack that send MIDI)
  76. outPort.setTooltip (tr ("MIDI output port number: the notes this plugin sends play the plugins whose input port it is"));
  77. outPort.onChange = [this] { setPort (outPort.getSelectedId() - 2, true); };
  78. outPort.setEnabled (channel && plugin.producesMidi());
  79. // FL's Info › Latency: what the plugin reports, or set by hand (menu: Reset, Set in ms / samples / beats)
  80. latency.setTooltip (tr ("Latency used by the delay compensation: what the plugin reports, or a value set by hand"));
  81. latency.onClick = [this] { showLatencyMenu(); };
  82. addChildComponent (latency);
  83. locate.setButtonText (tr ("Locate"));
  84. locate.setTooltip (tr ("Show the plugin's file in the file manager"));
  85. locate.onClick = [this] { juce::File (plugin.getPluginDescription().fileOrIdentifier).revealToUser(); };
  86. addChildComponent (locate);
  87. engine.addChangeListener (this);
  88. refresh();
  89. showTab (0);
  90. setSize (520, preferredHeight());
  91. }
  92. ~WrapperSettingsPage() override { engine.removeChangeListener (this); }
  93. int preferredHeight() const { return 410; }
  94. void paint (juce::Graphics& g) override
  95. {
  96. using namespace theme;
  97. g.fillAll (colour::bg1);
  98. g.setColour (colour::textSecondary);
  99. g.setFont (font (type::caption));
  100. g.drawText (tr ("version {0}", { plugin.getPluginDescription().version }), getWidth() - 200, 8, 184, tabHeight, juce::Justification::centredRight);
  101. for (const auto& [area, title] : groups)
  102. {
  103. g.setColour (colour::bg2);
  104. g.fillRoundedRectangle (area.toFloat(), radius::md);
  105. g.setColour (colour::textSecondary);
  106. g.setFont (font (type::caption, true));
  107. g.drawText (caps (title), area.withHeight (headerHeight).reduced (10, 0), juce::Justification::centredLeft);
  108. }
  109. g.setFont (font (type::body));
  110. for (const auto& [area, text, primary] : labels)
  111. {
  112. g.setColour (primary ? colour::textPrimary : colour::textSecondary);
  113. g.drawFittedText (text, area, juce::Justification::centredLeft, 1);
  114. }
  115. }
  116. void resized() override
  117. {
  118. groups.clear();
  119. labels.clear();
  120. auto area = getLocalBounds().reduced (10, 8);
  121. auto bar = area.removeFromTop (tabHeight);
  122. for (auto* t : tabs)
  123. t->setBounds (bar.removeFromLeft (juce::jmax (80, t->getBestWidthForHeight (tabHeight) + 16)));
  124. area.removeFromTop (8);
  125. for (auto* c : getChildren())
  126. if (! tabs.contains (dynamic_cast<juce::TextButton*> (c)))
  127. c->setVisible (false);
  128. auto group = [this] (juce::Rectangle<int>& from, int height, const juce::String& title) {
  129. auto r = from.removeFromTop (height);
  130. from.removeFromTop (8);
  131. groups.push_back ({ r, title });
  132. return r.withTrimmedTop (headerHeight).reduced (10, 4);
  133. };
  134. auto label = [this] (juce::Rectangle<int> r, const juce::String& text, bool primary = false) { labels.push_back ({ r, text, primary }); };
  135. auto show = [] (juce::Component& c, juce::Rectangle<int> r) {
  136. c.setBounds (r);
  137. c.setVisible (true);
  138. };
  139. if (tab == 0)
  140. {
  141. const auto d = plugin.getPluginDescription();
  142. auto info = group (area, headerHeight + 6 * rowHeight + 8, tr ("Info"));
  143. const std::pair<juce::String, juce::String> lines[] = {
  144. { tr ("Name"), d.name + (d.manufacturerName.isNotEmpty() ? " (" + d.manufacturerName + ")" : juce::String()) },
  145. { tr ("Type"), d.pluginFormatName + (d.isInstrument ? " " + tr ("instrument") : " " + tr ("effect")) },
  146. { tr ("Category"), d.category },
  147. { tr ("Inputs / outputs"), juce::String (plugin.getTotalNumInputChannels()) + " / " + juce::String (plugin.getTotalNumOutputChannels()) },
  148. { tr ("Parameters"), juce::String (plugin.getParameters().size()) },
  149. };
  150. for (const auto& [name, value] : lines)
  151. {
  152. auto row = info.removeFromTop (rowHeight);
  153. label (row.removeFromLeft (110), name);
  154. label (row, value, true);
  155. }
  156. auto row = info.removeFromTop (rowHeight);
  157. label (row.removeFromLeft (110), tr ("Latency"));
  158. show (latency, row.removeFromLeft (260).reduced (0, 2));
  159. int midiRows = 0;
  160. for (const auto& o : wrapperOptions())
  161. midiRows += juce::String (o.section) == "MIDI" ? 1 : 0;
  162. auto midi = group (area, headerHeight + (1 + midiRows) * rowHeight + 8, tr ("MIDI"));
  163. auto line = midi.removeFromTop (rowHeight);
  164. label (line.removeFromLeft (80), tr ("Input port"));
  165. show (inPort, line.removeFromLeft (70).reduced (0, 2));
  166. line.removeFromLeft (30);
  167. label (line.removeFromLeft (90), tr ("Output port"));
  168. show (outPort, line.removeFromLeft (70).reduced (0, 2));
  169. // FL's MIDI options (round 151): release velocity, the pitch bend range RPN (with its value), MOD X as
  170. // polyphonic aftertouch, All Notes Off on stop
  171. for (std::size_t i = 0; i < wrapperOptions().size(); ++i)
  172. if (juce::String (wrapperOptions()[i].section) == "MIDI")
  173. {
  174. auto row = midi.removeFromTop (rowHeight);
  175. if (wrapperOptions()[i].member == &PluginRef::sendBendRange)
  176. show (bendRange, row.removeFromRight (70).reduced (0, 2));
  177. show (*toggles[(int) i], row);
  178. }
  179. }
  180. else
  181. {
  182. const juce::String section = tab == 1 ? "Processing" : "Compatibility";
  183. int rows = 0;
  184. for (const auto& o : wrapperOptions())
  185. rows += section == o.section ? 1 : 0;
  186. auto box = group (area, headerHeight + rows * rowHeight + 8, tr (tab == 1 ? "Options" : "Compatibility"));
  187. for (std::size_t i = 0; i < wrapperOptions().size(); ++i)
  188. if (section == wrapperOptions()[i].section)
  189. show (*toggles[(int) i], box.removeFromTop (rowHeight).withTrimmedLeft (wrapperOptions()[i].needsFixed ? 22 : 0));
  190. if (tab == 2)
  191. {
  192. auto where = group (area, headerHeight + rowHeight + 8, tr ("Location"));
  193. show (locate, where.removeFromRight (90).withHeight (rowHeight).reduced (0, 2));
  194. label (where.removeFromLeft (50).withHeight (rowHeight), tr ("Path"));
  195. label (where.withHeight (rowHeight), plugin.getPluginDescription().fileOrIdentifier, true);
  196. }
  197. }
  198. repaint();
  199. }
  200. private:
  201. static constexpr int tabHeight = 24, headerHeight = 24, rowHeight = 24;
  202. void showTab (int t)
  203. {
  204. tab = t;
  205. for (int k = 0; k < tabs.size(); ++k)
  206. tabs[k]->setToggleState (k == t, juce::dontSendNotification);
  207. resized();
  208. }
  209. void setPort (int value, bool output)
  210. {
  211. engine.editSong ([fn = find, value, output] (Song& song) {
  212. if (auto* ref = fn (song))
  213. (output ? ref->midiOutPort : ref->midiInPort) = value;
  214. });
  215. }
  216. double rate() const { return plugin.getSampleRate() > 0 ? plugin.getSampleRate() : 44100.0; }
  217. void setLatencyMs (float ms)
  218. {
  219. engine.editSong ([fn = find, ms] (Song& song) {
  220. if (auto* ref = fn (song))
  221. ref->latencyOverrideMs = ms;
  222. });
  223. }
  224. void showLatencyMenu()
  225. {
  226. // FL's latency menu [EXEC]: Reset, Set in ms, Set in samples, Set in beats (beats at the song's tempo)
  227. juce::PopupMenu menu;
  228. menu.addItem (tr ("Reset"), [this] { setLatencyMs (-1.0f); });
  229. auto ask = [this] (int unit) {
  230. auto* ref = find (const_cast<Song&> (engine.getSong()));
  231. const auto bpm = juce::jmax (10.0, (double) engine.getSong().bpm);
  232. const auto ms = ref != nullptr && ref->latencyOverrideMs >= 0.0f ? (double) ref->latencyOverrideMs
  233. : plugin.getLatencySamples() * 1000.0 / rate();
  234. const auto current = unit == 0 ? ms : unit == 1 ? ms * rate() / 1000.0 : ms * bpm / 60000.0;
  235. const char* titles[] = { TR_NOOP ("Latency in ms"), TR_NOOP ("Latency in samples"), TR_NOOP ("Latency in beats") };
  236. auto* window = new juce::AlertWindow (tr ("Latency"), tr (titles[unit]), juce::MessageBoxIconType::NoIcon);
  237. window->addTextEditor ("value", juce::String (current, unit == 1 ? 0 : 3));
  238. window->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
  239. window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
  240. juce::Component::SafePointer<WrapperSettingsPage> safe (this);
  241. window->enterModalState (true, juce::ModalCallbackFunction::create ([safe, window, unit, bpm] (int result) {
  242. if (result != 1 || safe == nullptr)
  243. return;
  244. const auto v = juce::jmax (0.0, window->getTextEditorContents ("value").getDoubleValue());
  245. const auto ms = unit == 0 ? v : unit == 1 ? v * 1000.0 / safe->rate() : v * 60000.0 / bpm;
  246. safe->setLatencyMs ((float) juce::jlimit (0.0, 2000.0, ms));
  247. }), true);
  248. };
  249. menu.addItem (tr ("Set in ms..."), [ask] { ask (0); });
  250. menu.addItem (tr ("Set in samples..."), [ask] { ask (1); });
  251. menu.addItem (tr ("Set in beats..."), [ask] { ask (2); });
  252. menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&latency));
  253. }
  254. void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
  255. void refresh()
  256. {
  257. auto* ref = find (const_cast<Song&> (engine.getSong()));
  258. if (ref == nullptr)
  259. return;
  260. const auto& options = wrapperOptions();
  261. for (std::size_t i = 0; i < options.size(); ++i)
  262. {
  263. toggles[(int) i]->setToggleState (ref->*(options[i].member), juce::dontSendNotification);
  264. toggles[(int) i]->setEnabled (! options[i].needsFixed || ref->fixedBuffers);
  265. }
  266. // with Options › "Run plugins in a separate process" every plugin already runs bridged
  267. for (std::size_t i = 0; i < options.size(); ++i)
  268. if (options[i].member == &PluginRef::separateProcess && pluginSandboxEnabled())
  269. toggles[(int) i]->setToggleState (true, juce::dontSendNotification), toggles[(int) i]->setEnabled (false);
  270. inPort.setSelectedId (ref->midiInPort + 2, juce::dontSendNotification);
  271. bendRange.setSelectedId (ref->bendRange, juce::dontSendNotification);
  272. bendRange.setEnabled (ref->sendBendRange);
  273. outPort.setSelectedId (ref->midiOutPort + 2, juce::dontSendNotification);
  274. const auto reported = plugin.getLatencySamples();
  275. const auto text = ref->latencyOverrideMs >= 0.0f
  276. ? tr ("{0} ms (set by hand)", { juce::String (ref->latencyOverrideMs, 2) })
  277. : (reported > 0 ? tr ("{0} samples ({1} ms)", { juce::String (reported), juce::String (reported * 1000.0 / rate(), 1) })
  278. : tr ("none"));
  279. latency.setButtonText (text + juce::String::fromUTF8 (" \xe2\x96\xbe"));
  280. }
  281. struct Label
  282. {
  283. juce::Rectangle<int> area;
  284. juce::String text;
  285. bool primary = false;
  286. };
  287. AudioEngine& engine;
  288. std::function<PluginRef* (Song&)> find;
  289. juce::AudioPluginInstance& plugin;
  290. juce::OwnedArray<juce::TextButton> tabs;
  291. juce::OwnedArray<juce::ToggleButton> toggles;
  292. juce::ComboBox inPort, outPort, bendRange;
  293. juce::TextButton latency, locate;
  294. int tab = 0;
  295. std::vector<std::pair<juce::Rectangle<int>, juce::String>> groups;
  296. std::vector<Label> labels;
  297. };
  298. // The window's content with FL's wrapper header: the plugin's editor, or the wrapper settings page (gear).
  299. class WrappedEditor final : public juce::Component
  300. {
  301. public:
  302. WrappedEditor (juce::AudioProcessorEditor* e, AudioEngine& engine, std::function<PluginRef* (Song&)> find, juce::AudioPluginInstance& plugin,
  303. bool channel)
  304. : editor (e), page (engine, std::move (find), plugin, channel), presets (plugin, [&engine] { engine.markModified(); })
  305. {
  306. addAndMakeVisible (presets); // FL's wrapper presets: ◀ ▶ and the menu (round 162d, issue #8)
  307. for (auto* b : { &pluginTab, &settingsTab })
  308. {
  309. b->setClickingTogglesState (false); // LYNX's tab look (as the channel window's): the shown one filled
  310. addAndMakeVisible (b);
  311. }
  312. pluginTab.setTooltip (tr ("The plugin's own editor"));
  313. settingsTab.setTooltip (tr ("Plugin wrapper settings: processing, bridging and MIDI options"));
  314. pluginTab.onClick = [this] { show (false); };
  315. settingsTab.onClick = [this] { show (true); };
  316. addAndMakeVisible (editor.get());
  317. addChildComponent (page);
  318. pluginTab.setToggleState (true, juce::dontSendNotification);
  319. fitEditor();
  320. }
  321. ~WrappedEditor() override
  322. {
  323. editor = nullptr; // the editor goes first (the plugin may be released right after the window)
  324. }
  325. bool isEditorResizable() const { return editor != nullptr && editor->isResizable(); }
  326. void paint (juce::Graphics& g) override
  327. {
  328. g.setColour (theme::colour::bg0);
  329. g.fillRect (getLocalBounds().removeFromTop (headerHeight));
  330. }
  331. void resized() override
  332. {
  333. auto area = getLocalBounds();
  334. auto header = area.removeFromTop (headerHeight).reduced (4, 3);
  335. pluginTab.setBounds (header.removeFromLeft (80));
  336. header.removeFromLeft (4);
  337. settingsTab.setBounds (header.removeFromLeft (130));
  338. header.removeFromLeft (8);
  339. presets.setBounds (header.removeFromLeft (juce::jmin (presets.preferredWidth(), header.getWidth())));
  340. page.setBounds (area);
  341. if (editor != nullptr && ! settings)
  342. {
  343. const juce::ScopedValueSetter<bool> guard (laying, true);
  344. if (editor->isResizable())
  345. editor->setBounds (area);
  346. else
  347. editor->setTopLeftPosition (area.getPosition());
  348. }
  349. }
  350. void childBoundsChanged (juce::Component* child) override
  351. {
  352. if (child == editor.get() && ! laying && ! settings)
  353. fitEditor();
  354. }
  355. private:
  356. static constexpr int headerHeight = 30, minWidth = 4 + 80 + 4 + 130 + 8 + 250 + 4;
  357. void fitEditor()
  358. {
  359. if (editor != nullptr)
  360. setSize (juce::jmax (minWidth, editor->getWidth()), editor->getHeight() + headerHeight);
  361. }
  362. void show (bool showSettings)
  363. {
  364. settings = showSettings;
  365. pluginTab.setToggleState (! settings, juce::dontSendNotification);
  366. settingsTab.setToggleState (settings, juce::dontSendNotification);
  367. page.setVisible (settings);
  368. if (editor != nullptr)
  369. {
  370. editor->setVisible (! settings);
  371. // A plugin editor embedded as a native child window (VST3 / LV2 through JUCE's XEmbedComponent and CLAP /
  372. // VST2 through NativeEmbed on Linux) is not unmapped when its component is hidden: it stayed over the
  373. // Wrapper settings page and made it unreachable (issue #8). Moving it outside the window clips it away on
  374. // every platform; resized() puts it back.
  375. if (settings)
  376. editor->setTopLeftPosition (-12000, -12000); // (X11 positions are 16-bit, also when scaled)
  377. }
  378. if (settings)
  379. setSize (juce::jmax (getWidth(), page.getWidth()), juce::jmax (getHeight(), page.preferredHeight() + headerHeight));
  380. else
  381. fitEditor();
  382. resized();
  383. if (editor != nullptr)
  384. followNativeChildren (*editor);
  385. }
  386. // JUCE's XEmbedComponent only moves its X window when it is itself moved, not when a parent (the editor) is:
  387. // tell every one inside the editor (round 162d)
  388. static void followNativeChildren (juce::Component& c)
  389. {
  390. #if JUCE_LINUX || JUCE_BSD
  391. if (auto* x = dynamic_cast<juce::XEmbedComponent*> (&c))
  392. x->updateEmbeddedBounds();
  393. #endif
  394. for (auto* child : c.getChildren())
  395. followNativeChildren (*child);
  396. }
  397. std::unique_ptr<juce::AudioProcessorEditor> editor;
  398. WrapperSettingsPage page;
  399. pluginpresetui::PresetBar presets;
  400. juce::TextButton pluginTab { tr ("Plugin") }, settingsTab { juce::String::fromUTF8 ("\xe2\x9a\x99 ") + tr ("Wrapper settings") };
  401. bool settings = false, laying = false;
  402. };
  403. class PluginWindow final : public juce::DocumentWindow, private juce::AudioProcessorListener, private juce::Timer
  404. {
  405. public:
  406. PluginWindow (std::shared_ptr<void> keepAlive, juce::AudioPluginInstance& p, const juce::String& title, PluginWindows::WrapperContext context)
  407. : DocumentWindow (title, theme::colour::bg1, DocumentWindow::closeButton | DocumentWindow::minimiseButton),
  408. owner (std::move (keepAlive)),
  409. plugin (p)
  410. {
  411. setUsingNativeTitleBar (true);
  412. useClassicRendering();
  413. crashguard::note (("opening the editor of " + plugin.getName()).toStdString()); // session breadcrumb (round 111)
  414. juce::AudioProcessorEditor* editor = plugin.createEditorIfNeeded();
  415. if (editor == nullptr)
  416. editor = new juce::GenericAudioProcessorEditor (plugin); // plugin without a UI
  417. crashguard::note (("editor open: " + plugin.getName()).toStdString());
  418. const auto resizable = editor->isResizable();
  419. if (context.engine != nullptr && context.find) // FL's wrapper header and settings page (round 146a)
  420. setContentOwned (new WrappedEditor (editor, *context.engine, std::move (context.find), plugin, context.channel), true);
  421. else
  422. setContentOwned (editor, true);
  423. setResizable (resizable, false);
  424. centreWithSize (getWidth(), getHeight());
  425. setVisible (true);
  426. keepAboveMainWindow (*this);
  427. crashguard::note (("editor shown: " + plugin.getName()).toStdString()); // (its OpenGL / GPU setup runs when shown)
  428. plugin.addListener (this); // the editor's gestures: Last tweaked, automation recording (REA round 143)
  429. startTimerHz (10); // its moves without gestures (round 162d)
  430. }
  431. // round 157a: the window that holds a third-party editor draws LYNX's few pixels with GDI, not Direct2D (JUCE 8's
  432. // default). A plugin's OpenGL child window then sits in a classic redirected top-level window, as in every other
  433. // host — a Direct2D / DXGI swap-chain parent is where Intel's OpenGL driver crashed in SetPixelFormat (her
  434. // Auto-Tune Pro editor, 2026-10-25). (Re-applied whenever the native window is re-created.)
  435. void addToDesktop (int styleFlags, void* nativeWindowToAttachTo) override
  436. {
  437. DocumentWindow::addToDesktop (styleFlags, nativeWindowToAttachTo);
  438. useClassicRendering();
  439. }
  440. void useClassicRendering()
  441. {
  442. getProperties().set ("lynxGdi", true);
  443. #if JUCE_WINDOWS
  444. if (auto* peer = getPeer())
  445. if (const auto engines = peer->getAvailableRenderingEngines(); engines.size() > 1 && peer->getCurrentRenderingEngine() != 0)
  446. peer->setCurrentRenderingEngine (0); // "Software Renderer" (GDI)
  447. #endif
  448. }
  449. ~PluginWindow() override
  450. {
  451. crashguard::note (("closing the editor of " + plugin.getName()).toStdString());
  452. // round 165q: closing the active plugin window (its X, F12, Alt+F12, removing the plugin) let Windows hand the
  453. // activation to another program (seen: a terminal on the second screen) instead of LYNX, so Space and the
  454. // shortcuts went there. The main window takes it first, while LYNX is still the foreground program.
  455. if (isActiveWindow())
  456. activateMainWindow();
  457. stopTimer();
  458. plugin.removeListener (this);
  459. // the UI must be destroyed before the plugin (which may die together with `owner`)
  460. clearContentComponent();
  461. }
  462. void closeButtonPressed() override;
  463. juce::AudioPluginInstance* key() const noexcept { return &plugin; }
  464. void activeWindowStatusChanged() override
  465. {
  466. DocumentWindow::activeWindowStatusChanged();
  467. if (isActiveWindow())
  468. lastUsed() = &plugin;
  469. }
  470. static juce::AudioPluginInstance*& lastUsed()
  471. {
  472. static juce::AudioPluginInstance* last = nullptr;
  473. return last;
  474. }
  475. // True when nothing but this window keeps the plugin's adapter alive: the plugin was removed or replaced, its
  476. // channel deleted or the project closed (issue #9: the removed plugin's editor stayed on screen).
  477. bool orphaned() const noexcept { return owner != nullptr && owner.use_count() == 1; }
  478. private:
  479. // round 162d (issue #8): many plugins move their parameters without begin/end gestures, so their knobs never
  480. // became "Last tweaked". A change made on the UI thread while this window is active or under the mouse, when it
  481. // is the only parameter that moved since the last tick, counts as a tweak (core/LastTweaked.h; automation and
  482. // links run on the audio thread, preset loads move many parameters at once).
  483. void audioProcessorParameterChanged (juce::AudioProcessor*, int index, float) override
  484. {
  485. if (juce::MessageManager::getInstanceWithoutCreating() != nullptr && juce::MessageManager::getInstance()->isThisTheMessageThread())
  486. changes.changed (index);
  487. }
  488. void timerCallback() override
  489. {
  490. const auto mouse = juce::Desktop::getInstance().getMainMouseSource().getScreenPosition().roundToInt();
  491. const auto active = isActiveWindow() || (isShowing() && getScreenBounds().contains (mouse));
  492. if (const auto moved = changes.tick (active); moved >= 0 && PluginWindows::onGesture)
  493. {
  494. PluginWindows::onGesture (plugin, moved, true);
  495. PluginWindows::onGesture (plugin, moved, false);
  496. }
  497. }
  498. void audioProcessorChanged (juce::AudioProcessor*, const ChangeDetails&) override {}
  499. void audioProcessorParameterChangeGestureBegin (juce::AudioProcessor*, int index) override { gesture (index, true); }
  500. void audioProcessorParameterChangeGestureEnd (juce::AudioProcessor*, int index) override { gesture (index, false); }
  501. void gesture (int index, bool starting)
  502. {
  503. if (juce::MessageManager::getInstanceWithoutCreating() != nullptr && juce::MessageManager::getInstance()->isThisTheMessageThread())
  504. changes.gesture (index, starting);
  505. auto* p = &plugin;
  506. juce::MessageManager::callAsync ([p, index, starting] {
  507. if (PluginWindows::onGesture)
  508. PluginWindows::onGesture (*p, index, starting);
  509. });
  510. }
  511. std::shared_ptr<void> owner;
  512. juce::AudioPluginInstance& plugin;
  513. lasttweak::ChangeFilter changes;
  514. };
  515. } // namespace
  516. std::function<void (const juce::AudioPluginInstance&, int, bool)> PluginWindows::onGesture;
  517. namespace
  518. {
  519. std::map<juce::AudioPluginInstance*, std::unique_ptr<PluginWindow>>& windows()
  520. {
  521. static std::map<juce::AudioPluginInstance*, std::unique_ptr<PluginWindow>> open;
  522. return open;
  523. }
  524. // Closes the windows of plugins the engine no longer hosts (checked 4 times a second while a window is open; a removed
  525. // adapter is released by the engine within a few frames, when the audio thread has let go of its last snapshot).
  526. class OrphanReaper final : public juce::Timer
  527. {
  528. public:
  529. void timerCallback() override
  530. {
  531. auto& open = windows();
  532. bool any = false;
  533. for (const auto& [key, window] : open)
  534. any = any || window->orphaned();
  535. // issue #36: the window is the plugin's last owner here, so closing it frees the plugin; that happens from a
  536. // message of its own (editor first, then the plugin), not inside this timer callback while timers are running
  537. if (any && ! reaping)
  538. {
  539. reaping = true;
  540. juce::MessageManager::callAsync ([this] {
  541. reaping = false;
  542. auto& all = windows();
  543. for (auto it = all.begin(); it != all.end();)
  544. it = it->second->orphaned() ? all.erase (it) : std::next (it);
  545. if (all.empty())
  546. stopTimer();
  547. });
  548. }
  549. else if (open.empty())
  550. stopTimer();
  551. }
  552. private:
  553. bool reaping = false;
  554. };
  555. OrphanReaper& reaper()
  556. {
  557. static auto* r = new OrphanReaper(); // (never destroyed: a static Timer must not outlive the message manager)
  558. return *r;
  559. }
  560. void PluginWindow::closeButtonPressed()
  561. {
  562. const auto* k = key();
  563. // close after leaving this callback (the window deletes itself)
  564. juce::MessageManager::callAsync ([k] { windows().erase (const_cast<juce::AudioPluginInstance*> (k)); });
  565. }
  566. class ScanThread final : public juce::ThreadWithProgressWindow
  567. {
  568. public:
  569. ScanThread (AudioEngine& e, std::function<void (int)> done)
  570. : juce::ThreadWithProgressWindow (tr ("Scanning for plugins ({0})...", { platform::pluginFormatNames() }), true, true),
  571. engine (e),
  572. onDone (std::move (done))
  573. {
  574. }
  575. // called on the UI thread when the scan finishes (or is cancelled)
  576. void threadComplete (bool) override
  577. {
  578. if (onDone)
  579. onDone (found);
  580. juce::MessageManager::callAsync ([this] { delete this; });
  581. }
  582. void run() override
  583. {
  584. found = engine.getPluginHost().scan (engine.getPluginHost().pluginFolders(), [this] (float progress, const juce::String& file) {
  585. setProgress (progress);
  586. setStatusMessage (juce::File (file).getFileName());
  587. return ! threadShouldExit();
  588. });
  589. }
  590. int found = 0;
  591. private:
  592. AudioEngine& engine;
  593. std::function<void (int)> onDone;
  594. };
  595. } // namespace
  596. namespace PluginWindows
  597. {
  598. void open (std::shared_ptr<void> owner, juce::AudioPluginInstance& plugin, const juce::String& title, WrapperContext context)
  599. {
  600. auto& open = windows();
  601. if (auto it = open.find (&plugin); it != open.end())
  602. {
  603. it->second->toFront (true);
  604. return;
  605. }
  606. open[&plugin] = std::make_unique<PluginWindow> (std::move (owner), plugin, title, std::move (context));
  607. if (! reaper().isTimerRunning())
  608. reaper().startTimerHz (4);
  609. }
  610. void closeAll()
  611. {
  612. windows().clear();
  613. reaper().stopTimer();
  614. }
  615. void closeOrphans()
  616. {
  617. reaper().timerCallback();
  618. }
  619. std::vector<juce::AudioPluginInstance*> openPlugins()
  620. {
  621. std::vector<juce::AudioPluginInstance*> out;
  622. const auto* last = PluginWindow::lastUsed();
  623. for (auto& [plugin, window] : windows())
  624. if (plugin == last)
  625. out.insert (out.begin(), plugin);
  626. else
  627. out.push_back (plugin);
  628. return out;
  629. }
  630. bool isOpen (const juce::AudioPluginInstance& plugin)
  631. {
  632. return windows().count (const_cast<juce::AudioPluginInstance*> (&plugin)) > 0;
  633. }
  634. void close (const juce::AudioPluginInstance& plugin)
  635. {
  636. windows().erase (const_cast<juce::AudioPluginInstance*> (&plugin));
  637. }
  638. } // namespace PluginWindows
  639. void scanPluginsWithProgress (AudioEngine& engine, std::function<void (int)> onDone)
  640. {
  641. (new ScanThread (engine, std::move (onDone)))->launchThread(); // deletes itself when done
  642. }
  643. namespace
  644. {
  645. void toggleWrapperOption (AudioEngine& engine, const std::function<PluginRef* (Song&)>& find, juce::AudioPluginInstance* instance,
  646. bool PluginRef::*option, bool recreates)
  647. {
  648. if (recreates)
  649. {
  650. if (instance != nullptr && PluginWindows::isOpen (*instance))
  651. PluginWindows::close (*instance);
  652. engine.capturePluginStates(); // the new instance starts from the current settings
  653. }
  654. engine.editSong ([find, option] (Song& song) {
  655. if (auto* ref = find (song))
  656. ref->*option = ! (ref->*option);
  657. });
  658. }
  659. } // namespace
  660. juce::PopupMenu pluginProcessingMenu (AudioEngine& engine, const PluginRef& current, juce::AudioPluginInstance* instance,
  661. std::function<PluginRef* (Song&)> find)
  662. {
  663. auto toggle = [&engine, find, instance] (bool PluginRef::*option) {
  664. if (instance != nullptr)
  665. PluginWindows::close (*instance);
  666. engine.capturePluginStates(); // the new instance starts from the current settings
  667. engine.editSong ([find, option] (Song& song) {
  668. if (auto* ref = find (song))
  669. ref->*option = ! (ref->*option);
  670. });
  671. };
  672. juce::PopupMenu menu;
  673. menu.addItem (tr ("Use fixed size buffers (adds latency)"), true, current.fixedBuffers, [toggle] { toggle (&PluginRef::fixedBuffers); });
  674. // FL's options of fixed buffers (REA round 134): 2 ms blocks, or the whole device buffer
  675. menu.addItem (tr ("Process maximum size buffers (more latency, only when necessary)"), current.fixedBuffers, current.fixedBuffers && current.maxSizeBuffers,
  676. [toggle] { toggle (&PluginRef::maxSizeBuffers); });
  677. // FL's "Use maximum buffer size from host" (REA round 139): the plugin is prepared for the host's largest block
  678. // instead of the fixed block (for plugins that need it to size their buffers)
  679. menu.addItem (tr ("Use maximum buffer size from host"), current.fixedBuffers, current.fixedBuffers && current.hostMaxBuffer,
  680. [toggle] { toggle (&PluginRef::hostMaxBuffer); });
  681. // with Options › "Run plugins in a separate process" on, every plugin already runs in one
  682. const auto all = pluginSandboxEnabled();
  683. menu.addItem (all ? tr ("Run in a separate process (on for all plugins in Options)") : tr ("Run in a separate process"), ! all,
  684. all || current.separateProcess, [toggle] { toggle (&PluginRef::separateProcess); });
  685. // round 157a: this plugin always in its own process, in every project (e.g. after its editor crashed LYNX)
  686. if (! all && ! current.name.empty())
  687. {
  688. const auto name = juce::String::fromUTF8 (current.name.c_str());
  689. const auto always = pluginAlwaysSeparate (name);
  690. menu.addItem (tr ("Always run {0} in a separate process", { name }), true, always, [&engine, find, instance, name, always] {
  691. if (instance != nullptr)
  692. PluginWindows::close (*instance);
  693. engine.capturePluginStates();
  694. setPluginAlwaysSeparate (name, ! always);
  695. // this instance follows at once (a changed option re-creates it); others when their project opens
  696. engine.editSong ([find, on = ! always] (Song& song) { if (auto* ref = find (song)) ref->separateProcess = on; });
  697. });
  698. }
  699. // FL's "Allow threaded processing" (on by default): off keeps this plugin on the audio thread itself, for plugins
  700. // that misbehave when called from several threads. Nothing is re-created.
  701. menu.addItem (tr ("Allow threaded processing"), true, current.threaded, [&engine, find] {
  702. engine.editSong ([find] (Song& song) {
  703. if (auto* ref = find (song))
  704. ref->threaded = ! ref->threaded;
  705. });
  706. });
  707. // FL's wrapper "Allow smart disable" (on by default): off = never skipped in silence, even with the slot's
  708. // "Smart disable" on (for plugins that misbehave when they are not called)
  709. menu.addItem (tr ("Allow smart disable"), true, current.allowSmartDisable, [&engine, find] {
  710. engine.editSong ([find] (Song& song) {
  711. if (auto* ref = find (song))
  712. ref->allowSmartDisable = ! ref->allowSmartDisable;
  713. });
  714. });
  715. // FL's wrapper "MIDI input port": the MIDI Out channels on this port play the plugin (REA_rodada133 §4)
  716. juce::PopupMenu ports;
  717. auto setPort = [&engine, find] (int port) {
  718. engine.editSong ([find, port] (Song& song) {
  719. if (auto* ref = find (song))
  720. ref->midiInPort = port;
  721. });
  722. };
  723. ports.addItem (tr ("None"), true, current.midiInPort < 0, [setPort] { setPort (-1); });
  724. for (int port = 0; port < 32; ++port)
  725. ports.addItem (tr ("Port {0}", { juce::String (port) }), true, current.midiInPort == port, [setPort, port] { setPort (port); });
  726. menu.addSubMenu (current.midiInPort >= 0 ? tr ("MIDI input port ({0})", { juce::String (current.midiInPort) }) : tr ("MIDI input port"), ports);
  727. return menu;
  728. }
  729. void addPluginItems (juce::PopupMenu& menu, AudioEngine& engine, bool instruments, std::function<void (PluginRef)> onChosen, juce::Component* owner,
  730. std::function<void (ChannelDef)> onBuiltIn)
  731. {
  732. // FL's way (round 151): the favourites right here, every other plugin in the picker ("More plugins...", FL's
  733. // list of every generator / effect with its categories, search and favourite stars). The old menu listed all
  734. // of them: hundreds of items in four columns on a PC with many plugins.
  735. auto types = engine.getPluginHost().getKnownPlugins().getTypes();
  736. std::sort (types.begin(), types.end(), [] (const auto& a, const auto& b) { return a.name.compareIgnoreCase (b.name) < 0; });
  737. const auto& favourites = engine.getPluginHost().favourites();
  738. int kind = 0;
  739. for (const auto& type : types)
  740. {
  741. if (type.isInstrument != instruments)
  742. continue;
  743. ++kind;
  744. PluginRef ref;
  745. ref.id = type.createIdentifierString().toStdString();
  746. ref.name = type.name.toStdString();
  747. if (favourites.count (ref.id) == 0)
  748. continue;
  749. menu.addItem (juce::String::fromUTF8 ("\xe2\x98\x85 ") + type.name + " (" + type.manufacturerName + ") [" + type.pluginFormatName + "]",
  750. [ref, onChosen] { onChosen (ref); });
  751. }
  752. if (menu.getNumItems() > 0)
  753. menu.addSeparator();
  754. if (kind == 0 && ! onBuiltIn)
  755. menu.addItem (tr ("(no plugins found; use \"Scan for plugins\")"), false, false, [] {});
  756. else
  757. menu.addItem (instruments ? tr ("More plugins... ({0} instruments)", { juce::String (kind) }) : tr ("More plugins... ({0} effects)", { juce::String (kind) }),
  758. [&engine, instruments, onChosen, onBuiltIn, safe = juce::Component::SafePointer<juce::Component> (owner), hasOwner = owner != nullptr] {
  759. showPluginPicker (
  760. engine, instruments,
  761. [onChosen, safe, hasOwner] (PluginRef ref) {
  762. if (! hasOwner || safe != nullptr)
  763. onChosen (ref);
  764. },
  765. ! onBuiltIn ? std::function<void (ChannelDef)>()
  766. : [onBuiltIn, safe, hasOwner] (ChannelDef c) {
  767. if (! hasOwner || safe != nullptr)
  768. onBuiltIn (std::move (c));
  769. });
  770. });
  771. menu.addSeparator();
  772. menu.addItem (tr ("Scan for plugins ({0})...", { platform::pluginFormatNames() }), [&engine] { engine.getPluginHost().startBackgroundScan(); });
  773. }
  774. } // namespace lynx