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.

2888 lines
90KB

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