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.

2943 lines
91KB

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