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.

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