Audio plugin host https://kx.studio/carla
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.

3070 lines
98KB

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