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.

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