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.

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