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.

597 lines
20KB

  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 (ModifierKeys::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. auto* draggingSource = getMouseInputSourceForDrag (sourceComponent, inputSourceCausingDrag);
  315. auto lastMouseDown = draggingSource->getLastMouseDownPosition().roundToInt();
  316. Point<int> imageOffset;
  317. if (dragImage.isNull())
  318. {
  319. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  320. .convertedToFormat (Image::ARGB);
  321. dragImage.multiplyAllAlphas (0.6f);
  322. auto lo = 150;
  323. auto hi = 400;
  324. auto relPos = sourceComponent->getLocalPoint (nullptr, lastMouseDown);
  325. auto clipped = dragImage.getBounds().getConstrainedPoint (relPos);
  326. Random random;
  327. for (auto y = dragImage.getHeight(); --y >= 0;)
  328. {
  329. auto dy = (y - clipped.getY()) * (y - clipped.getY());
  330. for (auto x = dragImage.getWidth(); --x >= 0;)
  331. {
  332. auto dx = x - clipped.getX();
  333. auto distance = roundToInt (std::sqrt (dx * dx + dy));
  334. if (distance > lo)
  335. {
  336. auto alpha = (distance > hi) ? 0
  337. : (hi - distance) / (float) (hi - lo)
  338. + random.nextFloat() * 0.008f;
  339. dragImage.multiplyAlphaAt (x, y, alpha);
  340. }
  341. }
  342. }
  343. imageOffset = clipped;
  344. }
  345. else
  346. {
  347. if (imageOffsetFromMouse == nullptr)
  348. imageOffset = dragImage.getBounds().getCentre();
  349. else
  350. imageOffset = dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse);
  351. }
  352. auto* dragImageComponent = dragImageComponents.add (new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  353. draggingSource, *this, imageOffset));
  354. if (allowDraggingToExternalWindows)
  355. {
  356. if (! Desktop::canUseSemiTransparentWindows())
  357. dragImageComponent->setOpaque (true);
  358. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  359. | ComponentPeer::windowIsTemporary
  360. | ComponentPeer::windowIgnoresKeyPresses);
  361. }
  362. else
  363. {
  364. if (auto* thisComp = dynamic_cast<Component*> (this))
  365. {
  366. thisComp->addChildComponent (dragImageComponent);
  367. }
  368. else
  369. {
  370. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  371. return;
  372. }
  373. }
  374. dragImageComponent->updateLocation (false, lastMouseDown);
  375. #if JUCE_WINDOWS
  376. // Under heavy load, the layered window's paint callback can often be lost by the OS,
  377. // so forcing a repaint at least once makes sure that the window becomes visible..
  378. if (auto* peer = dragImageComponent->getPeer())
  379. peer->performAnyPendingRepaintsNow();
  380. #endif
  381. dragOperationStarted (dragImageComponent->sourceDetails);
  382. }
  383. bool DragAndDropContainer::isDragAndDropActive() const
  384. {
  385. return dragImageComponents.size() > 0;
  386. }
  387. int DragAndDropContainer::getNumCurrentDrags() const
  388. {
  389. return dragImageComponents.size();
  390. }
  391. var DragAndDropContainer::getCurrentDragDescription() const
  392. {
  393. // If you are performing drag and drop in a multi-touch environment then
  394. // you should use the getDragDescriptionForIndex() method instead!
  395. jassert (dragImageComponents.size() < 2);
  396. return dragImageComponents.size() != 0 ? dragImageComponents[0]->sourceDetails.description
  397. : var();
  398. }
  399. var DragAndDropContainer::getDragDescriptionForIndex (int index) const
  400. {
  401. if (! isPositiveAndBelow (index, dragImageComponents.size()))
  402. return {};
  403. return dragImageComponents.getUnchecked (index)->sourceDetails.description;
  404. }
  405. void DragAndDropContainer::setCurrentDragImage (const Image& newImage)
  406. {
  407. // If you are performing drag and drop in a multi-touch environment then
  408. // you should use the setDragImageForIndex() method instead!
  409. jassert (dragImageComponents.size() < 2);
  410. dragImageComponents[0]->updateImage (newImage);
  411. }
  412. void DragAndDropContainer::setDragImageForIndex (int index, const Image& newImage)
  413. {
  414. if (isPositiveAndBelow (index, dragImageComponents.size()))
  415. dragImageComponents.getUnchecked (index)->updateImage (newImage);
  416. }
  417. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  418. {
  419. return c != nullptr ? c->findParentComponentOfClass<DragAndDropContainer>() : nullptr;
  420. }
  421. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, StringArray&, bool&)
  422. {
  423. return false;
  424. }
  425. bool DragAndDropContainer::shouldDropTextWhenDraggedExternally (const DragAndDropTarget::SourceDetails&, String&)
  426. {
  427. return false;
  428. }
  429. void DragAndDropContainer::dragOperationStarted (const DragAndDropTarget::SourceDetails&) {}
  430. void DragAndDropContainer::dragOperationEnded (const DragAndDropTarget::SourceDetails&) {}
  431. const MouseInputSource* DragAndDropContainer::getMouseInputSourceForDrag (Component* sourceComponent,
  432. const MouseInputSource* inputSourceCausingDrag)
  433. {
  434. if (inputSourceCausingDrag == nullptr)
  435. {
  436. auto minDistance = std::numeric_limits<float>::max();
  437. auto& desktop = Desktop::getInstance();
  438. auto centrePoint = sourceComponent ? sourceComponent->getScreenBounds().getCentre().toFloat() : Point<float>();
  439. auto numDragging = desktop.getNumDraggingMouseSources();
  440. for (auto i = 0; i < numDragging; ++i)
  441. {
  442. if (auto* ms = desktop.getDraggingMouseSource (i))
  443. {
  444. auto distance = ms->getScreenPosition().getDistanceSquaredFrom (centrePoint);
  445. if (distance < minDistance)
  446. {
  447. minDistance = distance;
  448. inputSourceCausingDrag = ms;
  449. }
  450. }
  451. }
  452. }
  453. // You must call startDragging() from within a mouseDown or mouseDrag callback!
  454. jassert (inputSourceCausingDrag != nullptr && inputSourceCausingDrag->isDragging());
  455. return inputSourceCausingDrag;
  456. }
  457. //==============================================================================
  458. DragAndDropTarget::SourceDetails::SourceDetails (const var& desc, Component* comp, Point<int> pos) noexcept
  459. : description (desc),
  460. sourceComponent (comp),
  461. localPosition (pos)
  462. {
  463. }
  464. void DragAndDropTarget::itemDragEnter (const SourceDetails&) {}
  465. void DragAndDropTarget::itemDragMove (const SourceDetails&) {}
  466. void DragAndDropTarget::itemDragExit (const SourceDetails&) {}
  467. bool DragAndDropTarget::shouldDrawDragImageWhenOver() { return true; }
  468. //==============================================================================
  469. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int) {}
  470. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int) {}
  471. void FileDragAndDropTarget::fileDragExit (const StringArray&) {}
  472. void TextDragAndDropTarget::textDragEnter (const String&, int, int) {}
  473. void TextDragAndDropTarget::textDragMove (const String&, int, int) {}
  474. void TextDragAndDropTarget::textDragExit (const String&) {}
  475. } // namespace juce