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.

629 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 (transformOffsetCoordinates (sourceComponent, 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. Point<int> transformOffsetCoordinates (const Component* const sourceComponent, Point<int> offsetInSource) const
  208. {
  209. return getLocalPoint (sourceComponent, offsetInSource) - getLocalPoint (sourceComponent, Point<int>());
  210. }
  211. DragAndDropTarget* findTarget (Point<int> screenPos, Point<int>& relativePos,
  212. Component*& resultComponent) const
  213. {
  214. auto* hit = getParentComponent();
  215. if (hit == nullptr)
  216. hit = findDesktopComponentBelow (screenPos);
  217. else
  218. hit = hit->getComponentAt (hit->getLocalPoint (nullptr, screenPos));
  219. // (note: use a local copy of this in case the callback runs
  220. // a modal loop and deletes this object before the method completes)
  221. auto details = sourceDetails;
  222. while (hit != nullptr)
  223. {
  224. if (auto* ddt = dynamic_cast<DragAndDropTarget*> (hit))
  225. {
  226. if (ddt->isInterestedInDragSource (details))
  227. {
  228. relativePos = hit->getLocalPoint (nullptr, screenPos);
  229. resultComponent = hit;
  230. return ddt;
  231. }
  232. }
  233. hit = hit->getParentComponent();
  234. }
  235. resultComponent = nullptr;
  236. return nullptr;
  237. }
  238. void setNewScreenPos (Point<int> screenPos)
  239. {
  240. auto newPos = screenPos - imageOffset;
  241. if (auto* p = getParentComponent())
  242. newPos = p->getLocalPoint (nullptr, newPos);
  243. setTopLeftPosition (newPos);
  244. }
  245. void sendDragMove (DragAndDropTarget::SourceDetails& details) const
  246. {
  247. if (auto* target = getCurrentlyOver())
  248. if (target->isInterestedInDragSource (details))
  249. target->itemDragMove (details);
  250. }
  251. void checkForExternalDrag (DragAndDropTarget::SourceDetails& details, Point<int> screenPos)
  252. {
  253. if (! hasCheckedForExternalDrag)
  254. {
  255. if (Desktop::getInstance().findComponentAt (screenPos) == nullptr)
  256. {
  257. hasCheckedForExternalDrag = true;
  258. if (ComponentPeer::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  259. {
  260. StringArray files;
  261. auto canMoveFiles = false;
  262. if (owner.shouldDropFilesWhenDraggedExternally (details, files, canMoveFiles) && ! files.isEmpty())
  263. {
  264. MessageManager::callAsync ([=] { DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles); });
  265. deleteSelf();
  266. return;
  267. }
  268. String text;
  269. if (owner.shouldDropTextWhenDraggedExternally (details, text) && text.isNotEmpty())
  270. {
  271. MessageManager::callAsync ([=] { DragAndDropContainer::performExternalDragDropOfText (text); });
  272. deleteSelf();
  273. return;
  274. }
  275. }
  276. }
  277. }
  278. }
  279. void deleteSelf()
  280. {
  281. delete this;
  282. }
  283. void dismissWithAnimation (const bool shouldSnapBack)
  284. {
  285. setVisible (true);
  286. auto& animator = Desktop::getInstance().getAnimator();
  287. if (shouldSnapBack && sourceDetails.sourceComponent != nullptr)
  288. {
  289. auto target = sourceDetails.sourceComponent->localPointToGlobal (sourceDetails.sourceComponent->getLocalBounds().getCentre());
  290. auto ourCentre = localPointToGlobal (getLocalBounds().getCentre());
  291. animator.animateComponent (this,
  292. getBounds() + (target - ourCentre),
  293. 0.0f, 120,
  294. true, 1.0, 1.0);
  295. }
  296. else
  297. {
  298. animator.fadeOut (this, 120);
  299. }
  300. }
  301. bool isOriginalInputSource (const MouseInputSource& sourceToCheck)
  302. {
  303. return (sourceToCheck.getType() == originalInputSourceType
  304. && sourceToCheck.getIndex() == originalInputSourceIndex);
  305. }
  306. JUCE_DECLARE_NON_COPYABLE (DragImageComponent)
  307. };
  308. //==============================================================================
  309. DragAndDropContainer::DragAndDropContainer()
  310. {
  311. }
  312. DragAndDropContainer::~DragAndDropContainer()
  313. {
  314. }
  315. void DragAndDropContainer::startDragging (const var& sourceDescription,
  316. Component* sourceComponent,
  317. Image dragImage,
  318. const bool allowDraggingToExternalWindows,
  319. const Point<int>* imageOffsetFromMouse,
  320. const MouseInputSource* inputSourceCausingDrag)
  321. {
  322. if (isAlreadyDragging (sourceComponent))
  323. return;
  324. auto* draggingSource = getMouseInputSourceForDrag (sourceComponent, inputSourceCausingDrag);
  325. if (draggingSource == nullptr || ! draggingSource->isDragging())
  326. {
  327. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  328. return;
  329. }
  330. auto lastMouseDown = draggingSource->getLastMouseDownPosition().roundToInt();
  331. Point<int> imageOffset;
  332. if (dragImage.isNull())
  333. {
  334. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  335. .convertedToFormat (Image::ARGB);
  336. dragImage.multiplyAllAlphas (0.6f);
  337. auto lo = 150;
  338. auto hi = 400;
  339. auto relPos = sourceComponent->getLocalPoint (nullptr, lastMouseDown);
  340. auto clipped = dragImage.getBounds().getConstrainedPoint (relPos);
  341. Random random;
  342. for (auto y = dragImage.getHeight(); --y >= 0;)
  343. {
  344. auto dy = (y - clipped.getY()) * (y - clipped.getY());
  345. for (auto x = dragImage.getWidth(); --x >= 0;)
  346. {
  347. auto dx = x - clipped.getX();
  348. auto distance = roundToInt (std::sqrt (dx * dx + dy));
  349. if (distance > lo)
  350. {
  351. auto alpha = (distance > hi) ? 0
  352. : (float) (hi - distance) / (float) (hi - lo)
  353. + random.nextFloat() * 0.008f;
  354. dragImage.multiplyAlphaAt (x, y, alpha);
  355. }
  356. }
  357. }
  358. imageOffset = clipped;
  359. }
  360. else
  361. {
  362. if (imageOffsetFromMouse == nullptr)
  363. imageOffset = dragImage.getBounds().getCentre();
  364. else
  365. imageOffset = dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse);
  366. }
  367. auto* dragImageComponent = dragImageComponents.add (new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  368. draggingSource, *this, imageOffset));
  369. if (allowDraggingToExternalWindows)
  370. {
  371. if (! Desktop::canUseSemiTransparentWindows())
  372. dragImageComponent->setOpaque (true);
  373. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  374. | ComponentPeer::windowIsTemporary
  375. | ComponentPeer::windowIgnoresKeyPresses);
  376. }
  377. else
  378. {
  379. if (auto* thisComp = dynamic_cast<Component*> (this))
  380. {
  381. thisComp->addChildComponent (dragImageComponent);
  382. }
  383. else
  384. {
  385. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  386. return;
  387. }
  388. }
  389. dragImageComponent->sourceDetails.localPosition = sourceComponent->getLocalPoint (nullptr, lastMouseDown);
  390. dragImageComponent->updateLocation (false, lastMouseDown);
  391. #if JUCE_WINDOWS
  392. // Under heavy load, the layered window's paint callback can often be lost by the OS,
  393. // so forcing a repaint at least once makes sure that the window becomes visible..
  394. if (auto* peer = dragImageComponent->getPeer())
  395. peer->performAnyPendingRepaintsNow();
  396. #endif
  397. dragOperationStarted (dragImageComponent->sourceDetails);
  398. }
  399. bool DragAndDropContainer::isDragAndDropActive() const
  400. {
  401. return dragImageComponents.size() > 0;
  402. }
  403. int DragAndDropContainer::getNumCurrentDrags() const
  404. {
  405. return dragImageComponents.size();
  406. }
  407. var DragAndDropContainer::getCurrentDragDescription() const
  408. {
  409. // If you are performing drag and drop in a multi-touch environment then
  410. // you should use the getDragDescriptionForIndex() method instead!
  411. jassert (dragImageComponents.size() < 2);
  412. return dragImageComponents.size() != 0 ? dragImageComponents[0]->sourceDetails.description
  413. : var();
  414. }
  415. var DragAndDropContainer::getDragDescriptionForIndex (int index) const
  416. {
  417. if (! isPositiveAndBelow (index, dragImageComponents.size()))
  418. return {};
  419. return dragImageComponents.getUnchecked (index)->sourceDetails.description;
  420. }
  421. void DragAndDropContainer::setCurrentDragImage (const Image& newImage)
  422. {
  423. // If you are performing drag and drop in a multi-touch environment then
  424. // you should use the setDragImageForIndex() method instead!
  425. jassert (dragImageComponents.size() < 2);
  426. dragImageComponents[0]->updateImage (newImage);
  427. }
  428. void DragAndDropContainer::setDragImageForIndex (int index, const Image& newImage)
  429. {
  430. if (isPositiveAndBelow (index, dragImageComponents.size()))
  431. dragImageComponents.getUnchecked (index)->updateImage (newImage);
  432. }
  433. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  434. {
  435. return c != nullptr ? c->findParentComponentOfClass<DragAndDropContainer>() : nullptr;
  436. }
  437. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, StringArray&, bool&)
  438. {
  439. return false;
  440. }
  441. bool DragAndDropContainer::shouldDropTextWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, String&)
  442. {
  443. return false;
  444. }
  445. void DragAndDropContainer::dragOperationStarted (const DragAndDropTarget::SourceDetails&) {}
  446. void DragAndDropContainer::dragOperationEnded (const DragAndDropTarget::SourceDetails&) {}
  447. const MouseInputSource* DragAndDropContainer::getMouseInputSourceForDrag (Component* sourceComponent,
  448. const MouseInputSource* inputSourceCausingDrag)
  449. {
  450. if (inputSourceCausingDrag == nullptr)
  451. {
  452. auto minDistance = std::numeric_limits<float>::max();
  453. auto& desktop = Desktop::getInstance();
  454. auto centrePoint = sourceComponent ? sourceComponent->getScreenBounds().getCentre().toFloat() : Point<float>();
  455. auto numDragging = desktop.getNumDraggingMouseSources();
  456. for (auto i = 0; i < numDragging; ++i)
  457. {
  458. if (auto* ms = desktop.getDraggingMouseSource (i))
  459. {
  460. auto distance = ms->getScreenPosition().getDistanceSquaredFrom (centrePoint);
  461. if (distance < minDistance)
  462. {
  463. minDistance = distance;
  464. inputSourceCausingDrag = ms;
  465. }
  466. }
  467. }
  468. }
  469. // You must call startDragging() from within a mouseDown or mouseDrag callback!
  470. jassert (inputSourceCausingDrag != nullptr && inputSourceCausingDrag->isDragging());
  471. return inputSourceCausingDrag;
  472. }
  473. bool DragAndDropContainer::isAlreadyDragging (Component* component) const noexcept
  474. {
  475. for (auto* dragImageComp : dragImageComponents)
  476. {
  477. if (dragImageComp->sourceDetails.sourceComponent == component)
  478. return true;
  479. }
  480. return false;
  481. }
  482. //==============================================================================
  483. DragAndDropTarget::SourceDetails::SourceDetails (const var& desc, Component* comp, Point<int> pos) noexcept
  484. : description (desc),
  485. sourceComponent (comp),
  486. localPosition (pos)
  487. {
  488. }
  489. void DragAndDropTarget::itemDragEnter (const SourceDetails&) {}
  490. void DragAndDropTarget::itemDragMove (const SourceDetails&) {}
  491. void DragAndDropTarget::itemDragExit (const SourceDetails&) {}
  492. bool DragAndDropTarget::shouldDrawDragImageWhenOver() { return true; }
  493. //==============================================================================
  494. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int) {}
  495. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int) {}
  496. void FileDragAndDropTarget::fileDragExit (const StringArray&) {}
  497. void TextDragAndDropTarget::textDragEnter (const String&, int, int) {}
  498. void TextDragAndDropTarget::textDragMove (const String&, int, int) {}
  499. void TextDragAndDropTarget::textDragExit (const String&) {}
  500. } // namespace juce