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.

527 lines
18KB

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