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.

1348 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. numIns = f->getProcessor()->getTotalNumInputChannels();
  271. if (f->getProcessor()->acceptsMidi())
  272. ++numIns;
  273. numOuts = f->getProcessor()->getTotalNumOutputChannels();
  274. if (f->getProcessor()->producesMidi())
  275. ++numOuts;
  276. int w = 100;
  277. int h = 60;
  278. w = jmax (w, (jmax (numIns, numOuts) + 1) * 20);
  279. const int textWidth = font.getStringWidth (f->getProcessor()->getName());
  280. w = jmax (w, 16 + jmin (textWidth, 300));
  281. if (textWidth > 300)
  282. h = 100;
  283. setSize (w, h);
  284. setName (f->getProcessor()->getName());
  285. {
  286. auto p = graph.getNodePosition (pluginID);
  287. setCentreRelative ((float) p.x, (float) p.y);
  288. }
  289. if (numIns != numInputs || numOuts != numOutputs)
  290. {
  291. numInputs = numIns;
  292. numOutputs = numOuts;
  293. pins.clear();
  294. for (int i = 0; i < f->getProcessor()->getTotalNumInputChannels(); ++i)
  295. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, i }, true)));
  296. if (f->getProcessor()->acceptsMidi())
  297. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, AudioProcessorGraph::midiChannelIndex }, true)));
  298. for (int i = 0; i < f->getProcessor()->getTotalNumOutputChannels(); ++i)
  299. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, i }, false)));
  300. if (f->getProcessor()->producesMidi())
  301. addAndMakeVisible (pins.add (new PinComponent (panel, { pluginID, AudioProcessorGraph::midiChannelIndex }, false)));
  302. resized();
  303. }
  304. }
  305. AudioProcessor* getProcessor() const
  306. {
  307. if (auto node = graph.graph.getNodeForId (pluginID))
  308. return node->getProcessor();
  309. return {};
  310. }
  311. void showPopupMenu()
  312. {
  313. menu.reset (new PopupMenu);
  314. menu->addItem (1, "Delete this filter");
  315. menu->addItem (2, "Disconnect all pins");
  316. menu->addItem (3, "Toggle Bypass");
  317. menu->addSeparator();
  318. menu->addItem (10, "Show plugin GUI");
  319. menu->addItem (11, "Show all programs");
  320. menu->addItem (12, "Show all parameters");
  321. menu->addItem (13, "Show debug log");
  322. if (autoScaleOptionAvailable)
  323. addPluginAutoScaleOptionsSubMenu (dynamic_cast<AudioPluginInstance*> (getProcessor()), *menu);
  324. menu->addSeparator();
  325. menu->addItem (20, "Configure Audio I/O");
  326. menu->addItem (21, "Test state save/load");
  327. menu->showMenuAsync ({}, ModalCallbackFunction::create
  328. ([this] (int r) {
  329. switch (r)
  330. {
  331. case 1: graph.graph.removeNode (pluginID); break;
  332. case 2: graph.graph.disconnectNode (pluginID); break;
  333. case 3:
  334. {
  335. if (auto* node = graph.graph.getNodeForId (pluginID))
  336. node->setBypassed (! node->isBypassed());
  337. repaint();
  338. break;
  339. }
  340. case 10: showWindow (PluginWindow::Type::normal); break;
  341. case 11: showWindow (PluginWindow::Type::programs); break;
  342. case 12: showWindow (PluginWindow::Type::generic) ; break;
  343. case 13: showWindow (PluginWindow::Type::debug); break;
  344. case 20: showWindow (PluginWindow::Type::audioIO); break;
  345. case 21: testStateSaveLoad(); break;
  346. default: break;
  347. }
  348. }));
  349. }
  350. void testStateSaveLoad()
  351. {
  352. if (auto* processor = getProcessor())
  353. {
  354. MemoryBlock state;
  355. processor->getStateInformation (state);
  356. processor->setStateInformation (state.getData(), (int) state.getSize());
  357. }
  358. }
  359. void showWindow (PluginWindow::Type type)
  360. {
  361. if (auto node = graph.graph.getNodeForId (pluginID))
  362. if (auto* w = graph.getOrCreateWindowFor (node, type))
  363. w->toFront (true);
  364. }
  365. void timerCallback() override
  366. {
  367. // this should only be called on touch devices
  368. jassert (isOnTouchDevice());
  369. stopTimer();
  370. showPopupMenu();
  371. }
  372. void parameterValueChanged (int, float) override
  373. {
  374. // Parameter changes might come from the audio thread or elsewhere, but
  375. // we can only call repaint from the message thread.
  376. triggerAsyncUpdate();
  377. }
  378. void parameterGestureChanged (int, bool) override {}
  379. void handleAsyncUpdate() override { repaint(); }
  380. GraphEditorPanel& panel;
  381. PluginGraph& graph;
  382. const AudioProcessorGraph::NodeID pluginID;
  383. OwnedArray<PinComponent> pins;
  384. int numInputs = 0, numOutputs = 0;
  385. int pinSize = 16;
  386. Point<int> originalPos;
  387. Font font { 13.0f, Font::bold };
  388. int numIns = 0, numOuts = 0;
  389. DropShadowEffect shadow;
  390. std::unique_ptr<PopupMenu> menu;
  391. };
  392. //==============================================================================
  393. struct GraphEditorPanel::ConnectorComponent : public Component,
  394. public SettableTooltipClient
  395. {
  396. explicit ConnectorComponent (GraphEditorPanel& p)
  397. : panel (p), graph (p.graph)
  398. {
  399. setAlwaysOnTop (true);
  400. }
  401. void setInput (AudioProcessorGraph::NodeAndChannel newSource)
  402. {
  403. if (connection.source != newSource)
  404. {
  405. connection.source = newSource;
  406. update();
  407. }
  408. }
  409. void setOutput (AudioProcessorGraph::NodeAndChannel newDest)
  410. {
  411. if (connection.destination != newDest)
  412. {
  413. connection.destination = newDest;
  414. update();
  415. }
  416. }
  417. void dragStart (Point<float> pos)
  418. {
  419. lastInputPos = pos;
  420. resizeToFit();
  421. }
  422. void dragEnd (Point<float> pos)
  423. {
  424. lastOutputPos = pos;
  425. resizeToFit();
  426. }
  427. void update()
  428. {
  429. Point<float> p1, p2;
  430. getPoints (p1, p2);
  431. if (lastInputPos != p1 || lastOutputPos != p2)
  432. resizeToFit();
  433. }
  434. void resizeToFit()
  435. {
  436. Point<float> p1, p2;
  437. getPoints (p1, p2);
  438. auto newBounds = Rectangle<float> (p1, p2).expanded (4.0f).getSmallestIntegerContainer();
  439. if (newBounds != getBounds())
  440. setBounds (newBounds);
  441. else
  442. resized();
  443. repaint();
  444. }
  445. void getPoints (Point<float>& p1, Point<float>& p2) const
  446. {
  447. p1 = lastInputPos;
  448. p2 = lastOutputPos;
  449. if (auto* src = panel.getComponentForPlugin (connection.source.nodeID))
  450. p1 = src->getPinPos (connection.source.channelIndex, false);
  451. if (auto* dest = panel.getComponentForPlugin (connection.destination.nodeID))
  452. p2 = dest->getPinPos (connection.destination.channelIndex, true);
  453. }
  454. void paint (Graphics& g) override
  455. {
  456. if (connection.source.isMIDI() || connection.destination.isMIDI())
  457. g.setColour (Colours::red);
  458. else
  459. g.setColour (Colours::green);
  460. g.fillPath (linePath);
  461. }
  462. bool hitTest (int x, int y) override
  463. {
  464. auto pos = Point<int> (x, y).toFloat();
  465. if (hitPath.contains (pos))
  466. {
  467. double distanceFromStart, distanceFromEnd;
  468. getDistancesFromEnds (pos, distanceFromStart, distanceFromEnd);
  469. // avoid clicking the connector when over a pin
  470. return distanceFromStart > 7.0 && distanceFromEnd > 7.0;
  471. }
  472. return false;
  473. }
  474. void mouseDown (const MouseEvent&) override
  475. {
  476. dragging = false;
  477. }
  478. void mouseDrag (const MouseEvent& e) override
  479. {
  480. if (dragging)
  481. {
  482. panel.dragConnector (e);
  483. }
  484. else if (e.mouseWasDraggedSinceMouseDown())
  485. {
  486. dragging = true;
  487. graph.graph.removeConnection (connection);
  488. double distanceFromStart, distanceFromEnd;
  489. getDistancesFromEnds (getPosition().toFloat() + e.position, distanceFromStart, distanceFromEnd);
  490. const bool isNearerSource = (distanceFromStart < distanceFromEnd);
  491. AudioProcessorGraph::NodeAndChannel dummy { {}, 0 };
  492. panel.beginConnectorDrag (isNearerSource ? dummy : connection.source,
  493. isNearerSource ? connection.destination : dummy,
  494. e);
  495. }
  496. }
  497. void mouseUp (const MouseEvent& e) override
  498. {
  499. if (dragging)
  500. panel.endDraggingConnector (e);
  501. }
  502. void resized() override
  503. {
  504. Point<float> p1, p2;
  505. getPoints (p1, p2);
  506. lastInputPos = p1;
  507. lastOutputPos = p2;
  508. p1 -= getPosition().toFloat();
  509. p2 -= getPosition().toFloat();
  510. linePath.clear();
  511. linePath.startNewSubPath (p1);
  512. linePath.cubicTo (p1.x, p1.y + (p2.y - p1.y) * 0.33f,
  513. p2.x, p1.y + (p2.y - p1.y) * 0.66f,
  514. p2.x, p2.y);
  515. PathStrokeType wideStroke (8.0f);
  516. wideStroke.createStrokedPath (hitPath, linePath);
  517. PathStrokeType stroke (2.5f);
  518. stroke.createStrokedPath (linePath, linePath);
  519. auto arrowW = 5.0f;
  520. auto arrowL = 4.0f;
  521. Path arrow;
  522. arrow.addTriangle (-arrowL, arrowW,
  523. -arrowL, -arrowW,
  524. arrowL, 0.0f);
  525. arrow.applyTransform (AffineTransform()
  526. .rotated (MathConstants<float>::halfPi - (float) atan2 (p2.x - p1.x, p2.y - p1.y))
  527. .translated ((p1 + p2) * 0.5f));
  528. linePath.addPath (arrow);
  529. linePath.setUsingNonZeroWinding (true);
  530. }
  531. void getDistancesFromEnds (Point<float> p, double& distanceFromStart, double& distanceFromEnd) const
  532. {
  533. Point<float> p1, p2;
  534. getPoints (p1, p2);
  535. distanceFromStart = p1.getDistanceFrom (p);
  536. distanceFromEnd = p2.getDistanceFrom (p);
  537. }
  538. GraphEditorPanel& panel;
  539. PluginGraph& graph;
  540. AudioProcessorGraph::Connection connection { { {}, 0 }, { {}, 0 } };
  541. Point<float> lastInputPos, lastOutputPos;
  542. Path linePath, hitPath;
  543. bool dragging = false;
  544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConnectorComponent)
  545. };
  546. //==============================================================================
  547. GraphEditorPanel::GraphEditorPanel (PluginGraph& g) : graph (g)
  548. {
  549. graph.addChangeListener (this);
  550. setOpaque (true);
  551. }
  552. GraphEditorPanel::~GraphEditorPanel()
  553. {
  554. graph.removeChangeListener (this);
  555. draggingConnector = nullptr;
  556. nodes.clear();
  557. connectors.clear();
  558. }
  559. void GraphEditorPanel::paint (Graphics& g)
  560. {
  561. g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
  562. }
  563. void GraphEditorPanel::mouseDown (const MouseEvent& e)
  564. {
  565. if (isOnTouchDevice())
  566. {
  567. originalTouchPos = e.position.toInt();
  568. startTimer (750);
  569. }
  570. if (e.mods.isPopupMenu())
  571. showPopupMenu (e.position.toInt());
  572. }
  573. void GraphEditorPanel::mouseUp (const MouseEvent&)
  574. {
  575. if (isOnTouchDevice())
  576. {
  577. stopTimer();
  578. callAfterDelay (250, []() { PopupMenu::dismissAllActiveMenus(); });
  579. }
  580. }
  581. void GraphEditorPanel::mouseDrag (const MouseEvent& e)
  582. {
  583. if (isOnTouchDevice() && e.getDistanceFromDragStart() > 5)
  584. stopTimer();
  585. }
  586. void GraphEditorPanel::createNewPlugin (const PluginDescription& desc, Point<int> position)
  587. {
  588. graph.addPlugin (desc, position.toDouble() / Point<double> ((double) getWidth(), (double) getHeight()));
  589. }
  590. GraphEditorPanel::PluginComponent* GraphEditorPanel::getComponentForPlugin (AudioProcessorGraph::NodeID nodeID) const
  591. {
  592. for (auto* fc : nodes)
  593. if (fc->pluginID == nodeID)
  594. return fc;
  595. return nullptr;
  596. }
  597. GraphEditorPanel::ConnectorComponent* GraphEditorPanel::getComponentForConnection (const AudioProcessorGraph::Connection& conn) const
  598. {
  599. for (auto* cc : connectors)
  600. if (cc->connection == conn)
  601. return cc;
  602. return nullptr;
  603. }
  604. GraphEditorPanel::PinComponent* GraphEditorPanel::findPinAt (Point<float> pos) const
  605. {
  606. for (auto* fc : nodes)
  607. {
  608. // NB: A Visual Studio optimiser error means we have to put this Component* in a local
  609. // variable before trying to cast it, or it gets mysteriously optimised away..
  610. auto* comp = fc->getComponentAt (pos.toInt() - fc->getPosition());
  611. if (auto* pin = dynamic_cast<PinComponent*> (comp))
  612. return pin;
  613. }
  614. return nullptr;
  615. }
  616. void GraphEditorPanel::resized()
  617. {
  618. updateComponents();
  619. }
  620. void GraphEditorPanel::changeListenerCallback (ChangeBroadcaster*)
  621. {
  622. updateComponents();
  623. }
  624. void GraphEditorPanel::updateComponents()
  625. {
  626. for (int i = nodes.size(); --i >= 0;)
  627. if (graph.graph.getNodeForId (nodes.getUnchecked(i)->pluginID) == nullptr)
  628. nodes.remove (i);
  629. for (int i = connectors.size(); --i >= 0;)
  630. if (! graph.graph.isConnected (connectors.getUnchecked(i)->connection))
  631. connectors.remove (i);
  632. for (auto* fc : nodes)
  633. fc->update();
  634. for (auto* cc : connectors)
  635. cc->update();
  636. for (auto* f : graph.graph.getNodes())
  637. {
  638. if (getComponentForPlugin (f->nodeID) == nullptr)
  639. {
  640. auto* comp = nodes.add (new PluginComponent (*this, f->nodeID));
  641. addAndMakeVisible (comp);
  642. comp->update();
  643. }
  644. }
  645. for (auto& c : graph.graph.getConnections())
  646. {
  647. if (getComponentForConnection (c) == nullptr)
  648. {
  649. auto* comp = connectors.add (new ConnectorComponent (*this));
  650. addAndMakeVisible (comp);
  651. comp->setInput (c.source);
  652. comp->setOutput (c.destination);
  653. }
  654. }
  655. }
  656. void GraphEditorPanel::showPopupMenu (Point<int> mousePos)
  657. {
  658. menu.reset (new PopupMenu);
  659. if (auto* mainWindow = findParentComponentOfClass<MainHostWindow>())
  660. {
  661. mainWindow->addPluginsToMenu (*menu);
  662. menu->showMenuAsync ({},
  663. ModalCallbackFunction::create ([this, mousePos] (int r)
  664. {
  665. if (r > 0)
  666. if (auto* mainWin = findParentComponentOfClass<MainHostWindow>())
  667. createNewPlugin (mainWin->getChosenType (r), mousePos);
  668. }));
  669. }
  670. }
  671. void GraphEditorPanel::beginConnectorDrag (AudioProcessorGraph::NodeAndChannel source,
  672. AudioProcessorGraph::NodeAndChannel dest,
  673. const MouseEvent& e)
  674. {
  675. auto* c = dynamic_cast<ConnectorComponent*> (e.originalComponent);
  676. connectors.removeObject (c, false);
  677. draggingConnector.reset (c);
  678. if (draggingConnector == nullptr)
  679. draggingConnector.reset (new ConnectorComponent (*this));
  680. draggingConnector->setInput (source);
  681. draggingConnector->setOutput (dest);
  682. addAndMakeVisible (draggingConnector.get());
  683. draggingConnector->toFront (false);
  684. dragConnector (e);
  685. }
  686. void GraphEditorPanel::dragConnector (const MouseEvent& e)
  687. {
  688. auto e2 = e.getEventRelativeTo (this);
  689. if (draggingConnector != nullptr)
  690. {
  691. draggingConnector->setTooltip ({});
  692. auto pos = e2.position;
  693. if (auto* pin = findPinAt (pos))
  694. {
  695. auto connection = draggingConnector->connection;
  696. if (connection.source.nodeID == AudioProcessorGraph::NodeID() && ! pin->isInput)
  697. {
  698. connection.source = pin->pin;
  699. }
  700. else if (connection.destination.nodeID == AudioProcessorGraph::NodeID() && pin->isInput)
  701. {
  702. connection.destination = pin->pin;
  703. }
  704. if (graph.graph.canConnect (connection))
  705. {
  706. pos = (pin->getParentComponent()->getPosition() + pin->getBounds().getCentre()).toFloat();
  707. draggingConnector->setTooltip (pin->getTooltip());
  708. }
  709. }
  710. if (draggingConnector->connection.source.nodeID == AudioProcessorGraph::NodeID())
  711. draggingConnector->dragStart (pos);
  712. else
  713. draggingConnector->dragEnd (pos);
  714. }
  715. }
  716. void GraphEditorPanel::endDraggingConnector (const MouseEvent& e)
  717. {
  718. if (draggingConnector == nullptr)
  719. return;
  720. draggingConnector->setTooltip ({});
  721. auto e2 = e.getEventRelativeTo (this);
  722. auto connection = draggingConnector->connection;
  723. draggingConnector = nullptr;
  724. if (auto* pin = findPinAt (e2.position))
  725. {
  726. if (connection.source.nodeID == AudioProcessorGraph::NodeID())
  727. {
  728. if (pin->isInput)
  729. return;
  730. connection.source = pin->pin;
  731. }
  732. else
  733. {
  734. if (! pin->isInput)
  735. return;
  736. connection.destination = pin->pin;
  737. }
  738. graph.graph.addConnection (connection);
  739. }
  740. }
  741. void GraphEditorPanel::timerCallback()
  742. {
  743. // this should only be called on touch devices
  744. jassert (isOnTouchDevice());
  745. stopTimer();
  746. showPopupMenu (originalTouchPos);
  747. }
  748. //==============================================================================
  749. struct GraphDocumentComponent::TooltipBar : public Component,
  750. private Timer
  751. {
  752. TooltipBar()
  753. {
  754. startTimer (100);
  755. }
  756. void paint (Graphics& g) override
  757. {
  758. g.setFont (Font ((float) getHeight() * 0.7f, Font::bold));
  759. g.setColour (Colours::black);
  760. g.drawFittedText (tip, 10, 0, getWidth() - 12, getHeight(), Justification::centredLeft, 1);
  761. }
  762. void timerCallback() override
  763. {
  764. String newTip;
  765. if (auto* underMouse = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse())
  766. if (auto* ttc = dynamic_cast<TooltipClient*> (underMouse))
  767. if (! (underMouse->isMouseButtonDown() || underMouse->isCurrentlyBlockedByAnotherModalComponent()))
  768. newTip = ttc->getTooltip();
  769. if (newTip != tip)
  770. {
  771. tip = newTip;
  772. repaint();
  773. }
  774. }
  775. String tip;
  776. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TooltipBar)
  777. };
  778. //==============================================================================
  779. class GraphDocumentComponent::TitleBarComponent : public Component,
  780. private Button::Listener
  781. {
  782. public:
  783. explicit TitleBarComponent (GraphDocumentComponent& graphDocumentComponent)
  784. : owner (graphDocumentComponent)
  785. {
  786. static const unsigned char burgerMenuPathData[]
  787. = { 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,
  788. 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,
  789. 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,
  790. 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,
  791. 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,
  792. 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,
  793. 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,
  794. 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,
  795. 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,
  796. 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,
  797. 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,
  798. 65,99,101,0,0 };
  799. static const unsigned char pluginListPathData[]
  800. = { 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,
  801. 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,
  802. 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,
  803. 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,
  804. 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,
  805. 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,
  806. 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,
  807. 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,
  808. 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,
  809. 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,
  810. 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,
  811. 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,
  812. 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 };
  813. {
  814. Path p;
  815. p.loadPathFromData (burgerMenuPathData, sizeof (burgerMenuPathData));
  816. burgerButton.setShape (p, true, true, false);
  817. }
  818. {
  819. Path p;
  820. p.loadPathFromData (pluginListPathData, sizeof (pluginListPathData));
  821. pluginButton.setShape (p, true, true, false);
  822. }
  823. burgerButton.addListener (this);
  824. addAndMakeVisible (burgerButton);
  825. pluginButton.addListener (this);
  826. addAndMakeVisible (pluginButton);
  827. titleLabel.setJustificationType (Justification::centredLeft);
  828. addAndMakeVisible (titleLabel);
  829. setOpaque (true);
  830. }
  831. private:
  832. void paint (Graphics& g) override
  833. {
  834. auto titleBarBackgroundColour = getLookAndFeel().findColour (ResizableWindow::backgroundColourId).darker();
  835. g.setColour (titleBarBackgroundColour);
  836. g.fillRect (getLocalBounds());
  837. }
  838. void resized() override
  839. {
  840. auto r = getLocalBounds();
  841. burgerButton.setBounds (r.removeFromLeft (40).withSizeKeepingCentre (20, 20));
  842. pluginButton.setBounds (r.removeFromRight (40).withSizeKeepingCentre (20, 20));
  843. titleLabel.setFont (Font (static_cast<float> (getHeight()) * 0.5f, Font::plain));
  844. titleLabel.setBounds (r);
  845. }
  846. void buttonClicked (Button* b) override
  847. {
  848. owner.showSidePanel (b == &burgerButton);
  849. }
  850. GraphDocumentComponent& owner;
  851. Label titleLabel {"titleLabel", "Plugin Host"};
  852. ShapeButton burgerButton {"burgerButton", Colours::lightgrey, Colours::lightgrey, Colours::white};
  853. ShapeButton pluginButton {"pluginButton", Colours::lightgrey, Colours::lightgrey, Colours::white};
  854. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TitleBarComponent)
  855. };
  856. //==============================================================================
  857. struct GraphDocumentComponent::PluginListBoxModel : public ListBoxModel,
  858. public ChangeListener,
  859. public MouseListener
  860. {
  861. PluginListBoxModel (ListBox& lb, KnownPluginList& kpl)
  862. : owner (lb),
  863. knownPlugins (kpl)
  864. {
  865. knownPlugins.addChangeListener (this);
  866. owner.addMouseListener (this, true);
  867. #if JUCE_IOS
  868. scanner.reset (new AUScanner (knownPlugins));
  869. #endif
  870. }
  871. int getNumRows() override
  872. {
  873. return knownPlugins.getNumTypes();
  874. }
  875. void paintListBoxItem (int rowNumber, Graphics& g,
  876. int width, int height, bool rowIsSelected) override
  877. {
  878. g.fillAll (rowIsSelected ? Colour (0xff42A2C8)
  879. : Colour (0xff263238));
  880. g.setColour (rowIsSelected ? Colours::black : Colours::white);
  881. if (rowNumber < knownPlugins.getNumTypes())
  882. g.drawFittedText (knownPlugins.getTypes()[rowNumber].name, { 0, 0, width, height - 2 }, Justification::centred, 1);
  883. g.setColour (Colours::black.withAlpha (0.4f));
  884. g.drawRect (0, height - 1, width, 1);
  885. }
  886. var getDragSourceDescription (const SparseSet<int>& selectedRows) override
  887. {
  888. if (! isOverSelectedRow)
  889. return var();
  890. return String ("PLUGIN: " + String (selectedRows[0]));
  891. }
  892. void changeListenerCallback (ChangeBroadcaster*) override
  893. {
  894. owner.updateContent();
  895. }
  896. void mouseDown (const MouseEvent& e) override
  897. {
  898. isOverSelectedRow = owner.getRowPosition (owner.getSelectedRow(), true)
  899. .contains (e.getEventRelativeTo (&owner).getMouseDownPosition());
  900. }
  901. ListBox& owner;
  902. KnownPluginList& knownPlugins;
  903. bool isOverSelectedRow = false;
  904. #if JUCE_IOS
  905. std::unique_ptr<AUScanner> scanner;
  906. #endif
  907. JUCE_DECLARE_NON_COPYABLE (PluginListBoxModel)
  908. };
  909. //==============================================================================
  910. GraphDocumentComponent::GraphDocumentComponent (AudioPluginFormatManager& fm,
  911. AudioDeviceManager& dm,
  912. KnownPluginList& kpl)
  913. : graph (new PluginGraph (fm, kpl)),
  914. deviceManager (dm),
  915. pluginList (kpl),
  916. graphPlayer (getAppProperties().getUserSettings()->getBoolValue ("doublePrecisionProcessing", false))
  917. {
  918. init();
  919. deviceManager.addChangeListener (graphPanel.get());
  920. deviceManager.addAudioCallback (&graphPlayer);
  921. deviceManager.addMidiInputDeviceCallback ({}, &graphPlayer.getMidiMessageCollector());
  922. deviceManager.addChangeListener (this);
  923. }
  924. void GraphDocumentComponent::init()
  925. {
  926. updateMidiOutput();
  927. graphPanel.reset (new GraphEditorPanel (*graph));
  928. addAndMakeVisible (graphPanel.get());
  929. graphPlayer.setProcessor (&graph->graph);
  930. keyState.addListener (&graphPlayer.getMidiMessageCollector());
  931. keyboardComp.reset (new MidiKeyboardComponent (keyState, MidiKeyboardComponent::horizontalKeyboard));
  932. addAndMakeVisible (keyboardComp.get());
  933. statusBar.reset (new TooltipBar());
  934. addAndMakeVisible (statusBar.get());
  935. graphPanel->updateComponents();
  936. if (isOnTouchDevice())
  937. {
  938. titleBarComponent.reset (new TitleBarComponent (*this));
  939. addAndMakeVisible (titleBarComponent.get());
  940. pluginListBoxModel.reset (new PluginListBoxModel (pluginListBox, pluginList));
  941. pluginListBox.setModel (pluginListBoxModel.get());
  942. pluginListBox.setRowHeight (40);
  943. pluginListSidePanel.setContent (&pluginListBox, false);
  944. mobileSettingsSidePanel.setContent (new AudioDeviceSelectorComponent (deviceManager,
  945. 0, 2, 0, 2,
  946. true, true, true, false));
  947. addAndMakeVisible (pluginListSidePanel);
  948. addAndMakeVisible (mobileSettingsSidePanel);
  949. }
  950. }
  951. GraphDocumentComponent::~GraphDocumentComponent()
  952. {
  953. if (midiOutput != nullptr)
  954. midiOutput->stopBackgroundThread();
  955. releaseGraph();
  956. keyState.removeListener (&graphPlayer.getMidiMessageCollector());
  957. }
  958. void GraphDocumentComponent::resized()
  959. {
  960. auto r = [this]
  961. {
  962. auto bounds = getLocalBounds();
  963. if (auto* display = Desktop::getInstance().getDisplays().getDisplayForRect (getScreenBounds()))
  964. return display->safeAreaInsets.subtractedFrom (bounds);
  965. return bounds;
  966. }();
  967. const int titleBarHeight = 40;
  968. const int keysHeight = 60;
  969. const int statusHeight = 20;
  970. if (isOnTouchDevice())
  971. titleBarComponent->setBounds (r.removeFromTop(titleBarHeight));
  972. keyboardComp->setBounds (r.removeFromBottom (keysHeight));
  973. statusBar->setBounds (r.removeFromBottom (statusHeight));
  974. graphPanel->setBounds (r);
  975. checkAvailableWidth();
  976. }
  977. void GraphDocumentComponent::createNewPlugin (const PluginDescription& desc, Point<int> pos)
  978. {
  979. graphPanel->createNewPlugin (desc, pos);
  980. }
  981. void GraphDocumentComponent::unfocusKeyboardComponent()
  982. {
  983. keyboardComp->unfocusAllComponents();
  984. }
  985. void GraphDocumentComponent::releaseGraph()
  986. {
  987. deviceManager.removeAudioCallback (&graphPlayer);
  988. deviceManager.removeMidiInputDeviceCallback ({}, &graphPlayer.getMidiMessageCollector());
  989. if (graphPanel != nullptr)
  990. {
  991. deviceManager.removeChangeListener (graphPanel.get());
  992. graphPanel = nullptr;
  993. }
  994. keyboardComp = nullptr;
  995. statusBar = nullptr;
  996. graphPlayer.setProcessor (nullptr);
  997. graph = nullptr;
  998. }
  999. bool GraphDocumentComponent::isInterestedInDragSource (const SourceDetails& details)
  1000. {
  1001. return ((dynamic_cast<ListBox*> (details.sourceComponent.get()) != nullptr)
  1002. && details.description.toString().startsWith ("PLUGIN"));
  1003. }
  1004. void GraphDocumentComponent::itemDropped (const SourceDetails& details)
  1005. {
  1006. // don't allow items to be dropped behind the sidebar
  1007. if (pluginListSidePanel.getBounds().contains (details.localPosition))
  1008. return;
  1009. auto pluginTypeIndex = details.description.toString()
  1010. .fromFirstOccurrenceOf ("PLUGIN: ", false, false)
  1011. .getIntValue();
  1012. // must be a valid index!
  1013. jassert (isPositiveAndBelow (pluginTypeIndex, pluginList.getNumTypes()));
  1014. createNewPlugin (pluginList.getTypes()[pluginTypeIndex], details.localPosition);
  1015. }
  1016. void GraphDocumentComponent::showSidePanel (bool showSettingsPanel)
  1017. {
  1018. if (showSettingsPanel)
  1019. mobileSettingsSidePanel.showOrHide (true);
  1020. else
  1021. pluginListSidePanel.showOrHide (true);
  1022. checkAvailableWidth();
  1023. lastOpenedSidePanel = showSettingsPanel ? &mobileSettingsSidePanel
  1024. : &pluginListSidePanel;
  1025. }
  1026. void GraphDocumentComponent::hideLastSidePanel()
  1027. {
  1028. if (lastOpenedSidePanel != nullptr)
  1029. lastOpenedSidePanel->showOrHide (false);
  1030. if (mobileSettingsSidePanel.isPanelShowing()) lastOpenedSidePanel = &mobileSettingsSidePanel;
  1031. else if (pluginListSidePanel.isPanelShowing()) lastOpenedSidePanel = &pluginListSidePanel;
  1032. else lastOpenedSidePanel = nullptr;
  1033. }
  1034. void GraphDocumentComponent::checkAvailableWidth()
  1035. {
  1036. if (mobileSettingsSidePanel.isPanelShowing() && pluginListSidePanel.isPanelShowing())
  1037. {
  1038. if (getWidth() - (mobileSettingsSidePanel.getWidth() + pluginListSidePanel.getWidth()) < 150)
  1039. hideLastSidePanel();
  1040. }
  1041. }
  1042. void GraphDocumentComponent::setDoublePrecision (bool doublePrecision)
  1043. {
  1044. graphPlayer.setDoublePrecisionProcessing (doublePrecision);
  1045. }
  1046. bool GraphDocumentComponent::closeAnyOpenPluginWindows()
  1047. {
  1048. return graphPanel->graph.closeAnyOpenPluginWindows();
  1049. }
  1050. void GraphDocumentComponent::changeListenerCallback (ChangeBroadcaster*)
  1051. {
  1052. updateMidiOutput();
  1053. }
  1054. void GraphDocumentComponent::updateMidiOutput()
  1055. {
  1056. auto* defaultMidiOutput = deviceManager.getDefaultMidiOutput();
  1057. if (midiOutput != defaultMidiOutput)
  1058. {
  1059. midiOutput = defaultMidiOutput;
  1060. if (midiOutput != nullptr)
  1061. midiOutput->startBackgroundThread();
  1062. graphPlayer.setMidiOutput (midiOutput);
  1063. }
  1064. }