The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1352 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include <JuceHeader.h>
  19. #include "GraphEditorPanel.h"
  20. #include "../Plugins/InternalPlugins.h"
  21. #include "MainHostWindow.h"
  22. //==============================================================================
  23. #if JUCE_IOS
  24. class AUScanner
  25. {
  26. public:
  27. AUScanner (KnownPluginList& list)
  28. : knownPluginList (list), pool (5)
  29. {
  30. knownPluginList.clearBlacklistedFiles();
  31. paths = formatToScan.getDefaultLocationsToSearch();
  32. startScan();
  33. }
  34. private:
  35. KnownPluginList& knownPluginList;
  36. AudioUnitPluginFormat formatToScan;
  37. std::unique_ptr<PluginDirectoryScanner> scanner;
  38. FileSearchPath paths;
  39. ThreadPool pool;
  40. void startScan()
  41. {
  42. auto deadMansPedalFile = getAppProperties().getUserSettings()
  43. ->getFile().getSiblingFile ("RecentlyCrashedPluginsList");
  44. scanner.reset (new PluginDirectoryScanner (knownPluginList, formatToScan, paths,
  45. true, deadMansPedalFile, true));
  46. for (int i = 5; --i >= 0;)
  47. pool.addJob (new ScanJob (*this), true);
  48. }
  49. bool doNextScan()
  50. {
  51. String pluginBeingScanned;
  52. if (scanner->scanNextFile (true, pluginBeingScanned))
  53. return true;
  54. return false;
  55. }
  56. struct ScanJob : public ThreadPoolJob
  57. {
  58. ScanJob (AUScanner& s) : ThreadPoolJob ("pluginscan"), scanner (s) {}
  59. JobStatus runJob()
  60. {
  61. while (scanner.doNextScan() && ! shouldExit())
  62. {}
  63. return jobHasFinished;
  64. }
  65. AUScanner& scanner;
  66. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScanJob)
  67. };
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AUScanner)
  69. };
  70. #endif
  71. //==============================================================================
  72. struct GraphEditorPanel::PinComponent : public Component,
  73. public SettableTooltipClient
  74. {
  75. PinComponent (GraphEditorPanel& p, AudioProcessorGraph::NodeAndChannel pinToUse, bool isIn)
  76. : panel (p), graph (p.graph), pin (pinToUse), isInput (isIn)
  77. {
  78. if (auto node = graph.graph.getNodeForId (pin.nodeID))
  79. {
  80. String tip;
  81. if (pin.isMIDI())
  82. {
  83. tip = isInput ? "MIDI Input"
  84. : "MIDI Output";
  85. }
  86. else
  87. {
  88. auto& processor = *node->getProcessor();
  89. auto channel = processor.getOffsetInBusBufferForAbsoluteChannelIndex (isInput, pin.channelIndex, busIdx);
  90. if (auto* bus = processor.getBus (isInput, busIdx))
  91. tip = bus->getName() + ": " + AudioChannelSet::getAbbreviatedChannelTypeName (bus->getCurrentLayout().getTypeOfChannel (channel));
  92. else
  93. tip = (isInput ? "Main Input: "
  94. : "Main Output: ") + String (pin.channelIndex + 1);
  95. }
  96. setTooltip (tip);
  97. }
  98. setSize (16, 16);
  99. }
  100. void paint (Graphics& g) override
  101. {
  102. auto w = (float) getWidth();
  103. auto h = (float) getHeight();
  104. Path p;
  105. p.addEllipse (w * 0.25f, h * 0.25f, w * 0.5f, h * 0.5f);
  106. p.addRectangle (w * 0.4f, isInput ? (0.5f * h) : 0.0f, w * 0.2f, h * 0.5f);
  107. auto colour = (pin.isMIDI() ? Colours::red : Colours::green);
  108. g.setColour (colour.withRotatedHue ((float) busIdx / 5.0f));
  109. g.fillPath (p);
  110. }
  111. void mouseDown (const MouseEvent& e) override
  112. {
  113. AudioProcessorGraph::NodeAndChannel dummy { {}, 0 };
  114. panel.beginConnectorDrag (isInput ? dummy : pin,
  115. isInput ? pin : dummy,
  116. e);
  117. }
  118. void mouseDrag (const MouseEvent& e) override
  119. {
  120. panel.dragConnector (e);
  121. }
  122. void mouseUp (const MouseEvent& e) override
  123. {
  124. panel.endDraggingConnector (e);
  125. }
  126. GraphEditorPanel& panel;
  127. PluginGraph& graph;
  128. AudioProcessorGraph::NodeAndChannel pin;
  129. const bool isInput;
  130. int busIdx = 0;
  131. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PinComponent)
  132. };
  133. //==============================================================================
  134. struct GraphEditorPanel::PluginComponent : public Component,
  135. public Timer,
  136. private AudioProcessorParameter::Listener,
  137. private AsyncUpdater
  138. {
  139. PluginComponent (GraphEditorPanel& p, AudioProcessorGraph::NodeID id) : panel (p), graph (p.graph), pluginID (id)
  140. {
  141. shadow.setShadowProperties (DropShadow (Colours::black.withAlpha (0.5f), 3, { 0, 1 }));
  142. setComponentEffect (&shadow);
  143. if (auto f = graph.graph.getNodeForId (pluginID))
  144. {
  145. if (auto* processor = f->getProcessor())
  146. {
  147. if (auto* bypassParam = processor->getBypassParameter())
  148. bypassParam->addListener (this);
  149. }
  150. }
  151. setSize (150, 60);
  152. }
  153. PluginComponent (const PluginComponent&) = delete;
  154. PluginComponent& operator= (const PluginComponent&) = delete;
  155. ~PluginComponent() override
  156. {
  157. if (auto f = graph.graph.getNodeForId (pluginID))
  158. {
  159. if (auto* processor = f->getProcessor())
  160. {
  161. if (auto* bypassParam = processor->getBypassParameter())
  162. bypassParam->removeListener (this);
  163. }
  164. }
  165. }
  166. void mouseDown (const MouseEvent& e) override
  167. {
  168. originalPos = localPointToGlobal (Point<int>());
  169. toFront (true);
  170. if (isOnTouchDevice())
  171. {
  172. startTimer (750);
  173. }
  174. else
  175. {
  176. if (e.mods.isPopupMenu())
  177. showPopupMenu();
  178. }
  179. }
  180. void mouseDrag (const MouseEvent& e) override
  181. {
  182. if (isOnTouchDevice() && e.getDistanceFromDragStart() > 5)
  183. stopTimer();
  184. if (! e.mods.isPopupMenu())
  185. {
  186. auto pos = originalPos + e.getOffsetFromDragStart();
  187. if (getParentComponent() != nullptr)
  188. pos = getParentComponent()->getLocalPoint (nullptr, pos);
  189. pos += getLocalBounds().getCentre();
  190. graph.setNodePosition (pluginID,
  191. { pos.x / (double) getParentWidth(),
  192. pos.y / (double) getParentHeight() });
  193. panel.updateComponents();
  194. }
  195. }
  196. void mouseUp (const MouseEvent& e) override
  197. {
  198. if (isOnTouchDevice())
  199. {
  200. stopTimer();
  201. callAfterDelay (250, []() { PopupMenu::dismissAllActiveMenus(); });
  202. }
  203. if (e.mouseWasDraggedSinceMouseDown())
  204. {
  205. graph.setChangedFlag (true);
  206. }
  207. else if (e.getNumberOfClicks() == 2)
  208. {
  209. if (auto f = graph.graph.getNodeForId (pluginID))
  210. if (auto* w = graph.getOrCreateWindowFor (f, PluginWindow::Type::normal))
  211. w->toFront (true);
  212. }
  213. }
  214. bool hitTest (int x, int y) override
  215. {
  216. for (auto* child : getChildren())
  217. if (child->getBounds().contains (x, y))
  218. return true;
  219. return x >= 3 && x < getWidth() - 6 && y >= pinSize && y < getHeight() - pinSize;
  220. }
  221. void paint (Graphics& g) override
  222. {
  223. auto boxArea = getLocalBounds().reduced (4, pinSize);
  224. bool isBypassed = false;
  225. if (auto* f = graph.graph.getNodeForId (pluginID))
  226. isBypassed = f->isBypassed();
  227. auto boxColour = findColour (TextEditor::backgroundColourId);
  228. if (isBypassed)
  229. boxColour = boxColour.brighter();
  230. g.setColour (boxColour);
  231. g.fillRect (boxArea.toFloat());
  232. g.setColour (findColour (TextEditor::textColourId));
  233. g.setFont (font);
  234. g.drawFittedText (getName(), boxArea, Justification::centred, 2);
  235. }
  236. void resized() override
  237. {
  238. if (auto f = graph.graph.getNodeForId (pluginID))
  239. {
  240. if (auto* processor = f->getProcessor())
  241. {
  242. for (auto* pin : pins)
  243. {
  244. const bool isInput = pin->isInput;
  245. auto channelIndex = pin->pin.channelIndex;
  246. int busIdx = 0;
  247. processor->getOffsetInBusBufferForAbsoluteChannelIndex (isInput, channelIndex, busIdx);
  248. const int total = isInput ? numIns : numOuts;
  249. const int index = pin->pin.isMIDI() ? (total - 1) : channelIndex;
  250. auto totalSpaces = static_cast<float> (total) + (static_cast<float> (jmax (0, processor->getBusCount (isInput) - 1)) * 0.5f);
  251. auto indexPos = static_cast<float> (index) + (static_cast<float> (busIdx) * 0.5f);
  252. pin->setBounds (proportionOfWidth ((1.0f + indexPos) / (totalSpaces + 1.0f)) - pinSize / 2,
  253. pin->isInput ? 0 : (getHeight() - pinSize),
  254. pinSize, pinSize);
  255. }
  256. }
  257. }
  258. }
  259. Point<float> getPinPos (int index, bool isInput) const
  260. {
  261. for (auto* pin : pins)
  262. if (pin->pin.channelIndex == index && isInput == pin->isInput)
  263. return getPosition().toFloat() + pin->getBounds().getCentre().toFloat();
  264. return {};
  265. }
  266. void update()
  267. {
  268. const AudioProcessorGraph::Node::Ptr f (graph.graph.getNodeForId (pluginID));
  269. jassert (f != nullptr);
  270. auto& processor = *f->getProcessor();
  271. numIns = processor.getTotalNumInputChannels();
  272. if (processor.acceptsMidi())
  273. ++numIns;
  274. numOuts = processor.getTotalNumOutputChannels();
  275. if (processor.producesMidi())
  276. ++numOuts;
  277. int w = 100;
  278. int h = 60;
  279. w = jmax (w, (jmax (numIns, numOuts) + 1) * 20);
  280. const int textWidth = font.getStringWidth (processor.getName());
  281. w = jmax (w, 16 + jmin (textWidth, 300));
  282. if (textWidth > 300)
  283. h = 100;
  284. setSize (w, h);
  285. setName (processor.getName() + formatSuffix);
  286. {
  287. auto p = graph.getNodePosition (pluginID);
  288. setCentreRelative ((float) p.x, (float) p.y);
  289. }
  290. if (numIns != numInputs || numOuts != numOutputs)
  291. {
  292. numInputs = numIns;
  293. numOutputs = numOuts;
  294. pins.clear();
  295. for (int i = 0; i < processor.getTotalNumInputChannels(); ++i)
  296. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, i }, true)));
  297. if (processor.acceptsMidi())
  298. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, AudioProcessorGraph::midiChannelIndex }, true)));
  299. for (int i = 0; i < processor.getTotalNumOutputChannels(); ++i)
  300. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, i }, false)));
  301. if (processor.producesMidi())
  302. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, AudioProcessorGraph::midiChannelIndex }, false)));
  303. resized();
  304. }
  305. }
  306. AudioProcessor* getProcessor() const
  307. {
  308. if (auto node = graph.graph.getNodeForId (pluginID))
  309. return node->getProcessor();
  310. return {};
  311. }
  312. void showPopupMenu()
  313. {
  314. menu.reset (new PopupMenu);
  315. menu->addItem (1, "Delete this filter");
  316. menu->addItem (2, "Disconnect all pins");
  317. menu->addItem (3, "Toggle Bypass");
  318. menu->addSeparator();
  319. if (getProcessor()->hasEditor())
  320. menu->addItem (10, "Show plugin GUI");
  321. menu->addItem (11, "Show all programs");
  322. menu->addItem (12, "Show all parameters");
  323. menu->addItem (13, "Show debug log");
  324. if (autoScaleOptionAvailable)
  325. addPluginAutoScaleOptionsSubMenu (dynamic_cast<AudioPluginInstance*> (getProcessor()), *menu);
  326. menu->addSeparator();
  327. menu->addItem (20, "Configure Audio I/O");
  328. menu->addItem (21, "Test state save/load");
  329. menu->showMenuAsync ({}, ModalCallbackFunction::create
  330. ([this] (int r) {
  331. switch (r)
  332. {
  333. case 1: graph.graph.removeNode (pluginID); break;
  334. case 2: graph.graph.disconnectNode (pluginID); break;
  335. case 3:
  336. {
  337. if (auto* node = graph.graph.getNodeForId (pluginID))
  338. node->setBypassed (! node->isBypassed());
  339. repaint();
  340. break;
  341. }
  342. case 10: showWindow (PluginWindow::Type::normal); break;
  343. case 11: showWindow (PluginWindow::Type::programs); break;
  344. case 12: showWindow (PluginWindow::Type::generic) ; break;
  345. case 13: showWindow (PluginWindow::Type::debug); break;
  346. case 20: showWindow (PluginWindow::Type::audioIO); break;
  347. case 21: testStateSaveLoad(); break;
  348. default: break;
  349. }
  350. }));
  351. }
  352. void testStateSaveLoad()
  353. {
  354. if (auto* processor = getProcessor())
  355. {
  356. MemoryBlock state;
  357. processor->getStateInformation (state);
  358. processor->setStateInformation (state.getData(), (int) state.getSize());
  359. }
  360. }
  361. void showWindow (PluginWindow::Type type)
  362. {
  363. if (auto node = graph.graph.getNodeForId (pluginID))
  364. if (auto* w = graph.getOrCreateWindowFor (node, type))
  365. w->toFront (true);
  366. }
  367. void timerCallback() override
  368. {
  369. // this should only be called on touch devices
  370. jassert (isOnTouchDevice());
  371. stopTimer();
  372. showPopupMenu();
  373. }
  374. void parameterValueChanged (int, float) override
  375. {
  376. // Parameter changes might come from the audio thread or elsewhere, but
  377. // we can only call repaint from the message thread.
  378. triggerAsyncUpdate();
  379. }
  380. void parameterGestureChanged (int, bool) override {}
  381. void handleAsyncUpdate() override { repaint(); }
  382. GraphEditorPanel& panel;
  383. PluginGraph& graph;
  384. const AudioProcessorGraph::NodeID pluginID;
  385. OwnedArray<PinComponent> pins;
  386. int numInputs = 0, numOutputs = 0;
  387. int pinSize = 16;
  388. Point<int> originalPos;
  389. Font font { 13.0f, Font::bold };
  390. int numIns = 0, numOuts = 0;
  391. DropShadowEffect shadow;
  392. std::unique_ptr<PopupMenu> menu;
  393. const String formatSuffix = getFormatSuffix (getProcessor());
  394. };
  395. //==============================================================================
  396. struct GraphEditorPanel::ConnectorComponent : public Component,
  397. public SettableTooltipClient
  398. {
  399. explicit ConnectorComponent (GraphEditorPanel& p)
  400. : panel (p), graph (p.graph)
  401. {
  402. setAlwaysOnTop (true);
  403. }
  404. void setInput (AudioProcessorGraph::NodeAndChannel newSource)
  405. {
  406. if (connection.source != newSource)
  407. {
  408. connection.source = newSource;
  409. update();
  410. }
  411. }
  412. void setOutput (AudioProcessorGraph::NodeAndChannel newDest)
  413. {
  414. if (connection.destination != newDest)
  415. {
  416. connection.destination = newDest;
  417. update();
  418. }
  419. }
  420. void dragStart (Point<float> pos)
  421. {
  422. lastInputPos = pos;
  423. resizeToFit();
  424. }
  425. void dragEnd (Point<float> pos)
  426. {
  427. lastOutputPos = pos;
  428. resizeToFit();
  429. }
  430. void update()
  431. {
  432. Point<float> p1, p2;
  433. getPoints (p1, p2);
  434. if (lastInputPos != p1 || lastOutputPos != p2)
  435. resizeToFit();
  436. }
  437. void resizeToFit()
  438. {
  439. Point<float> p1, p2;
  440. getPoints (p1, p2);
  441. auto newBounds = Rectangle<float> (p1, p2).expanded (4.0f).getSmallestIntegerContainer();
  442. if (newBounds != getBounds())
  443. setBounds (newBounds);
  444. else
  445. resized();
  446. repaint();
  447. }
  448. void getPoints (Point<float>& p1, Point<float>& p2) const
  449. {
  450. p1 = lastInputPos;
  451. p2 = lastOutputPos;
  452. if (auto* src = panel.getComponentForPlugin (connection.source.nodeID))
  453. p1 = src->getPinPos (connection.source.channelIndex, false);
  454. if (auto* dest = panel.getComponentForPlugin (connection.destination.nodeID))
  455. p2 = dest->getPinPos (connection.destination.channelIndex, true);
  456. }
  457. void paint (Graphics& g) override
  458. {
  459. if (connection.source.isMIDI() || connection.destination.isMIDI())
  460. g.setColour (Colours::red);
  461. else
  462. g.setColour (Colours::green);
  463. g.fillPath (linePath);
  464. }
  465. bool hitTest (int x, int y) override
  466. {
  467. auto pos = Point<int> (x, y).toFloat();
  468. if (hitPath.contains (pos))
  469. {
  470. double distanceFromStart, distanceFromEnd;
  471. getDistancesFromEnds (pos, distanceFromStart, distanceFromEnd);
  472. // avoid clicking the connector when over a pin
  473. return distanceFromStart > 7.0 && distanceFromEnd > 7.0;
  474. }
  475. return false;
  476. }
  477. void mouseDown (const MouseEvent&) override
  478. {
  479. dragging = false;
  480. }
  481. void mouseDrag (const MouseEvent& e) override
  482. {
  483. if (dragging)
  484. {
  485. panel.dragConnector (e);
  486. }
  487. else if (e.mouseWasDraggedSinceMouseDown())
  488. {
  489. dragging = true;
  490. graph.graph.removeConnection (connection);
  491. double distanceFromStart, distanceFromEnd;
  492. getDistancesFromEnds (getPosition().toFloat() + e.position, distanceFromStart, distanceFromEnd);
  493. const bool isNearerSource = (distanceFromStart < distanceFromEnd);
  494. AudioProcessorGraph::NodeAndChannel dummy { {}, 0 };
  495. panel.beginConnectorDrag (isNearerSource ? dummy : connection.source,
  496. isNearerSource ? connection.destination : dummy,
  497. e);
  498. }
  499. }
  500. void mouseUp (const MouseEvent& e) override
  501. {
  502. if (dragging)
  503. panel.endDraggingConnector (e);
  504. }
  505. void resized() override
  506. {
  507. Point<float> p1, p2;
  508. getPoints (p1, p2);
  509. lastInputPos = p1;
  510. lastOutputPos = p2;
  511. p1 -= getPosition().toFloat();
  512. p2 -= getPosition().toFloat();
  513. linePath.clear();
  514. linePath.startNewSubPath (p1);
  515. linePath.cubicTo (p1.x, p1.y + (p2.y - p1.y) * 0.33f,
  516. p2.x, p1.y + (p2.y - p1.y) * 0.66f,
  517. p2.x, p2.y);
  518. PathStrokeType wideStroke (8.0f);
  519. wideStroke.createStrokedPath (hitPath, linePath);
  520. PathStrokeType stroke (2.5f);
  521. stroke.createStrokedPath (linePath, linePath);
  522. auto arrowW = 5.0f;
  523. auto arrowL = 4.0f;
  524. Path arrow;
  525. arrow.addTriangle (-arrowL, arrowW,
  526. -arrowL, -arrowW,
  527. arrowL, 0.0f);
  528. arrow.applyTransform (AffineTransform()
  529. .rotated (MathConstants<float>::halfPi - (float) atan2 (p2.x - p1.x, p2.y - p1.y))
  530. .translated ((p1 + p2) * 0.5f));
  531. linePath.addPath (arrow);
  532. linePath.setUsingNonZeroWinding (true);
  533. }
  534. void getDistancesFromEnds (Point<float> p, double& distanceFromStart, double& distanceFromEnd) const
  535. {
  536. Point<float> p1, p2;
  537. getPoints (p1, p2);
  538. distanceFromStart = p1.getDistanceFrom (p);
  539. distanceFromEnd = p2.getDistanceFrom (p);
  540. }
  541. GraphEditorPanel& panel;
  542. PluginGraph& graph;
  543. AudioProcessorGraph::Connection connection { { {}, 0 }, { {}, 0 } };
  544. Point<float> lastInputPos, lastOutputPos;
  545. Path linePath, hitPath;
  546. bool dragging = false;
  547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectorComponent)
  548. };
  549. //==============================================================================
  550. GraphEditorPanel::GraphEditorPanel (PluginGraph& g) : graph (g)
  551. {
  552. graph.addChangeListener (this);
  553. setOpaque (true);
  554. }
  555. GraphEditorPanel::~GraphEditorPanel()
  556. {
  557. graph.removeChangeListener (this);
  558. draggingConnector = nullptr;
  559. nodes.clear();
  560. connectors.clear();
  561. }
  562. void GraphEditorPanel::paint (Graphics& g)
  563. {
  564. g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
  565. }
  566. void GraphEditorPanel::mouseDown (const MouseEvent& e)
  567. {
  568. if (isOnTouchDevice())
  569. {
  570. originalTouchPos = e.position.toInt();
  571. startTimer (750);
  572. }
  573. if (e.mods.isPopupMenu())
  574. showPopupMenu (e.position.toInt());
  575. }
  576. void GraphEditorPanel::mouseUp (const MouseEvent&)
  577. {
  578. if (isOnTouchDevice())
  579. {
  580. stopTimer();
  581. callAfterDelay (250, []() { PopupMenu::dismissAllActiveMenus(); });
  582. }
  583. }
  584. void GraphEditorPanel::mouseDrag (const MouseEvent& e)
  585. {
  586. if (isOnTouchDevice() && e.getDistanceFromDragStart() > 5)
  587. stopTimer();
  588. }
  589. void GraphEditorPanel::createNewPlugin (const PluginDescription& desc, Point<int> position)
  590. {
  591. graph.addPlugin (desc, position.toDouble() / Point<double> ((double) getWidth(), (double) getHeight()));
  592. }
  593. GraphEditorPanel::PluginComponent* GraphEditorPanel::getComponentForPlugin (AudioProcessorGraph::NodeID nodeID) const
  594. {
  595. for (auto* fc : nodes)
  596. if (fc->pluginID == nodeID)
  597. return fc;
  598. return nullptr;
  599. }
  600. GraphEditorPanel::ConnectorComponent* GraphEditorPanel::getComponentForConnection (const AudioProcessorGraph::Connection& conn) const
  601. {
  602. for (auto* cc : connectors)
  603. if (cc->connection == conn)
  604. return cc;
  605. return nullptr;
  606. }
  607. GraphEditorPanel::PinComponent* GraphEditorPanel::findPinAt (Point<float> pos) const
  608. {
  609. for (auto* fc : nodes)
  610. {
  611. // NB: A Visual Studio optimiser error means we have to put this Component* in a local
  612. // variable before trying to cast it, or it gets mysteriously optimised away..
  613. auto* comp = fc->getComponentAt (pos.toInt() - fc->getPosition());
  614. if (auto* pin = dynamic_cast<PinComponent*> (comp))
  615. return pin;
  616. }
  617. return nullptr;
  618. }
  619. void GraphEditorPanel::resized()
  620. {
  621. updateComponents();
  622. }
  623. void GraphEditorPanel::changeListenerCallback (ChangeBroadcaster*)
  624. {
  625. updateComponents();
  626. }
  627. void GraphEditorPanel::updateComponents()
  628. {
  629. for (int i = nodes.size(); --i >= 0;)
  630. if (graph.graph.getNodeForId (nodes.getUnchecked(i)->pluginID) == nullptr)
  631. nodes.remove (i);
  632. for (int i = connectors.size(); --i >= 0;)
  633. if (! graph.graph.isConnected (connectors.getUnchecked(i)->connection))
  634. connectors.remove (i);
  635. for (auto* fc : nodes)
  636. fc->update();
  637. for (auto* cc : connectors)
  638. cc->update();
  639. for (auto* f : graph.graph.getNodes())
  640. {
  641. if (getComponentForPlugin (f->nodeID) == nullptr)
  642. {
  643. auto* comp = nodes.add (new PluginComponent (*this, f->nodeID));
  644. addAndMakeVisible (comp);
  645. comp->update();
  646. }
  647. }
  648. for (auto& c : graph.graph.getConnections())
  649. {
  650. if (getComponentForConnection (c) == nullptr)
  651. {
  652. auto* comp = connectors.add (new ConnectorComponent (*this));
  653. addAndMakeVisible (comp);
  654. comp->setInput (c.source);
  655. comp->setOutput (c.destination);
  656. }
  657. }
  658. }
  659. void GraphEditorPanel::showPopupMenu (Point<int> mousePos)
  660. {
  661. menu.reset (new PopupMenu);
  662. if (auto* mainWindow = findParentComponentOfClass<MainHostWindow>())
  663. {
  664. mainWindow->addPluginsToMenu (*menu);
  665. menu->showMenuAsync ({},
  666. ModalCallbackFunction::create ([this, mousePos] (int r)
  667. {
  668. if (r > 0)
  669. if (auto* mainWin = findParentComponentOfClass<MainHostWindow>())
  670. createNewPlugin (mainWin->getChosenType (r), mousePos);
  671. }));
  672. }
  673. }
  674. void GraphEditorPanel::beginConnectorDrag (AudioProcessorGraph::NodeAndChannel source,
  675. AudioProcessorGraph::NodeAndChannel dest,
  676. const MouseEvent& e)
  677. {
  678. auto* c = dynamic_cast<ConnectorComponent*> (e.originalComponent);
  679. connectors.removeObject (c, false);
  680. draggingConnector.reset (c);
  681. if (draggingConnector == nullptr)
  682. draggingConnector.reset (new ConnectorComponent (*this));
  683. draggingConnector->setInput (source);
  684. draggingConnector->setOutput (dest);
  685. addAndMakeVisible (draggingConnector.get());
  686. draggingConnector->toFront (false);
  687. dragConnector (e);
  688. }
  689. void GraphEditorPanel::dragConnector (const MouseEvent& e)
  690. {
  691. auto e2 = e.getEventRelativeTo (this);
  692. if (draggingConnector != nullptr)
  693. {
  694. draggingConnector->setTooltip ({});
  695. auto pos = e2.position;
  696. if (auto* pin = findPinAt (pos))
  697. {
  698. auto connection = draggingConnector->connection;
  699. if (connection.source.nodeID == AudioProcessorGraph::NodeID() && ! pin->isInput)
  700. {
  701. connection.source = pin->pin;
  702. }
  703. else if (connection.destination.nodeID == AudioProcessorGraph::NodeID() && pin->isInput)
  704. {
  705. connection.destination = pin->pin;
  706. }
  707. if (graph.graph.canConnect (connection))
  708. {
  709. pos = (pin->getParentComponent()->getPosition() + pin->getBounds().getCentre()).toFloat();
  710. draggingConnector->setTooltip (pin->getTooltip());
  711. }
  712. }
  713. if (draggingConnector->connection.source.nodeID == AudioProcessorGraph::NodeID())
  714. draggingConnector->dragStart (pos);
  715. else
  716. draggingConnector->dragEnd (pos);
  717. }
  718. }
  719. void GraphEditorPanel::endDraggingConnector (const MouseEvent& e)
  720. {
  721. if (draggingConnector == nullptr)
  722. return;
  723. draggingConnector->setTooltip ({});
  724. auto e2 = e.getEventRelativeTo (this);
  725. auto connection = draggingConnector->connection;
  726. draggingConnector = nullptr;
  727. if (auto* pin = findPinAt (e2.position))
  728. {
  729. if (connection.source.nodeID == AudioProcessorGraph::NodeID())
  730. {
  731. if (pin->isInput)
  732. return;
  733. connection.source = pin->pin;
  734. }
  735. else
  736. {
  737. if (! pin->isInput)
  738. return;
  739. connection.destination = pin->pin;
  740. }
  741. graph.graph.addConnection (connection);
  742. }
  743. }
  744. void GraphEditorPanel::timerCallback()
  745. {
  746. // this should only be called on touch devices
  747. jassert (isOnTouchDevice());
  748. stopTimer();
  749. showPopupMenu (originalTouchPos);
  750. }
  751. //==============================================================================
  752. struct GraphDocumentComponent::TooltipBar : public Component,
  753. private Timer
  754. {
  755. TooltipBar()
  756. {
  757. startTimer (100);
  758. }
  759. void paint (Graphics& g) override
  760. {
  761. g.setFont (Font ((float) getHeight() * 0.7f, Font::bold));
  762. g.setColour (Colours::black);
  763. g.drawFittedText (tip, 10, 0, getWidth() - 12, getHeight(), Justification::centredLeft, 1);
  764. }
  765. void timerCallback() override
  766. {
  767. String newTip;
  768. if (auto* underMouse = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse())
  769. if (auto* ttc = dynamic_cast<TooltipClient*> (underMouse))
  770. if (! (underMouse->isMouseButtonDown() || underMouse->isCurrentlyBlockedByAnotherModalComponent()))
  771. newTip = ttc->getTooltip();
  772. if (newTip != tip)
  773. {
  774. tip = newTip;
  775. repaint();
  776. }
  777. }
  778. String tip;
  779. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipBar)
  780. };
  781. //==============================================================================
  782. class GraphDocumentComponent::TitleBarComponent : public Component,
  783. private Button::Listener
  784. {
  785. public:
  786. explicit TitleBarComponent (GraphDocumentComponent& graphDocumentComponent)
  787. : owner (graphDocumentComponent)
  788. {
  789. static const unsigned char burgerMenuPathData[]
  790. = { 110,109,0,0,128,64,0,0,32,65,108,0,0,224,65,0,0,32,65,98,254,212,232,65,0,0,32,65,0,0,240,65,252,
  791. 169,17,65,0,0,240,65,0,0,0,65,98,0,0,240,65,8,172,220,64,254,212,232,65,0,0,192,64,0,0,224,65,0,0,
  792. 192,64,108,0,0,128,64,0,0,192,64,98,16,88,57,64,0,0,192,64,0,0,0,64,8,172,220,64,0,0,0,64,0,0,0,65,
  793. 98,0,0,0,64,252,169,17,65,16,88,57,64,0,0,32,65,0,0,128,64,0,0,32,65,99,109,0,0,224,65,0,0,96,65,108,
  794. 0,0,128,64,0,0,96,65,98,16,88,57,64,0,0,96,65,0,0,0,64,4,86,110,65,0,0,0,64,0,0,128,65,98,0,0,0,64,
  795. 254,212,136,65,16,88,57,64,0,0,144,65,0,0,128,64,0,0,144,65,108,0,0,224,65,0,0,144,65,98,254,212,232,
  796. 65,0,0,144,65,0,0,240,65,254,212,136,65,0,0,240,65,0,0,128,65,98,0,0,240,65,4,86,110,65,254,212,232,
  797. 65,0,0,96,65,0,0,224,65,0,0,96,65,99,109,0,0,224,65,0,0,176,65,108,0,0,128,64,0,0,176,65,98,16,88,57,
  798. 64,0,0,176,65,0,0,0,64,2,43,183,65,0,0,0,64,0,0,192,65,98,0,0,0,64,254,212,200,65,16,88,57,64,0,0,208,
  799. 65,0,0,128,64,0,0,208,65,108,0,0,224,65,0,0,208,65,98,254,212,232,65,0,0,208,65,0,0,240,65,254,212,
  800. 200,65,0,0,240,65,0,0,192,65,98,0,0,240,65,2,43,183,65,254,212,232,65,0,0,176,65,0,0,224,65,0,0,176,
  801. 65,99,101,0,0 };
  802. static const unsigned char pluginListPathData[]
  803. = { 110,109,193,202,222,64,80,50,21,64,108,0,0,48,65,0,0,0,0,108,160,154,112,65,80,50,21,64,108,0,0,48,65,80,
  804. 50,149,64,108,193,202,222,64,80,50,21,64,99,109,0,0,192,64,251,220,127,64,108,160,154,32,65,165,135,202,
  805. 64,108,160,154,32,65,250,220,47,65,108,0,0,192,64,102,144,10,65,108,0,0,192,64,251,220,127,64,99,109,0,0,
  806. 128,65,251,220,127,64,108,0,0,128,65,103,144,10,65,108,96,101,63,65,251,220,47,65,108,96,101,63,65,166,135,
  807. 202,64,108,0,0,128,65,251,220,127,64,99,109,96,101,79,65,148,76,69,65,108,0,0,136,65,0,0,32,65,108,80,
  808. 77,168,65,148,76,69,65,108,0,0,136,65,40,153,106,65,108,96,101,79,65,148,76,69,65,99,109,0,0,64,65,63,247,
  809. 95,65,108,80,77,128,65,233,161,130,65,108,80,77,128,65,125,238,167,65,108,0,0,64,65,51,72,149,65,108,0,0,64,
  810. 65,63,247,95,65,99,109,0,0,176,65,63,247,95,65,108,0,0,176,65,51,72,149,65,108,176,178,143,65,125,238,167,65,
  811. 108,176,178,143,65,233,161,130,65,108,0,0,176,65,63,247,95,65,99,109,12,86,118,63,148,76,69,65,108,0,0,160,
  812. 64,0,0,32,65,108,159,154,16,65,148,76,69,65,108,0,0,160,64,40,153,106,65,108,12,86,118,63,148,76,69,65,99,
  813. 109,0,0,0,0,63,247,95,65,108,62,53,129,64,233,161,130,65,108,62,53,129,64,125,238,167,65,108,0,0,0,0,51,
  814. 72,149,65,108,0,0,0,0,63,247,95,65,99,109,0,0,32,65,63,247,95,65,108,0,0,32,65,51,72,149,65,108,193,202,190,
  815. 64,125,238,167,65,108,193,202,190,64,233,161,130,65,108,0,0,32,65,63,247,95,65,99,101,0,0 };
  816. {
  817. Path p;
  818. p.loadPathFromData (burgerMenuPathData, sizeof (burgerMenuPathData));
  819. burgerButton.setShape (p, true, true, false);
  820. }
  821. {
  822. Path p;
  823. p.loadPathFromData (pluginListPathData, sizeof (pluginListPathData));
  824. pluginButton.setShape (p, true, true, false);
  825. }
  826. burgerButton.addListener (this);
  827. addAndMakeVisible (burgerButton);
  828. pluginButton.addListener (this);
  829. addAndMakeVisible (pluginButton);
  830. titleLabel.setJustificationType (Justification::centredLeft);
  831. addAndMakeVisible (titleLabel);
  832. setOpaque (true);
  833. }
  834. private:
  835. void paint (Graphics& g) override
  836. {
  837. auto titleBarBackgroundColour = getLookAndFeel().findColour (ResizableWindow::backgroundColourId).darker();
  838. g.setColour (titleBarBackgroundColour);
  839. g.fillRect (getLocalBounds());
  840. }
  841. void resized() override
  842. {
  843. auto r = getLocalBounds();
  844. burgerButton.setBounds (r.removeFromLeft (40).withSizeKeepingCentre (20, 20));
  845. pluginButton.setBounds (r.removeFromRight (40).withSizeKeepingCentre (20, 20));
  846. titleLabel.setFont (Font (static_cast<float> (getHeight()) * 0.5f, Font::plain));
  847. titleLabel.setBounds (r);
  848. }
  849. void buttonClicked (Button* b) override
  850. {
  851. owner.showSidePanel (b == &burgerButton);
  852. }
  853. GraphDocumentComponent& owner;
  854. Label titleLabel {"titleLabel", "Plugin Host"};
  855. ShapeButton burgerButton {"burgerButton", Colours::lightgrey, Colours::lightgrey, Colours::white};
  856. ShapeButton pluginButton {"pluginButton", Colours::lightgrey, Colours::lightgrey, Colours::white};
  857. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TitleBarComponent)
  858. };
  859. //==============================================================================
  860. struct GraphDocumentComponent::PluginListBoxModel : public ListBoxModel,
  861. public ChangeListener,
  862. public MouseListener
  863. {
  864. PluginListBoxModel (ListBox& lb, KnownPluginList& kpl)
  865. : owner (lb),
  866. knownPlugins (kpl)
  867. {
  868. knownPlugins.addChangeListener (this);
  869. owner.addMouseListener (this, true);
  870. #if JUCE_IOS
  871. scanner.reset (new AUScanner (knownPlugins));
  872. #endif
  873. }
  874. int getNumRows() override
  875. {
  876. return knownPlugins.getNumTypes();
  877. }
  878. void paintListBoxItem (int rowNumber, Graphics& g,
  879. int width, int height, bool rowIsSelected) override
  880. {
  881. g.fillAll (rowIsSelected ? Colour (0xff42A2C8)
  882. : Colour (0xff263238));
  883. g.setColour (rowIsSelected ? Colours::black : Colours::white);
  884. if (rowNumber < knownPlugins.getNumTypes())
  885. g.drawFittedText (knownPlugins.getTypes()[rowNumber].name, { 0, 0, width, height - 2 }, Justification::centred, 1);
  886. g.setColour (Colours::black.withAlpha (0.4f));
  887. g.drawRect (0, height - 1, width, 1);
  888. }
  889. var getDragSourceDescription (const SparseSet<int>& selectedRows) override
  890. {
  891. if (! isOverSelectedRow)
  892. return var();
  893. return String ("PLUGIN: " + String (selectedRows[0]));
  894. }
  895. void changeListenerCallback (ChangeBroadcaster*) override
  896. {
  897. owner.updateContent();
  898. }
  899. void mouseDown (const MouseEvent& e) override
  900. {
  901. isOverSelectedRow = owner.getRowPosition (owner.getSelectedRow(), true)
  902. .contains (e.getEventRelativeTo (&owner).getMouseDownPosition());
  903. }
  904. ListBox& owner;
  905. KnownPluginList& knownPlugins;
  906. bool isOverSelectedRow = false;
  907. #if JUCE_IOS
  908. std::unique_ptr<AUScanner> scanner;
  909. #endif
  910. JUCE_DECLARE_NON_COPYABLE (PluginListBoxModel)
  911. };
  912. //==============================================================================
  913. GraphDocumentComponent::GraphDocumentComponent (AudioPluginFormatManager& fm,
  914. AudioDeviceManager& dm,
  915. KnownPluginList& kpl)
  916. : graph (new PluginGraph (fm, kpl)),
  917. deviceManager (dm),
  918. pluginList (kpl),
  919. graphPlayer (getAppProperties().getUserSettings()->getBoolValue ("doublePrecisionProcessing", false))
  920. {
  921. init();
  922. deviceManager.addChangeListener (graphPanel.get());
  923. deviceManager.addAudioCallback (&graphPlayer);
  924. deviceManager.addMidiInputDeviceCallback ({}, &graphPlayer.getMidiMessageCollector());
  925. deviceManager.addChangeListener (this);
  926. }
  927. void GraphDocumentComponent::init()
  928. {
  929. updateMidiOutput();
  930. graphPanel.reset (new GraphEditorPanel (*graph));
  931. addAndMakeVisible (graphPanel.get());
  932. graphPlayer.setProcessor (&graph->graph);
  933. keyState.addListener (&graphPlayer.getMidiMessageCollector());
  934. keyboardComp.reset (new MidiKeyboardComponent (keyState, MidiKeyboardComponent::horizontalKeyboard));
  935. addAndMakeVisible (keyboardComp.get());
  936. statusBar.reset (new TooltipBar());
  937. addAndMakeVisible (statusBar.get());
  938. graphPanel->updateComponents();
  939. if (isOnTouchDevice())
  940. {
  941. titleBarComponent.reset (new TitleBarComponent (*this));
  942. addAndMakeVisible (titleBarComponent.get());
  943. pluginListBoxModel.reset (new PluginListBoxModel (pluginListBox, pluginList));
  944. pluginListBox.setModel (pluginListBoxModel.get());
  945. pluginListBox.setRowHeight (40);
  946. pluginListSidePanel.setContent (&pluginListBox, false);
  947. mobileSettingsSidePanel.setContent (new AudioDeviceSelectorComponent (deviceManager,
  948. 0, 2, 0, 2,
  949. true, true, true, false));
  950. addAndMakeVisible (pluginListSidePanel);
  951. addAndMakeVisible (mobileSettingsSidePanel);
  952. }
  953. }
  954. GraphDocumentComponent::~GraphDocumentComponent()
  955. {
  956. if (midiOutput != nullptr)
  957. midiOutput->stopBackgroundThread();
  958. releaseGraph();
  959. keyState.removeListener (&graphPlayer.getMidiMessageCollector());
  960. }
  961. void GraphDocumentComponent::resized()
  962. {
  963. auto r = [this]
  964. {
  965. auto bounds = getLocalBounds();
  966. if (auto* display = Desktop::getInstance().getDisplays().getDisplayForRect (getScreenBounds()))
  967. return display->safeAreaInsets.subtractedFrom (bounds);
  968. return bounds;
  969. }();
  970. const int titleBarHeight = 40;
  971. const int keysHeight = 60;
  972. const int statusHeight = 20;
  973. if (isOnTouchDevice())
  974. titleBarComponent->setBounds (r.removeFromTop(titleBarHeight));
  975. keyboardComp->setBounds (r.removeFromBottom (keysHeight));
  976. statusBar->setBounds (r.removeFromBottom (statusHeight));
  977. graphPanel->setBounds (r);
  978. checkAvailableWidth();
  979. }
  980. void GraphDocumentComponent::createNewPlugin (const PluginDescription& desc, Point<int> pos)
  981. {
  982. graphPanel->createNewPlugin (desc, pos);
  983. }
  984. void GraphDocumentComponent::unfocusKeyboardComponent()
  985. {
  986. keyboardComp->unfocusAllComponents();
  987. }
  988. void GraphDocumentComponent::releaseGraph()
  989. {
  990. deviceManager.removeAudioCallback (&graphPlayer);
  991. deviceManager.removeMidiInputDeviceCallback ({}, &graphPlayer.getMidiMessageCollector());
  992. if (graphPanel != nullptr)
  993. {
  994. deviceManager.removeChangeListener (graphPanel.get());
  995. graphPanel = nullptr;
  996. }
  997. keyboardComp = nullptr;
  998. statusBar = nullptr;
  999. graphPlayer.setProcessor (nullptr);
  1000. graph = nullptr;
  1001. }
  1002. bool GraphDocumentComponent::isInterestedInDragSource (const SourceDetails& details)
  1003. {
  1004. return ((dynamic_cast<ListBox*> (details.sourceComponent.get()) != nullptr)
  1005. && details.description.toString().startsWith ("PLUGIN"));
  1006. }
  1007. void GraphDocumentComponent::itemDropped (const SourceDetails& details)
  1008. {
  1009. // don't allow items to be dropped behind the sidebar
  1010. if (pluginListSidePanel.getBounds().contains (details.localPosition))
  1011. return;
  1012. auto pluginTypeIndex = details.description.toString()
  1013. .fromFirstOccurrenceOf ("PLUGIN: ", false, false)
  1014. .getIntValue();
  1015. // must be a valid index!
  1016. jassert (isPositiveAndBelow (pluginTypeIndex, pluginList.getNumTypes()));
  1017. createNewPlugin (pluginList.getTypes()[pluginTypeIndex], details.localPosition);
  1018. }
  1019. void GraphDocumentComponent::showSidePanel (bool showSettingsPanel)
  1020. {
  1021. if (showSettingsPanel)
  1022. mobileSettingsSidePanel.showOrHide (true);
  1023. else
  1024. pluginListSidePanel.showOrHide (true);
  1025. checkAvailableWidth();
  1026. lastOpenedSidePanel = showSettingsPanel ? &mobileSettingsSidePanel
  1027. : &pluginListSidePanel;
  1028. }
  1029. void GraphDocumentComponent::hideLastSidePanel()
  1030. {
  1031. if (lastOpenedSidePanel != nullptr)
  1032. lastOpenedSidePanel->showOrHide (false);
  1033. if (mobileSettingsSidePanel.isPanelShowing()) lastOpenedSidePanel = &mobileSettingsSidePanel;
  1034. else if (pluginListSidePanel.isPanelShowing()) lastOpenedSidePanel = &pluginListSidePanel;
  1035. else lastOpenedSidePanel = nullptr;
  1036. }
  1037. void GraphDocumentComponent::checkAvailableWidth()
  1038. {
  1039. if (mobileSettingsSidePanel.isPanelShowing() && pluginListSidePanel.isPanelShowing())
  1040. {
  1041. if (getWidth() - (mobileSettingsSidePanel.getWidth() + pluginListSidePanel.getWidth()) < 150)
  1042. hideLastSidePanel();
  1043. }
  1044. }
  1045. void GraphDocumentComponent::setDoublePrecision (bool doublePrecision)
  1046. {
  1047. graphPlayer.setDoublePrecisionProcessing (doublePrecision);
  1048. }
  1049. bool GraphDocumentComponent::closeAnyOpenPluginWindows()
  1050. {
  1051. return graphPanel->graph.closeAnyOpenPluginWindows();
  1052. }
  1053. void GraphDocumentComponent::changeListenerCallback (ChangeBroadcaster*)
  1054. {
  1055. updateMidiOutput();
  1056. }
  1057. void GraphDocumentComponent::updateMidiOutput()
  1058. {
  1059. auto* defaultMidiOutput = deviceManager.getDefaultMidiOutput();
  1060. if (midiOutput != defaultMidiOutput)
  1061. {
  1062. midiOutput = defaultMidiOutput;
  1063. if (midiOutput != nullptr)
  1064. midiOutput->startBackgroundThread();
  1065. graphPlayer.setMidiOutput (midiOutput);
  1066. }
  1067. }