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.

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