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.

3046 lines
91KB

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