The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3053 lines
98KB

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