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.

2907 lines
90KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. #define CHECK_MESSAGE_MANAGER_IS_LOCKED \
  18. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  19. #define CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN \
  20. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager() || getPeer() == nullptr);
  21. Component* Component::currentlyFocusedComponent = nullptr;
  22. //==============================================================================
  23. class Component::MouseListenerList
  24. {
  25. public:
  26. MouseListenerList() noexcept
  27. : numDeepMouseListeners (0)
  28. {
  29. }
  30. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31. {
  32. if (! listeners.contains (newListener))
  33. {
  34. if (wantsEventsForAllNestedChildComponents)
  35. {
  36. listeners.insert (0, newListener);
  37. ++numDeepMouseListeners;
  38. }
  39. else
  40. {
  41. listeners.add (newListener);
  42. }
  43. }
  44. }
  45. void removeListener (MouseListener* const listenerToRemove)
  46. {
  47. const int index = listeners.indexOf (listenerToRemove);
  48. if (index >= 0)
  49. {
  50. if (index < numDeepMouseListeners)
  51. --numDeepMouseListeners;
  52. listeners.remove (index);
  53. }
  54. }
  55. static void sendMouseEvent (Component& comp, Component::BailOutChecker& checker,
  56. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  57. {
  58. if (checker.shouldBailOut())
  59. return;
  60. if (MouseListenerList* const list = comp.mouseListeners)
  61. {
  62. for (int i = list->listeners.size(); --i >= 0;)
  63. {
  64. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  65. if (checker.shouldBailOut())
  66. return;
  67. i = jmin (i, list->listeners.size());
  68. }
  69. }
  70. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  71. {
  72. MouseListenerList* const list = p->mouseListeners;
  73. if (list != nullptr && list->numDeepMouseListeners > 0)
  74. {
  75. BailOutChecker2 checker2 (checker, p);
  76. for (int i = list->numDeepMouseListeners; --i >= 0;)
  77. {
  78. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  79. if (checker2.shouldBailOut())
  80. return;
  81. i = jmin (i, list->numDeepMouseListeners);
  82. }
  83. }
  84. }
  85. }
  86. static void sendWheelEvent (Component& comp, Component::BailOutChecker& checker,
  87. const MouseEvent& e, const MouseWheelDetails& wheel)
  88. {
  89. if (MouseListenerList* const list = comp.mouseListeners)
  90. {
  91. for (int i = list->listeners.size(); --i >= 0;)
  92. {
  93. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  94. if (checker.shouldBailOut())
  95. return;
  96. i = jmin (i, list->listeners.size());
  97. }
  98. }
  99. for (Component* p = comp.parentComponent; p != nullptr; p = p->parentComponent)
  100. {
  101. MouseListenerList* const list = p->mouseListeners;
  102. if (list != nullptr && list->numDeepMouseListeners > 0)
  103. {
  104. BailOutChecker2 checker2 (checker, p);
  105. for (int i = list->numDeepMouseListeners; --i >= 0;)
  106. {
  107. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheel);
  108. if (checker2.shouldBailOut())
  109. return;
  110. i = jmin (i, list->numDeepMouseListeners);
  111. }
  112. }
  113. }
  114. }
  115. private:
  116. Array <MouseListener*> listeners;
  117. int numDeepMouseListeners;
  118. class BailOutChecker2
  119. {
  120. public:
  121. BailOutChecker2 (Component::BailOutChecker& boc, Component* const comp)
  122. : checker (boc), safePointer (comp)
  123. {
  124. }
  125. bool shouldBailOut() const noexcept
  126. {
  127. return checker.shouldBailOut() || safePointer == 0;
  128. }
  129. private:
  130. Component::BailOutChecker& checker;
  131. const WeakReference<Component> safePointer;
  132. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2)
  133. };
  134. JUCE_DECLARE_NON_COPYABLE (MouseListenerList)
  135. };
  136. //==============================================================================
  137. struct Component::ComponentHelpers
  138. {
  139. #if JUCE_MODAL_LOOPS_PERMITTED
  140. static void* runModalLoopCallback (void* userData)
  141. {
  142. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  143. }
  144. #endif
  145. static Identifier getColourPropertyId (const int colourId)
  146. {
  147. String s;
  148. s.preallocateBytes (32);
  149. s << "jcclr_" << String::toHexString (colourId);
  150. return s;
  151. }
  152. //==============================================================================
  153. static inline bool hitTest (Component& comp, Point<int> localPoint)
  154. {
  155. return isPositiveAndBelow (localPoint.x, comp.getWidth())
  156. && isPositiveAndBelow (localPoint.y, comp.getHeight())
  157. && comp.hitTest (localPoint.x, localPoint.y);
  158. }
  159. static Point<int> convertFromParentSpace (const Component& comp, Point<int> pointInParentSpace)
  160. {
  161. if (comp.affineTransform == nullptr)
  162. return pointInParentSpace - comp.getPosition();
  163. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  164. }
  165. static Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  166. {
  167. if (comp.affineTransform == nullptr)
  168. return areaInParentSpace - comp.getPosition();
  169. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  170. }
  171. static Point<int> convertToParentSpace (const Component& comp, Point<int> pointInLocalSpace)
  172. {
  173. if (comp.affineTransform == nullptr)
  174. return pointInLocalSpace + comp.getPosition();
  175. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  176. }
  177. static Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  178. {
  179. if (comp.affineTransform == nullptr)
  180. return areaInLocalSpace + comp.getPosition();
  181. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  182. }
  183. template <typename Type>
  184. static Type convertFromDistantParentSpace (const Component* parent, const Component& target, const Type& coordInParent)
  185. {
  186. const Component* const directParent = target.getParentComponent();
  187. jassert (directParent != nullptr);
  188. if (directParent == parent)
  189. return convertFromParentSpace (target, coordInParent);
  190. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  191. }
  192. template <typename Type>
  193. static Type convertCoordinate (const Component* target, const Component* source, Type p)
  194. {
  195. while (source != nullptr)
  196. {
  197. if (source == target)
  198. return p;
  199. if (source->isParentOf (target))
  200. return convertFromDistantParentSpace (source, *target, p);
  201. if (source->isOnDesktop())
  202. {
  203. p = source->getPeer()->localToGlobal (p);
  204. source = nullptr;
  205. }
  206. else
  207. {
  208. p = convertToParentSpace (*source, p);
  209. source = source->getParentComponent();
  210. }
  211. }
  212. jassert (source == nullptr);
  213. if (target == nullptr)
  214. return p;
  215. const Component* const topLevelComp = target->getTopLevelComponent();
  216. if (topLevelComp->isOnDesktop())
  217. p = topLevelComp->getPeer()->globalToLocal (p);
  218. else
  219. p = convertFromParentSpace (*topLevelComp, p);
  220. if (topLevelComp == target)
  221. return p;
  222. return convertFromDistantParentSpace (topLevelComp, *target, p);
  223. }
  224. static Rectangle<int> getUnclippedArea (const Component& comp)
  225. {
  226. Rectangle<int> r (comp.getLocalBounds());
  227. if (Component* const p = comp.getParentComponent())
  228. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  229. return r;
  230. }
  231. static bool clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, Point<int> delta)
  232. {
  233. bool nothingChanged = true;
  234. for (int i = comp.childComponentList.size(); --i >= 0;)
  235. {
  236. const Component& child = *comp.childComponentList.getUnchecked(i);
  237. if (child.isVisible() && ! child.isTransformed())
  238. {
  239. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  240. if (! newClip.isEmpty())
  241. {
  242. if (child.isOpaque() && child.componentTransparency == 0)
  243. {
  244. g.excludeClipRegion (newClip + delta);
  245. nothingChanged = false;
  246. }
  247. else
  248. {
  249. const Point<int> childPos (child.getPosition());
  250. if (clipObscuredRegions (child, g, newClip - childPos, childPos + delta))
  251. nothingChanged = false;
  252. }
  253. }
  254. }
  255. }
  256. return nothingChanged;
  257. }
  258. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  259. Point<int> delta, const Rectangle<int>& clipRect,
  260. const Component* const compToAvoid)
  261. {
  262. for (int i = comp.childComponentList.size(); --i >= 0;)
  263. {
  264. const Component* const c = comp.childComponentList.getUnchecked(i);
  265. if (c != compToAvoid && c->isVisible())
  266. {
  267. if (c->isOpaque() && c->componentTransparency == 0)
  268. {
  269. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  270. childBounds.translate (delta.x, delta.y);
  271. result.subtract (childBounds);
  272. }
  273. else
  274. {
  275. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  276. newClip.translate (-c->getX(), -c->getY());
  277. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  278. newClip, compToAvoid);
  279. }
  280. }
  281. }
  282. }
  283. static Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  284. {
  285. if (Component* p = comp.getParentComponent())
  286. return p->getLocalBounds();
  287. return Desktop::getInstance().getDisplays().getMainDisplay().userArea;
  288. }
  289. };
  290. //==============================================================================
  291. Component::Component()
  292. : parentComponent (nullptr),
  293. lookAndFeel (nullptr),
  294. effect (nullptr),
  295. componentFlags (0),
  296. componentTransparency (0)
  297. {
  298. }
  299. Component::Component (const String& name)
  300. : componentName (name),
  301. parentComponent (nullptr),
  302. lookAndFeel (nullptr),
  303. effect (nullptr),
  304. componentFlags (0),
  305. componentTransparency (0)
  306. {
  307. }
  308. Component::~Component()
  309. {
  310. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  311. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  312. masterReference.clear();
  313. while (childComponentList.size() > 0)
  314. removeChildComponent (childComponentList.size() - 1, false, true);
  315. if (parentComponent != nullptr)
  316. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  317. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  318. giveAwayFocus (currentlyFocusedComponent != this);
  319. if (flags.hasHeavyweightPeerFlag)
  320. removeFromDesktop();
  321. // Something has added some children to this component during its destructor! Not a smart idea!
  322. jassert (childComponentList.size() == 0);
  323. }
  324. //==============================================================================
  325. void Component::setName (const String& name)
  326. {
  327. // if component methods are being called from threads other than the message
  328. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  329. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  330. if (componentName != name)
  331. {
  332. componentName = name;
  333. if (flags.hasHeavyweightPeerFlag)
  334. if (ComponentPeer* const peer = getPeer())
  335. peer->setTitle (name);
  336. BailOutChecker checker (this);
  337. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  338. }
  339. }
  340. void Component::setComponentID (const String& newID)
  341. {
  342. componentID = newID;
  343. }
  344. void Component::setVisible (bool shouldBeVisible)
  345. {
  346. if (flags.visibleFlag != shouldBeVisible)
  347. {
  348. // if component methods are being called from threads other than the message
  349. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  350. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  351. const WeakReference<Component> safePointer (this);
  352. flags.visibleFlag = shouldBeVisible;
  353. if (shouldBeVisible)
  354. repaint();
  355. else
  356. repaintParent();
  357. sendFakeMouseMove();
  358. if (! shouldBeVisible)
  359. {
  360. if (cachedImage != nullptr)
  361. cachedImage->releaseResources();
  362. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  363. {
  364. if (parentComponent != nullptr)
  365. parentComponent->grabKeyboardFocus();
  366. else
  367. giveAwayFocus (true);
  368. }
  369. }
  370. if (safePointer != nullptr)
  371. {
  372. sendVisibilityChangeMessage();
  373. if (safePointer != nullptr && flags.hasHeavyweightPeerFlag)
  374. {
  375. if (ComponentPeer* const peer = getPeer())
  376. {
  377. peer->setVisible (shouldBeVisible);
  378. internalHierarchyChanged();
  379. }
  380. }
  381. }
  382. }
  383. }
  384. void Component::visibilityChanged() {}
  385. void Component::sendVisibilityChangeMessage()
  386. {
  387. BailOutChecker checker (this);
  388. visibilityChanged();
  389. if (! checker.shouldBailOut())
  390. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  391. }
  392. bool Component::isShowing() const
  393. {
  394. if (! flags.visibleFlag)
  395. return false;
  396. if (parentComponent != nullptr)
  397. return parentComponent->isShowing();
  398. if (const ComponentPeer* const peer = getPeer())
  399. return ! peer->isMinimised();
  400. return false;
  401. }
  402. //==============================================================================
  403. void* Component::getWindowHandle() const
  404. {
  405. if (const ComponentPeer* const peer = getPeer())
  406. return peer->getNativeHandle();
  407. return nullptr;
  408. }
  409. //==============================================================================
  410. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  411. {
  412. // if component methods are being called from threads other than the message
  413. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  414. CHECK_MESSAGE_MANAGER_IS_LOCKED
  415. if (isOpaque())
  416. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  417. else
  418. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  419. // don't use getPeer(), so that we only get the peer that's specifically
  420. // for this comp, and not for one of its parents.
  421. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  422. if (peer == nullptr || styleWanted != peer->getStyleFlags())
  423. {
  424. const WeakReference<Component> safePointer (this);
  425. #if JUCE_LINUX
  426. // it's wise to give the component a non-zero size before
  427. // putting it on the desktop, as X windows get confused by this, and
  428. // a (1, 1) minimum size is enforced here.
  429. setSize (jmax (1, getWidth()),
  430. jmax (1, getHeight()));
  431. #endif
  432. const Point<int> topLeft (getScreenPosition());
  433. bool wasFullscreen = false;
  434. bool wasMinimised = false;
  435. ComponentBoundsConstrainer* currentConstainer = nullptr;
  436. Rectangle<int> oldNonFullScreenBounds;
  437. int oldRenderingEngine = -1;
  438. if (peer != nullptr)
  439. {
  440. ScopedPointer<ComponentPeer> oldPeerToDelete (peer);
  441. wasFullscreen = peer->isFullScreen();
  442. wasMinimised = peer->isMinimised();
  443. currentConstainer = peer->getConstrainer();
  444. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  445. oldRenderingEngine = peer->getCurrentRenderingEngine();
  446. flags.hasHeavyweightPeerFlag = false;
  447. Desktop::getInstance().removeDesktopComponent (this);
  448. internalHierarchyChanged(); // give comps a chance to react to the peer change before the old peer is deleted.
  449. if (safePointer == nullptr)
  450. return;
  451. setTopLeftPosition (topLeft);
  452. }
  453. if (parentComponent != nullptr)
  454. parentComponent->removeChildComponent (this);
  455. if (safePointer != nullptr)
  456. {
  457. flags.hasHeavyweightPeerFlag = true;
  458. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  459. Desktop::getInstance().addDesktopComponent (this);
  460. bounds.setPosition (topLeft);
  461. peer->setBounds (bounds, false);
  462. if (oldRenderingEngine >= 0)
  463. peer->setCurrentRenderingEngine (oldRenderingEngine);
  464. peer->setVisible (isVisible());
  465. peer = ComponentPeer::getPeerFor (this);
  466. if (peer == nullptr)
  467. return;
  468. if (wasFullscreen)
  469. {
  470. peer->setFullScreen (true);
  471. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  472. }
  473. if (wasMinimised)
  474. peer->setMinimised (true);
  475. #if JUCE_WINDOWS
  476. if (isAlwaysOnTop())
  477. peer->setAlwaysOnTop (true);
  478. #endif
  479. peer->setConstrainer (currentConstainer);
  480. repaint();
  481. internalHierarchyChanged();
  482. }
  483. }
  484. }
  485. void Component::removeFromDesktop()
  486. {
  487. // if component methods are being called from threads other than the message
  488. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  489. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  490. if (flags.hasHeavyweightPeerFlag)
  491. {
  492. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  493. jassert (peer != nullptr);
  494. flags.hasHeavyweightPeerFlag = false;
  495. delete peer;
  496. Desktop::getInstance().removeDesktopComponent (this);
  497. }
  498. }
  499. bool Component::isOnDesktop() const noexcept
  500. {
  501. return flags.hasHeavyweightPeerFlag;
  502. }
  503. ComponentPeer* Component::getPeer() const
  504. {
  505. if (flags.hasHeavyweightPeerFlag)
  506. return ComponentPeer::getPeerFor (this);
  507. if (parentComponent == nullptr)
  508. return nullptr;
  509. return parentComponent->getPeer();
  510. }
  511. void Component::userTriedToCloseWindow()
  512. {
  513. /* This means that the user's trying to get rid of your window with the 'close window' system
  514. menu option (on windows) or possibly the task manager - you should really handle this
  515. and delete or hide your component in an appropriate way.
  516. If you want to ignore the event and don't want to trigger this assertion, just override
  517. this method and do nothing.
  518. */
  519. jassertfalse;
  520. }
  521. void Component::minimisationStateChanged (bool) {}
  522. //==============================================================================
  523. void Component::setOpaque (const bool shouldBeOpaque)
  524. {
  525. if (shouldBeOpaque != flags.opaqueFlag)
  526. {
  527. flags.opaqueFlag = shouldBeOpaque;
  528. if (flags.hasHeavyweightPeerFlag)
  529. if (const ComponentPeer* const peer = ComponentPeer::getPeerFor (this))
  530. addToDesktop (peer->getStyleFlags()); // recreates the heavyweight window
  531. repaint();
  532. }
  533. }
  534. bool Component::isOpaque() const noexcept
  535. {
  536. return flags.opaqueFlag;
  537. }
  538. //==============================================================================
  539. class StandardCachedComponentImage : public CachedComponentImage
  540. {
  541. public:
  542. StandardCachedComponentImage (Component& c) noexcept : owner (c) {}
  543. void paint (Graphics& g) override
  544. {
  545. const Rectangle<int> bounds (owner.getLocalBounds());
  546. if (image.isNull() || image.getBounds() != bounds)
  547. {
  548. image = Image (owner.isOpaque() ? Image::RGB : Image::ARGB,
  549. jmax (1, bounds.getWidth()), jmax (1, bounds.getHeight()), ! owner.isOpaque());
  550. validArea.clear();
  551. }
  552. {
  553. Graphics imG (image);
  554. LowLevelGraphicsContext& lg = imG.getInternalContext();
  555. for (const Rectangle<int>* i = validArea.begin(), * const e = validArea.end(); i != e; ++i)
  556. lg.excludeClipRectangle (*i);
  557. if (! lg.isClipEmpty())
  558. {
  559. if (! owner.isOpaque())
  560. {
  561. lg.setFill (Colours::transparentBlack);
  562. lg.fillRect (bounds, true);
  563. lg.setFill (Colours::black);
  564. }
  565. owner.paintEntireComponent (imG, true);
  566. }
  567. }
  568. validArea = bounds;
  569. g.setColour (Colours::black.withAlpha (owner.getAlpha()));
  570. g.drawImageAt (image, 0, 0);
  571. }
  572. void invalidateAll() { validArea.clear(); }
  573. void invalidate (const Rectangle<int>& area) { validArea.subtract (area); }
  574. void releaseResources() { image = Image::null; }
  575. private:
  576. Image image;
  577. RectangleList validArea;
  578. Component& owner;
  579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StandardCachedComponentImage)
  580. };
  581. void Component::setCachedComponentImage (CachedComponentImage* newCachedImage)
  582. {
  583. if (cachedImage != newCachedImage)
  584. {
  585. cachedImage = newCachedImage;
  586. repaint();
  587. }
  588. }
  589. void Component::setBufferedToImage (const bool shouldBeBuffered)
  590. {
  591. // This assertion means that this component is already using a custom CachedComponentImage,
  592. // so by calling setBufferedToImage, you'll be deleting the custom one - this is almost certainly
  593. // not what you wanted to happen... If you really do know what you're doing here, and want to
  594. // avoid this assertion, just call setCachedComponentImage (nullptr) before setBufferedToImage().
  595. jassert (cachedImage == nullptr || dynamic_cast <StandardCachedComponentImage*> (cachedImage.get()) != nullptr);
  596. if (shouldBeBuffered)
  597. {
  598. if (cachedImage == nullptr)
  599. cachedImage = new StandardCachedComponentImage (*this);
  600. }
  601. else
  602. {
  603. cachedImage = nullptr;
  604. }
  605. }
  606. //==============================================================================
  607. void Component::reorderChildInternal (const int sourceIndex, const int destIndex)
  608. {
  609. if (sourceIndex != destIndex)
  610. {
  611. Component* const c = childComponentList.getUnchecked (sourceIndex);
  612. jassert (c != nullptr);
  613. c->repaintParent();
  614. childComponentList.move (sourceIndex, destIndex);
  615. sendFakeMouseMove();
  616. internalChildrenChanged();
  617. }
  618. }
  619. void Component::toFront (const bool setAsForeground)
  620. {
  621. // if component methods are being called from threads other than the message
  622. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  623. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  624. if (flags.hasHeavyweightPeerFlag)
  625. {
  626. if (ComponentPeer* const peer = getPeer())
  627. {
  628. peer->toFront (setAsForeground);
  629. if (setAsForeground && ! hasKeyboardFocus (true))
  630. grabKeyboardFocus();
  631. }
  632. }
  633. else if (parentComponent != nullptr)
  634. {
  635. const Array<Component*>& childList = parentComponent->childComponentList;
  636. if (childList.getLast() != this)
  637. {
  638. const int index = childList.indexOf (this);
  639. if (index >= 0)
  640. {
  641. int insertIndex = -1;
  642. if (! flags.alwaysOnTopFlag)
  643. {
  644. insertIndex = childList.size() - 1;
  645. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  646. --insertIndex;
  647. }
  648. parentComponent->reorderChildInternal (index, insertIndex);
  649. }
  650. }
  651. if (setAsForeground)
  652. {
  653. internalBroughtToFront();
  654. grabKeyboardFocus();
  655. }
  656. }
  657. }
  658. void Component::toBehind (Component* const other)
  659. {
  660. if (other != nullptr && other != this)
  661. {
  662. // the two components must belong to the same parent..
  663. jassert (parentComponent == other->parentComponent);
  664. if (parentComponent != nullptr)
  665. {
  666. const Array<Component*>& childList = parentComponent->childComponentList;
  667. const int index = childList.indexOf (this);
  668. if (index >= 0 && childList [index + 1] != other)
  669. {
  670. int otherIndex = childList.indexOf (other);
  671. if (otherIndex >= 0)
  672. {
  673. if (index < otherIndex)
  674. --otherIndex;
  675. parentComponent->reorderChildInternal (index, otherIndex);
  676. }
  677. }
  678. }
  679. else if (isOnDesktop())
  680. {
  681. jassert (other->isOnDesktop());
  682. if (other->isOnDesktop())
  683. {
  684. ComponentPeer* const us = getPeer();
  685. ComponentPeer* const them = other->getPeer();
  686. jassert (us != nullptr && them != nullptr);
  687. if (us != nullptr && them != nullptr)
  688. us->toBehind (them);
  689. }
  690. }
  691. }
  692. }
  693. void Component::toBack()
  694. {
  695. if (isOnDesktop())
  696. {
  697. jassertfalse; //xxx need to add this to native window
  698. }
  699. else if (parentComponent != nullptr)
  700. {
  701. const Array<Component*>& childList = parentComponent->childComponentList;
  702. if (childList.getFirst() != this)
  703. {
  704. const int index = childList.indexOf (this);
  705. if (index > 0)
  706. {
  707. int insertIndex = 0;
  708. if (flags.alwaysOnTopFlag)
  709. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  710. ++insertIndex;
  711. parentComponent->reorderChildInternal (index, insertIndex);
  712. }
  713. }
  714. }
  715. }
  716. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  717. {
  718. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  719. {
  720. BailOutChecker checker (this);
  721. flags.alwaysOnTopFlag = shouldStayOnTop;
  722. if (isOnDesktop())
  723. {
  724. if (ComponentPeer* const peer = getPeer())
  725. {
  726. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  727. {
  728. // some kinds of peer can't change their always-on-top status, so
  729. // for these, we'll need to create a new window
  730. const int oldFlags = peer->getStyleFlags();
  731. removeFromDesktop();
  732. addToDesktop (oldFlags);
  733. }
  734. }
  735. }
  736. if (shouldStayOnTop && ! checker.shouldBailOut())
  737. toFront (false);
  738. if (! checker.shouldBailOut())
  739. internalHierarchyChanged();
  740. }
  741. }
  742. bool Component::isAlwaysOnTop() const noexcept
  743. {
  744. return flags.alwaysOnTopFlag;
  745. }
  746. //==============================================================================
  747. int Component::proportionOfWidth (const float proportion) const noexcept { return roundToInt (proportion * bounds.getWidth()); }
  748. int Component::proportionOfHeight (const float proportion) const noexcept { return roundToInt (proportion * bounds.getHeight()); }
  749. int Component::getParentWidth() const noexcept
  750. {
  751. return parentComponent != nullptr ? parentComponent->getWidth()
  752. : getParentMonitorArea().getWidth();
  753. }
  754. int Component::getParentHeight() const noexcept
  755. {
  756. return parentComponent != nullptr ? parentComponent->getHeight()
  757. : getParentMonitorArea().getHeight();
  758. }
  759. int Component::getScreenX() const { return getScreenPosition().x; }
  760. int Component::getScreenY() const { return getScreenPosition().y; }
  761. Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  762. Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  763. Rectangle<int> Component::getParentMonitorArea() const
  764. {
  765. return Desktop::getInstance().getDisplays().getDisplayContaining (getScreenBounds().getCentre()).userArea;
  766. }
  767. Point<int> Component::getLocalPoint (const Component* source, Point<int> point) const
  768. {
  769. return ComponentHelpers::convertCoordinate (this, source, point);
  770. }
  771. Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  772. {
  773. return ComponentHelpers::convertCoordinate (this, source, area);
  774. }
  775. Point<int> Component::localPointToGlobal (Point<int> point) const
  776. {
  777. return ComponentHelpers::convertCoordinate (nullptr, this, point);
  778. }
  779. Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  780. {
  781. return ComponentHelpers::convertCoordinate (nullptr, this, area);
  782. }
  783. // Deprecated methods...
  784. Point<int> Component::relativePositionToGlobal (Point<int> relativePosition) const
  785. {
  786. return localPointToGlobal (relativePosition);
  787. }
  788. Point<int> Component::globalPositionToRelative (Point<int> screenPosition) const
  789. {
  790. return getLocalPoint (nullptr, screenPosition);
  791. }
  792. Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, Point<int> positionRelativeToThis) const
  793. {
  794. return targetComponent == nullptr ? localPointToGlobal (positionRelativeToThis)
  795. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  796. }
  797. //==============================================================================
  798. void Component::setBounds (const int x, const int y, int w, int h)
  799. {
  800. // if component methods are being called from threads other than the message
  801. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  802. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  803. if (w < 0) w = 0;
  804. if (h < 0) h = 0;
  805. const bool wasResized = (getWidth() != w || getHeight() != h);
  806. const bool wasMoved = (getX() != x || getY() != y);
  807. #if JUCE_DEBUG
  808. // It's a very bad idea to try to resize a window during its paint() method!
  809. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  810. #endif
  811. if (wasMoved || wasResized)
  812. {
  813. const bool showing = isShowing();
  814. if (showing)
  815. {
  816. // send a fake mouse move to trigger enter/exit messages if needed..
  817. sendFakeMouseMove();
  818. if (! flags.hasHeavyweightPeerFlag)
  819. repaintParent();
  820. }
  821. bounds.setBounds (x, y, w, h);
  822. if (showing)
  823. {
  824. if (wasResized)
  825. repaint();
  826. else if (! flags.hasHeavyweightPeerFlag)
  827. repaintParent();
  828. }
  829. else if (cachedImage != nullptr)
  830. {
  831. cachedImage->invalidateAll();
  832. }
  833. if (flags.hasHeavyweightPeerFlag)
  834. if (ComponentPeer* const peer = getPeer())
  835. peer->setBounds (getBounds(), false);
  836. sendMovedResizedMessages (wasMoved, wasResized);
  837. }
  838. }
  839. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  840. {
  841. BailOutChecker checker (this);
  842. if (wasMoved)
  843. {
  844. moved();
  845. if (checker.shouldBailOut())
  846. return;
  847. }
  848. if (wasResized)
  849. {
  850. resized();
  851. if (checker.shouldBailOut())
  852. return;
  853. for (int i = childComponentList.size(); --i >= 0;)
  854. {
  855. childComponentList.getUnchecked(i)->parentSizeChanged();
  856. if (checker.shouldBailOut())
  857. return;
  858. i = jmin (i, childComponentList.size());
  859. }
  860. }
  861. if (parentComponent != nullptr)
  862. parentComponent->childBoundsChanged (this);
  863. if (! checker.shouldBailOut())
  864. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  865. *this, wasMoved, wasResized);
  866. }
  867. void Component::setSize (const int w, const int h)
  868. {
  869. setBounds (getX(), getY(), w, h);
  870. }
  871. void Component::setTopLeftPosition (const int x, const int y)
  872. {
  873. setBounds (x, y, getWidth(), getHeight());
  874. }
  875. void Component::setTopLeftPosition (Point<int> pos)
  876. {
  877. setBounds (pos.x, pos.y, getWidth(), getHeight());
  878. }
  879. void Component::setTopRightPosition (const int x, const int y)
  880. {
  881. setTopLeftPosition (x - getWidth(), y);
  882. }
  883. void Component::setBounds (const Rectangle<int>& r)
  884. {
  885. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  886. }
  887. void Component::setBounds (const RelativeRectangle& newBounds)
  888. {
  889. newBounds.applyToComponent (*this);
  890. }
  891. void Component::setBounds (const String& newBoundsExpression)
  892. {
  893. setBounds (RelativeRectangle (newBoundsExpression));
  894. }
  895. void Component::setBoundsRelative (const float x, const float y,
  896. const float w, const float h)
  897. {
  898. const int pw = getParentWidth();
  899. const int ph = getParentHeight();
  900. setBounds (roundToInt (x * pw),
  901. roundToInt (y * ph),
  902. roundToInt (w * pw),
  903. roundToInt (h * ph));
  904. }
  905. void Component::setCentrePosition (const int x, const int y)
  906. {
  907. setTopLeftPosition (x - getWidth() / 2,
  908. y - getHeight() / 2);
  909. }
  910. void Component::setCentreRelative (const float x, const float y)
  911. {
  912. setCentrePosition (roundToInt (getParentWidth() * x),
  913. roundToInt (getParentHeight() * y));
  914. }
  915. void Component::centreWithSize (const int width, const int height)
  916. {
  917. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  918. setBounds (parentArea.getCentreX() - width / 2,
  919. parentArea.getCentreY() - height / 2,
  920. width, height);
  921. }
  922. void Component::setBoundsInset (const BorderSize<int>& borders)
  923. {
  924. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  925. }
  926. void Component::setBoundsToFit (int x, int y, int width, int height,
  927. const Justification& justification,
  928. const bool onlyReduceInSize)
  929. {
  930. // it's no good calling this method unless both the component and
  931. // target rectangle have a finite size.
  932. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  933. if (getWidth() > 0 && getHeight() > 0
  934. && width > 0 && height > 0)
  935. {
  936. int newW, newH;
  937. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  938. {
  939. newW = getWidth();
  940. newH = getHeight();
  941. }
  942. else
  943. {
  944. const double imageRatio = getHeight() / (double) getWidth();
  945. const double targetRatio = height / (double) width;
  946. if (imageRatio <= targetRatio)
  947. {
  948. newW = width;
  949. newH = jmin (height, roundToInt (newW * imageRatio));
  950. }
  951. else
  952. {
  953. newH = height;
  954. newW = jmin (width, roundToInt (newH / imageRatio));
  955. }
  956. }
  957. if (newW > 0 && newH > 0)
  958. setBounds (justification.appliedToRectangle (Rectangle<int> (newW, newH),
  959. Rectangle<int> (x, y, width, height)));
  960. }
  961. }
  962. //==============================================================================
  963. bool Component::isTransformed() const noexcept
  964. {
  965. return affineTransform != nullptr;
  966. }
  967. void Component::setTransform (const AffineTransform& newTransform)
  968. {
  969. // If you pass in a transform with no inverse, the component will have no dimensions,
  970. // and there will be all sorts of maths errors when converting coordinates.
  971. jassert (! newTransform.isSingularity());
  972. if (newTransform.isIdentity())
  973. {
  974. if (affineTransform != nullptr)
  975. {
  976. repaint();
  977. affineTransform = nullptr;
  978. repaint();
  979. sendMovedResizedMessages (false, false);
  980. }
  981. }
  982. else if (affineTransform == nullptr)
  983. {
  984. repaint();
  985. affineTransform = new AffineTransform (newTransform);
  986. repaint();
  987. sendMovedResizedMessages (false, false);
  988. }
  989. else if (*affineTransform != newTransform)
  990. {
  991. repaint();
  992. *affineTransform = newTransform;
  993. repaint();
  994. sendMovedResizedMessages (false, false);
  995. }
  996. }
  997. AffineTransform Component::getTransform() const
  998. {
  999. return affineTransform != nullptr ? *affineTransform : AffineTransform::identity;
  1000. }
  1001. //==============================================================================
  1002. bool Component::hitTest (int x, int y)
  1003. {
  1004. if (! flags.ignoresMouseClicksFlag)
  1005. return true;
  1006. if (flags.allowChildMouseClicksFlag)
  1007. {
  1008. for (int i = childComponentList.size(); --i >= 0;)
  1009. {
  1010. Component& child = *childComponentList.getUnchecked (i);
  1011. if (child.isVisible()
  1012. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  1013. return true;
  1014. }
  1015. }
  1016. return false;
  1017. }
  1018. void Component::setInterceptsMouseClicks (const bool allowClicks,
  1019. const bool allowClicksOnChildComponents) noexcept
  1020. {
  1021. flags.ignoresMouseClicksFlag = ! allowClicks;
  1022. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  1023. }
  1024. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  1025. bool& allowsClicksOnChildComponents) const noexcept
  1026. {
  1027. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  1028. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  1029. }
  1030. bool Component::contains (Point<int> point)
  1031. {
  1032. if (ComponentHelpers::hitTest (*this, point))
  1033. {
  1034. if (parentComponent != nullptr)
  1035. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  1036. if (flags.hasHeavyweightPeerFlag)
  1037. if (const ComponentPeer* const peer = getPeer())
  1038. return peer->contains (point, true);
  1039. }
  1040. return false;
  1041. }
  1042. bool Component::reallyContains (Point<int> point, const bool returnTrueIfWithinAChild)
  1043. {
  1044. if (! contains (point))
  1045. return false;
  1046. Component* const top = getTopLevelComponent();
  1047. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  1048. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  1049. }
  1050. Component* Component::getComponentAt (Point<int> position)
  1051. {
  1052. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  1053. {
  1054. for (int i = childComponentList.size(); --i >= 0;)
  1055. {
  1056. Component* child = childComponentList.getUnchecked(i);
  1057. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  1058. if (child != nullptr)
  1059. return child;
  1060. }
  1061. return this;
  1062. }
  1063. return nullptr;
  1064. }
  1065. Component* Component::getComponentAt (const int x, const int y)
  1066. {
  1067. return getComponentAt (Point<int> (x, y));
  1068. }
  1069. //==============================================================================
  1070. void Component::addChildComponent (Component* const child, int zOrder)
  1071. {
  1072. // if component methods are being called from threads other than the message
  1073. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1074. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1075. if (child != nullptr && child->parentComponent != this)
  1076. {
  1077. if (child->parentComponent != nullptr)
  1078. child->parentComponent->removeChildComponent (child);
  1079. else
  1080. child->removeFromDesktop();
  1081. child->parentComponent = this;
  1082. if (child->isVisible())
  1083. child->repaintParent();
  1084. if (! child->isAlwaysOnTop())
  1085. {
  1086. if (zOrder < 0 || zOrder > childComponentList.size())
  1087. zOrder = childComponentList.size();
  1088. while (zOrder > 0)
  1089. {
  1090. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  1091. break;
  1092. --zOrder;
  1093. }
  1094. }
  1095. childComponentList.insert (zOrder, child);
  1096. child->internalHierarchyChanged();
  1097. internalChildrenChanged();
  1098. }
  1099. }
  1100. void Component::addAndMakeVisible (Component* const child, int zOrder)
  1101. {
  1102. if (child != nullptr)
  1103. {
  1104. child->setVisible (true);
  1105. addChildComponent (child, zOrder);
  1106. }
  1107. }
  1108. void Component::addChildAndSetID (Component* const child, const String& childID)
  1109. {
  1110. if (child != nullptr)
  1111. {
  1112. child->setComponentID (childID);
  1113. addAndMakeVisible (child);
  1114. }
  1115. }
  1116. void Component::removeChildComponent (Component* const child)
  1117. {
  1118. removeChildComponent (childComponentList.indexOf (child), true, true);
  1119. }
  1120. Component* Component::removeChildComponent (const int index)
  1121. {
  1122. return removeChildComponent (index, true, true);
  1123. }
  1124. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1125. {
  1126. // if component methods are being called from threads other than the message
  1127. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1128. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1129. Component* const child = childComponentList [index];
  1130. if (child != nullptr)
  1131. {
  1132. sendParentEvents = sendParentEvents && child->isShowing();
  1133. if (sendParentEvents)
  1134. {
  1135. sendFakeMouseMove();
  1136. if (child->isVisible())
  1137. child->repaintParent();
  1138. }
  1139. childComponentList.remove (index);
  1140. child->parentComponent = nullptr;
  1141. if (child->cachedImage != nullptr)
  1142. child->cachedImage->releaseResources();
  1143. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1144. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1145. {
  1146. if (sendParentEvents)
  1147. {
  1148. const WeakReference<Component> thisPointer (this);
  1149. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1150. if (thisPointer == nullptr)
  1151. return child;
  1152. grabKeyboardFocus();
  1153. }
  1154. else
  1155. {
  1156. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1157. }
  1158. }
  1159. if (sendChildEvents)
  1160. child->internalHierarchyChanged();
  1161. if (sendParentEvents)
  1162. internalChildrenChanged();
  1163. }
  1164. return child;
  1165. }
  1166. //==============================================================================
  1167. void Component::removeAllChildren()
  1168. {
  1169. while (childComponentList.size() > 0)
  1170. removeChildComponent (childComponentList.size() - 1);
  1171. }
  1172. void Component::deleteAllChildren()
  1173. {
  1174. while (childComponentList.size() > 0)
  1175. delete (removeChildComponent (childComponentList.size() - 1));
  1176. }
  1177. int Component::getNumChildComponents() const noexcept
  1178. {
  1179. return childComponentList.size();
  1180. }
  1181. Component* Component::getChildComponent (const int index) const noexcept
  1182. {
  1183. return childComponentList [index];
  1184. }
  1185. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1186. {
  1187. return childComponentList.indexOf (const_cast <Component*> (child));
  1188. }
  1189. Component* Component::findChildWithID (const String& targetID) const noexcept
  1190. {
  1191. for (int i = childComponentList.size(); --i >= 0;)
  1192. {
  1193. Component* const c = childComponentList.getUnchecked(i);
  1194. if (c->componentID == targetID)
  1195. return c;
  1196. }
  1197. return nullptr;
  1198. }
  1199. Component* Component::getTopLevelComponent() const noexcept
  1200. {
  1201. const Component* comp = this;
  1202. while (comp->parentComponent != nullptr)
  1203. comp = comp->parentComponent;
  1204. return const_cast <Component*> (comp);
  1205. }
  1206. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1207. {
  1208. while (possibleChild != nullptr)
  1209. {
  1210. possibleChild = possibleChild->parentComponent;
  1211. if (possibleChild == this)
  1212. return true;
  1213. }
  1214. return false;
  1215. }
  1216. //==============================================================================
  1217. void Component::parentHierarchyChanged() {}
  1218. void Component::childrenChanged() {}
  1219. void Component::internalChildrenChanged()
  1220. {
  1221. if (componentListeners.isEmpty())
  1222. {
  1223. childrenChanged();
  1224. }
  1225. else
  1226. {
  1227. BailOutChecker checker (this);
  1228. childrenChanged();
  1229. if (! checker.shouldBailOut())
  1230. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1231. }
  1232. }
  1233. void Component::internalHierarchyChanged()
  1234. {
  1235. BailOutChecker checker (this);
  1236. parentHierarchyChanged();
  1237. if (checker.shouldBailOut())
  1238. return;
  1239. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1240. if (checker.shouldBailOut())
  1241. return;
  1242. for (int i = childComponentList.size(); --i >= 0;)
  1243. {
  1244. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1245. if (checker.shouldBailOut())
  1246. {
  1247. // you really shouldn't delete the parent component during a callback telling you
  1248. // that it's changed..
  1249. jassertfalse;
  1250. return;
  1251. }
  1252. i = jmin (i, childComponentList.size());
  1253. }
  1254. }
  1255. //==============================================================================
  1256. #if JUCE_MODAL_LOOPS_PERMITTED
  1257. int Component::runModalLoop()
  1258. {
  1259. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1260. {
  1261. // use a callback so this can be called from non-gui threads
  1262. return (int) (pointer_sized_int) MessageManager::getInstance()
  1263. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1264. }
  1265. if (! isCurrentlyModal())
  1266. enterModalState (true);
  1267. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1268. }
  1269. #endif
  1270. //==============================================================================
  1271. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1272. ModalComponentManager::Callback* callback,
  1273. const bool deleteWhenDismissed)
  1274. {
  1275. // if component methods are being called from threads other than the message
  1276. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1277. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1278. // Check for an attempt to make a component modal when it already is!
  1279. // This can cause nasty problems..
  1280. jassert (! flags.currentlyModalFlag);
  1281. if (! isCurrentlyModal())
  1282. {
  1283. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  1284. mcm->startModal (this, deleteWhenDismissed);
  1285. mcm->attachCallback (this, callback);
  1286. flags.currentlyModalFlag = true;
  1287. setVisible (true);
  1288. if (shouldTakeKeyboardFocus)
  1289. grabKeyboardFocus();
  1290. }
  1291. }
  1292. void Component::exitModalState (const int returnValue)
  1293. {
  1294. if (flags.currentlyModalFlag)
  1295. {
  1296. if (MessageManager::getInstance()->isThisTheMessageThread())
  1297. {
  1298. ModalComponentManager::getInstance()->endModal (this, returnValue);
  1299. flags.currentlyModalFlag = false;
  1300. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1301. }
  1302. else
  1303. {
  1304. class ExitModalStateMessage : public CallbackMessage
  1305. {
  1306. public:
  1307. ExitModalStateMessage (Component* const c, const int res)
  1308. : target (c), result (res) {}
  1309. void messageCallback()
  1310. {
  1311. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1312. target->exitModalState (result);
  1313. }
  1314. private:
  1315. WeakReference<Component> target;
  1316. int result;
  1317. };
  1318. (new ExitModalStateMessage (this, returnValue))->post();
  1319. }
  1320. }
  1321. }
  1322. bool Component::isCurrentlyModal() const noexcept
  1323. {
  1324. return flags.currentlyModalFlag
  1325. && getCurrentlyModalComponent() == this;
  1326. }
  1327. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1328. {
  1329. Component* const mc = getCurrentlyModalComponent();
  1330. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1331. || mc->canModalEventBeSentToComponent (this));
  1332. }
  1333. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1334. {
  1335. return ModalComponentManager::getInstance()->getNumModalComponents();
  1336. }
  1337. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1338. {
  1339. return ModalComponentManager::getInstance()->getModalComponent (index);
  1340. }
  1341. //==============================================================================
  1342. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1343. {
  1344. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1345. }
  1346. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1347. {
  1348. return flags.bringToFrontOnClickFlag;
  1349. }
  1350. //==============================================================================
  1351. void Component::setMouseCursor (const MouseCursor& newCursor)
  1352. {
  1353. if (cursor != newCursor)
  1354. {
  1355. cursor = newCursor;
  1356. if (flags.visibleFlag)
  1357. updateMouseCursor();
  1358. }
  1359. }
  1360. MouseCursor Component::getMouseCursor()
  1361. {
  1362. return cursor;
  1363. }
  1364. void Component::updateMouseCursor() const
  1365. {
  1366. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1367. }
  1368. //==============================================================================
  1369. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1370. {
  1371. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1372. }
  1373. //==============================================================================
  1374. void Component::setAlpha (const float newAlpha)
  1375. {
  1376. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1377. if (componentTransparency != newIntAlpha)
  1378. {
  1379. componentTransparency = newIntAlpha;
  1380. if (flags.hasHeavyweightPeerFlag)
  1381. {
  1382. if (ComponentPeer* const peer = getPeer())
  1383. peer->setAlpha (newAlpha);
  1384. }
  1385. else
  1386. {
  1387. repaint();
  1388. }
  1389. }
  1390. }
  1391. float Component::getAlpha() const
  1392. {
  1393. return (255 - componentTransparency) / 255.0f;
  1394. }
  1395. //==============================================================================
  1396. void Component::repaint()
  1397. {
  1398. internalRepaintUnchecked (getLocalBounds(), true);
  1399. }
  1400. void Component::repaint (const int x, const int y, const int w, const int h)
  1401. {
  1402. internalRepaint (Rectangle<int> (x, y, w, h));
  1403. }
  1404. void Component::repaint (const Rectangle<int>& area)
  1405. {
  1406. internalRepaint (area);
  1407. }
  1408. void Component::repaintParent()
  1409. {
  1410. if (parentComponent != nullptr)
  1411. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1412. }
  1413. void Component::internalRepaint (const Rectangle<int>& area)
  1414. {
  1415. const Rectangle<int> r (area.getIntersection (getLocalBounds()));
  1416. if (! r.isEmpty())
  1417. internalRepaintUnchecked (r, false);
  1418. }
  1419. void Component::internalRepaintUnchecked (const Rectangle<int>& area, const bool isEntireComponent)
  1420. {
  1421. if (flags.visibleFlag)
  1422. {
  1423. if (cachedImage != nullptr)
  1424. {
  1425. if (isEntireComponent)
  1426. cachedImage->invalidateAll();
  1427. else
  1428. cachedImage->invalidate (area);
  1429. }
  1430. if (flags.hasHeavyweightPeerFlag)
  1431. {
  1432. // if component methods are being called from threads other than the message
  1433. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1434. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1435. if (ComponentPeer* const peer = getPeer())
  1436. peer->repaint (area);
  1437. }
  1438. else
  1439. {
  1440. if (parentComponent != nullptr)
  1441. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1442. }
  1443. }
  1444. }
  1445. //==============================================================================
  1446. void Component::paint (Graphics&)
  1447. {
  1448. // all painting is done in the subclasses
  1449. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  1450. }
  1451. void Component::paintOverChildren (Graphics&)
  1452. {
  1453. // all painting is done in the subclasses
  1454. }
  1455. //==============================================================================
  1456. void Component::paintWithinParentContext (Graphics& g)
  1457. {
  1458. g.setOrigin (getX(), getY());
  1459. if (cachedImage != nullptr)
  1460. cachedImage->paint (g);
  1461. else
  1462. paintEntireComponent (g, false);
  1463. }
  1464. void Component::paintComponentAndChildren (Graphics& g)
  1465. {
  1466. const Rectangle<int> clipBounds (g.getClipBounds());
  1467. if (flags.dontClipGraphicsFlag)
  1468. {
  1469. paint (g);
  1470. }
  1471. else
  1472. {
  1473. g.saveState();
  1474. if (ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>()) || ! g.isClipEmpty())
  1475. paint (g);
  1476. g.restoreState();
  1477. }
  1478. for (int i = 0; i < childComponentList.size(); ++i)
  1479. {
  1480. Component& child = *childComponentList.getUnchecked (i);
  1481. if (child.isVisible())
  1482. {
  1483. if (child.affineTransform != nullptr)
  1484. {
  1485. g.saveState();
  1486. g.addTransform (*child.affineTransform);
  1487. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1488. child.paintWithinParentContext (g);
  1489. g.restoreState();
  1490. }
  1491. else if (clipBounds.intersects (child.getBounds()))
  1492. {
  1493. g.saveState();
  1494. if (child.flags.dontClipGraphicsFlag)
  1495. {
  1496. child.paintWithinParentContext (g);
  1497. }
  1498. else if (g.reduceClipRegion (child.getBounds()))
  1499. {
  1500. bool nothingClipped = true;
  1501. for (int j = i + 1; j < childComponentList.size(); ++j)
  1502. {
  1503. const Component& sibling = *childComponentList.getUnchecked (j);
  1504. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1505. {
  1506. nothingClipped = false;
  1507. g.excludeClipRegion (sibling.getBounds());
  1508. }
  1509. }
  1510. if (nothingClipped || ! g.isClipEmpty())
  1511. child.paintWithinParentContext (g);
  1512. }
  1513. g.restoreState();
  1514. }
  1515. }
  1516. }
  1517. g.saveState();
  1518. paintOverChildren (g);
  1519. g.restoreState();
  1520. }
  1521. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1522. {
  1523. #if JUCE_DEBUG
  1524. flags.isInsidePaintCall = true;
  1525. #endif
  1526. if (effect != nullptr)
  1527. {
  1528. const float scale = g.getInternalContext().getTargetDeviceScaleFactor();
  1529. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1530. (int) (scale * getWidth()), (int) (scale * getHeight()), ! flags.opaqueFlag);
  1531. {
  1532. Graphics g2 (effectImage);
  1533. g2.addTransform (AffineTransform::scale (scale));
  1534. paintComponentAndChildren (g2);
  1535. }
  1536. g.saveState();
  1537. g.addTransform (AffineTransform::scale (1.0f / scale));
  1538. effect->applyEffect (effectImage, g, scale, ignoreAlphaLevel ? 1.0f : getAlpha());
  1539. g.restoreState();
  1540. }
  1541. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1542. {
  1543. if (componentTransparency < 255)
  1544. {
  1545. g.beginTransparencyLayer (getAlpha());
  1546. paintComponentAndChildren (g);
  1547. g.endTransparencyLayer();
  1548. }
  1549. }
  1550. else
  1551. {
  1552. paintComponentAndChildren (g);
  1553. }
  1554. #if JUCE_DEBUG
  1555. flags.isInsidePaintCall = false;
  1556. #endif
  1557. }
  1558. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1559. {
  1560. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1561. }
  1562. //==============================================================================
  1563. Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  1564. const bool clipImageToComponentBounds)
  1565. {
  1566. Rectangle<int> r (areaToGrab);
  1567. if (clipImageToComponentBounds)
  1568. r = r.getIntersection (getLocalBounds());
  1569. if (r.isEmpty())
  1570. return Image();
  1571. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1572. r.getWidth(), r.getHeight(), true);
  1573. Graphics imageContext (componentImage);
  1574. imageContext.setOrigin (-r.getX(), -r.getY());
  1575. paintEntireComponent (imageContext, true);
  1576. return componentImage;
  1577. }
  1578. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1579. {
  1580. if (effect != newEffect)
  1581. {
  1582. effect = newEffect;
  1583. repaint();
  1584. }
  1585. }
  1586. //==============================================================================
  1587. LookAndFeel& Component::getLookAndFeel() const noexcept
  1588. {
  1589. for (const Component* c = this; c != nullptr; c = c->parentComponent)
  1590. if (c->lookAndFeel != nullptr)
  1591. return *(c->lookAndFeel);
  1592. return LookAndFeel::getDefaultLookAndFeel();
  1593. }
  1594. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1595. {
  1596. if (lookAndFeel != newLookAndFeel)
  1597. {
  1598. lookAndFeel = newLookAndFeel;
  1599. sendLookAndFeelChange();
  1600. }
  1601. }
  1602. void Component::lookAndFeelChanged() {}
  1603. void Component::colourChanged() {}
  1604. void Component::sendLookAndFeelChange()
  1605. {
  1606. const WeakReference<Component> safePointer (this);
  1607. repaint();
  1608. lookAndFeelChanged();
  1609. if (safePointer != nullptr)
  1610. {
  1611. colourChanged();
  1612. if (safePointer != nullptr)
  1613. {
  1614. for (int i = childComponentList.size(); --i >= 0;)
  1615. {
  1616. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1617. if (safePointer == nullptr)
  1618. return;
  1619. i = jmin (i, childComponentList.size());
  1620. }
  1621. }
  1622. }
  1623. }
  1624. Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1625. {
  1626. if (const var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId)))
  1627. return Colour ((uint32) static_cast <int> (*v));
  1628. if (inheritFromParent && parentComponent != nullptr
  1629. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1630. return parentComponent->findColour (colourId, true);
  1631. return getLookAndFeel().findColour (colourId);
  1632. }
  1633. bool Component::isColourSpecified (const int colourId) const
  1634. {
  1635. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1636. }
  1637. void Component::removeColour (const int colourId)
  1638. {
  1639. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1640. colourChanged();
  1641. }
  1642. void Component::setColour (const int colourId, Colour colour)
  1643. {
  1644. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1645. colourChanged();
  1646. }
  1647. void Component::copyAllExplicitColoursTo (Component& target) const
  1648. {
  1649. bool changed = false;
  1650. for (int i = properties.size(); --i >= 0;)
  1651. {
  1652. const Identifier name (properties.getName(i));
  1653. if (name.toString().startsWith ("jcclr_"))
  1654. if (target.properties.set (name, properties [name]))
  1655. changed = true;
  1656. }
  1657. if (changed)
  1658. target.colourChanged();
  1659. }
  1660. //==============================================================================
  1661. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1662. {
  1663. return nullptr;
  1664. }
  1665. //==============================================================================
  1666. Component::Positioner::Positioner (Component& c) noexcept
  1667. : component (c)
  1668. {
  1669. }
  1670. Component::Positioner* Component::getPositioner() const noexcept
  1671. {
  1672. return positioner;
  1673. }
  1674. void Component::setPositioner (Positioner* newPositioner)
  1675. {
  1676. // You can only assign a positioner to the component that it was created for!
  1677. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1678. positioner = newPositioner;
  1679. }
  1680. //==============================================================================
  1681. Rectangle<int> Component::getLocalBounds() const noexcept
  1682. {
  1683. return bounds.withZeroOrigin();
  1684. }
  1685. Rectangle<int> Component::getBoundsInParent() const noexcept
  1686. {
  1687. return affineTransform == nullptr ? bounds
  1688. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  1689. }
  1690. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  1691. {
  1692. result.clear();
  1693. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  1694. if (! unclipped.isEmpty())
  1695. {
  1696. result.add (unclipped);
  1697. if (includeSiblings)
  1698. {
  1699. const Component* const c = getTopLevelComponent();
  1700. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  1701. c->getLocalBounds(), this);
  1702. }
  1703. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, nullptr);
  1704. result.consolidate();
  1705. }
  1706. }
  1707. //==============================================================================
  1708. void Component::mouseEnter (const MouseEvent&) {}
  1709. void Component::mouseExit (const MouseEvent&) {}
  1710. void Component::mouseDown (const MouseEvent&) {}
  1711. void Component::mouseUp (const MouseEvent&) {}
  1712. void Component::mouseDrag (const MouseEvent&) {}
  1713. void Component::mouseMove (const MouseEvent&) {}
  1714. void Component::mouseDoubleClick (const MouseEvent&) {}
  1715. void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1716. {
  1717. // the base class just passes this event up to its parent..
  1718. if (parentComponent != nullptr)
  1719. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent), wheel);
  1720. }
  1721. void Component::mouseMagnify (const MouseEvent& e, float magnifyAmount)
  1722. {
  1723. // the base class just passes this event up to its parent..
  1724. if (parentComponent != nullptr)
  1725. parentComponent->mouseMagnify (e.getEventRelativeTo (parentComponent), magnifyAmount);
  1726. }
  1727. //==============================================================================
  1728. void Component::resized() {}
  1729. void Component::moved() {}
  1730. void Component::childBoundsChanged (Component*) {}
  1731. void Component::parentSizeChanged() {}
  1732. void Component::addComponentListener (ComponentListener* const newListener)
  1733. {
  1734. // if component methods are being called from threads other than the message
  1735. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1736. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1737. componentListeners.add (newListener);
  1738. }
  1739. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1740. {
  1741. componentListeners.remove (listenerToRemove);
  1742. }
  1743. //==============================================================================
  1744. void Component::inputAttemptWhenModal()
  1745. {
  1746. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1747. getLookAndFeel().playAlertSound();
  1748. }
  1749. bool Component::canModalEventBeSentToComponent (const Component*)
  1750. {
  1751. return false;
  1752. }
  1753. void Component::internalModalInputAttempt()
  1754. {
  1755. if (Component* const current = getCurrentlyModalComponent())
  1756. current->inputAttemptWhenModal();
  1757. }
  1758. //==============================================================================
  1759. void Component::postCommandMessage (const int commandId)
  1760. {
  1761. class CustomCommandMessage : public CallbackMessage
  1762. {
  1763. public:
  1764. CustomCommandMessage (Component* const c, const int command)
  1765. : target (c), commandId (command) {}
  1766. void messageCallback()
  1767. {
  1768. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1769. target->handleCommandMessage (commandId);
  1770. }
  1771. private:
  1772. WeakReference<Component> target;
  1773. int commandId;
  1774. };
  1775. (new CustomCommandMessage (this, commandId))->post();
  1776. }
  1777. void Component::handleCommandMessage (int)
  1778. {
  1779. // used by subclasses
  1780. }
  1781. //==============================================================================
  1782. void Component::addMouseListener (MouseListener* const newListener,
  1783. const bool wantsEventsForAllNestedChildComponents)
  1784. {
  1785. // if component methods are being called from threads other than the message
  1786. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1787. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1788. // If you register a component as a mouselistener for itself, it'll receive all the events
  1789. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1790. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1791. if (mouseListeners == nullptr)
  1792. mouseListeners = new MouseListenerList();
  1793. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1794. }
  1795. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1796. {
  1797. // if component methods are being called from threads other than the message
  1798. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1799. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1800. if (mouseListeners != nullptr)
  1801. mouseListeners->removeListener (listenerToRemove);
  1802. }
  1803. //==============================================================================
  1804. void Component::internalMouseEnter (MouseInputSource& source, Point<int> relativePos, Time time)
  1805. {
  1806. if (isCurrentlyBlockedByAnotherModalComponent())
  1807. {
  1808. // if something else is modal, always just show a normal mouse cursor
  1809. source.showMouseCursor (MouseCursor::NormalCursor);
  1810. return;
  1811. }
  1812. if (flags.repaintOnMouseActivityFlag)
  1813. repaint();
  1814. BailOutChecker checker (this);
  1815. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1816. this, this, time, relativePos, time, 0, false);
  1817. mouseEnter (me);
  1818. if (checker.shouldBailOut())
  1819. return;
  1820. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1821. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1822. }
  1823. void Component::internalMouseExit (MouseInputSource& source, Point<int> relativePos, Time time)
  1824. {
  1825. if (flags.repaintOnMouseActivityFlag)
  1826. repaint();
  1827. BailOutChecker checker (this);
  1828. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1829. this, this, time, relativePos, time, 0, false);
  1830. mouseExit (me);
  1831. if (checker.shouldBailOut())
  1832. return;
  1833. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1834. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1835. }
  1836. void Component::internalMouseDown (MouseInputSource& source, Point<int> relativePos, Time time)
  1837. {
  1838. Desktop& desktop = Desktop::getInstance();
  1839. BailOutChecker checker (this);
  1840. if (isCurrentlyBlockedByAnotherModalComponent())
  1841. {
  1842. flags.mouseDownWasBlocked = true;
  1843. internalModalInputAttempt();
  1844. if (checker.shouldBailOut())
  1845. return;
  1846. // If processing the input attempt has exited the modal loop, we'll allow the event
  1847. // to be delivered..
  1848. if (isCurrentlyBlockedByAnotherModalComponent())
  1849. {
  1850. // allow blocked mouse-events to go to global listeners..
  1851. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1852. this, this, time, relativePos, time,
  1853. source.getNumberOfMultipleClicks(), false);
  1854. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1855. return;
  1856. }
  1857. }
  1858. flags.mouseDownWasBlocked = false;
  1859. for (Component* c = this; c != nullptr; c = c->parentComponent)
  1860. {
  1861. if (c->isBroughtToFrontOnMouseClick())
  1862. {
  1863. c->toFront (true);
  1864. if (checker.shouldBailOut())
  1865. return;
  1866. }
  1867. }
  1868. if (! flags.dontFocusOnMouseClickFlag)
  1869. {
  1870. grabFocusInternal (focusChangedByMouseClick, true);
  1871. if (checker.shouldBailOut())
  1872. return;
  1873. }
  1874. if (flags.repaintOnMouseActivityFlag)
  1875. repaint();
  1876. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1877. this, this, time, relativePos, time,
  1878. source.getNumberOfMultipleClicks(), false);
  1879. mouseDown (me);
  1880. if (checker.shouldBailOut())
  1881. return;
  1882. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1883. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  1884. }
  1885. void Component::internalMouseUp (MouseInputSource& source, Point<int> relativePos,
  1886. Time time, const ModifierKeys oldModifiers)
  1887. {
  1888. if (flags.mouseDownWasBlocked && isCurrentlyBlockedByAnotherModalComponent())
  1889. return;
  1890. BailOutChecker checker (this);
  1891. if (flags.repaintOnMouseActivityFlag)
  1892. repaint();
  1893. const MouseEvent me (source, relativePos,
  1894. oldModifiers, this, this, time,
  1895. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1896. source.getLastMouseDownTime(),
  1897. source.getNumberOfMultipleClicks(),
  1898. source.hasMouseMovedSignificantlySincePressed());
  1899. mouseUp (me);
  1900. if (checker.shouldBailOut())
  1901. return;
  1902. Desktop& desktop = Desktop::getInstance();
  1903. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseUp, me);
  1904. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  1905. if (checker.shouldBailOut())
  1906. return;
  1907. // check for double-click
  1908. if (me.getNumberOfClicks() >= 2)
  1909. {
  1910. mouseDoubleClick (me);
  1911. if (checker.shouldBailOut())
  1912. return;
  1913. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  1914. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  1915. }
  1916. }
  1917. void Component::internalMouseDrag (MouseInputSource& source, Point<int> relativePos, Time time)
  1918. {
  1919. if (! isCurrentlyBlockedByAnotherModalComponent())
  1920. {
  1921. BailOutChecker checker (this);
  1922. const MouseEvent me (source, relativePos,
  1923. source.getCurrentModifiers(), this, this, time,
  1924. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1925. source.getLastMouseDownTime(),
  1926. source.getNumberOfMultipleClicks(),
  1927. source.hasMouseMovedSignificantlySincePressed());
  1928. mouseDrag (me);
  1929. if (checker.shouldBailOut())
  1930. return;
  1931. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseDrag, me);
  1932. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  1933. }
  1934. }
  1935. void Component::internalMouseMove (MouseInputSource& source, Point<int> relativePos, Time time)
  1936. {
  1937. Desktop& desktop = Desktop::getInstance();
  1938. if (isCurrentlyBlockedByAnotherModalComponent())
  1939. {
  1940. // allow blocked mouse-events to go to global listeners..
  1941. desktop.sendMouseMove();
  1942. }
  1943. else
  1944. {
  1945. BailOutChecker checker (this);
  1946. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1947. this, this, time, relativePos, time, 0, false);
  1948. mouseMove (me);
  1949. if (checker.shouldBailOut())
  1950. return;
  1951. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseMove, me);
  1952. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  1953. }
  1954. }
  1955. void Component::internalMouseWheel (MouseInputSource& source, Point<int> relativePos,
  1956. Time time, const MouseWheelDetails& wheel)
  1957. {
  1958. Desktop& desktop = Desktop::getInstance();
  1959. BailOutChecker checker (this);
  1960. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1961. this, this, time, relativePos, time, 0, false);
  1962. if (isCurrentlyBlockedByAnotherModalComponent())
  1963. {
  1964. // allow blocked mouse-events to go to global listeners..
  1965. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  1966. }
  1967. else
  1968. {
  1969. mouseWheelMove (me, wheel);
  1970. if (checker.shouldBailOut())
  1971. return;
  1972. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  1973. if (! checker.shouldBailOut())
  1974. MouseListenerList::sendWheelEvent (*this, checker, me, wheel);
  1975. }
  1976. }
  1977. void Component::internalMagnifyGesture (MouseInputSource& source, Point<int> relativePos,
  1978. Time time, float amount)
  1979. {
  1980. if (! isCurrentlyBlockedByAnotherModalComponent())
  1981. {
  1982. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1983. this, this, time, relativePos, time, 0, false);
  1984. mouseMagnify (me, amount);
  1985. }
  1986. }
  1987. void Component::sendFakeMouseMove() const
  1988. {
  1989. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  1990. if (! mainMouse.isDragging())
  1991. mainMouse.triggerFakeMove();
  1992. }
  1993. void JUCE_CALLTYPE Component::beginDragAutoRepeat (const int interval)
  1994. {
  1995. Desktop::getInstance().beginDragAutoRepeat (interval);
  1996. }
  1997. //==============================================================================
  1998. void Component::broughtToFront()
  1999. {
  2000. }
  2001. void Component::internalBroughtToFront()
  2002. {
  2003. if (flags.hasHeavyweightPeerFlag)
  2004. Desktop::getInstance().componentBroughtToFront (this);
  2005. BailOutChecker checker (this);
  2006. broughtToFront();
  2007. if (checker.shouldBailOut())
  2008. return;
  2009. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  2010. if (checker.shouldBailOut())
  2011. return;
  2012. // When brought to the front and there's a modal component blocking this one,
  2013. // we need to bring the modal one to the front instead..
  2014. if (Component* const cm = getCurrentlyModalComponent())
  2015. if (cm->getTopLevelComponent() != getTopLevelComponent())
  2016. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2017. // non-front components can't get focus when another modal comp is
  2018. // active, and therefore can't receive mouse-clicks
  2019. }
  2020. //==============================================================================
  2021. void Component::focusGained (FocusChangeType) {}
  2022. void Component::focusLost (FocusChangeType) {}
  2023. void Component::focusOfChildComponentChanged (FocusChangeType) {}
  2024. void Component::internalFocusGain (const FocusChangeType cause)
  2025. {
  2026. internalFocusGain (cause, WeakReference<Component> (this));
  2027. }
  2028. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  2029. {
  2030. focusGained (cause);
  2031. if (safePointer != nullptr)
  2032. internalChildFocusChange (cause, safePointer);
  2033. }
  2034. void Component::internalFocusLoss (const FocusChangeType cause)
  2035. {
  2036. const WeakReference<Component> safePointer (this);
  2037. focusLost (focusChangedDirectly);
  2038. if (safePointer != nullptr)
  2039. internalChildFocusChange (cause, safePointer);
  2040. }
  2041. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  2042. {
  2043. const bool childIsNowFocused = hasKeyboardFocus (true);
  2044. if (flags.childCompFocusedFlag != childIsNowFocused)
  2045. {
  2046. flags.childCompFocusedFlag = childIsNowFocused;
  2047. focusOfChildComponentChanged (cause);
  2048. if (safePointer == nullptr)
  2049. return;
  2050. }
  2051. if (parentComponent != nullptr)
  2052. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  2053. }
  2054. void Component::setWantsKeyboardFocus (const bool wantsFocus) noexcept
  2055. {
  2056. flags.wantsFocusFlag = wantsFocus;
  2057. }
  2058. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  2059. {
  2060. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  2061. }
  2062. bool Component::getMouseClickGrabsKeyboardFocus() const noexcept
  2063. {
  2064. return ! flags.dontFocusOnMouseClickFlag;
  2065. }
  2066. bool Component::getWantsKeyboardFocus() const noexcept
  2067. {
  2068. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  2069. }
  2070. void Component::setFocusContainer (const bool shouldBeFocusContainer) noexcept
  2071. {
  2072. flags.isFocusContainerFlag = shouldBeFocusContainer;
  2073. }
  2074. bool Component::isFocusContainer() const noexcept
  2075. {
  2076. return flags.isFocusContainerFlag;
  2077. }
  2078. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  2079. int Component::getExplicitFocusOrder() const
  2080. {
  2081. return properties [juce_explicitFocusOrderId];
  2082. }
  2083. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  2084. {
  2085. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  2086. }
  2087. KeyboardFocusTraverser* Component::createFocusTraverser()
  2088. {
  2089. if (flags.isFocusContainerFlag || parentComponent == nullptr)
  2090. return new KeyboardFocusTraverser();
  2091. return parentComponent->createFocusTraverser();
  2092. }
  2093. void Component::takeKeyboardFocus (const FocusChangeType cause)
  2094. {
  2095. // give the focus to this component
  2096. if (currentlyFocusedComponent != this)
  2097. {
  2098. // get the focus onto our desktop window
  2099. if (ComponentPeer* const peer = getPeer())
  2100. {
  2101. const WeakReference<Component> safePointer (this);
  2102. peer->grabFocus();
  2103. if (peer->isFocused() && currentlyFocusedComponent != this)
  2104. {
  2105. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  2106. currentlyFocusedComponent = this;
  2107. Desktop::getInstance().triggerFocusCallback();
  2108. // call this after setting currentlyFocusedComponent so that the one that's
  2109. // losing it has a chance to see where focus is going
  2110. if (componentLosingFocus != nullptr)
  2111. componentLosingFocus->internalFocusLoss (cause);
  2112. if (currentlyFocusedComponent == this)
  2113. internalFocusGain (cause, safePointer);
  2114. }
  2115. }
  2116. }
  2117. }
  2118. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  2119. {
  2120. if (isShowing())
  2121. {
  2122. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == nullptr))
  2123. {
  2124. takeKeyboardFocus (cause);
  2125. }
  2126. else
  2127. {
  2128. if (isParentOf (currentlyFocusedComponent)
  2129. && currentlyFocusedComponent->isShowing())
  2130. {
  2131. // do nothing if the focused component is actually a child of ours..
  2132. }
  2133. else
  2134. {
  2135. // find the default child component..
  2136. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2137. if (traverser != nullptr)
  2138. {
  2139. Component* const defaultComp = traverser->getDefaultComponent (this);
  2140. traverser = nullptr;
  2141. if (defaultComp != nullptr)
  2142. {
  2143. defaultComp->grabFocusInternal (cause, false);
  2144. return;
  2145. }
  2146. }
  2147. if (canTryParent && parentComponent != nullptr)
  2148. {
  2149. // if no children want it and we're allowed to try our parent comp,
  2150. // then pass up to parent, which will try our siblings.
  2151. parentComponent->grabFocusInternal (cause, true);
  2152. }
  2153. }
  2154. }
  2155. }
  2156. }
  2157. void Component::grabKeyboardFocus()
  2158. {
  2159. // if component methods are being called from threads other than the message
  2160. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2161. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2162. grabFocusInternal (focusChangedDirectly, true);
  2163. }
  2164. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  2165. {
  2166. // if component methods are being called from threads other than the message
  2167. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2168. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2169. if (parentComponent != nullptr)
  2170. {
  2171. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2172. if (traverser != nullptr)
  2173. {
  2174. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  2175. : traverser->getPreviousComponent (this);
  2176. traverser = nullptr;
  2177. if (nextComp != nullptr)
  2178. {
  2179. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2180. {
  2181. const WeakReference<Component> nextCompPointer (nextComp);
  2182. internalModalInputAttempt();
  2183. if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2184. return;
  2185. }
  2186. nextComp->grabFocusInternal (focusChangedByTabKey, true);
  2187. return;
  2188. }
  2189. }
  2190. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  2191. }
  2192. }
  2193. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  2194. {
  2195. return (currentlyFocusedComponent == this)
  2196. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  2197. }
  2198. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept
  2199. {
  2200. return currentlyFocusedComponent;
  2201. }
  2202. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  2203. {
  2204. Component* const componentLosingFocus = currentlyFocusedComponent;
  2205. currentlyFocusedComponent = nullptr;
  2206. if (sendFocusLossEvent && componentLosingFocus != nullptr)
  2207. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  2208. Desktop::getInstance().triggerFocusCallback();
  2209. }
  2210. //==============================================================================
  2211. bool Component::isEnabled() const noexcept
  2212. {
  2213. return (! flags.isDisabledFlag)
  2214. && (parentComponent == nullptr || parentComponent->isEnabled());
  2215. }
  2216. void Component::setEnabled (const bool shouldBeEnabled)
  2217. {
  2218. if (flags.isDisabledFlag == shouldBeEnabled)
  2219. {
  2220. flags.isDisabledFlag = ! shouldBeEnabled;
  2221. // if any parent components are disabled, setting our flag won't make a difference,
  2222. // so no need to send a change message
  2223. if (parentComponent == nullptr || parentComponent->isEnabled())
  2224. sendEnablementChangeMessage();
  2225. }
  2226. }
  2227. void Component::enablementChanged() {}
  2228. void Component::sendEnablementChangeMessage()
  2229. {
  2230. const WeakReference<Component> safePointer (this);
  2231. enablementChanged();
  2232. if (safePointer == nullptr)
  2233. return;
  2234. for (int i = getNumChildComponents(); --i >= 0;)
  2235. {
  2236. if (Component* const c = getChildComponent (i))
  2237. {
  2238. c->sendEnablementChangeMessage();
  2239. if (safePointer == nullptr)
  2240. return;
  2241. }
  2242. }
  2243. }
  2244. //==============================================================================
  2245. bool Component::isMouseOver (const bool includeChildren) const
  2246. {
  2247. const Desktop& desktop = Desktop::getInstance();
  2248. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2249. {
  2250. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2251. Component* const c = mi->getComponentUnderMouse();
  2252. if ((c == this || (includeChildren && isParentOf (c)))
  2253. && c->reallyContains (c->getLocalPoint (nullptr, mi->getScreenPosition()), false))
  2254. return true;
  2255. }
  2256. return false;
  2257. }
  2258. bool Component::isMouseButtonDown() const
  2259. {
  2260. const Desktop& desktop = Desktop::getInstance();
  2261. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2262. {
  2263. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2264. if (mi->isDragging() && mi->getComponentUnderMouse() == this)
  2265. return true;
  2266. }
  2267. return false;
  2268. }
  2269. bool Component::isMouseOverOrDragging() const
  2270. {
  2271. const Desktop& desktop = Desktop::getInstance();
  2272. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2273. if (desktop.getMouseSource(i)->getComponentUnderMouse() == this)
  2274. return true;
  2275. return false;
  2276. }
  2277. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept
  2278. {
  2279. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  2280. }
  2281. Point<int> Component::getMouseXYRelative() const
  2282. {
  2283. return getLocalPoint (nullptr, Desktop::getMousePosition());
  2284. }
  2285. //==============================================================================
  2286. void Component::addKeyListener (KeyListener* const newListener)
  2287. {
  2288. if (keyListeners == nullptr)
  2289. keyListeners = new Array <KeyListener*>();
  2290. keyListeners->addIfNotAlreadyThere (newListener);
  2291. }
  2292. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  2293. {
  2294. if (keyListeners != nullptr)
  2295. keyListeners->removeFirstMatchingValue (listenerToRemove);
  2296. }
  2297. bool Component::keyPressed (const KeyPress&) { return false; }
  2298. bool Component::keyStateChanged (const bool /*isKeyDown*/) { return false; }
  2299. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  2300. {
  2301. if (parentComponent != nullptr)
  2302. parentComponent->modifierKeysChanged (modifiers);
  2303. }
  2304. void Component::internalModifierKeysChanged()
  2305. {
  2306. sendFakeMouseMove();
  2307. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  2308. }
  2309. //==============================================================================
  2310. Component::BailOutChecker::BailOutChecker (Component* const component)
  2311. : safePointer (component)
  2312. {
  2313. jassert (component != nullptr);
  2314. }
  2315. bool Component::BailOutChecker::shouldBailOut() const noexcept
  2316. {
  2317. return safePointer == nullptr;
  2318. }