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.

618 lines
21KB

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