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.

2942 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* const 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. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager() || ! isShowing());
  1106. if (child != nullptr && child->parentComponent != this)
  1107. {
  1108. if (child->parentComponent != nullptr)
  1109. child->parentComponent->removeChildComponent (child);
  1110. else
  1111. child->removeFromDesktop();
  1112. child->parentComponent = this;
  1113. if (child->isVisible())
  1114. child->repaintParent();
  1115. if (! child->isAlwaysOnTop())
  1116. {
  1117. if (zOrder < 0 || zOrder > childComponentList.size())
  1118. zOrder = childComponentList.size();
  1119. while (zOrder > 0)
  1120. {
  1121. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  1122. break;
  1123. --zOrder;
  1124. }
  1125. }
  1126. childComponentList.insert (zOrder, child);
  1127. child->internalHierarchyChanged();
  1128. internalChildrenChanged();
  1129. }
  1130. }
  1131. void Component::addAndMakeVisible (Component* const child, int zOrder)
  1132. {
  1133. if (child != nullptr)
  1134. {
  1135. child->setVisible (true);
  1136. addChildComponent (child, zOrder);
  1137. }
  1138. }
  1139. void Component::addChildAndSetID (Component* const child, const String& componentID)
  1140. {
  1141. if (child != nullptr)
  1142. {
  1143. child->setComponentID (componentID);
  1144. addAndMakeVisible (child);
  1145. }
  1146. }
  1147. void Component::removeChildComponent (Component* const child)
  1148. {
  1149. removeChildComponent (childComponentList.indexOf (child), true, true);
  1150. }
  1151. Component* Component::removeChildComponent (const int index)
  1152. {
  1153. return removeChildComponent (index, true, true);
  1154. }
  1155. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  1156. {
  1157. // if component methods are being called from threads other than the message
  1158. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1159. CHECK_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN
  1160. Component* const child = childComponentList [index];
  1161. if (child != nullptr)
  1162. {
  1163. sendParentEvents = sendParentEvents && child->isShowing();
  1164. if (sendParentEvents)
  1165. {
  1166. sendFakeMouseMove();
  1167. if (child->isVisible())
  1168. child->repaintParent();
  1169. }
  1170. childComponentList.remove (index);
  1171. child->parentComponent = nullptr;
  1172. if (child->cachedImage != nullptr)
  1173. child->cachedImage->releaseResources();
  1174. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  1175. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  1176. {
  1177. if (sendParentEvents)
  1178. {
  1179. const WeakReference<Component> thisPointer (this);
  1180. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1181. if (thisPointer == nullptr)
  1182. return child;
  1183. grabKeyboardFocus();
  1184. }
  1185. else
  1186. {
  1187. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  1188. }
  1189. }
  1190. if (sendChildEvents)
  1191. child->internalHierarchyChanged();
  1192. if (sendParentEvents)
  1193. internalChildrenChanged();
  1194. }
  1195. return child;
  1196. }
  1197. //==============================================================================
  1198. void Component::removeAllChildren()
  1199. {
  1200. while (childComponentList.size() > 0)
  1201. removeChildComponent (childComponentList.size() - 1);
  1202. }
  1203. void Component::deleteAllChildren()
  1204. {
  1205. while (childComponentList.size() > 0)
  1206. delete (removeChildComponent (childComponentList.size() - 1));
  1207. }
  1208. int Component::getNumChildComponents() const noexcept
  1209. {
  1210. return childComponentList.size();
  1211. }
  1212. Component* Component::getChildComponent (const int index) const noexcept
  1213. {
  1214. return childComponentList [index];
  1215. }
  1216. int Component::getIndexOfChildComponent (const Component* const child) const noexcept
  1217. {
  1218. return childComponentList.indexOf (const_cast <Component*> (child));
  1219. }
  1220. Component* Component::findChildWithID (const String& targetID) const noexcept
  1221. {
  1222. for (int i = childComponentList.size(); --i >= 0;)
  1223. {
  1224. Component* const c = childComponentList.getUnchecked(i);
  1225. if (c->componentID == targetID)
  1226. return c;
  1227. }
  1228. return nullptr;
  1229. }
  1230. Component* Component::getTopLevelComponent() const noexcept
  1231. {
  1232. const Component* comp = this;
  1233. while (comp->parentComponent != nullptr)
  1234. comp = comp->parentComponent;
  1235. return const_cast <Component*> (comp);
  1236. }
  1237. bool Component::isParentOf (const Component* possibleChild) const noexcept
  1238. {
  1239. while (possibleChild != nullptr)
  1240. {
  1241. possibleChild = possibleChild->parentComponent;
  1242. if (possibleChild == this)
  1243. return true;
  1244. }
  1245. return false;
  1246. }
  1247. //==============================================================================
  1248. void Component::parentHierarchyChanged() {}
  1249. void Component::childrenChanged() {}
  1250. void Component::internalChildrenChanged()
  1251. {
  1252. if (componentListeners.isEmpty())
  1253. {
  1254. childrenChanged();
  1255. }
  1256. else
  1257. {
  1258. BailOutChecker checker (this);
  1259. childrenChanged();
  1260. if (! checker.shouldBailOut())
  1261. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  1262. }
  1263. }
  1264. void Component::internalHierarchyChanged()
  1265. {
  1266. BailOutChecker checker (this);
  1267. parentHierarchyChanged();
  1268. if (checker.shouldBailOut())
  1269. return;
  1270. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  1271. if (checker.shouldBailOut())
  1272. return;
  1273. for (int i = childComponentList.size(); --i >= 0;)
  1274. {
  1275. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  1276. if (checker.shouldBailOut())
  1277. {
  1278. // you really shouldn't delete the parent component during a callback telling you
  1279. // that it's changed..
  1280. jassertfalse;
  1281. return;
  1282. }
  1283. i = jmin (i, childComponentList.size());
  1284. }
  1285. }
  1286. //==============================================================================
  1287. #if JUCE_MODAL_LOOPS_PERMITTED
  1288. int Component::runModalLoop()
  1289. {
  1290. if (! MessageManager::getInstance()->isThisTheMessageThread())
  1291. {
  1292. // use a callback so this can be called from non-gui threads
  1293. return (int) (pointer_sized_int) MessageManager::getInstance()
  1294. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  1295. }
  1296. if (! isCurrentlyModal())
  1297. enterModalState (true);
  1298. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  1299. }
  1300. #endif
  1301. //==============================================================================
  1302. void Component::enterModalState (const bool shouldTakeKeyboardFocus,
  1303. ModalComponentManager::Callback* callback,
  1304. const bool deleteWhenDismissed)
  1305. {
  1306. // if component methods are being called from threads other than the message
  1307. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1308. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1309. // Check for an attempt to make a component modal when it already is!
  1310. // This can cause nasty problems..
  1311. jassert (! flags.currentlyModalFlag);
  1312. if (! isCurrentlyModal())
  1313. {
  1314. ModalComponentManager* const mcm = ModalComponentManager::getInstance();
  1315. mcm->startModal (this, deleteWhenDismissed);
  1316. mcm->attachCallback (this, callback);
  1317. flags.currentlyModalFlag = true;
  1318. setVisible (true);
  1319. if (shouldTakeKeyboardFocus)
  1320. grabKeyboardFocus();
  1321. }
  1322. }
  1323. void Component::exitModalState (const int returnValue)
  1324. {
  1325. if (flags.currentlyModalFlag)
  1326. {
  1327. if (MessageManager::getInstance()->isThisTheMessageThread())
  1328. {
  1329. ModalComponentManager::getInstance()->endModal (this, returnValue);
  1330. flags.currentlyModalFlag = false;
  1331. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1332. }
  1333. else
  1334. {
  1335. class ExitModalStateMessage : public CallbackMessage
  1336. {
  1337. public:
  1338. ExitModalStateMessage (Component* const target_, const int result_)
  1339. : target (target_), result (result_) {}
  1340. void messageCallback()
  1341. {
  1342. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1343. target->exitModalState (result);
  1344. }
  1345. private:
  1346. WeakReference<Component> target;
  1347. int result;
  1348. };
  1349. (new ExitModalStateMessage (this, returnValue))->post();
  1350. }
  1351. }
  1352. }
  1353. bool Component::isCurrentlyModal() const noexcept
  1354. {
  1355. return flags.currentlyModalFlag
  1356. && getCurrentlyModalComponent() == this;
  1357. }
  1358. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  1359. {
  1360. Component* const mc = getCurrentlyModalComponent();
  1361. return ! (mc == nullptr || mc == this || mc->isParentOf (this)
  1362. || mc->canModalEventBeSentToComponent (this));
  1363. }
  1364. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept
  1365. {
  1366. return ModalComponentManager::getInstance()->getNumModalComponents();
  1367. }
  1368. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept
  1369. {
  1370. return ModalComponentManager::getInstance()->getModalComponent (index);
  1371. }
  1372. //==============================================================================
  1373. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) noexcept
  1374. {
  1375. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  1376. }
  1377. bool Component::isBroughtToFrontOnMouseClick() const noexcept
  1378. {
  1379. return flags.bringToFrontOnClickFlag;
  1380. }
  1381. //==============================================================================
  1382. void Component::setMouseCursor (const MouseCursor& newCursor)
  1383. {
  1384. if (cursor != newCursor)
  1385. {
  1386. cursor = newCursor;
  1387. if (flags.visibleFlag)
  1388. updateMouseCursor();
  1389. }
  1390. }
  1391. MouseCursor Component::getMouseCursor()
  1392. {
  1393. return cursor;
  1394. }
  1395. void Component::updateMouseCursor() const
  1396. {
  1397. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  1398. }
  1399. //==============================================================================
  1400. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) noexcept
  1401. {
  1402. flags.repaintOnMouseActivityFlag = shouldRepaint;
  1403. }
  1404. //==============================================================================
  1405. void Component::setAlpha (const float newAlpha)
  1406. {
  1407. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  1408. if (componentTransparency != newIntAlpha)
  1409. {
  1410. componentTransparency = newIntAlpha;
  1411. if (flags.hasHeavyweightPeerFlag)
  1412. {
  1413. ComponentPeer* const peer = getPeer();
  1414. if (peer != nullptr)
  1415. peer->setAlpha (newAlpha);
  1416. }
  1417. else
  1418. {
  1419. repaint();
  1420. }
  1421. }
  1422. }
  1423. float Component::getAlpha() const
  1424. {
  1425. return (255 - componentTransparency) / 255.0f;
  1426. }
  1427. //==============================================================================
  1428. void Component::repaint()
  1429. {
  1430. internalRepaintUnchecked (getLocalBounds(), true);
  1431. }
  1432. void Component::repaint (const int x, const int y, const int w, const int h)
  1433. {
  1434. internalRepaint (Rectangle<int> (x, y, w, h));
  1435. }
  1436. void Component::repaint (const Rectangle<int>& area)
  1437. {
  1438. internalRepaint (area);
  1439. }
  1440. void Component::repaintParent()
  1441. {
  1442. if (parentComponent != nullptr)
  1443. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, getLocalBounds()));
  1444. }
  1445. void Component::internalRepaint (const Rectangle<int>& area)
  1446. {
  1447. const Rectangle<int> r (area.getIntersection (getLocalBounds()));
  1448. if (! r.isEmpty())
  1449. internalRepaintUnchecked (r, false);
  1450. }
  1451. void Component::internalRepaintUnchecked (const Rectangle<int>& area, const bool isEntireComponent)
  1452. {
  1453. if (flags.visibleFlag)
  1454. {
  1455. if (cachedImage != nullptr)
  1456. {
  1457. if (isEntireComponent)
  1458. cachedImage->invalidateAll();
  1459. else
  1460. cachedImage->invalidate (area);
  1461. }
  1462. if (flags.hasHeavyweightPeerFlag)
  1463. {
  1464. // if component methods are being called from threads other than the message
  1465. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1466. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1467. ComponentPeer* const peer = getPeer();
  1468. if (peer != nullptr)
  1469. peer->repaint (area);
  1470. }
  1471. else
  1472. {
  1473. if (parentComponent != nullptr)
  1474. parentComponent->internalRepaint (ComponentHelpers::convertToParentSpace (*this, area));
  1475. }
  1476. }
  1477. }
  1478. //==============================================================================
  1479. void Component::paint (Graphics&)
  1480. {
  1481. // all painting is done in the subclasses
  1482. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  1483. }
  1484. void Component::paintOverChildren (Graphics&)
  1485. {
  1486. // all painting is done in the subclasses
  1487. }
  1488. //==============================================================================
  1489. void Component::paintWithinParentContext (Graphics& g)
  1490. {
  1491. g.setOrigin (getX(), getY());
  1492. if (cachedImage != nullptr)
  1493. cachedImage->paint (g);
  1494. else
  1495. paintEntireComponent (g, false);
  1496. }
  1497. void Component::paintComponentAndChildren (Graphics& g)
  1498. {
  1499. const Rectangle<int> clipBounds (g.getClipBounds());
  1500. if (flags.dontClipGraphicsFlag)
  1501. {
  1502. paint (g);
  1503. }
  1504. else
  1505. {
  1506. g.saveState();
  1507. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  1508. if (! g.isClipEmpty())
  1509. paint (g);
  1510. g.restoreState();
  1511. }
  1512. for (int i = 0; i < childComponentList.size(); ++i)
  1513. {
  1514. Component& child = *childComponentList.getUnchecked (i);
  1515. if (child.isVisible())
  1516. {
  1517. if (child.affineTransform != nullptr)
  1518. {
  1519. g.saveState();
  1520. g.addTransform (*child.affineTransform);
  1521. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  1522. child.paintWithinParentContext (g);
  1523. g.restoreState();
  1524. }
  1525. else if (clipBounds.intersects (child.getBounds()))
  1526. {
  1527. g.saveState();
  1528. if (child.flags.dontClipGraphicsFlag)
  1529. {
  1530. child.paintWithinParentContext (g);
  1531. }
  1532. else if (g.reduceClipRegion (child.getBounds()))
  1533. {
  1534. bool nothingClipped = true;
  1535. for (int j = i + 1; j < childComponentList.size(); ++j)
  1536. {
  1537. const Component& sibling = *childComponentList.getUnchecked (j);
  1538. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == nullptr)
  1539. {
  1540. nothingClipped = false;
  1541. g.excludeClipRegion (sibling.getBounds());
  1542. }
  1543. }
  1544. if (nothingClipped || ! g.isClipEmpty())
  1545. child.paintWithinParentContext (g);
  1546. }
  1547. g.restoreState();
  1548. }
  1549. }
  1550. }
  1551. g.saveState();
  1552. paintOverChildren (g);
  1553. g.restoreState();
  1554. }
  1555. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  1556. {
  1557. #if JUCE_DEBUG
  1558. flags.isInsidePaintCall = true;
  1559. #endif
  1560. if (effect != nullptr)
  1561. {
  1562. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1563. getWidth(), getHeight(), ! flags.opaqueFlag);
  1564. {
  1565. Graphics g2 (effectImage);
  1566. paintComponentAndChildren (g2);
  1567. }
  1568. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  1569. }
  1570. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  1571. {
  1572. if (componentTransparency < 255)
  1573. {
  1574. g.beginTransparencyLayer (getAlpha());
  1575. paintComponentAndChildren (g);
  1576. g.endTransparencyLayer();
  1577. }
  1578. }
  1579. else
  1580. {
  1581. paintComponentAndChildren (g);
  1582. }
  1583. #if JUCE_DEBUG
  1584. flags.isInsidePaintCall = false;
  1585. #endif
  1586. }
  1587. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) noexcept
  1588. {
  1589. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  1590. }
  1591. //==============================================================================
  1592. Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  1593. const bool clipImageToComponentBounds)
  1594. {
  1595. Rectangle<int> r (areaToGrab);
  1596. if (clipImageToComponentBounds)
  1597. r = r.getIntersection (getLocalBounds());
  1598. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  1599. jmax (1, r.getWidth()),
  1600. jmax (1, r.getHeight()),
  1601. true);
  1602. Graphics imageContext (componentImage);
  1603. imageContext.setOrigin (-r.getX(), -r.getY());
  1604. paintEntireComponent (imageContext, true);
  1605. return componentImage;
  1606. }
  1607. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  1608. {
  1609. if (effect != newEffect)
  1610. {
  1611. effect = newEffect;
  1612. repaint();
  1613. }
  1614. }
  1615. //==============================================================================
  1616. LookAndFeel& Component::getLookAndFeel() const noexcept
  1617. {
  1618. const Component* c = this;
  1619. do
  1620. {
  1621. if (c->lookAndFeel != nullptr)
  1622. return *(c->lookAndFeel);
  1623. c = c->parentComponent;
  1624. }
  1625. while (c != nullptr);
  1626. return LookAndFeel::getDefaultLookAndFeel();
  1627. }
  1628. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  1629. {
  1630. if (lookAndFeel != newLookAndFeel)
  1631. {
  1632. lookAndFeel = newLookAndFeel;
  1633. sendLookAndFeelChange();
  1634. }
  1635. }
  1636. void Component::lookAndFeelChanged() {}
  1637. void Component::colourChanged() {}
  1638. void Component::sendLookAndFeelChange()
  1639. {
  1640. const WeakReference<Component> safePointer (this);
  1641. repaint();
  1642. lookAndFeelChanged();
  1643. if (safePointer != nullptr)
  1644. {
  1645. colourChanged();
  1646. if (safePointer != nullptr)
  1647. {
  1648. for (int i = childComponentList.size(); --i >= 0;)
  1649. {
  1650. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  1651. if (safePointer == nullptr)
  1652. return;
  1653. i = jmin (i, childComponentList.size());
  1654. }
  1655. }
  1656. }
  1657. }
  1658. Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  1659. {
  1660. const var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  1661. if (v != nullptr)
  1662. return Colour ((uint32) static_cast <int> (*v));
  1663. if (inheritFromParent && parentComponent != nullptr
  1664. && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourId)))
  1665. return parentComponent->findColour (colourId, true);
  1666. return getLookAndFeel().findColour (colourId);
  1667. }
  1668. bool Component::isColourSpecified (const int colourId) const
  1669. {
  1670. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  1671. }
  1672. void Component::removeColour (const int colourId)
  1673. {
  1674. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  1675. colourChanged();
  1676. }
  1677. void Component::setColour (const int colourId, const Colour& colour)
  1678. {
  1679. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  1680. colourChanged();
  1681. }
  1682. void Component::copyAllExplicitColoursTo (Component& target) const
  1683. {
  1684. bool changed = false;
  1685. for (int i = properties.size(); --i >= 0;)
  1686. {
  1687. const Identifier name (properties.getName(i));
  1688. if (name.toString().startsWith ("jcclr_"))
  1689. if (target.properties.set (name, properties [name]))
  1690. changed = true;
  1691. }
  1692. if (changed)
  1693. target.colourChanged();
  1694. }
  1695. //==============================================================================
  1696. MarkerList* Component::getMarkers (bool /*xAxis*/)
  1697. {
  1698. return nullptr;
  1699. }
  1700. //==============================================================================
  1701. Component::Positioner::Positioner (Component& component_) noexcept
  1702. : component (component_)
  1703. {
  1704. }
  1705. Component::Positioner* Component::getPositioner() const noexcept
  1706. {
  1707. return positioner;
  1708. }
  1709. void Component::setPositioner (Positioner* newPositioner)
  1710. {
  1711. // You can only assign a positioner to the component that it was created for!
  1712. jassert (newPositioner == nullptr || this == &(newPositioner->getComponent()));
  1713. positioner = newPositioner;
  1714. }
  1715. //==============================================================================
  1716. Rectangle<int> Component::getLocalBounds() const noexcept
  1717. {
  1718. return bounds.withZeroOrigin();
  1719. }
  1720. Rectangle<int> Component::getBoundsInParent() const noexcept
  1721. {
  1722. return affineTransform == nullptr ? bounds
  1723. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  1724. }
  1725. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  1726. {
  1727. result.clear();
  1728. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  1729. if (! unclipped.isEmpty())
  1730. {
  1731. result.add (unclipped);
  1732. if (includeSiblings)
  1733. {
  1734. const Component* const c = getTopLevelComponent();
  1735. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  1736. c->getLocalBounds(), this);
  1737. }
  1738. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, nullptr);
  1739. result.consolidate();
  1740. }
  1741. }
  1742. //==============================================================================
  1743. void Component::mouseEnter (const MouseEvent&) {}
  1744. void Component::mouseExit (const MouseEvent&) {}
  1745. void Component::mouseDown (const MouseEvent&) {}
  1746. void Component::mouseUp (const MouseEvent&) {}
  1747. void Component::mouseDrag (const MouseEvent&) {}
  1748. void Component::mouseMove (const MouseEvent&) {}
  1749. void Component::mouseDoubleClick (const MouseEvent&) {}
  1750. void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  1751. {
  1752. // the base class just passes this event up to its parent..
  1753. if (parentComponent != nullptr)
  1754. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent), wheel);
  1755. }
  1756. //==============================================================================
  1757. void Component::resized() {}
  1758. void Component::moved() {}
  1759. void Component::childBoundsChanged (Component*) {}
  1760. void Component::parentSizeChanged() {}
  1761. void Component::addComponentListener (ComponentListener* const newListener)
  1762. {
  1763. // if component methods are being called from threads other than the message
  1764. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1765. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1766. componentListeners.add (newListener);
  1767. }
  1768. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  1769. {
  1770. componentListeners.remove (listenerToRemove);
  1771. }
  1772. //==============================================================================
  1773. void Component::inputAttemptWhenModal()
  1774. {
  1775. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1776. getLookAndFeel().playAlertSound();
  1777. }
  1778. bool Component::canModalEventBeSentToComponent (const Component*)
  1779. {
  1780. return false;
  1781. }
  1782. void Component::internalModalInputAttempt()
  1783. {
  1784. Component* const current = getCurrentlyModalComponent();
  1785. if (current != nullptr)
  1786. current->inputAttemptWhenModal();
  1787. }
  1788. //==============================================================================
  1789. void Component::postCommandMessage (const int commandId)
  1790. {
  1791. class CustomCommandMessage : public CallbackMessage
  1792. {
  1793. public:
  1794. CustomCommandMessage (Component* const target_, const int commandId_)
  1795. : target (target_), commandId (commandId_) {}
  1796. void messageCallback()
  1797. {
  1798. if (target.get() != nullptr) // (get() required for VS2003 bug)
  1799. target->handleCommandMessage (commandId);
  1800. }
  1801. private:
  1802. WeakReference<Component> target;
  1803. int commandId;
  1804. };
  1805. (new CustomCommandMessage (this, commandId))->post();
  1806. }
  1807. void Component::handleCommandMessage (int)
  1808. {
  1809. // used by subclasses
  1810. }
  1811. //==============================================================================
  1812. void Component::addMouseListener (MouseListener* const newListener,
  1813. const bool wantsEventsForAllNestedChildComponents)
  1814. {
  1815. // if component methods are being called from threads other than the message
  1816. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1817. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1818. // If you register a component as a mouselistener for itself, it'll receive all the events
  1819. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  1820. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  1821. if (mouseListeners == nullptr)
  1822. mouseListeners = new MouseListenerList();
  1823. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  1824. }
  1825. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  1826. {
  1827. // if component methods are being called from threads other than the message
  1828. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  1829. CHECK_MESSAGE_MANAGER_IS_LOCKED
  1830. if (mouseListeners != nullptr)
  1831. mouseListeners->removeListener (listenerToRemove);
  1832. }
  1833. //==============================================================================
  1834. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1835. {
  1836. if (isCurrentlyBlockedByAnotherModalComponent())
  1837. {
  1838. // if something else is modal, always just show a normal mouse cursor
  1839. source.showMouseCursor (MouseCursor::NormalCursor);
  1840. return;
  1841. }
  1842. if (flags.repaintOnMouseActivityFlag)
  1843. repaint();
  1844. BailOutChecker checker (this);
  1845. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1846. this, this, time, relativePos, time, 0, false);
  1847. mouseEnter (me);
  1848. if (checker.shouldBailOut())
  1849. return;
  1850. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseEnter, me);
  1851. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  1852. }
  1853. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1854. {
  1855. if (isCurrentlyBlockedByAnotherModalComponent() && source.getComponentUnderMouse() != this)
  1856. return;
  1857. if (flags.repaintOnMouseActivityFlag)
  1858. repaint();
  1859. BailOutChecker checker (this);
  1860. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1861. this, this, time, relativePos, time, 0, false);
  1862. mouseExit (me);
  1863. if (checker.shouldBailOut())
  1864. return;
  1865. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseExit, me);
  1866. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  1867. }
  1868. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1869. {
  1870. Desktop& desktop = Desktop::getInstance();
  1871. BailOutChecker checker (this);
  1872. if (isCurrentlyBlockedByAnotherModalComponent())
  1873. {
  1874. internalModalInputAttempt();
  1875. if (checker.shouldBailOut())
  1876. return;
  1877. // If processing the input attempt has exited the modal loop, we'll allow the event
  1878. // to be delivered..
  1879. if (isCurrentlyBlockedByAnotherModalComponent())
  1880. {
  1881. // allow blocked mouse-events to go to global listeners..
  1882. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1883. this, this, time, relativePos, time,
  1884. source.getNumberOfMultipleClicks(), false);
  1885. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1886. return;
  1887. }
  1888. }
  1889. for (Component* c = this; c != nullptr; c = c->parentComponent)
  1890. {
  1891. if (c->isBroughtToFrontOnMouseClick())
  1892. {
  1893. c->toFront (true);
  1894. if (checker.shouldBailOut())
  1895. return;
  1896. }
  1897. }
  1898. if (! flags.dontFocusOnMouseClickFlag)
  1899. {
  1900. grabFocusInternal (focusChangedByMouseClick, true);
  1901. if (checker.shouldBailOut())
  1902. return;
  1903. }
  1904. if (flags.repaintOnMouseActivityFlag)
  1905. repaint();
  1906. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1907. this, this, time, relativePos, time,
  1908. source.getNumberOfMultipleClicks(), false);
  1909. mouseDown (me);
  1910. if (checker.shouldBailOut())
  1911. return;
  1912. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseDown, me);
  1913. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  1914. }
  1915. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  1916. {
  1917. if (! isCurrentlyBlockedByAnotherModalComponent())
  1918. {
  1919. BailOutChecker checker (this);
  1920. if (flags.repaintOnMouseActivityFlag)
  1921. repaint();
  1922. const MouseEvent me (source, relativePos,
  1923. oldModifiers, this, this, time,
  1924. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1925. source.getLastMouseDownTime(),
  1926. source.getNumberOfMultipleClicks(),
  1927. source.hasMouseMovedSignificantlySincePressed());
  1928. mouseUp (me);
  1929. if (checker.shouldBailOut())
  1930. return;
  1931. Desktop& desktop = Desktop::getInstance();
  1932. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseUp, me);
  1933. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  1934. if (checker.shouldBailOut())
  1935. return;
  1936. // check for double-click
  1937. if (me.getNumberOfClicks() >= 2)
  1938. {
  1939. mouseDoubleClick (me);
  1940. if (checker.shouldBailOut())
  1941. return;
  1942. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  1943. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  1944. }
  1945. }
  1946. }
  1947. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1948. {
  1949. if (! isCurrentlyBlockedByAnotherModalComponent())
  1950. {
  1951. BailOutChecker checker (this);
  1952. const MouseEvent me (source, relativePos,
  1953. source.getCurrentModifiers(), this, this, time,
  1954. getLocalPoint (nullptr, source.getLastMouseDownPosition()),
  1955. source.getLastMouseDownTime(),
  1956. source.getNumberOfMultipleClicks(),
  1957. source.hasMouseMovedSignificantlySincePressed());
  1958. mouseDrag (me);
  1959. if (checker.shouldBailOut())
  1960. return;
  1961. Desktop::getInstance().getMouseListeners().callChecked (checker, &MouseListener::mouseDrag, me);
  1962. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  1963. }
  1964. }
  1965. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  1966. {
  1967. Desktop& desktop = Desktop::getInstance();
  1968. if (isCurrentlyBlockedByAnotherModalComponent())
  1969. {
  1970. // allow blocked mouse-events to go to global listeners..
  1971. desktop.sendMouseMove();
  1972. }
  1973. else
  1974. {
  1975. BailOutChecker checker (this);
  1976. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1977. this, this, time, relativePos, time, 0, false);
  1978. mouseMove (me);
  1979. if (checker.shouldBailOut())
  1980. return;
  1981. desktop.getMouseListeners().callChecked (checker, &MouseListener::mouseMove, me);
  1982. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  1983. }
  1984. }
  1985. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  1986. const Time& time, const MouseWheelDetails& wheel)
  1987. {
  1988. Desktop& desktop = Desktop::getInstance();
  1989. BailOutChecker checker (this);
  1990. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  1991. this, this, time, relativePos, time, 0, false);
  1992. if (isCurrentlyBlockedByAnotherModalComponent())
  1993. {
  1994. // allow blocked mouse-events to go to global listeners..
  1995. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  1996. }
  1997. else
  1998. {
  1999. mouseWheelMove (me, wheel);
  2000. if (checker.shouldBailOut())
  2001. return;
  2002. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheel);
  2003. if (! checker.shouldBailOut())
  2004. MouseListenerList::sendWheelEvent (*this, checker, me, wheel);
  2005. }
  2006. }
  2007. void Component::sendFakeMouseMove() const
  2008. {
  2009. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  2010. if (! mainMouse.isDragging())
  2011. mainMouse.triggerFakeMove();
  2012. }
  2013. void JUCE_CALLTYPE Component::beginDragAutoRepeat (const int interval)
  2014. {
  2015. Desktop::getInstance().beginDragAutoRepeat (interval);
  2016. }
  2017. //==============================================================================
  2018. void Component::broughtToFront()
  2019. {
  2020. }
  2021. void Component::internalBroughtToFront()
  2022. {
  2023. if (flags.hasHeavyweightPeerFlag)
  2024. Desktop::getInstance().componentBroughtToFront (this);
  2025. BailOutChecker checker (this);
  2026. broughtToFront();
  2027. if (checker.shouldBailOut())
  2028. return;
  2029. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  2030. if (checker.shouldBailOut())
  2031. return;
  2032. // When brought to the front and there's a modal component blocking this one,
  2033. // we need to bring the modal one to the front instead..
  2034. Component* const cm = getCurrentlyModalComponent();
  2035. if (cm != nullptr && cm->getTopLevelComponent() != getTopLevelComponent())
  2036. ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows,
  2037. // non-front components can't get focus when another modal comp is
  2038. // active, and therefore can't receive mouse-clicks
  2039. }
  2040. //==============================================================================
  2041. void Component::focusGained (FocusChangeType) {}
  2042. void Component::focusLost (FocusChangeType) {}
  2043. void Component::focusOfChildComponentChanged (FocusChangeType) {}
  2044. void Component::internalFocusGain (const FocusChangeType cause)
  2045. {
  2046. internalFocusGain (cause, WeakReference<Component> (this));
  2047. }
  2048. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  2049. {
  2050. focusGained (cause);
  2051. if (safePointer != nullptr)
  2052. internalChildFocusChange (cause, safePointer);
  2053. }
  2054. void Component::internalFocusLoss (const FocusChangeType cause)
  2055. {
  2056. const WeakReference<Component> safePointer (this);
  2057. focusLost (focusChangedDirectly);
  2058. if (safePointer != nullptr)
  2059. internalChildFocusChange (cause, safePointer);
  2060. }
  2061. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  2062. {
  2063. const bool childIsNowFocused = hasKeyboardFocus (true);
  2064. if (flags.childCompFocusedFlag != childIsNowFocused)
  2065. {
  2066. flags.childCompFocusedFlag = childIsNowFocused;
  2067. focusOfChildComponentChanged (cause);
  2068. if (safePointer == nullptr)
  2069. return;
  2070. }
  2071. if (parentComponent != nullptr)
  2072. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  2073. }
  2074. void Component::setWantsKeyboardFocus (const bool wantsFocus) noexcept
  2075. {
  2076. flags.wantsFocusFlag = wantsFocus;
  2077. }
  2078. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  2079. {
  2080. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  2081. }
  2082. bool Component::getMouseClickGrabsKeyboardFocus() const noexcept
  2083. {
  2084. return ! flags.dontFocusOnMouseClickFlag;
  2085. }
  2086. bool Component::getWantsKeyboardFocus() const noexcept
  2087. {
  2088. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  2089. }
  2090. void Component::setFocusContainer (const bool shouldBeFocusContainer) noexcept
  2091. {
  2092. flags.isFocusContainerFlag = shouldBeFocusContainer;
  2093. }
  2094. bool Component::isFocusContainer() const noexcept
  2095. {
  2096. return flags.isFocusContainerFlag;
  2097. }
  2098. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  2099. int Component::getExplicitFocusOrder() const
  2100. {
  2101. return properties [juce_explicitFocusOrderId];
  2102. }
  2103. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  2104. {
  2105. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  2106. }
  2107. KeyboardFocusTraverser* Component::createFocusTraverser()
  2108. {
  2109. if (flags.isFocusContainerFlag || parentComponent == nullptr)
  2110. return new KeyboardFocusTraverser();
  2111. return parentComponent->createFocusTraverser();
  2112. }
  2113. void Component::takeKeyboardFocus (const FocusChangeType cause)
  2114. {
  2115. // give the focus to this component
  2116. if (currentlyFocusedComponent != this)
  2117. {
  2118. // get the focus onto our desktop window
  2119. ComponentPeer* const peer = getPeer();
  2120. if (peer != nullptr)
  2121. {
  2122. const WeakReference<Component> safePointer (this);
  2123. peer->grabFocus();
  2124. if (peer->isFocused() && currentlyFocusedComponent != this)
  2125. {
  2126. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  2127. currentlyFocusedComponent = this;
  2128. Desktop::getInstance().triggerFocusCallback();
  2129. // call this after setting currentlyFocusedComponent so that the one that's
  2130. // losing it has a chance to see where focus is going
  2131. if (componentLosingFocus != nullptr)
  2132. componentLosingFocus->internalFocusLoss (cause);
  2133. if (currentlyFocusedComponent == this)
  2134. internalFocusGain (cause, safePointer);
  2135. }
  2136. }
  2137. }
  2138. }
  2139. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  2140. {
  2141. if (isShowing())
  2142. {
  2143. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == nullptr))
  2144. {
  2145. takeKeyboardFocus (cause);
  2146. }
  2147. else
  2148. {
  2149. if (isParentOf (currentlyFocusedComponent)
  2150. && currentlyFocusedComponent->isShowing())
  2151. {
  2152. // do nothing if the focused component is actually a child of ours..
  2153. }
  2154. else
  2155. {
  2156. // find the default child component..
  2157. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2158. if (traverser != nullptr)
  2159. {
  2160. Component* const defaultComp = traverser->getDefaultComponent (this);
  2161. traverser = nullptr;
  2162. if (defaultComp != nullptr)
  2163. {
  2164. defaultComp->grabFocusInternal (cause, false);
  2165. return;
  2166. }
  2167. }
  2168. if (canTryParent && parentComponent != nullptr)
  2169. {
  2170. // if no children want it and we're allowed to try our parent comp,
  2171. // then pass up to parent, which will try our siblings.
  2172. parentComponent->grabFocusInternal (cause, true);
  2173. }
  2174. }
  2175. }
  2176. }
  2177. }
  2178. void Component::grabKeyboardFocus()
  2179. {
  2180. // if component methods are being called from threads other than the message
  2181. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  2182. CHECK_MESSAGE_MANAGER_IS_LOCKED
  2183. grabFocusInternal (focusChangedDirectly, true);
  2184. }
  2185. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  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. if (parentComponent != nullptr)
  2191. {
  2192. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  2193. if (traverser != nullptr)
  2194. {
  2195. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  2196. : traverser->getPreviousComponent (this);
  2197. traverser = nullptr;
  2198. if (nextComp != nullptr)
  2199. {
  2200. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2201. {
  2202. const WeakReference<Component> nextCompPointer (nextComp);
  2203. internalModalInputAttempt();
  2204. if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  2205. return;
  2206. }
  2207. nextComp->grabFocusInternal (focusChangedByTabKey, true);
  2208. return;
  2209. }
  2210. }
  2211. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  2212. }
  2213. }
  2214. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  2215. {
  2216. return (currentlyFocusedComponent == this)
  2217. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  2218. }
  2219. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept
  2220. {
  2221. return currentlyFocusedComponent;
  2222. }
  2223. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  2224. {
  2225. Component* const componentLosingFocus = currentlyFocusedComponent;
  2226. currentlyFocusedComponent = nullptr;
  2227. if (sendFocusLossEvent && componentLosingFocus != nullptr)
  2228. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  2229. Desktop::getInstance().triggerFocusCallback();
  2230. }
  2231. //==============================================================================
  2232. bool Component::isEnabled() const noexcept
  2233. {
  2234. return (! flags.isDisabledFlag)
  2235. && (parentComponent == nullptr || parentComponent->isEnabled());
  2236. }
  2237. void Component::setEnabled (const bool shouldBeEnabled)
  2238. {
  2239. if (flags.isDisabledFlag == shouldBeEnabled)
  2240. {
  2241. flags.isDisabledFlag = ! shouldBeEnabled;
  2242. // if any parent components are disabled, setting our flag won't make a difference,
  2243. // so no need to send a change message
  2244. if (parentComponent == nullptr || parentComponent->isEnabled())
  2245. sendEnablementChangeMessage();
  2246. }
  2247. }
  2248. void Component::enablementChanged() {}
  2249. void Component::sendEnablementChangeMessage()
  2250. {
  2251. const WeakReference<Component> safePointer (this);
  2252. enablementChanged();
  2253. if (safePointer == nullptr)
  2254. return;
  2255. for (int i = getNumChildComponents(); --i >= 0;)
  2256. {
  2257. Component* const c = getChildComponent (i);
  2258. if (c != nullptr)
  2259. {
  2260. c->sendEnablementChangeMessage();
  2261. if (safePointer == nullptr)
  2262. return;
  2263. }
  2264. }
  2265. }
  2266. //==============================================================================
  2267. bool Component::isMouseOver (const bool includeChildren) const
  2268. {
  2269. const Desktop& desktop = Desktop::getInstance();
  2270. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2271. {
  2272. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2273. Component* const c = mi->getComponentUnderMouse();
  2274. if ((c == this || (includeChildren && isParentOf (c)))
  2275. && c->reallyContains (c->getLocalPoint (nullptr, mi->getScreenPosition()), false))
  2276. return true;
  2277. }
  2278. return false;
  2279. }
  2280. bool Component::isMouseButtonDown() const
  2281. {
  2282. const Desktop& desktop = Desktop::getInstance();
  2283. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2284. {
  2285. const MouseInputSource* const mi = desktop.getMouseSource(i);
  2286. if (mi->isDragging() && mi->getComponentUnderMouse() == this)
  2287. return true;
  2288. }
  2289. return false;
  2290. }
  2291. bool Component::isMouseOverOrDragging() const
  2292. {
  2293. const Desktop& desktop = Desktop::getInstance();
  2294. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  2295. if (desktop.getMouseSource(i)->getComponentUnderMouse() == this)
  2296. return true;
  2297. return false;
  2298. }
  2299. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept
  2300. {
  2301. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  2302. }
  2303. Point<int> Component::getMouseXYRelative() const
  2304. {
  2305. return getLocalPoint (nullptr, Desktop::getMousePosition());
  2306. }
  2307. //==============================================================================
  2308. void Component::addKeyListener (KeyListener* const newListener)
  2309. {
  2310. if (keyListeners == nullptr)
  2311. keyListeners = new Array <KeyListener*>();
  2312. keyListeners->addIfNotAlreadyThere (newListener);
  2313. }
  2314. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  2315. {
  2316. if (keyListeners != nullptr)
  2317. keyListeners->removeValue (listenerToRemove);
  2318. }
  2319. bool Component::keyPressed (const KeyPress&) { return false; }
  2320. bool Component::keyStateChanged (const bool /*isKeyDown*/) { return false; }
  2321. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  2322. {
  2323. if (parentComponent != nullptr)
  2324. parentComponent->modifierKeysChanged (modifiers);
  2325. }
  2326. void Component::internalModifierKeysChanged()
  2327. {
  2328. sendFakeMouseMove();
  2329. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  2330. }
  2331. //==============================================================================
  2332. Component::BailOutChecker::BailOutChecker (Component* const component)
  2333. : safePointer (component)
  2334. {
  2335. jassert (component != nullptr);
  2336. }
  2337. bool Component::BailOutChecker::shouldBailOut() const noexcept
  2338. {
  2339. return safePointer == nullptr;
  2340. }