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.

2938 lines
92KB

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