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.

2996 lines
89KB

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