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.

1313 lines
42KB

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