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.

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