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.

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