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.

587 lines
20KB

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