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.

3076 lines
99KB

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