Audio plugin host https://kx.studio/carla
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.

624 lines
21KB

  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. namespace juce
  19. {
  20. bool juce_performDragDropFiles (const StringArray&, const bool copyFiles, bool& shouldStop);
  21. bool juce_performDragDropText (const String&, bool& shouldStop);
  22. //==============================================================================
  23. class DragAndDropContainer::DragImageComponent : public Component,
  24. private Timer
  25. {
  26. public:
  27. DragImageComponent (const Image& im,
  28. const var& desc,
  29. Component* const sourceComponent,
  30. const MouseInputSource* draggingSource,
  31. DragAndDropContainer& ddc,
  32. Point<int> offset)
  33. : sourceDetails (desc, sourceComponent, Point<int>()),
  34. image (im), owner (ddc),
  35. mouseDragSource (draggingSource->getComponentUnderMouse()),
  36. imageOffset (offset),
  37. originalInputSourceIndex (draggingSource->getIndex()),
  38. originalInputSourceType (draggingSource->getType())
  39. {
  40. updateSize();
  41. if (mouseDragSource == nullptr)
  42. mouseDragSource = sourceComponent;
  43. mouseDragSource->addMouseListener (this, false);
  44. startTimer (200);
  45. setInterceptsMouseClicks (false, false);
  46. setAlwaysOnTop (true);
  47. }
  48. ~DragImageComponent() override
  49. {
  50. owner.dragImageComponents.remove (owner.dragImageComponents.indexOf (this), false);
  51. if (mouseDragSource != nullptr)
  52. {
  53. mouseDragSource->removeMouseListener (this);
  54. if (auto* current = getCurrentlyOver())
  55. if (current->isInterestedInDragSource (sourceDetails))
  56. current->itemDragExit (sourceDetails);
  57. }
  58. owner.dragOperationEnded (sourceDetails);
  59. }
  60. void paint (Graphics& g) override
  61. {
  62. if (isOpaque())
  63. g.fillAll (Colours::white);
  64. g.setOpacity (1.0f);
  65. g.drawImageAt (image, 0, 0);
  66. }
  67. void mouseUp (const MouseEvent& e) override
  68. {
  69. if (e.originalComponent != this && isOriginalInputSource (e.source))
  70. {
  71. if (mouseDragSource != nullptr)
  72. mouseDragSource->removeMouseListener (this);
  73. // (note: use a local copy of this in case the callback runs
  74. // a modal loop and deletes this object before the method completes)
  75. auto details = sourceDetails;
  76. DragAndDropTarget* finalTarget = nullptr;
  77. auto wasVisible = isVisible();
  78. setVisible (false);
  79. Component* unused;
  80. finalTarget = findTarget (e.getScreenPosition(), details.localPosition, unused);
  81. if (wasVisible) // fade the component and remove it - it'll be deleted later by the timer callback
  82. dismissWithAnimation (finalTarget == nullptr);
  83. if (auto* parent = getParentComponent())
  84. parent->removeChildComponent (this);
  85. if (finalTarget != nullptr)
  86. {
  87. currentlyOverComp = nullptr;
  88. finalTarget->itemDropped (details);
  89. }
  90. // careful - this object could now be deleted..
  91. }
  92. }
  93. void mouseDrag (const MouseEvent& e) override
  94. {
  95. if (e.originalComponent != this && isOriginalInputSource (e.source))
  96. updateLocation (true, e.getScreenPosition());
  97. }
  98. void updateLocation (const bool canDoExternalDrag, Point<int> screenPos)
  99. {
  100. auto details = sourceDetails;
  101. setNewScreenPos (screenPos);
  102. Component* newTargetComp;
  103. auto* newTarget = findTarget (screenPos, details.localPosition, newTargetComp);
  104. setVisible (newTarget == nullptr || newTarget->shouldDrawDragImageWhenOver());
  105. if (newTargetComp != currentlyOverComp)
  106. {
  107. if (auto* lastTarget = getCurrentlyOver())
  108. if (details.sourceComponent != nullptr && lastTarget->isInterestedInDragSource (details))
  109. lastTarget->itemDragExit (details);
  110. currentlyOverComp = newTargetComp;
  111. if (newTarget != nullptr
  112. && newTarget->isInterestedInDragSource (details))
  113. newTarget->itemDragEnter (details);
  114. }
  115. sendDragMove (details);
  116. if (canDoExternalDrag)
  117. {
  118. auto now = Time::getCurrentTime();
  119. if (getCurrentlyOver() != nullptr)
  120. lastTimeOverTarget = now;
  121. else if (now > lastTimeOverTarget + RelativeTime::milliseconds (700))
  122. checkForExternalDrag (details, screenPos);
  123. }
  124. forceMouseCursorUpdate();
  125. }
  126. void updateImage (const Image& newImage)
  127. {
  128. image = newImage;
  129. updateSize();
  130. repaint();
  131. }
  132. void timerCallback() override
  133. {
  134. forceMouseCursorUpdate();
  135. if (sourceDetails.sourceComponent == nullptr)
  136. {
  137. deleteSelf();
  138. }
  139. else
  140. {
  141. for (auto& s : Desktop::getInstance().getMouseSources())
  142. {
  143. if (isOriginalInputSource (s) && ! s.isDragging())
  144. {
  145. if (mouseDragSource != nullptr)
  146. mouseDragSource->removeMouseListener (this);
  147. deleteSelf();
  148. break;
  149. }
  150. }
  151. }
  152. }
  153. bool keyPressed (const KeyPress& key) override
  154. {
  155. if (key == KeyPress::escapeKey)
  156. {
  157. dismissWithAnimation (true);
  158. deleteSelf();
  159. return true;
  160. }
  161. return false;
  162. }
  163. bool canModalEventBeSentToComponent (const Component* targetComponent) override
  164. {
  165. return targetComponent == mouseDragSource;
  166. }
  167. // (overridden to avoid beeps when dragging)
  168. void inputAttemptWhenModal() override {}
  169. DragAndDropTarget::SourceDetails sourceDetails;
  170. private:
  171. Image image;
  172. DragAndDropContainer& owner;
  173. WeakReference<Component> mouseDragSource, currentlyOverComp;
  174. const Point<int> imageOffset;
  175. bool hasCheckedForExternalDrag = false;
  176. Time lastTimeOverTarget;
  177. int originalInputSourceIndex;
  178. MouseInputSource::InputSourceType originalInputSourceType;
  179. void updateSize()
  180. {
  181. setSize (image.getWidth(), image.getHeight());
  182. }
  183. void forceMouseCursorUpdate()
  184. {
  185. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  186. }
  187. DragAndDropTarget* getCurrentlyOver() const noexcept
  188. {
  189. return dynamic_cast<DragAndDropTarget*> (currentlyOverComp.get());
  190. }
  191. static Component* findDesktopComponentBelow (Point<int> screenPos)
  192. {
  193. auto& desktop = Desktop::getInstance();
  194. for (auto i = desktop.getNumComponents(); --i >= 0;)
  195. {
  196. auto* desktopComponent = desktop.getComponent (i);
  197. auto dPoint = desktopComponent->getLocalPoint (nullptr, screenPos);
  198. if (auto* c = desktopComponent->getComponentAt (dPoint))
  199. {
  200. auto cPoint = c->getLocalPoint (desktopComponent, dPoint);
  201. if (c->hitTest (cPoint.getX(), cPoint.getY()))
  202. return c;
  203. }
  204. }
  205. return nullptr;
  206. }
  207. DragAndDropTarget* findTarget (Point<int> screenPos, Point<int>& relativePos,
  208. Component*& resultComponent) const
  209. {
  210. auto* hit = getParentComponent();
  211. if (hit == nullptr)
  212. hit = findDesktopComponentBelow (screenPos);
  213. else
  214. hit = hit->getComponentAt (hit->getLocalPoint (nullptr, screenPos));
  215. // (note: use a local copy of this in case the callback runs
  216. // a modal loop and deletes this object before the method completes)
  217. auto details = sourceDetails;
  218. while (hit != nullptr)
  219. {
  220. if (auto* ddt = dynamic_cast<DragAndDropTarget*> (hit))
  221. {
  222. if (ddt->isInterestedInDragSource (details))
  223. {
  224. relativePos = hit->getLocalPoint (nullptr, screenPos);
  225. resultComponent = hit;
  226. return ddt;
  227. }
  228. }
  229. hit = hit->getParentComponent();
  230. }
  231. resultComponent = nullptr;
  232. return nullptr;
  233. }
  234. void setNewScreenPos (Point<int> screenPos)
  235. {
  236. auto newPos = screenPos - imageOffset;
  237. if (auto* p = getParentComponent())
  238. newPos = p->getLocalPoint (nullptr, newPos);
  239. setTopLeftPosition (newPos);
  240. }
  241. void sendDragMove (DragAndDropTarget::SourceDetails& details) const
  242. {
  243. if (auto* target = getCurrentlyOver())
  244. if (target->isInterestedInDragSource (details))
  245. target->itemDragMove (details);
  246. }
  247. void checkForExternalDrag (DragAndDropTarget::SourceDetails& details, Point<int> screenPos)
  248. {
  249. if (! hasCheckedForExternalDrag)
  250. {
  251. if (Desktop::getInstance().findComponentAt (screenPos) == nullptr)
  252. {
  253. hasCheckedForExternalDrag = true;
  254. if (ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  255. {
  256. StringArray files;
  257. auto canMoveFiles = false;
  258. if (owner.shouldDropFilesWhenDraggedExternally (details, files, canMoveFiles) && ! files.isEmpty())
  259. {
  260. MessageManager::callAsync ([=] { DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles); });
  261. deleteSelf();
  262. return;
  263. }
  264. String text;
  265. if (owner.shouldDropTextWhenDraggedExternally (details, text) && text.isNotEmpty())
  266. {
  267. MessageManager::callAsync ([=] { DragAndDropContainer::performExternalDragDropOfText (text); });
  268. deleteSelf();
  269. return;
  270. }
  271. }
  272. }
  273. }
  274. }
  275. void deleteSelf()
  276. {
  277. delete this;
  278. }
  279. void dismissWithAnimation (const bool shouldSnapBack)
  280. {
  281. setVisible (true);
  282. auto& animator = Desktop::getInstance().getAnimator();
  283. if (shouldSnapBack && sourceDetails.sourceComponent != nullptr)
  284. {
  285. auto target = sourceDetails.sourceComponent->localPointToGlobal (sourceDetails.sourceComponent->getLocalBounds().getCentre());
  286. auto ourCentre = localPointToGlobal (getLocalBounds().getCentre());
  287. animator.animateComponent (this,
  288. getBounds() + (target - ourCentre),
  289. 0.0f, 120,
  290. true, 1.0, 1.0);
  291. }
  292. else
  293. {
  294. animator.fadeOut (this, 120);
  295. }
  296. }
  297. bool isOriginalInputSource (const MouseInputSource& sourceToCheck)
  298. {
  299. return (sourceToCheck.getType() == originalInputSourceType
  300. && sourceToCheck.getIndex() == originalInputSourceIndex);
  301. }
  302. JUCE_DECLARE_NON_COPYABLE (DragImageComponent)
  303. };
  304. //==============================================================================
  305. DragAndDropContainer::DragAndDropContainer()
  306. {
  307. }
  308. DragAndDropContainer::~DragAndDropContainer()
  309. {
  310. }
  311. void DragAndDropContainer::startDragging (const var& sourceDescription,
  312. Component* sourceComponent,
  313. Image dragImage,
  314. const bool allowDraggingToExternalWindows,
  315. const Point<int>* imageOffsetFromMouse,
  316. const MouseInputSource* inputSourceCausingDrag)
  317. {
  318. if (isAlreadyDragging (sourceComponent))
  319. return;
  320. auto* draggingSource = getMouseInputSourceForDrag (sourceComponent, inputSourceCausingDrag);
  321. if (draggingSource == nullptr || ! draggingSource->isDragging())
  322. {
  323. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  324. return;
  325. }
  326. auto lastMouseDown = draggingSource->getLastMouseDownPosition().roundToInt();
  327. Point<int> imageOffset;
  328. if (dragImage.isNull())
  329. {
  330. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  331. .convertedToFormat (Image::ARGB);
  332. dragImage.multiplyAllAlphas (0.6f);
  333. auto lo = 150;
  334. auto hi = 400;
  335. auto relPos = sourceComponent->getLocalPoint (nullptr, lastMouseDown);
  336. auto clipped = dragImage.getBounds().getConstrainedPoint (relPos);
  337. Random random;
  338. for (auto y = dragImage.getHeight(); --y >= 0;)
  339. {
  340. auto dy = (y - clipped.getY()) * (y - clipped.getY());
  341. for (auto x = dragImage.getWidth(); --x >= 0;)
  342. {
  343. auto dx = x - clipped.getX();
  344. auto distance = roundToInt (std::sqrt (dx * dx + dy));
  345. if (distance > lo)
  346. {
  347. auto alpha = (distance > hi) ? 0
  348. : (float) (hi - distance) / (float) (hi - lo)
  349. + random.nextFloat() * 0.008f;
  350. dragImage.multiplyAlphaAt (x, y, alpha);
  351. }
  352. }
  353. }
  354. imageOffset = clipped;
  355. }
  356. else
  357. {
  358. if (imageOffsetFromMouse == nullptr)
  359. imageOffset = dragImage.getBounds().getCentre();
  360. else
  361. imageOffset = dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse);
  362. }
  363. auto* dragImageComponent = dragImageComponents.add (new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  364. draggingSource, *this, imageOffset));
  365. if (allowDraggingToExternalWindows)
  366. {
  367. if (! Desktop::canUseSemiTransparentWindows())
  368. dragImageComponent->setOpaque (true);
  369. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  370. | ComponentPeer::windowIsTemporary
  371. | ComponentPeer::windowIgnoresKeyPresses);
  372. }
  373. else
  374. {
  375. if (auto* thisComp = dynamic_cast<Component*> (this))
  376. {
  377. thisComp->addChildComponent (dragImageComponent);
  378. }
  379. else
  380. {
  381. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  382. return;
  383. }
  384. }
  385. dragImageComponent->sourceDetails.localPosition = sourceComponent->getLocalPoint (nullptr, lastMouseDown);
  386. dragImageComponent->updateLocation (false, lastMouseDown);
  387. #if JUCE_WINDOWS
  388. // Under heavy load, the layered window's paint callback can often be lost by the OS,
  389. // so forcing a repaint at least once makes sure that the window becomes visible..
  390. if (auto* peer = dragImageComponent->getPeer())
  391. peer->performAnyPendingRepaintsNow();
  392. #endif
  393. dragOperationStarted (dragImageComponent->sourceDetails);
  394. }
  395. bool DragAndDropContainer::isDragAndDropActive() const
  396. {
  397. return dragImageComponents.size() > 0;
  398. }
  399. int DragAndDropContainer::getNumCurrentDrags() const
  400. {
  401. return dragImageComponents.size();
  402. }
  403. var DragAndDropContainer::getCurrentDragDescription() const
  404. {
  405. // If you are performing drag and drop in a multi-touch environment then
  406. // you should use the getDragDescriptionForIndex() method instead!
  407. jassert (dragImageComponents.size() < 2);
  408. return dragImageComponents.size() != 0 ? dragImageComponents[0]->sourceDetails.description
  409. : var();
  410. }
  411. var DragAndDropContainer::getDragDescriptionForIndex (int index) const
  412. {
  413. if (! isPositiveAndBelow (index, dragImageComponents.size()))
  414. return {};
  415. return dragImageComponents.getUnchecked (index)->sourceDetails.description;
  416. }
  417. void DragAndDropContainer::setCurrentDragImage (const Image& newImage)
  418. {
  419. // If you are performing drag and drop in a multi-touch environment then
  420. // you should use the setDragImageForIndex() method instead!
  421. jassert (dragImageComponents.size() < 2);
  422. dragImageComponents[0]->updateImage (newImage);
  423. }
  424. void DragAndDropContainer::setDragImageForIndex (int index, const Image& newImage)
  425. {
  426. if (isPositiveAndBelow (index, dragImageComponents.size()))
  427. dragImageComponents.getUnchecked (index)->updateImage (newImage);
  428. }
  429. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  430. {
  431. return c != nullptr ? c->findParentComponentOfClass<DragAndDropContainer>() : nullptr;
  432. }
  433. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, StringArray&, bool&)
  434. {
  435. return false;
  436. }
  437. bool DragAndDropContainer::shouldDropTextWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, String&)
  438. {
  439. return false;
  440. }
  441. void DragAndDropContainer::dragOperationStarted (const DragAndDropTarget::SourceDetails&) {}
  442. void DragAndDropContainer::dragOperationEnded (const DragAndDropTarget::SourceDetails&) {}
  443. const MouseInputSource* DragAndDropContainer::getMouseInputSourceForDrag (Component* sourceComponent,
  444. const MouseInputSource* inputSourceCausingDrag)
  445. {
  446. if (inputSourceCausingDrag == nullptr)
  447. {
  448. auto minDistance = std::numeric_limits<float>::max();
  449. auto& desktop = Desktop::getInstance();
  450. auto centrePoint = sourceComponent ? sourceComponent->getScreenBounds().getCentre().toFloat() : Point<float>();
  451. auto numDragging = desktop.getNumDraggingMouseSources();
  452. for (auto i = 0; i < numDragging; ++i)
  453. {
  454. if (auto* ms = desktop.getDraggingMouseSource (i))
  455. {
  456. auto distance = ms->getScreenPosition().getDistanceSquaredFrom (centrePoint);
  457. if (distance < minDistance)
  458. {
  459. minDistance = distance;
  460. inputSourceCausingDrag = ms;
  461. }
  462. }
  463. }
  464. }
  465. // You must call startDragging() from within a mouseDown or mouseDrag callback!
  466. jassert (inputSourceCausingDrag != nullptr && inputSourceCausingDrag->isDragging());
  467. return inputSourceCausingDrag;
  468. }
  469. bool DragAndDropContainer::isAlreadyDragging (Component* component) const noexcept
  470. {
  471. for (auto* dragImageComp : dragImageComponents)
  472. {
  473. if (dragImageComp->sourceDetails.sourceComponent == component)
  474. return true;
  475. }
  476. return false;
  477. }
  478. //==============================================================================
  479. DragAndDropTarget::SourceDetails::SourceDetails (const var& desc, Component* comp, Point<int> pos) noexcept
  480. : description (desc),
  481. sourceComponent (comp),
  482. localPosition (pos)
  483. {
  484. }
  485. void DragAndDropTarget::itemDragEnter (const SourceDetails&) {}
  486. void DragAndDropTarget::itemDragMove (const SourceDetails&) {}
  487. void DragAndDropTarget::itemDragExit (const SourceDetails&) {}
  488. bool DragAndDropTarget::shouldDrawDragImageWhenOver() { return true; }
  489. //==============================================================================
  490. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int) {}
  491. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int) {}
  492. void FileDragAndDropTarget::fileDragExit (const StringArray&) {}
  493. void TextDragAndDropTarget::textDragEnter (const String&, int, int) {}
  494. void TextDragAndDropTarget::textDragMove (const String&, int, int) {}
  495. void TextDragAndDropTarget::textDragExit (const String&) {}
  496. } // namespace juce