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.

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