/* ============================================================================== This file is part of the JUCE framework. Copyright (c) Raw Material Software Limited JUCE is an open source framework subject to commercial or open source licensing. By downloading, installing, or using the JUCE framework, or combining the JUCE framework with any other source code, object code, content or any other copyrightable work, you agree to the terms of the JUCE End User Licence Agreement, and all incorporated terms including the JUCE Privacy Policy and the JUCE Website Terms of Service, as applicable, which will bind you. If you do not agree to the terms of these agreements, we will not license the JUCE framework to you, and you must discontinue the installation or download process and cease use of the JUCE framework. JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/ JUCE Privacy Policy: https://juce.com/juce-privacy-policy JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/ Or: You may also use this code under the terms of the AGPLv3: https://www.gnu.org/licenses/agpl-3.0.en.html THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #define JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN \ jassert ((MessageManager::getInstanceWithoutCreating() != nullptr \ && MessageManager::getInstanceWithoutCreating()->currentThreadHasLockedMessageManager()) \ || getPeer() == nullptr); namespace juce { static Component* findFirstEnabledAncestor (Component* in) { if (in == nullptr) return nullptr; if (in->isEnabled()) return in; return findFirstEnabledAncestor (in->getParentComponent()); } Component* Component::currentlyFocusedComponent = nullptr; //============================================================================== class HierarchyChecker { public: /* Creates a bail-out checker for comp and its ancestors, that will return true from shouldBailOut() if all of comp's ancestors are destroyed. @param comp a safe pointer to a component. The pointer will be updated to point to the nearest non-null ancestor on each call to shouldBailOut. */ HierarchyChecker (Component::SafePointer* comp, const MouseEvent& originalEvent) : closestAncestor (*comp), me (originalEvent) { for (Component* c = *comp; c != nullptr; c = c->getParentComponent()) hierarchy.push_back ({ c, c->getLocalPoint (me.eventComponent, me.position), c->getLocalPoint (me.eventComponent, me.mouseDownPosition) }); } Component* nearestNonNullParent() const { return closestAncestor; } /* Searches for the closest ancestor, and returns true if the closest ancestor is nullptr. */ bool shouldBailOut() const { closestAncestor = findNearestNonNullEntry().component; return closestAncestor == nullptr; } MouseEvent eventWithNearestParent() const { const auto nearest = findNearestNonNullEntry(); return { me.source, nearest.position, me.mods, me.pressure, me.orientation, me.rotation, me.tiltX, me.tiltY, nearest.component, nearest.component, me.eventTime, nearest.mouseDownPosition, me.mouseDownTime, me.getNumberOfClicks(), me.mouseWasDraggedSinceMouseDown() }; } template void forEach (Callback&& callback) { for (auto& item : hierarchy) if (item.component != nullptr) callback (*item.component); } private: struct Entry { Component::SafePointer component; Point position, mouseDownPosition; }; Entry findNearestNonNullEntry() const { for (const auto& entry : hierarchy) if (entry.component != nullptr) return entry; return { nullptr, me.position, me.mouseDownPosition }; } Component::SafePointer& closestAncestor; std::vector hierarchy; const MouseEvent me; }; //============================================================================== class Component::MouseListenerList { public: MouseListenerList() noexcept {} void addListener (MouseListener* newListener, bool wantsEventsForAllNestedChildComponents) { if (! listeners.contains (newListener)) { if (wantsEventsForAllNestedChildComponents) { listeners.insert (0, newListener); ++numDeepMouseListeners; } else { listeners.add (newListener); } } } void removeListener (MouseListener* listenerToRemove) { auto index = listeners.indexOf (listenerToRemove); if (index >= 0) { if (index < numDeepMouseListeners) --numDeepMouseListeners; listeners.remove (index); } } template static void sendMouseEvent (HierarchyChecker& checker, EventMethod&& eventMethod, Params&&... params) { const auto callListeners = [&] (auto& parentComp, const auto findNumListeners) { if (parentComp.componentData == nullptr) return true; const auto& list = parentComp.componentData->mouseListeners; const WeakReference safePointer { &parentComp }; for (int i = findNumListeners (list); --i >= 0; i = jmin (i, findNumListeners (list))) { (list.listeners.getUnchecked (i)->*eventMethod) (checker.eventWithNearestParent(), params...); if (checker.shouldBailOut() || safePointer == nullptr) return false; } return true; }; if (auto* parent = checker.nearestNonNullParent()) if (! callListeners (*parent, [] (auto& list) { return list.listeners.size(); })) return; if (auto* parent = checker.nearestNonNullParent()) for (Component* p = parent->parentComponent; p != nullptr; p = p->parentComponent) if (! callListeners (*p, [] (auto& list) { return list.numDeepMouseListeners; })) return; } private: Array listeners; int numDeepMouseListeners = 0; JUCE_DECLARE_NON_COPYABLE (MouseListenerList) }; class Component::Data { public: std::unique_ptr positioner; AffineTransform affineTransform; std::unique_ptr effectState; MouseListenerList mouseListeners; Array keyListeners; ComponentPaintDiagnostics* currentDiagnostics{}; std::unique_ptr cachedImage{}; std::unique_ptr accessibilityHandler; }; class Component::EffectState { public: explicit EffectState (ImageEffectFilter& i) : effect (&i) {} ImageEffectFilter& getEffect() const { return *effect; } bool setEffect (ImageEffectFilter& i) { return std::exchange (effect, &i) != &i; } void paint (Graphics& g, Component& c, bool ignoreAlphaLevel, OpaqueLayer& opaqueLayer, ComponentPaintDiagnostics& diagnostics) { auto scale = g.getInternalContext().getPhysicalPixelScaleFactor(); auto scaledBounds = c.getLocalBounds() * scale; const auto preferredType = g.getInternalContext().getPreferredImageTypeForTemporaryImages(); const auto pixelData = effectImage.getPixelData(); const auto shouldCreateImage = pixelData == nullptr || pixelData->width != scaledBounds.getWidth() || pixelData->height != scaledBounds.getHeight() || pixelData->createType()->getTypeID() != preferredType->getTypeID(); if (shouldCreateImage) { effectImage = Image { c.isOpaque() ? Image::RGB : Image::ARGB, scaledBounds.getWidth(), scaledBounds.getHeight(), false, *preferredType }; effectImage.setBackupEnabled (false); } if (! c.isOpaque()) effectImage.clear (effectImage.getBounds()); { Graphics g2 (effectImage); g2.addTransform (AffineTransform::scale ((float) scaledBounds.getWidth() / (float) c.getWidth(), (float) scaledBounds.getHeight() / (float) c.getHeight())); // Draw the component without any effect applied const ScopeGuard scope { [&c, x = std::move (c.componentData->effectState)]() mutable { c.componentData->effectState = std::move (x); } }; c.paintEntireComponent (g2, false, opaqueLayer, diagnostics); } Graphics::ScopedSaveState ss (g); g.addTransform (AffineTransform::scale (1.0f / scale)); const auto diagnosticTimer = diagnostics.applyEffectDuration.createTimer(); effect->applyEffect (effectImage, g, scale, ignoreAlphaLevel ? 1.0f : c.getAlpha()); } void releaseResources() { effectImage = {}; } private: Image effectImage; ImageEffectFilter* effect; }; auto Component::createDataIfNeeded() -> Data& { if (componentData == nullptr) componentData = std::make_unique(); return *componentData; } const Array* Component::getKeyListeners() const { if (auto* x = componentData.get()) return &x->keyListeners; return nullptr; } //============================================================================== class Component::OpaqueLayer { public: explicit OpaqueLayer (const Component* c) : currentComponent (c) { jassert (c != nullptr); appendOpaqueChildren (*c, {}, c->getLocalBounds()); } [[nodiscard]] auto pushComponent (Component& component) { removeOpaqueComponent (component); currentComponent = &component; const auto pos = component.getPosition(); offsetFromOrigin += pos; return ScopeGuard { [this, pos] { offsetFromOrigin -= pos; currentComponent = nullptr; } }; } Rectangle getCurrentComponentBounds (const juce::Graphics& g) { // This function must only be called while the object returned by // pushComponent() is still alive! jassert (currentComponent != nullptr); const auto pos = currentComponent->getPosition(); const auto bounds = getNonOccludedBoundsForCurrentComponent (g.getClipBounds() - pos); if (! bounds.isEmpty()) return bounds + pos; removeOpaqueChildren (*currentComponent); return {}; } Rectangle getCurrentComponentPaintBounds (const juce::Graphics& g) { // This function must only be called while the object returned by // pushComponent() is still alive! jassert (currentComponent != nullptr); return getNonOccludedBoundsForCurrentComponent (g.getClipBounds()); } void removeOpaqueComponentAndChildren (const Component& component) { removeOpaqueComponent (component); removeOpaqueChildren (component); } private: enum class ObscuredBy { childrenOnly, allButChildren }; template Rectangle getNonOccludedBoundsForCurrentComponent (Rectangle clipBounds) const { auto visibleBounds = currentComponent->getLocalBounds().getIntersection (clipBounds); if (visibleBounds.isEmpty()) return {}; RectangleList visibleRegions { visibleBounds }; const auto occlude = [&] (const OpaqueComponentInfo& opaqueComponentInfo) { const auto opaqueBounds = opaqueComponentInfo.clippedBounds - offsetFromOrigin; if (! opaqueBounds.intersects (visibleBounds)) return; if (opaqueBounds.contains (visibleBounds)) visibleRegions.clear(); else visibleRegions.subtract (opaqueBounds); visibleBounds = visibleRegions.getBounds(); }; if constexpr (obscuredBy == ObscuredBy::childrenOnly) { for (auto i = currentPosition; i < opaqueComponents.size(); ++i) { const auto& opaqueComponentInfo = opaqueComponents.getReference (i); if (! currentComponent->isParentOf (opaqueComponentInfo.component)) break; occlude (opaqueComponentInfo); if (visibleBounds.isEmpty()) return {}; } } else { for (int i = opaqueComponents.size(); --i >= currentPosition;) { const auto& opaqueComponentInfo = opaqueComponents.getReference (i); if (currentComponent->isParentOf (opaqueComponentInfo.component)) break; occlude (opaqueComponentInfo); if (visibleBounds.isEmpty()) return {}; } } return visibleBounds; } void removeOpaqueComponent (const Component& component) { if (opaqueComponents[currentPosition].component == &component) ++currentPosition; } void removeOpaqueChildren (const Component& component) { for (const auto* child : component.getChildren()) { if (currentPosition == opaqueComponents.size()) return; if (! isVisibleToLayer (*child)) continue; removeOpaqueComponentAndChildren (*child); } } static bool isVisibleToLayer (const Component& c) { return detail::ComponentHelpers::isVisibleWithNonZeroArea (c) && c.componentTransparency == 0 && ! c.isTransformed(); } void appendOpaqueChildren (const Component& parent, Point parentOrigin, Rectangle parentClippedBounds) { for (auto* child : parent.getChildren()) { if (! isVisibleToLayer (*child)) continue; const auto childBounds = child->getBounds() + parentOrigin; const auto childClippedBounds = parentClippedBounds.getIntersection (childBounds); if (childClippedBounds.isEmpty()) continue; if (child->isOpaque()) opaqueComponents.add ({ child, childClippedBounds }); appendOpaqueChildren (*child, childBounds.getPosition(), childClippedBounds); } } struct OpaqueComponentInfo { const Component* component; Rectangle clippedBounds; }; int currentPosition{}; Point offsetFromOrigin{}; const Component* currentComponent; Array opaqueComponents; }; //============================================================================== Component::Component() noexcept : componentFlags (0) { } Component::Component (const String& name) noexcept : componentName (name), componentFlags (0) { } Component::~Component() { static_assert (sizeof (flags) <= sizeof (componentFlags), "componentFlags has too many bits!"); componentListeners.call ([this] (ComponentListener& l) { l.componentBeingDeleted (*this); }); while (childComponentList.size() > 0) removeChildComponent (childComponentList.size() - 1, false, true); masterReference.clear(); if (parentComponent != nullptr) parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false); else giveAwayKeyboardFocusInternal (isParentOf (currentlyFocusedComponent)); if (flags.hasHeavyweightPeerFlag) removeFromDesktop(); // Something has added some children to this component during its destructor! Not a smart idea! jassert (childComponentList.size() == 0); } //============================================================================== void Component::setName (const String& name) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN if (componentName != name) { componentName = name; if (flags.hasHeavyweightPeerFlag) if (auto* peer = getPeer()) peer->setTitle (name); BailOutChecker checker (this); componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentNameChanged (*this); }); } } void Component::setComponentID (const String& newID) { componentID = newID; } void Component::setVisible (bool shouldBeVisible) { if (flags.visibleFlag != shouldBeVisible) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN const WeakReference safePointer (this); flags.visibleFlag = shouldBeVisible; if (shouldBeVisible) repaint(); else repaintParent(); sendFakeMouseMove(); if (! shouldBeVisible) { detail::ComponentHelpers::releaseAllCachedImageResources (*this); if (hasKeyboardFocus (true)) { if (parentComponent != nullptr) parentComponent->grabKeyboardFocus(); // ensure that keyboard focus is given away if it wasn't taken by parent giveAwayKeyboardFocus(); } } if (safePointer != nullptr) { sendVisibilityChangeMessage(); if (safePointer != nullptr && flags.hasHeavyweightPeerFlag) { if (auto* peer = getPeer()) { peer->setVisible (shouldBeVisible); internalHierarchyChanged(); } } } } } void Component::visibilityChanged() {} void Component::sendVisibilityChangeMessage() { BailOutChecker checker (this); visibilityChanged(); if (! checker.shouldBailOut()) componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentVisibilityChanged (*this); }); } bool Component::isShowing() const { if (! flags.visibleFlag) return false; if (parentComponent != nullptr) return parentComponent->isShowing(); if (auto* peer = getPeer()) return ! peer->isMinimised(); return false; } //============================================================================== void* Component::getWindowHandle() const { if (auto* peer = getPeer()) return peer->getNativeHandle(); return nullptr; } //============================================================================== static DesktopWindowOptions withPlatformParent (const DesktopWindowOptions& options, [[maybe_unused]] void* nativeWindowToAttachTo) { #if JUCE_WINDOWS return options.withParentHWND (nativeWindowToAttachTo); #elif JUCE_MAC return options.withParentNSView (nativeWindowToAttachTo); #elif JUCE_IOS return options.withParentUIView (nativeWindowToAttachTo); #elif JUCE_ANDROID // The object may be an Activity or a ViewGroup, and the peer checks which return options.withParentAndroidViewGroup (nativeWindowToAttachTo); #elif JUCE_LINUX || JUCE_BSD return options.withParentX11Window ((uint64_t) (pointer_sized_uint) nativeWindowToAttachTo); #else return options; #endif } void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo) { // A window that is recreated with only its style flags keeps the component it was opened from. auto* peer = ComponentPeer::getPeerFor (this); addToDesktop (withPlatformParent (DesktopWindowOptions().withStyleFlags (styleWanted), nativeWindowToAttachTo) .withAssociatedComponent (peer != nullptr ? peer->getAssociatedComponent() : nullptr)); } void Component::addToDesktop (const DesktopWindowOptions& options) { createDesktopWindow (options); } void Component::createDesktopWindow (const DesktopWindowOptions& optionsIn) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED const auto options = optionsIn.withAssociatedComponent (std::invoke ([&]() -> Component* { // Following the windows that the associated component's window was opened from must not // lead back to this window, which also covers a component inside this window. for (auto* opener = optionsIn.getAssociatedComponent(); opener != nullptr;) { auto* window = opener->getTopLevelComponent(); if (window == this) { // This window is being associated with a component that is inside it, or inside // a window that was opened from it. jassertfalse; return nullptr; } auto* windowPeer = window->getPeer(); opener = windowPeer != nullptr ? windowPeer->getAssociatedComponent() : nullptr; } return optionsIn.getAssociatedComponent(); })); const auto styleWanted = isOpaque() ? options.getStyleFlags() & ~ComponentPeer::windowIsSemiTransparent : options.getStyleFlags() | ComponentPeer::windowIsSemiTransparent; // don't use getPeer(), so that we only get the peer that's specifically // for this comp, and not for one of its parents. auto* peer = ComponentPeer::getPeerFor (this); if (peer == nullptr || styleWanted != peer->getStyleFlags() || ! peer->setAssociatedComponent (options.getAssociatedComponent())) { const WeakReference safePointer (this); #if JUCE_LINUX || JUCE_BSD // it's wise to give the component a non-zero size before // putting it on the desktop, as X windows get confused by this, and // a (1, 1) minimum size is enforced here. setSize (jmax (1, getWidth()), jmax (1, getHeight())); #endif const auto unscaledPosition = detail::ScalingHelpers::scaledScreenPosToUnscaled (getScreenPosition()); const auto topLeft = detail::ScalingHelpers::unscaledScreenPosToScaled (*this, unscaledPosition); bool wasFullscreen = false; bool wasMinimised = false; ComponentBoundsConstrainer* currentConstrainer = nullptr; Rectangle oldNonFullScreenBounds; int oldRenderingEngine = -1; std::optional oldCustomScale; if (peer != nullptr) { std::unique_ptr oldPeerToDelete (peer); wasFullscreen = peer->isFullScreen(); wasMinimised = peer->isMinimised(); currentConstrainer = peer->getConstrainer(); oldNonFullScreenBounds = peer->getNonFullScreenBounds(); oldRenderingEngine = peer->getCurrentRenderingEngine(); oldCustomScale = peer->getCustomPlatformScaleFactor(); flags.hasHeavyweightPeerFlag = false; Desktop::getInstance().removeDesktopComponent (this); internalHierarchyChanged(); // give comps a chance to react to the peer change before the old peer is deleted if (safePointer == nullptr) return; setTopLeftPosition (topLeft); } if (parentComponent != nullptr) parentComponent->removeChildComponent (this); if (safePointer != nullptr) { flags.hasHeavyweightPeerFlag = true; peer = createNewPeer (options.withStyleFlags (styleWanted)); Desktop::getInstance().addDesktopComponent (this); peer->setCustomPlatformScaleFactor (oldCustomScale); boundsRelativeToParent.setPosition (topLeft); peer->updateBounds(); if (oldRenderingEngine >= 0) peer->setCurrentRenderingEngine (oldRenderingEngine); peer->setVisible (isVisible()); peer = ComponentPeer::getPeerFor (this); if (peer == nullptr) return; if (wasFullscreen) { peer->setFullScreen (true); peer->setNonFullScreenBounds (oldNonFullScreenBounds); } if (wasMinimised) peer->setMinimised (true); #if JUCE_WINDOWS if (isAlwaysOnTop()) peer->setAlwaysOnTop (true); #endif peer->setConstrainer (currentConstrainer); repaint(); #if JUCE_LINUX // Creating the peer Image on Linux will change the reported position of the window. If // the Image creation is interleaved with the coming configureNotifyEvents the window // will appear in the wrong position. To avoid this, we force the Image creation here, // before handling any of the configureNotifyEvents. The Linux implementation of // performAnyPendingRepaintsNow() will force update the peer position if necessary. peer->performAnyPendingRepaintsNow(); #endif internalHierarchyChanged(); for (auto* other : Desktop::getInstance().findComponentsAssociatedWith (*peer)) if (auto* otherPeer = other->getPeer()) otherPeer->associationChanged(); if (auto* handler = getAccessibilityHandler()) detail::AccessibilityHelpers::notifyAccessibilityEvent (*handler, detail::AccessibilityHelpers::Event::windowOpened); } } } void Component::removeFromDesktop() { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN if (flags.hasHeavyweightPeerFlag) { if (auto* handler = getAccessibilityHandler()) detail::AccessibilityHelpers::notifyAccessibilityEvent (*handler, detail::AccessibilityHelpers::Event::windowClosed); detail::ComponentHelpers::releaseAllCachedImageResources (*this); auto* peer = ComponentPeer::getPeerFor (this); jassert (peer != nullptr); flags.hasHeavyweightPeerFlag = false; delete peer; Desktop::getInstance().removeDesktopComponent (this); } } bool Component::isOnDesktop() const noexcept { return flags.hasHeavyweightPeerFlag; } ComponentPeer* Component::getPeer() const { if (flags.hasHeavyweightPeerFlag) return ComponentPeer::getPeerFor (this); if (parentComponent == nullptr) return nullptr; return parentComponent->getPeer(); } void Component::userTriedToCloseWindow() { /* This means that the user's trying to get rid of your window with the 'close window' system menu option (on windows) or possibly the task manager - you should really handle this and delete or hide your component in an appropriate way. If you want to ignore the event and don't want to trigger this assertion, just override this method and do nothing. */ jassertfalse; } void Component::minimisationStateChanged (bool) {} float Component::getDesktopScaleFactor() const { return Desktop::getInstance().getGlobalScaleFactor(); } //============================================================================== void Component::setOpaque (bool shouldBeOpaque) { if (shouldBeOpaque != flags.opaqueFlag) { flags.opaqueFlag = shouldBeOpaque; if (flags.hasHeavyweightPeerFlag) if (auto* peer = ComponentPeer::getPeerFor (this)) addToDesktop (peer->getStyleFlags()); // recreates the heavyweight window repaint(); } } bool Component::isOpaque() const noexcept { return flags.opaqueFlag; } //============================================================================== void Component::setCachedComponentImage (CachedComponentImage* newCachedImage) { auto& cachedImage = createDataIfNeeded().cachedImage; if (newCachedImage == cachedImage.get()) return; cachedImage = std::unique_ptr { newCachedImage }; repaint(); } CachedComponentImage* Component::getCachedComponentImage() const noexcept { return componentData != nullptr ? componentData->cachedImage.get() : nullptr; } void Component::setBufferedToImage (bool shouldBeBuffered) { // This assertion means that this component is already using a custom // CachedComponentImage, so by calling setBufferedToImage, you'll be // deleting the custom one - this is almost certainly not what you wanted // to happen. If you really do know what you're doing here, and want to // avoid this assertion, just call setCachedComponentImage (nullptr) before // setBufferedToImage(). jassert (componentData == nullptr || componentData->cachedImage.get() == nullptr || dynamic_cast (componentData->cachedImage.get()) != nullptr); if (shouldBeBuffered) { createDataIfNeeded().cachedImage = std::make_unique (*this); } else if (componentData != nullptr) { componentData->cachedImage.reset(); } } void Component::invalidateCachedImageResources() { if (componentData == nullptr) return; if (componentData->cachedImage != nullptr) componentData->cachedImage->releaseResources(); if (componentData->effectState != nullptr) componentData->effectState->releaseResources(); } //============================================================================== void Component::reorderChildInternal (int sourceIndex, int destIndex) { if (sourceIndex != destIndex) { auto* c = childComponentList.getUnchecked (sourceIndex); jassert (c != nullptr); c->repaintParent(); childComponentList.move (sourceIndex, destIndex); sendFakeMouseMove(); internalChildrenChanged(); } } void Component::toFront (bool shouldGrabKeyboardFocus) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN if (flags.hasHeavyweightPeerFlag) { if (auto* peer = getPeer()) { peer->toFront (shouldGrabKeyboardFocus); if (shouldGrabKeyboardFocus && ! hasKeyboardFocus (true)) grabKeyboardFocus(); } } else if (parentComponent != nullptr) { auto& childList = parentComponent->childComponentList; if (childList.getLast() != this) { auto index = childList.indexOf (this); if (index >= 0) { int insertIndex = -1; if (! flags.alwaysOnTopFlag) { insertIndex = childList.size() - 1; while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop()) --insertIndex; } parentComponent->reorderChildInternal (index, insertIndex); } } if (shouldGrabKeyboardFocus) { internalBroughtToFront(); if (isShowing()) grabKeyboardFocus(); } } } void Component::toBehind (Component* other) { if (other != nullptr && other != this) { // the two components must belong to the same parent jassert (parentComponent == other->parentComponent); if (parentComponent != nullptr) { auto& childList = parentComponent->childComponentList; auto index = childList.indexOf (this); if (index >= 0 && childList [index + 1] != other) { auto otherIndex = childList.indexOf (other); if (otherIndex >= 0) { if (index < otherIndex) --otherIndex; parentComponent->reorderChildInternal (index, otherIndex); } } } else if (isOnDesktop()) { jassert (other->isOnDesktop()); if (other->isOnDesktop()) { auto* us = getPeer(); auto* them = other->getPeer(); jassert (us != nullptr && them != nullptr); if (us != nullptr && them != nullptr) us->toBehind (them); } } } } void Component::toBack() { if (isOnDesktop()) { jassertfalse; //xxx need to add this to native window } else if (parentComponent != nullptr) { auto& childList = parentComponent->childComponentList; if (childList.getFirst() != this) { auto index = childList.indexOf (this); if (index > 0) { int insertIndex = 0; if (flags.alwaysOnTopFlag) while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop()) ++insertIndex; parentComponent->reorderChildInternal (index, insertIndex); } } } } void Component::setAlwaysOnTop (bool shouldStayOnTop) { if (shouldStayOnTop != flags.alwaysOnTopFlag) { BailOutChecker checker (this); flags.alwaysOnTopFlag = shouldStayOnTop; if (isOnDesktop()) { if (auto* peer = getPeer()) { if (! peer->setAlwaysOnTop (shouldStayOnTop)) { // some kinds of peer can't change their always-on-top status, so // for these, we'll need to create a new window auto oldFlags = peer->getStyleFlags(); removeFromDesktop(); addToDesktop (oldFlags); } } } if (shouldStayOnTop && ! checker.shouldBailOut()) toFront (false); if (! checker.shouldBailOut()) internalHierarchyChanged(); } } bool Component::isAlwaysOnTop() const noexcept { return flags.alwaysOnTopFlag; } //============================================================================== int Component::proportionOfWidth (float proportion) const noexcept { return roundToInt (proportion * (float) boundsRelativeToParent.getWidth()); } int Component::proportionOfHeight (float proportion) const noexcept { return roundToInt (proportion * (float) boundsRelativeToParent.getHeight()); } int Component::getParentWidth() const noexcept { return parentComponent != nullptr ? parentComponent->getWidth() : getParentMonitorArea().getWidth(); } int Component::getParentHeight() const noexcept { return parentComponent != nullptr ? parentComponent->getHeight() : getParentMonitorArea().getHeight(); } Rectangle Component::getParentMonitorArea() const { return Desktop::getInstance().getDisplays().getDisplayForRect (getScreenBounds())->userBounds.toNearestInt(); } int Component::getScreenX() const { return getScreenPosition().x; } int Component::getScreenY() const { return getScreenPosition().y; } Point Component::getScreenPosition() const { return localPointToGlobal (Point()); } Rectangle Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); } Point Component::getLocalPoint (const Component* source, Point point) const { return detail::ComponentHelpers::convertCoordinate (this, source, point); } Point Component::getLocalPoint (const Component* source, Point point) const { return detail::ComponentHelpers::convertCoordinate (this, source, point); } Rectangle Component::getLocalArea (const Component* source, Rectangle area) const { return detail::ComponentHelpers::convertCoordinate (this, source, area); } Rectangle Component::getLocalArea (const Component* source, Rectangle area) const { return detail::ComponentHelpers::convertCoordinate (this, source, area); } Point Component::localPointToGlobal (Point point) const { return detail::ComponentHelpers::convertCoordinate (nullptr, this, point); } Point Component::localPointToGlobal (Point point) const { return detail::ComponentHelpers::convertCoordinate (nullptr, this, point); } Rectangle Component::localAreaToGlobal (Rectangle area) const { return detail::ComponentHelpers::convertCoordinate (nullptr, this, area); } Rectangle Component::localAreaToGlobal (Rectangle area) const { return detail::ComponentHelpers::convertCoordinate (nullptr, this, area); } //============================================================================== void Component::setBounds (int x, int y, int w, int h) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN if (w < 0) w = 0; if (h < 0) h = 0; const bool wasResized = (getWidth() != w || getHeight() != h); const bool wasMoved = (getX() != x || getY() != y); #if JUCE_DEBUG // It's a very bad idea to try to resize a window during its paint() method! jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop())); #endif if (wasMoved || wasResized) { const bool showing = isShowing(); if (showing) { // send a fake mouse move to trigger enter/exit messages if needed sendFakeMouseMove(); if (! flags.hasHeavyweightPeerFlag) repaintParent(); } boundsRelativeToParent.setBounds (x, y, w, h); if (showing) { if (wasResized) repaint(); else if (! flags.hasHeavyweightPeerFlag) repaintParent(); } else if (componentData != nullptr && componentData->cachedImage != nullptr) { componentData->cachedImage->invalidateAll(); } flags.isMoveCallbackPending = wasMoved; flags.isResizeCallbackPending = wasResized; if (flags.hasHeavyweightPeerFlag) if (auto* peer = getPeer()) peer->updateBounds(); sendMovedResizedMessagesIfPending(); } } void Component::sendMovedResizedMessagesIfPending() { const bool wasMoved = flags.isMoveCallbackPending; const bool wasResized = flags.isResizeCallbackPending; if (wasMoved || wasResized) { flags.isMoveCallbackPending = false; flags.isResizeCallbackPending = false; sendMovedResizedMessages (wasMoved, wasResized); } } void Component::sendMovedResizedMessages (bool wasMoved, bool wasResized) { BailOutChecker checker (this); if (wasMoved) { moved(); if (checker.shouldBailOut()) return; } if (wasResized) { resized(); if (checker.shouldBailOut()) return; for (int i = childComponentList.size(); --i >= 0;) { childComponentList.getUnchecked (i)->parentSizeChanged(); if (checker.shouldBailOut()) return; i = jmin (i, childComponentList.size()); } } if (parentComponent != nullptr) parentComponent->childBoundsChanged (this); if (! checker.shouldBailOut()) { componentListeners.callChecked (checker, [this, wasMoved, wasResized] (ComponentListener& l) { l.componentMovedOrResized (*this, wasMoved, wasResized); }); } if ((wasMoved || wasResized) && ! checker.shouldBailOut()) if (auto* handler = getAccessibilityHandler()) detail::AccessibilityHelpers::notifyAccessibilityEvent (*handler, detail::AccessibilityHelpers::Event::elementMovedOrResized); } void Component::setSize (int w, int h) { setBounds (getX(), getY(), w, h); } void Component::setTopLeftPosition (int x, int y) { setTopLeftPosition ({ x, y }); } void Component::setTopLeftPosition (Point pos) { setBounds (pos.x, pos.y, getWidth(), getHeight()); } void Component::setTopRightPosition (int x, int y) { setTopRightPosition ({ x, y }); } void Component::setTopRightPosition (Point pos) { setTopLeftPosition (pos.x - getWidth(), pos.y); } void Component::setBounds (Rectangle r) { setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight()); } void Component::setCentrePosition (Point p) { setBounds (getBounds().withCentre (p.transformedBy (getTransform().inverted()))); } void Component::setCentrePosition (int x, int y) { setCentrePosition ({ x, y }); } void Component::setCentreRelative (float x, float y) { setCentrePosition (roundToInt ((float) getParentWidth() * x), roundToInt ((float) getParentHeight() * y)); } void Component::setBoundsRelative (Rectangle target) { setBounds ((target * Point ((float) getParentWidth(), (float) getParentHeight())).toNearestInt()); } void Component::setBoundsRelative (float x, float y, float w, float h) { setBoundsRelative ({ x, y, w, h }); } void Component::centreWithSize (int width, int height) { auto parentArea = detail::ComponentHelpers::getParentOrMainMonitorBounds (*this) .transformedBy (getTransform().inverted()); setBounds (parentArea.getCentreX() - width / 2, parentArea.getCentreY() - height / 2, width, height); } void Component::setBoundsInset (BorderSize borders) { setBounds (borders.subtractedFrom (detail::ComponentHelpers::getParentOrMainMonitorBounds (*this))); } void Component::setBoundsToFit (Rectangle targetArea, Justification justification, bool onlyReduceInSize) { if (getLocalBounds().isEmpty() || targetArea.isEmpty()) { // it's no good calling this method unless both the component and // target rectangle have a finite size. jassertfalse; return; } auto sourceArea = targetArea.withZeroOrigin(); if (onlyReduceInSize && getWidth() <= targetArea.getWidth() && getHeight() <= targetArea.getHeight()) { sourceArea = getLocalBounds(); } else { auto sourceRatio = getHeight() / (double) getWidth(); auto targetRatio = targetArea.getHeight() / (double) targetArea.getWidth(); if (sourceRatio <= targetRatio) sourceArea.setHeight (jmin (targetArea.getHeight(), roundToInt (targetArea.getWidth() * sourceRatio))); else sourceArea.setWidth (jmin (targetArea.getWidth(), roundToInt (targetArea.getHeight() / sourceRatio))); } if (! sourceArea.isEmpty()) setBounds (justification.appliedToRectangle (sourceArea, targetArea)); } //============================================================================== void Component::setTransform (const AffineTransform& newTransform) { auto& affineTransform = createDataIfNeeded().affineTransform; if (affineTransform == newTransform) return; repaint(); affineTransform = newTransform; repaint(); sendMovedResizedMessages (false, false); } bool Component::isTransformed() const noexcept { return componentData != nullptr && ! componentData->affineTransform.isIdentity(); } AffineTransform Component::getTransform() const { return componentData != nullptr ? componentData->affineTransform : AffineTransform(); } float Component::getApproximateScaleFactorForComponent (const Component* targetComponent) { AffineTransform transform; for (auto* target = targetComponent; target != nullptr; target = target->getParentComponent()) { transform = transform.followedBy (target->getTransform()); if (target->isOnDesktop()) transform = transform.scaled (target->getDesktopScaleFactor()); } auto transformScale = std::sqrt (std::abs (transform.getDeterminant())); return transformScale / Desktop::getInstance().getGlobalScaleFactor(); } //============================================================================== bool Component::hitTest (int x, int y) { if (! flags.ignoresMouseClicksFlag) return true; if (flags.allowChildMouseClicksFlag) { for (int i = childComponentList.size(); --i >= 0;) { auto& child = *childComponentList.getUnchecked (i); if (child.isVisible() && detail::ComponentHelpers::hitTest (child, detail::ComponentHelpers::convertFromParentSpace (child, Point (x, y).toFloat()))) return true; } } return false; } void Component::setInterceptsMouseClicks (bool allowClicks, bool allowClicksOnChildComponents) noexcept { flags.ignoresMouseClicksFlag = ! allowClicks; flags.allowChildMouseClicksFlag = allowClicksOnChildComponents; } void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent, bool& allowsClicksOnChildComponents) const noexcept { allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag; allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag; } bool Component::contains (Point point) { return contains (point.toFloat()); } bool Component::contains (Point point) { if (detail::ComponentHelpers::hitTest (*this, point)) { if (parentComponent != nullptr) return parentComponent->contains (detail::ComponentHelpers::convertToParentSpace (*this, point)); if (flags.hasHeavyweightPeerFlag) if (auto* peer = getPeer()) return peer->contains (detail::ComponentHelpers::localPositionToRawPeerPos (*this, point).roundToInt(), true); } return false; } bool Component::reallyContains (Point point, bool returnTrueIfWithinAChild) { return reallyContains (point.toFloat(), returnTrueIfWithinAChild); } bool Component::reallyContains (Point point, bool returnTrueIfWithinAChild) { if (! contains (point)) return false; auto* top = getTopLevelComponent(); auto* compAtPosition = top->getComponentAt (top->getLocalPoint (this, point)); return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition)); } Component* Component::getComponentAt (Point position) { return getComponentAt (position.toFloat()); } Component* Component::getComponentAt (Point position) { if (flags.visibleFlag && detail::ComponentHelpers::hitTest (*this, position)) { for (int i = childComponentList.size(); --i >= 0;) { auto* child = childComponentList.getUnchecked (i); child = child->getComponentAt (detail::ComponentHelpers::convertFromParentSpace (*child, position)); if (child != nullptr) return child; } return this; } return nullptr; } Component* Component::getComponentAt (int x, int y) { return getComponentAt (Point { x, y }); } //============================================================================== void Component::addChildComponent (Component& child, int zOrder) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN jassert (this != &child); // adding a component to itself!? if (child.parentComponent != this) { if (child.parentComponent != nullptr) child.parentComponent->removeChildComponent (&child); else child.removeFromDesktop(); child.parentComponent = this; if (child.isVisible()) child.repaintParent(); if (! child.isAlwaysOnTop()) { if (zOrder < 0 || zOrder > childComponentList.size()) zOrder = childComponentList.size(); while (zOrder > 0) { if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop()) break; --zOrder; } } childComponentList.insert (zOrder, &child); child.internalHierarchyChanged(); internalChildrenChanged(); } } void Component::addAndMakeVisible (Component& child, int zOrder) { child.setVisible (true); addChildComponent (child, zOrder); } void Component::addChildComponent (Component* child, int zOrder) { if (child != nullptr) addChildComponent (*child, zOrder); } void Component::addAndMakeVisible (Component* child, int zOrder) { if (child != nullptr) addAndMakeVisible (*child, zOrder); } void Component::addChildAndSetID (Component* child, const String& childID) { if (child != nullptr) { child->setComponentID (childID); addAndMakeVisible (child); } } void Component::removeChildComponent (Component* child) { removeChildComponent (childComponentList.indexOf (child), true, true); } Component* Component::removeChildComponent (int index) { return removeChildComponent (index, true, true); } Component* Component::removeChildComponent (int index, bool sendParentEvents, bool sendChildEvents) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED_OR_OFFSCREEN if (auto* child = childComponentList [index]) { sendParentEvents = sendParentEvents && child->isShowing(); if (sendParentEvents) { sendFakeMouseMove(); if (child->isVisible()) child->repaintParent(); } childComponentList.remove (index); child->parentComponent = nullptr; detail::ComponentHelpers::releaseAllCachedImageResources (*child); // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus) if (child->hasKeyboardFocus (true)) { const WeakReference safeThis (this); child->giveAwayKeyboardFocusInternal (sendChildEvents || currentlyFocusedComponent != child); if (sendParentEvents) { if (safeThis == nullptr) return child; grabKeyboardFocus(); } } if (sendChildEvents) child->internalHierarchyChanged(); if (sendParentEvents) internalChildrenChanged(); return child; } return nullptr; } //============================================================================== void Component::removeAllChildren() { while (! childComponentList.isEmpty()) removeChildComponent (childComponentList.size() - 1); } void Component::deleteAllChildren() { while (! childComponentList.isEmpty()) delete (removeChildComponent (childComponentList.size() - 1)); } int Component::getNumChildComponents() const noexcept { return childComponentList.size(); } Component* Component::getChildComponent (int index) const noexcept { return childComponentList[index]; } int Component::getIndexOfChildComponent (const Component* child) const noexcept { return childComponentList.indexOf (const_cast (child)); } Component* Component::findChildWithID (StringRef targetID) const noexcept { for (auto* c : childComponentList) if (c->componentID == targetID) return c; return nullptr; } Component* Component::getTopLevelComponent() const noexcept { auto* comp = this; while (comp->parentComponent != nullptr) comp = comp->parentComponent; return const_cast (comp); } bool Component::isParentOf (const Component* possibleChild) const noexcept { while (possibleChild != nullptr) { possibleChild = possibleChild->parentComponent; if (possibleChild == this) return true; } return false; } //============================================================================== void Component::parentHierarchyChanged() {} void Component::childrenChanged() {} void Component::internalChildrenChanged() { if (componentListeners.isEmpty()) { childrenChanged(); } else { BailOutChecker checker (this); childrenChanged(); if (! checker.shouldBailOut()) componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentChildrenChanged (*this); }); } } void Component::internalHierarchyChanged() { BailOutChecker checker (this); parentHierarchyChanged(); if (checker.shouldBailOut()) return; componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentParentHierarchyChanged (*this); }); if (checker.shouldBailOut()) return; for (int i = childComponentList.size(); --i >= 0;) { childComponentList.getUnchecked (i)->internalHierarchyChanged(); if (checker.shouldBailOut()) { // you really shouldn't delete the parent component during a callback telling you // that it's changed jassertfalse; return; } i = jmin (i, childComponentList.size()); } if (flags.hasHeavyweightPeerFlag) if (auto* handler = getAccessibilityHandler()) handler->notifyAccessibilityEvent (AccessibilityEvent::structureChanged); } //============================================================================== #if JUCE_MODAL_LOOPS_PERMITTED int Component::runModalLoop() { if (! MessageManager::getInstance()->isThisTheMessageThread()) { // use a callback so this can be called from non-gui threads return (int) (pointer_sized_int) MessageManager::getInstance() ->callFunctionOnMessageThread (&detail::ComponentHelpers::runModalLoopCallback, this); } if (! isCurrentlyModal (false)) enterModalState (true); return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent(); } #endif //============================================================================== void Component::enterModalState (bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* callback, bool deleteWhenDismissed) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED SafePointer safeReference { this }; if (! isCurrentlyModal (false)) { // While this component is in modal state it may block other components from receiving // mouseExit events. To keep mouseEnter and mouseExit calls balanced on these components, // we must manually force the mouse to "leave" blocked components. detail::ComponentHelpers::sendMouseEventToComponentsThatAreBlockedByModal (*this, &Component::internalMouseExit); if (safeReference == nullptr) { // If you hit this assertion, the mouse-exit event above has caused the modal component to be deleted. jassertfalse; return; } auto& mcm = *ModalComponentManager::getInstance(); mcm.startModal ({}, this, deleteWhenDismissed); mcm.attachCallback (this, callback); setVisible (true); if (shouldTakeKeyboardFocus) grabKeyboardFocus(); } else { // Probably a bad idea to try to make a component modal twice! jassertfalse; } } void Component::exitModalState (int returnValue) { WeakReference deletionChecker (this); if (isCurrentlyModal (false)) { if (MessageManager::getInstance()->isThisTheMessageThread()) { auto& mcm = *ModalComponentManager::getInstance(); mcm.endModal ({}, this, returnValue); mcm.bringModalComponentsToFront(); // While this component is in modal state it may block other components from receiving // mouseEnter events. To keep mouseEnter and mouseExit calls balanced on these components, // we must manually force the mouse to "enter" blocked components. if (deletionChecker != nullptr) detail::ComponentHelpers::sendMouseEventToComponentsThatAreBlockedByModal (*deletionChecker, &Component::internalMouseEnter); } else { MessageManager::callAsync ([target = WeakReference { this }, returnValue] { if (target != nullptr) target->exitModalState (returnValue); }); } } } bool Component::isCurrentlyModal (bool onlyConsiderForemostModalComponent) const noexcept { auto& mcm = *ModalComponentManager::getInstance(); return onlyConsiderForemostModalComponent ? mcm.isFrontModalComponent (this) : mcm.isModal (this); } bool Component::isCurrentlyBlockedByAnotherModalComponent() const { return detail::ComponentHelpers::modalWouldBlockComponent (*this, getCurrentlyModalComponent()); } int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() noexcept { if (auto* manager = ModalComponentManager::getInstanceWithoutCreating()) return manager->getNumModalComponents(); return {}; } Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) noexcept { if (auto* manager = ModalComponentManager::getInstanceWithoutCreating()) return manager->getModalComponent (index); return {}; } //============================================================================== void Component::setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) noexcept { flags.bringToFrontOnClickFlag = shouldBeBroughtToFront; } bool Component::isBroughtToFrontOnMouseClick() const noexcept { return flags.bringToFrontOnClickFlag; } //============================================================================== void Component::setMouseCursor (const MouseCursor& newCursor) { if (cursor != newCursor) { cursor = newCursor; if (flags.visibleFlag) updateMouseCursor(); } } MouseCursor Component::getMouseCursor() { return cursor; } void Component::updateMouseCursor() const { Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate(); } //============================================================================== void Component::setRepaintsOnMouseActivity (bool shouldRepaint) noexcept { flags.repaintOnMouseActivityFlag = shouldRepaint; } //============================================================================== float Component::getAlpha() const noexcept { return (255 - componentTransparency) / 255.0f; } void Component::setAlpha (float newAlpha) { auto newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0))); if (componentTransparency != newIntAlpha) { componentTransparency = newIntAlpha; alphaChanged(); } } void Component::alphaChanged() { if (flags.hasHeavyweightPeerFlag) { if (auto* peer = getPeer()) peer->setAlpha (getAlpha()); } else { repaint(); } } //============================================================================== void Component::repaint() { internalRepaintUnchecked (getLocalBounds(), true); } void Component::repaint (int x, int y, int w, int h) { internalRepaint ({ x, y, w, h }); } void Component::repaint (Rectangle area) { internalRepaint (area); } void Component::repaintParent() { if (parentComponent != nullptr) parentComponent->internalRepaint (detail::ComponentHelpers::convertToParentSpace (*this, getLocalBounds())); } void Component::internalRepaint (Rectangle area) { area = area.getIntersection (getLocalBounds()); if (! area.isEmpty()) internalRepaintUnchecked (area, false); } void Component::internalRepaintUnchecked (Rectangle area, bool isEntireComponent) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED if (flags.visibleFlag) { if (componentData != nullptr && componentData->cachedImage != nullptr) if (! (isEntireComponent ? componentData->cachedImage->invalidateAll() : componentData->cachedImage->invalidate (area))) return; if (area.isEmpty()) return; if (flags.hasHeavyweightPeerFlag) { if (auto* peer = getPeer()) { // Tweak the scaling so that the component's integer size exactly aligns with the peer's scaled size auto peerBounds = peer->getBounds(); auto scaled = area * Point ((float) peerBounds.getWidth() / (float) getWidth(), (float) peerBounds.getHeight() / (float) getHeight()); peer->repaint (isTransformed() ? scaled.transformedBy (componentData->affineTransform) : scaled); } } else { if (parentComponent != nullptr) parentComponent->internalRepaint (detail::ComponentHelpers::convertToParentSpace (*this, area)); } } } //============================================================================== void Component::paint (Graphics&) { // if your component is marked as opaque, you must implement a paint // method and ensure that its entire area is completely painted. jassert (getBounds().isEmpty() || ! isOpaque()); } void Component::paintOverChildren (Graphics&) { // all painting is done in the subclasses } //============================================================================== void Component::paintWithinParentContext (Graphics& g, OpaqueLayer& opaqueLayer, ComponentPaintDiagnostics& diagnostics) { g.setOrigin (getPosition()); if (componentData == nullptr || componentData->cachedImage == nullptr) { paintEntireComponent (g, false, opaqueLayer, diagnostics); return; } opaqueLayer.removeOpaqueComponentAndChildren (*this); const ScopedValueSetter scopedDiagnostics { componentData->currentDiagnostics, &diagnostics }; componentData->currentDiagnostics->readFromCache = true; componentData->cachedImage->paint (g); } void Component::paintComponentAndChildren (Graphics& g, OpaqueLayer& opaqueLayer, ComponentPaintDiagnostics& diagnostics) { #if JUCE_ETW_TRACELOGGING { int depth = 0; auto parent = getParentComponent(); while (parent) { parent = parent->getParentComponent(); depth++; } JUCE_TRACE_LOG_PAINT_COMPONENT_AND_CHILDREN (depth); } #endif const auto paintBounds = opaqueLayer.getCurrentComponentPaintBounds (g); if (! paintBounds.isEmpty()) { Graphics::ScopedSaveState ss (g); if (! isPaintingUnclipped()) g.reduceClipRegion (paintBounds); const auto diagnosticTimer = diagnostics.paintDuration.createTimer(); paint (g); } for (auto* child : getChildren()) { if (! detail::ComponentHelpers::isVisibleWithNonZeroArea (*child)) continue; ComponentPaintDiagnostics childDiagnostics; const ScopeGuard scopedListenerCallback { [&] { child->componentListeners.call ([&] (auto& l) { l.componentPainted (*child, childDiagnostics); }); } }; const auto diagnosticTimer = childDiagnostics.totalPaintDuration.createTimer(); if (child->isTransformed() || child->componentTransparency != 0) { Graphics::ScopedSaveState ss (g); if (child->isTransformed()) g.addTransform (child->componentData->affineTransform); child->paintWithinParentContext (g, opaqueLayer, childDiagnostics); } else { const auto componentPopper = opaqueLayer.pushComponent (*child); const auto componentBounds = opaqueLayer.getCurrentComponentBounds (g); if (componentBounds.isEmpty()) continue; Graphics::ScopedSaveState ss (g); if (! child->isPaintingUnclipped()) g.reduceClipRegion (componentBounds); child->paintWithinParentContext (g, opaqueLayer, childDiagnostics); } } Graphics::ScopedSaveState ss (g); if (! isPaintingUnclipped()) g.reduceClipRegion (getLocalBounds()); const auto diagnosticTimer = diagnostics.paintOverChildrenDuration.createTimer(); paintOverChildren (g); } void Component::paintEntireComponent (Graphics& g, bool ignoreAlphaLevel) { OpaqueLayer opaqueLayer { this }; // If we are writing into a cached image we don't want to generate a // completely independent callback, so we skip the creation of a new // diagnostics object and use the diagnostics captured in the original call // to paint this component. However, if while painting into the cache we // end up in a recursive call to painting this component, it is preferable // that we create an independent callback so the user can decide what to do // with the data from multiple paint method invocations. // // Note: readFromCache is set directly *before* reading from the cache and // wroteToCache is set directly *before* writing to the cache. This means // we can use them as flags to detect if we are already reading from or // writing to a cache. if (componentData != nullptr && componentData->currentDiagnostics != nullptr && componentData->currentDiagnostics->readFromCache && ! componentData->currentDiagnostics->wroteToCache) { componentData->currentDiagnostics->wroteToCache = true; paintEntireComponent (g, ignoreAlphaLevel, opaqueLayer, *componentData->currentDiagnostics); return; } ComponentPaintDiagnostics diagnostics; const ScopeGuard scopedListenerCallback { [&] { componentListeners.call ([&] (auto& l) { l.componentPainted (*this, diagnostics); }); } }; const auto diagnosticTimer = diagnostics.totalPaintDuration.createTimer(); paintEntireComponent (g, ignoreAlphaLevel, opaqueLayer, diagnostics); } void Component::paintEntireComponent (Graphics& g, bool ignoreAlphaLevel, OpaqueLayer& opaqueLayer, ComponentPaintDiagnostics& diagnostics) { // If sizing a top-level-window and the OS paint message is delivered synchronously // before resized() is called, then we'll invoke the callback here, to make sure // the components inside have had a chance to sort their sizes out. #if JUCE_DEBUG if (! flags.isInsidePaintCall) // (avoids an assertion in plugins hosted in WaveLab) #endif sendMovedResizedMessagesIfPending(); #if JUCE_DEBUG flags.isInsidePaintCall = true; #endif if (componentData != nullptr && componentData->effectState != nullptr) { componentData->effectState->paint (g, *this, ignoreAlphaLevel, opaqueLayer, diagnostics); } else if (componentTransparency > 0 && ! ignoreAlphaLevel) { if (componentTransparency < 255) { OpaqueLayer transparentOpaqueLayer { this }; g.beginTransparencyLayer (getAlpha()); paintComponentAndChildren (g, transparentOpaqueLayer, diagnostics); g.endTransparencyLayer(); } } else if (isTransformed()) { OpaqueLayer transformedOpaqueLayer { this }; paintComponentAndChildren (g, transformedOpaqueLayer, diagnostics); } else { paintComponentAndChildren (g, opaqueLayer, diagnostics); } #if JUCE_DEBUG flags.isInsidePaintCall = false; #endif } void Component::setPaintingIsUnclipped (bool shouldPaintWithoutClipping) noexcept { flags.dontClipGraphicsFlag = shouldPaintWithoutClipping; } bool Component::isPaintingUnclipped() const noexcept { return flags.dontClipGraphicsFlag; } //============================================================================== Image Component::createComponentSnapshot (Rectangle areaToGrab, bool clipImageToComponentBounds, float scaleFactor, const ImageType& imageType) { auto r = areaToGrab; if (clipImageToComponentBounds) r = r.getIntersection (getLocalBounds()); if (r.isEmpty()) return {}; auto w = roundToInt (scaleFactor * (float) r.getWidth()); auto h = roundToInt (scaleFactor * (float) r.getHeight()); Image image (flags.opaqueFlag ? Image::RGB : Image::ARGB, w, h, ! flags.opaqueFlag, imageType); Graphics g (image); if (w != getWidth() || h != getHeight()) g.addTransform (AffineTransform::scale ((float) w / (float) r.getWidth(), (float) h / (float) r.getHeight())); g.setOrigin (-r.getPosition()); paintEntireComponent (g, true); return image; } ImageEffectFilter* Component::getComponentEffect() const noexcept { return componentData != nullptr && componentData->effectState != nullptr ? &componentData->effectState->getEffect() : nullptr; } void Component::setComponentEffect (ImageEffectFilter* newEffect) { auto& effectState = createDataIfNeeded().effectState; if (newEffect == nullptr && effectState == nullptr) return; const auto needsRepaint = std::invoke ([&] { if (newEffect == nullptr) { effectState.reset(); return true; } if (effectState == nullptr) { effectState = std::make_unique (*newEffect); return true; } return effectState->setEffect (*newEffect); }); if (needsRepaint) repaint(); } //============================================================================== LookAndFeel& Component::getLookAndFeel() const noexcept { for (auto* c = this; c != nullptr; c = c->parentComponent) if (auto lf = c->lookAndFeel.get()) return *lf; return LookAndFeel::getDefaultLookAndFeel(); } void Component::setLookAndFeel (LookAndFeel* newLookAndFeel) { if (lookAndFeel != newLookAndFeel) { lookAndFeel = newLookAndFeel; sendLookAndFeelChange(); } } FontOptions Component::withDefaultMetrics (FontOptions opt) const { return getLookAndFeel().withDefaultMetrics (std::move (opt)); } void Component::lookAndFeelChanged() {} void Component::colourChanged() {} void Component::sendLookAndFeelChange() { const WeakReference safePointer (this); repaint(); lookAndFeelChanged(); if (safePointer != nullptr) { colourChanged(); if (safePointer != nullptr) { for (int i = childComponentList.size(); --i >= 0;) { childComponentList.getUnchecked (i)->sendLookAndFeelChange(); if (safePointer == nullptr) return; i = jmin (i, childComponentList.size()); } } } } Colour Component::findColour (int colourID, bool inheritFromParent) const { if (auto* v = properties.getVarPointer (detail::ComponentHelpers::getColourPropertyID (colourID))) return Colour ((uint32) static_cast (*v)); if (inheritFromParent && parentComponent != nullptr && (lookAndFeel == nullptr || ! lookAndFeel->isColourSpecified (colourID))) return parentComponent->findColour (colourID, true); return getLookAndFeel().findColour (colourID); } bool Component::isColourSpecified (int colourID) const { return properties.contains (detail::ComponentHelpers::getColourPropertyID (colourID)); } void Component::removeColour (int colourID) { if (properties.remove (detail::ComponentHelpers::getColourPropertyID (colourID))) colourChanged(); } void Component::setColour (int colourID, Colour colour) { if (properties.set (detail::ComponentHelpers::getColourPropertyID (colourID), (int) colour.getARGB())) colourChanged(); } void Component::copyAllExplicitColoursTo (Component& target) const { bool changed = false; for (int i = properties.size(); --i >= 0;) { auto name = properties.getName (i); if (name.toString().startsWith (detail::colourPropertyPrefix)) if (target.properties.set (name, properties [name])) changed = true; } if (changed) target.colourChanged(); } //============================================================================== Component::Positioner::Positioner (Component& c) noexcept : component (c) { } Component::Positioner* Component::getPositioner() const noexcept { return componentData != nullptr ? componentData->positioner.get() : nullptr; } void Component::setPositioner (Positioner* newPositioner) { // You can only assign a positioner to the component that it was created for! jassert (newPositioner == nullptr || this == &(newPositioner->getComponent())); createDataIfNeeded().positioner.reset (newPositioner); } //============================================================================== Rectangle Component::getLocalBounds() const noexcept { return boundsRelativeToParent.withZeroOrigin(); } Rectangle Component::getBoundsInParent() const noexcept { return isTransformed() ? boundsRelativeToParent.transformedBy (componentData->affineTransform) : boundsRelativeToParent; } //============================================================================== void Component::mouseEnter (const MouseEvent&) {} void Component::mouseExit (const MouseEvent&) {} void Component::mouseDown (const MouseEvent&) {} void Component::mouseUp (const MouseEvent&) {} void Component::mouseDrag (const MouseEvent&) {} void Component::mouseMove (const MouseEvent&) {} void Component::mouseDoubleClick (const MouseEvent&) {} void Component::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel) { // the base class just passes this event up to the nearest enabled ancestor if (auto* enabledComponent = findFirstEnabledAncestor (getParentComponent())) enabledComponent->mouseWheelMove (e.getEventRelativeTo (enabledComponent), wheel); } void Component::mouseMagnify (const MouseEvent& e, float magnifyAmount) { // the base class just passes this event up to the nearest enabled ancestor if (auto* enabledComponent = findFirstEnabledAncestor (getParentComponent())) enabledComponent->mouseMagnify (e.getEventRelativeTo (enabledComponent), magnifyAmount); } //============================================================================== void Component::resized() {} void Component::moved() {} void Component::childBoundsChanged (Component*) {} void Component::parentSizeChanged() {} void Component::addComponentListener (ComponentListener* newListener) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS if (getParentComponent() != nullptr) { JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED } #endif componentListeners.add (newListener); } void Component::removeComponentListener (ComponentListener* listenerToRemove) { componentListeners.remove (listenerToRemove); } //============================================================================== void Component::inputAttemptWhenModal() { ModalComponentManager::getInstance()->bringModalComponentsToFront(); getLookAndFeel().playAlertSound(); } bool Component::canModalEventBeSentToComponent (const Component*) { return false; } void Component::internalModalInputAttempt() { if (auto* current = getCurrentlyModalComponent()) current->inputAttemptWhenModal(); } //============================================================================== void Component::postCommandMessage (int commandID) { MessageManager::callAsync ([target = WeakReference { this }, commandID] { if (target != nullptr) target->handleCommandMessage (commandID); }); } void Component::handleCommandMessage (int) { // used by subclasses } //============================================================================== void Component::addMouseListener (MouseListener* newListener, bool wantsEventsForAllNestedChildComponents) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED // If you register a component as a mouselistener for itself, it'll receive all the events // twice - once via the direct callback that all components get anyway, and then again as a listener! jassert ((newListener != this) || wantsEventsForAllNestedChildComponents); createDataIfNeeded().mouseListeners.addListener (newListener, wantsEventsForAllNestedChildComponents); } void Component::removeMouseListener (MouseListener* listenerToRemove) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED if (componentData != nullptr) componentData->mouseListeners.removeListener (listenerToRemove); } //============================================================================== void Component::internalMouseEnter (SafePointer target, MouseInputSource source, Point relativePos, Time time) { if (target->isCurrentlyBlockedByAnotherModalComponent()) { // if something else is modal, always just show a normal mouse cursor source.showMouseCursor (MouseCursor::NormalCursor); return; } if (target->flags.repaintOnMouseActivityFlag) target->repaint(); const auto me = makeMouseEvent (source, detail::PointerState().withPosition (relativePos), source.getCurrentModifiers(), target, target, time, relativePos, time, 0, false); HierarchyChecker checker (&target, me); target->mouseEnter (me); if (checker.shouldBailOut()) return; target->flags.cachedMouseInsideComponent = true; if (checker.shouldBailOut()) return; Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseEnter (me); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseEnter); } void Component::internalMouseExit (SafePointer target, MouseInputSource source, Point relativePos, Time time) { if (target->isCurrentlyBlockedByAnotherModalComponent()) { // if something else is modal, always just show a normal mouse cursor source.showMouseCursor (MouseCursor::NormalCursor); return; } if (target->flags.repaintOnMouseActivityFlag) target->repaint(); target->flags.cachedMouseInsideComponent = false; const auto me = makeMouseEvent (source, detail::PointerState().withPosition (relativePos), source.getCurrentModifiers(), target, target, time, relativePos, time, 0, false); HierarchyChecker checker (&target, me); target->mouseExit (me); if (checker.shouldBailOut()) return; Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseExit (me); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseExit); } void Component::internalMouseDown (SafePointer target, MouseInputSource source, const detail::PointerState& relativePointerState, Time time) { auto& desktop = Desktop::getInstance(); const auto me = makeMouseEvent (source, relativePointerState, source.getCurrentModifiers(), target, target, time, relativePointerState.position, time, source.getNumberOfMultipleClicks(), false); HierarchyChecker checker (&target, me); if (target->isCurrentlyBlockedByAnotherModalComponent()) { target->flags.mouseDownWasBlocked = true; target->internalModalInputAttempt(); if (checker.shouldBailOut()) return; // If processing the input attempt has exited the modal loop, we'll allow the event // to be delivered. if (target->isCurrentlyBlockedByAnotherModalComponent()) { // allow blocked mouse-events to go to global listeners desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDown (checker.eventWithNearestParent()); }); return; } } target->flags.mouseDownWasBlocked = false; checker.forEach ([] (auto& comp) { if (comp.isBroughtToFrontOnMouseClick()) comp.toFront (true); }); if (checker.shouldBailOut()) return; target->grabKeyboardFocusInternal (focusChangedByMouseClick, true, FocusChangeDirection::unknown); if (checker.shouldBailOut()) return; if (target->flags.repaintOnMouseActivityFlag) target->repaint(); // The target may have been replaced by an ancestor if the original component was deleted // while being brought to the front or given focus, so the event is retargeted to match. target->mouseDown (checker.eventWithNearestParent()); if (checker.shouldBailOut()) return; desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDown (checker.eventWithNearestParent()); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseDown); } void Component::internalMouseUp (SafePointer target, MouseInputSource source, const detail::PointerState& relativePointerState, Time time, const ModifierKeys oldModifiers) { const auto originalTarget = target; const auto me = makeMouseEvent (source, relativePointerState, oldModifiers, target, target, time, target->getLocalPoint (nullptr, source.getLastMouseDownPosition()), source.getLastMouseDownTime(), source.getNumberOfMultipleClicks(), source.isLongPressOrDrag()); HierarchyChecker checker (&target, me); if (target->flags.mouseDownWasBlocked && target->isCurrentlyBlockedByAnotherModalComponent()) { // Global listeners still need to know about the mouse up auto& desktop = Desktop::getInstance(); desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseUp (checker.eventWithNearestParent()); }); return; } if (target->flags.repaintOnMouseActivityFlag) target->repaint(); target->mouseUp (me); if (checker.shouldBailOut()) return; auto& desktop = Desktop::getInstance(); desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseUp (checker.eventWithNearestParent()); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseUp); if (checker.shouldBailOut()) return; // check for double-click if (me.getNumberOfClicks() >= 2) { if (target == originalTarget) target->mouseDoubleClick (checker.eventWithNearestParent()); if (checker.shouldBailOut()) return; desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { l.mouseDoubleClick (checker.eventWithNearestParent()); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseDoubleClick); } } void Component::internalMouseDrag (SafePointer target, MouseInputSource source, const detail::PointerState& relativePointerState, Time time) { if (! target->isCurrentlyBlockedByAnotherModalComponent()) { const auto me = makeMouseEvent (source, relativePointerState, source.getCurrentModifiers(), target, target, time, target->getLocalPoint (nullptr, source.getLastMouseDownPosition()), source.getLastMouseDownTime(), source.getNumberOfMultipleClicks(), source.isLongPressOrDrag()); HierarchyChecker checker (&target, me); target->mouseDrag (me); if (checker.shouldBailOut()) return; Desktop::getInstance().getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseDrag (checker.eventWithNearestParent()); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseDrag); } } void Component::internalMouseMove (SafePointer target, MouseInputSource source, Point relativePos, Time time) { auto& desktop = Desktop::getInstance(); if (target->isCurrentlyBlockedByAnotherModalComponent()) { // allow blocked mouse-events to go to global listeners desktop.sendMouseMove(); } else { const auto me = makeMouseEvent (source, detail::PointerState().withPosition (relativePos), source.getCurrentModifiers(), target, target, time, relativePos, time, 0, false); HierarchyChecker checker (&target, me); target->mouseMove (me); if (checker.shouldBailOut()) return; desktop.getMouseListeners().callChecked (checker, [&] (MouseListener& l) { l.mouseMove (checker.eventWithNearestParent()); }); MouseListenerList::sendMouseEvent (checker, &MouseListener::mouseMove); } } template void Component::internalMouseGesture (SafePointer target, MouseInputSource source, Point relativePos, Time time, EventMethod eventMethod, const Params&... params) { auto& desktop = Desktop::getInstance(); const auto me = makeMouseEvent (source, detail::PointerState().withPosition (relativePos), source.getCurrentModifiers(), target, target, time, relativePos, time, 0, false); HierarchyChecker checker (&target, me); const auto sendToGlobalListeners = [&] { desktop.mouseListeners.callChecked (checker, [&] (MouseListener& l) { std::invoke (eventMethod, l, checker.eventWithNearestParent(), params...); }); }; if (target->isCurrentlyBlockedByAnotherModalComponent()) { // allow blocked mouse-events to go to global listeners sendToGlobalListeners(); return; } std::invoke (eventMethod, *target, me, params...); if (checker.shouldBailOut()) return; sendToGlobalListeners(); if (! checker.shouldBailOut()) MouseListenerList::sendMouseEvent (checker, eventMethod, params...); } void Component::internalMouseWheel (SafePointer target, MouseInputSource source, Point relativePos, Time time, const MouseWheelDetails& wheel) { internalMouseGesture (target, source, relativePos, time, &MouseListener::mouseWheelMove, wheel); } void Component::internalMagnifyGesture (SafePointer target, MouseInputSource source, Point relativePos, Time time, float amount) { internalMouseGesture (target, source, relativePos, time, &MouseListener::mouseMagnify, amount); } void Component::sendFakeMouseMove() const { if (flags.ignoresMouseClicksFlag && ! flags.allowChildMouseClicksFlag) return; auto mainMouse = Desktop::getInstance().getMainMouseSource(); if (! mainMouse.isDragging()) mainMouse.triggerFakeMove(); } void JUCE_CALLTYPE Component::beginDragAutoRepeat (int interval) { Desktop::getInstance().beginDragAutoRepeat (interval); } //============================================================================== void Component::broughtToFront() { } void Component::internalBroughtToFront() { if (flags.hasHeavyweightPeerFlag) Desktop::getInstance().componentBroughtToFront (this); BailOutChecker checker (this); broughtToFront(); if (checker.shouldBailOut()) return; componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentBroughtToFront (*this); }); if (checker.shouldBailOut()) return; // When brought to the front and there's a modal component blocking this one, // we need to bring the modal one to the front instead. if (auto* cm = getCurrentlyModalComponent()) if (cm->getTopLevelComponent() != getTopLevelComponent()) ModalComponentManager::getInstance()->bringModalComponentsToFront (false); // very important that this is false, otherwise in Windows, // non-front components can't get focus when another modal comp is // active, and therefore can't receive mouse-clicks } //============================================================================== void Component::focusGained (FocusChangeType) {} void Component::focusGainedWithDirection (FocusChangeType, FocusChangeDirection) {} void Component::focusLost (FocusChangeType) {} void Component::focusOfChildComponentChanged (FocusChangeType) {} void Component::internalKeyboardFocusGain (FocusChangeType cause) { internalKeyboardFocusGain (cause, WeakReference (this), FocusChangeDirection::unknown); } void Component::internalKeyboardFocusGain (FocusChangeType cause, const WeakReference& safePointer, FocusChangeDirection direction) { focusGainedWithDirection (cause, direction); focusGained (cause); if (safePointer == nullptr) return; if (hasKeyboardFocus (false)) if (auto* handler = getAccessibilityHandler()) handler->grabFocus(); if (safePointer == nullptr) return; internalChildKeyboardFocusChange (cause, safePointer); } void Component::internalKeyboardFocusLoss (FocusChangeType cause) { const WeakReference safePointer (this); focusLost (cause); if (safePointer != nullptr) { if (auto* handler = getAccessibilityHandler()) handler->giveAwayFocus(); internalChildKeyboardFocusChange (cause, safePointer); } } void Component::internalChildKeyboardFocusChange (FocusChangeType cause, const WeakReference& safePointer) { const bool childIsNowKeyboardFocused = hasKeyboardFocus (true); if (flags.childKeyboardFocusedFlag != childIsNowKeyboardFocused) { flags.childKeyboardFocusedFlag = childIsNowKeyboardFocused; focusOfChildComponentChanged (cause); if (safePointer == nullptr) return; } if (parentComponent != nullptr) parentComponent->internalChildKeyboardFocusChange (cause, parentComponent); } void Component::setWantsKeyboardFocus (bool wantsFocus) noexcept { flags.wantsKeyboardFocusFlag = wantsFocus; } void Component::setMouseClickGrabsKeyboardFocus (bool shouldGrabFocus) { flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus; } bool Component::getMouseClickGrabsKeyboardFocus() const noexcept { return ! flags.dontFocusOnMouseClickFlag; } bool Component::getWantsKeyboardFocus() const noexcept { return flags.wantsKeyboardFocusFlag && ! flags.isDisabledFlag; } void Component::setFocusContainerType (FocusContainerType containerType) noexcept { flags.isFocusContainerFlag = (containerType == FocusContainerType::focusContainer || containerType == FocusContainerType::keyboardFocusContainer); flags.isKeyboardFocusContainerFlag = (containerType == FocusContainerType::keyboardFocusContainer); } bool Component::isFocusContainer() const noexcept { return flags.isFocusContainerFlag; } bool Component::isKeyboardFocusContainer() const noexcept { return flags.isKeyboardFocusContainerFlag; } template static Component* findContainer (const Component* child, FocusContainerFn isFocusContainer) { if (auto* parent = child->getParentComponent()) { if ((parent->*isFocusContainer)() || parent->getParentComponent() == nullptr) return parent; return findContainer (parent, isFocusContainer); } return nullptr; } Component* Component::findFocusContainer() const { return findContainer (this, &Component::isFocusContainer); } Component* Component::findKeyboardFocusContainer() const { return findContainer (this, &Component::isKeyboardFocusContainer); } static const Identifier explicitFocusOrderId ("_jexfo"); int Component::getExplicitFocusOrder() const { return properties [explicitFocusOrderId]; } void Component::setExplicitFocusOrder (int newFocusOrderIndex) { properties.set (explicitFocusOrderId, newFocusOrderIndex); } std::unique_ptr Component::createFocusTraverser() { if (flags.isFocusContainerFlag || parentComponent == nullptr) return std::make_unique(); return parentComponent->createFocusTraverser(); } std::unique_ptr Component::createKeyboardFocusTraverser() { if (flags.isKeyboardFocusContainerFlag || parentComponent == nullptr) return std::make_unique(); return parentComponent->createKeyboardFocusTraverser(); } void Component::takeKeyboardFocus (FocusChangeType cause, FocusChangeDirection direction) { if (currentlyFocusedComponent == this) return; if (auto* peer = getPeer()) { const WeakReference safePointer (this); peer->grabFocus(); if (! peer->isFocused() || currentlyFocusedComponent == this) return; WeakReference componentLosingFocus (currentlyFocusedComponent); if (auto* losingFocus = componentLosingFocus.get()) if (auto* otherPeer = losingFocus->getPeer()) otherPeer->closeInputMethodContext(); currentlyFocusedComponent = this; Desktop::getInstance().triggerFocusCallback(); // call this after setting currentlyFocusedComponent so that the one that's // losing it has a chance to see where focus is going if (componentLosingFocus != nullptr) componentLosingFocus->internalKeyboardFocusLoss (cause); if (currentlyFocusedComponent == this) internalKeyboardFocusGain (cause, safePointer, direction); } } void Component::grabKeyboardFocusInternal (FocusChangeType cause, bool canTryParent, FocusChangeDirection direction) { if (flags.dontFocusOnMouseClickFlag && cause == FocusChangeType::focusChangedByMouseClick) return; if (! isShowing()) return; if (flags.wantsKeyboardFocusFlag && (isEnabled() || parentComponent == nullptr)) { takeKeyboardFocus (cause, direction); return; } if (isParentOf (currentlyFocusedComponent) && currentlyFocusedComponent->isShowing()) return; if (auto traverser = createKeyboardFocusTraverser()) { if (auto* defaultComp = traverser->getDefaultComponent (this)) { defaultComp->grabKeyboardFocusInternal (cause, false, direction); return; } } // if no children want it and we're allowed to try our parent comp, // then pass up to parent, which will try our siblings. if (canTryParent && parentComponent != nullptr) parentComponent->grabKeyboardFocusInternal (cause, true, direction); } void Component::grabKeyboardFocus() { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED grabKeyboardFocusInternal (focusChangedDirectly, true, FocusChangeDirection::unknown); // A component can only be focused when it's actually on the screen! // If this fails then you're probably trying to grab the focus before you've // added the component to a parent or made it visible. Or maybe one of its parent // components isn't yet visible. jassert (isShowing() || isOnDesktop()); } void Component::giveAwayKeyboardFocusInternal (bool sendFocusLossEvent) { if (hasKeyboardFocus (true)) { if (auto* componentLosingFocus = currentlyFocusedComponent) { if (auto* otherPeer = componentLosingFocus->getPeer()) otherPeer->closeInputMethodContext(); currentlyFocusedComponent = nullptr; if (sendFocusLossEvent && componentLosingFocus != nullptr) componentLosingFocus->internalKeyboardFocusLoss (focusChangedDirectly); Desktop::getInstance().triggerFocusCallback(); } } } void Component::giveAwayKeyboardFocus() { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED giveAwayKeyboardFocusInternal (true); } void Component::moveKeyboardFocusToSibling (bool moveToNext) { // if component methods are being called from threads other than the message // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe. JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED if (parentComponent != nullptr) { if (auto traverser = createKeyboardFocusTraverser()) { auto findComponentToFocus = [&]() -> Component* { if (auto* comp = (moveToNext ? traverser->getNextComponent (this) : traverser->getPreviousComponent (this))) return comp; if (auto* focusContainer = findKeyboardFocusContainer()) { auto allFocusableComponents = traverser->getAllComponents (focusContainer); if (! allFocusableComponents.empty()) return moveToNext ? allFocusableComponents.front() : allFocusableComponents.back(); } return nullptr; }; if (auto* nextComp = findComponentToFocus()) { if (nextComp->isCurrentlyBlockedByAnotherModalComponent()) { const WeakReference nextCompPointer (nextComp); internalModalInputAttempt(); if (nextCompPointer == nullptr || nextComp->isCurrentlyBlockedByAnotherModalComponent()) return; } nextComp->grabKeyboardFocusInternal (focusChangedByTabKey, true, moveToNext ? FocusChangeDirection::forward : FocusChangeDirection::backward); return; } } parentComponent->moveKeyboardFocusToSibling (moveToNext); } } bool Component::hasKeyboardFocus (bool trueIfChildIsFocused) const { return (currentlyFocusedComponent == this) || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent)); } Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() noexcept { return currentlyFocusedComponent; } void JUCE_CALLTYPE Component::unfocusAllComponents() { if (currentlyFocusedComponent != nullptr) currentlyFocusedComponent->giveAwayKeyboardFocus(); } //============================================================================== bool Component::isEnabled() const noexcept { return (! flags.isDisabledFlag) && (parentComponent == nullptr || parentComponent->isEnabled()); } void Component::setEnabled (bool shouldBeEnabled) { if (flags.isDisabledFlag == shouldBeEnabled) { flags.isDisabledFlag = ! shouldBeEnabled; // if any parent components are disabled, setting our flag won't make a difference, // so no need to send a change message if (parentComponent == nullptr || parentComponent->isEnabled()) sendEnablementChangeMessage(); BailOutChecker checker (this); componentListeners.callChecked (checker, [this] (ComponentListener& l) { l.componentEnablementChanged (*this); }); if (! shouldBeEnabled && hasKeyboardFocus (true)) { if (parentComponent != nullptr) parentComponent->grabKeyboardFocus(); // ensure that keyboard focus is given away if it wasn't taken by parent giveAwayKeyboardFocus(); } } } void Component::enablementChanged() {} void Component::sendEnablementChangeMessage() { const WeakReference safePointer (this); enablementChanged(); if (safePointer == nullptr) return; for (int i = getNumChildComponents(); --i >= 0;) { if (auto* c = getChildComponent (i)) { c->sendEnablementChangeMessage(); if (safePointer == nullptr) return; } } } //============================================================================== bool Component::isMouseOver (bool includeChildren) const { if (! MessageManager::getInstance()->isThisTheMessageThread()) return flags.cachedMouseInsideComponent; for (auto& ms : Desktop::getInstance().getMouseSources()) { auto* c = ms.getComponentUnderMouse(); if (c != nullptr && (c == this || (includeChildren && isParentOf (c)))) if (ms.isDragging() || ! (ms.isTouch() || ms.isPen())) if (c->reallyContains (c->getLocalPoint (nullptr, ms.getScreenPosition()), false)) return true; } return false; } bool Component::isMouseButtonDown (bool includeChildren) const { for (auto& ms : Desktop::getInstance().getMouseSources()) { auto* c = ms.getComponentUnderMouse(); if (c == this || (includeChildren && isParentOf (c))) if (ms.isDragging()) return true; } return false; } bool Component::isMouseOverOrDragging (bool includeChildren) const { for (auto& ms : Desktop::getInstance().getMouseSources()) { auto* c = ms.getComponentUnderMouse(); if (c == this || (includeChildren && isParentOf (c))) if (ms.isDragging() || ! ms.isTouch()) return true; } return false; } bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() noexcept { return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(); } Point Component::getMouseXYRelative() const { return getLocalPoint (nullptr, Desktop::getMousePositionFloat()).roundToInt(); } //============================================================================== void Component::addKeyListener (KeyListener* newListener) { createDataIfNeeded().keyListeners.addIfNotAlreadyThere (newListener); } void Component::removeKeyListener (KeyListener* listenerToRemove) { if (componentData != nullptr) componentData->keyListeners.removeFirstMatchingValue (listenerToRemove); } bool Component::keyPressed (const KeyPress&) { return false; } bool Component::keyStateChanged (bool /*isKeyDown*/) { return false; } void Component::modifierKeysChanged (const ModifierKeys& modifiers) { if (parentComponent != nullptr) parentComponent->modifierKeysChanged (modifiers); } void Component::internalModifierKeysChanged() { sendFakeMouseMove(); modifierKeysChanged (ModifierKeys::currentModifiers); } //============================================================================== Component::BailOutChecker::BailOutChecker (Component* component) : safePointer (component) { jassert (component != nullptr); } bool Component::BailOutChecker::shouldBailOut() const noexcept { return safePointer == nullptr; } //============================================================================== void Component::setTitle (const String& newTitle) { componentTitle = newTitle; } void Component::setDescription (const String& newDescription) { componentDescription = newDescription; } void Component::setHelpText (const String& newHelpText) { componentHelpText = newHelpText; } void Component::setAccessible (bool shouldBeAccessible) { flags.accessibilityIgnoredFlag = ! shouldBeAccessible; if (flags.accessibilityIgnoredFlag) invalidateAccessibilityHandler(); } bool Component::isAccessible() const noexcept { return (! flags.accessibilityIgnoredFlag && (parentComponent == nullptr || parentComponent->isAccessible())); } std::unique_ptr Component::createAccessibilityHandler() { return std::make_unique (*this, AccessibilityRole::unspecified); } std::unique_ptr Component::createIgnoredAccessibilityHandler (Component& comp) { return std::make_unique (comp, AccessibilityRole::ignored); } void Component::invalidateAccessibilityHandler() { if (componentData != nullptr) componentData->accessibilityHandler = nullptr; } AccessibilityHandler* Component::getAccessibilityHandler() { if (! isAccessible() || getWindowHandle() == nullptr) return nullptr; auto& accessibilityHandler = createDataIfNeeded().accessibilityHandler; if (accessibilityHandler == nullptr || accessibilityHandler->getTypeIndex() != std::type_index (typeid (*this))) { accessibilityHandler = createAccessibilityHandler(); // On Android, notifying that an element was created can cause the system to request // the accessibility node info for the new element. If we're not careful, this will lead // to recursive calls, as each time an element is created, new node info will be requested, // causing an element to be created, causing a new info request... // By assigning the accessibility handler before notifying the system that an element was // created, the if() predicate above should evaluate to false on recursive calls, // terminating the recursion. if (accessibilityHandler != nullptr) detail::AccessibilityHelpers::notifyAccessibilityEvent (*accessibilityHandler, detail::AccessibilityHelpers::Event::elementCreated); else jassertfalse; // createAccessibilityHandler must return non-null } return accessibilityHandler.get(); } #if JUCE_UNIT_TESTS struct ComponentTests : public UnitTest { ComponentTests() : UnitTest ("Component", UnitTestCategories::gui) { } class TestComponent : private ComponentListener, public Component { public: TestComponent() { addComponentListener (this); } void paint (Graphics& g) override { lastClipBounds = g.getClipBounds(); ++numPaintCalls; } void paintOverChildren (Graphics&) final { ++numPaintOverChildrenCalls; } int numPaintCalls{}; int numPaintOverChildrenCalls{}; int numCacheHits{}; int numComponentPaintedCalls{}; Rectangle lastClipBounds; private: void componentPainted (Component&, const ComponentPaintDiagnostics& d) final { ++numComponentPaintedCalls; if (d.readFromCache && ! d.wroteToCache) numCacheHits += 1; } }; class RecursiveTestComponent : public TestComponent { public: void paint (Graphics& g) override { TestComponent::paint (g); if (isPainting) return; const ScopedValueSetter svs { isPainting, true }; paintEntireComponent (g, false); } private: bool isPainting{}; }; void paintComponentBounds (Component& componentToRepaint) { auto* topLevelComponent = componentToRepaint.getTopLevelComponent(); topLevelComponent->createComponentSnapshot (topLevelComponent->getLocalArea (&componentToRepaint, componentToRepaint.getLocalBounds())); } void runTest() override { ScopedJuceInitialiser_GUI libraryInitialiser; testCase ("Painting a parents bounds paints both parent and child", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child); expectEquals (parent.numPaintCalls, 0); expectEquals (parent.numPaintOverChildrenCalls, 0); expectEquals (parent.numComponentPaintedCalls, 0); expectEquals (child.numPaintCalls, 0); expectEquals (child.numPaintOverChildrenCalls, 0); expectEquals (child.numComponentPaintedCalls, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (parent.numPaintOverChildrenCalls, 1); expectEquals (parent.numComponentPaintedCalls, 1); expectEquals (child.numPaintCalls, 1); expectEquals (child.numPaintOverChildrenCalls, 1); expectEquals (child.numComponentPaintedCalls, 1); }); testCase ("Non-opaque children require their parent to repaint", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child); paintComponentBounds (child); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 1); }); testCase ("Opaque children don't require their parent to repaint", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); child.setOpaque (true); parent.addAndMakeVisible (child); paintComponentBounds (child); expectEquals (parent.numPaintCalls, 0); expectEquals (child.numPaintCalls, 1); expectEquals (parent.numPaintOverChildrenCalls, 1); }); testCase ("Opaque children don't require their parent to repaint (even when the parent uses setPaintingIsUnclipped (true))", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setPaintingIsUnclipped (true); parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); child.setOpaque (true); parent.addAndMakeVisible (child); paintComponentBounds (child); expectEquals (parent.numPaintCalls, 0); expectEquals (child.numPaintCalls, 1); expectEquals (parent.numPaintOverChildrenCalls, 1); }); testCase ("A partially obscured parent will repaint with reduced clip bounds", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.removeFromTop (50)); child.setOpaque (true); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 1); expect (parent.lastClipBounds == bounds); }); testCase ("A totally obscured parent will never repaint", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds.removeFromTop (50)); child1.setOpaque (true); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); parent.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (parent.numPaintOverChildrenCalls, 1); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 1); }); testCase ("An opaque component will hide sibling components behind it", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); parent.addAndMakeVisible (child2); child3.setBounds (bounds); parent.addAndMakeVisible (child3); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (parent.numPaintOverChildrenCalls, 1); expectEquals (child1.numPaintCalls, 0); expectEquals (child1.numPaintOverChildrenCalls, 0); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 1); }); testCase ("An opaque component will hide parent-sibling components behind it", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); parent.addAndMakeVisible (child1); child2.setBounds (bounds); parent.addAndMakeVisible (child2); child3.setBounds (bounds); child3.setOpaque (true); child2.addAndMakeVisible (child3); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (parent.numPaintOverChildrenCalls, 1); expectEquals (child1.numPaintCalls, 0); expectEquals (child1.numPaintOverChildrenCalls, 0); expectEquals (child2.numPaintCalls, 0); expectEquals (child2.numPaintOverChildrenCalls, 1); expectEquals (child3.numPaintCalls, 1); }); testCase ("An opaque component will reduce the clip bounds of sibling components behind it", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); parent.addAndMakeVisible (child1); child2.setBounds (bounds.removeFromTop (50)); child2.setOpaque (true); parent.addAndMakeVisible (child2); child3.setBounds (child1.getBounds()); parent.addAndMakeVisible (child3); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 1); expect (child1.lastClipBounds == bounds); expect (child3.lastClipBounds == child3.getBounds()); }); testCase ("A child component will be clipped when painted", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child); expect (parent.lastClipBounds.isEmpty()); expect (child.lastClipBounds.isEmpty()); paintComponentBounds (parent); expect (parent.lastClipBounds == parent.getLocalBounds()); expect (child.lastClipBounds == child.getLocalBounds()); }); testCase ("setPaintingIsUnclipped (true) will cause a child to have its parents clip bounds", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.reduced (25)); child.setPaintingIsUnclipped (true); parent.addAndMakeVisible (child); paintComponentBounds (parent); expect (child.lastClipBounds == child.getLocalArea (&parent, parent.getLocalBounds())); }); testCase ("Opaque components hide parents that use setPaintingIsUnclipped (true)", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); parent.setPaintingIsUnclipped (true); child.setBounds (bounds); child.setOpaque (true); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child.numPaintCalls, 1); }); testCase ("Invisible child components will not be considered opaque", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); child.setOpaque (true); parent.addChildComponent (child); expect (! child.isVisible()); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 0); }); testCase ("Invisible sibling components will not be considered opaque", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); parent.addChildComponent (child2); expect ( child1.isVisible()); expect (! child2.isVisible()); paintComponentBounds (parent); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 0); }); testCase ("Components with an invisible parent will not be considered opaque", [&] { TestComponent parent; TestComponent child; TestComponent grandchild; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); parent.addChildComponent (child); grandchild.setBounds (bounds); grandchild.setOpaque (true); child.addAndMakeVisible (grandchild); expect (! child.isVisible()); expect (grandchild.isVisible()); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 0); expectEquals (grandchild.numPaintCalls, 0); }); testCase ("Components with a width of 0 will not have their paint functions called", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.withWidth (0)); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 0); expectEquals (child.numPaintOverChildrenCalls, 0); }); testCase ("Components with a height of 0 will not have their paint functions called", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds.withHeight (0)); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 0); expectEquals (child.numPaintOverChildrenCalls, 0); }); testCase ("Transparent components will not be considered opaque", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); child.setOpaque (true); child.setAlpha (0.5f); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 1); }); testCase ("Opaque components will only be considered opaque up to a transparent parent", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child1.setAlpha (0.5f); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); child1.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); }); testCase ("Transformed components will not be considered opaque", [&] { TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); child.setOpaque (true); child.setTransform (AffineTransform::rotation (degreesToRadians (45.0f))); parent.addAndMakeVisible (child); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child.numPaintCalls, 1); }); testCase ("Opaque components will only be considered opaque up to a transformed parent", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child1.setTransform (AffineTransform::rotation (degreesToRadians (45.0f))); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); child1.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); }); testCase ("Nested opaque components prevent parents from being painted", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child1.setOpaque (true); parent.addAndMakeVisible (child1); child2.setBounds (bounds); child2.setOpaque (true); child1.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); }); testCase ("Areas of an opaque component outside its parent will not be considered opaque", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; parent.setBounds ({ 0, 0, 100, 100 }); child1.setBounds ({ 50, 0, 50, 100 }); parent.addAndMakeVisible (child1); child2.setBounds ({ -50, 0, 100, 100 }); child2.setOpaque (true); child1.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expect (parent.lastClipBounds == Rectangle { 0, 0, 50, 100 }); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); expect (child2.lastClipBounds == Rectangle { 50, 0, 50, 100 }); }); testCase ("Painting a component that is buffered to an image, results in a cache hit", [&] { // Note top-level components can't be buffered to an image! TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); child.setBufferedToImage (true); parent.addAndMakeVisible (child); // paint the component once first paintComponentBounds (child); expectEquals (child.numPaintCalls, 1); expectEquals (child.numCacheHits, 0); // repaint the component without invalidating it paintComponentBounds (child); expectEquals (child.numPaintCalls, 1); expectEquals (child.numCacheHits, 1); // repaint the component without invalidating it again paintComponentBounds (child); expectEquals (child.numPaintCalls, 1); expectEquals (child.numCacheHits, 2); }); testCase ("Painting a component that is buffered to an image, after calling repaint, " "results in a cache miss", [&] { // Note top-level components can't be buffered to an image! TestComponent parent; TestComponent child; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); child.setBufferedToImage (true); parent.addAndMakeVisible (child); // paint the component once first paintComponentBounds (child); expectEquals (child.numPaintCalls, 1); expectEquals (child.numCacheHits, 0); // repaint the component after invalidating it child.repaint(); paintComponentBounds (child); expectEquals (child.numPaintCalls, 2); expectEquals (child.numCacheHits, 0); // repaint the component without invalidating it paintComponentBounds (child); expectEquals (child.numPaintCalls, 2); expectEquals (child.numCacheHits, 1); }); testCase ("A component that is buffered to an image but obscured by an opaque child, " "still paints the cached image", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; TestComponent child4; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child2.setBounds (bounds); child3.setBounds (bounds); child4.setBounds (bounds); child2.setBufferedToImage (true); child3.setOpaque (true); parent.addAndMakeVisible (child1); parent.addAndMakeVisible (child2); child2.addAndMakeVisible (child3); parent.addAndMakeVisible (child4); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 0); expectEquals (child3.numPaintCalls, 1); expectEquals (child4.numPaintCalls, 1); expectEquals (child2.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 0); expectEquals (child3.numPaintCalls, 1); expectEquals (child4.numPaintCalls, 2); expectEquals (child2.numCacheHits, 1); }); testCase ("A component that is buffered to an image is obscured by an opaque component", [&] { TestComponent parent; TestComponent child1; TestComponent child2; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child2.setBounds (bounds); child1.setBufferedToImage (true); child2.setOpaque (true); parent.addAndMakeVisible (child1); parent.addAndMakeVisible (child2); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); expectEquals (child1.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 0); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 2); expectEquals (child1.numCacheHits, 0); child2.setVisible (false); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 2); expectEquals (child1.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 2); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 2); expectEquals (child1.numCacheHits, 1); }); testCase ("A component that is a child of a component buffered to an image is not " "obscured by an opaque component outside the buffered image", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child2.setBounds (bounds.reduced (25)); child3.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child1); child1.addAndMakeVisible (child2); parent.addAndMakeVisible (child3); child1.setBufferedToImage (true); child3.setOpaque (true); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 1); expectEquals (child1.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 2); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 2); expectEquals (child1.numCacheHits, 1); }); testCase ("A component that is a child of a component buffered to an image is obscured by " "an opaque component inside the buffered image", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds); child2.setBounds (bounds.reduced (25)); child3.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child1); child1.addAndMakeVisible (child2); child1.addAndMakeVisible (child3); child1.setBufferedToImage (true); child3.setOpaque (true); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 0); expectEquals (child3.numPaintCalls, 1); expectEquals (child1.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 2); expectEquals (child1.numPaintCalls, 1); expectEquals (child2.numPaintCalls, 0); expectEquals (child3.numPaintCalls, 1); expectEquals (child1.numCacheHits, 1); }); testCase ("An opaque component that is a child of a component buffered to an image " "obscures components outside the buffered image", [&] { TestComponent parent; TestComponent child1; TestComponent child2; TestComponent child3; Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child1.setBounds (bounds.reduced (25)); child2.setBounds (bounds); child3.setBounds (bounds.reduced (25)); parent.addAndMakeVisible (child1); parent.addAndMakeVisible (child2); child2.addAndMakeVisible (child3); child2.setBufferedToImage (true); child3.setOpaque (true); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 1); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 1); expectEquals (child2.numCacheHits, 0); paintComponentBounds (parent); expectEquals (parent.numPaintCalls, 2); expectEquals (child1.numPaintCalls, 0); expectEquals (child2.numPaintCalls, 1); expectEquals (child3.numPaintCalls, 1); expectEquals (child2.numCacheHits, 1); }); testCase ("Recursive paint calls trigger additional componentPainted callbacks", [&] { RecursiveTestComponent component; component.setBounds ({ 0, 0, 100, 100 }); paintComponentBounds (component); expectEquals (component.numPaintCalls, 2); expectEquals (component.numComponentPaintedCalls, 2); }); testCase ("A component cached to an image always triggers a componentPainted callback", [&] { TestComponent parent; TestComponent child; const Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); parent.addAndMakeVisible (child); child.setBufferedToImage (true); paintComponentBounds (child); expectEquals (child.numPaintCalls, 1); expectEquals (child.numComponentPaintedCalls, 1); paintComponentBounds (parent); expectEquals (child.numPaintCalls, 1); expectEquals (child.numComponentPaintedCalls, 2); }); testCase ("Recursive paint calls in a component cached to an image, " "trigger additional componentPainted callbacks when writing to the cache", [&] { TestComponent parent; RecursiveTestComponent child; const Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); child.setBounds (bounds); parent.addAndMakeVisible (child); child.setBufferedToImage (true); paintComponentBounds (child); expectEquals (child.numPaintCalls, 2); expectEquals (child.numComponentPaintedCalls, 2); paintComponentBounds (parent); expectEquals (child.numPaintCalls, 2); expectEquals (child.numComponentPaintedCalls, 3); }); testCase ("Components with an effect can be semi-transparent", [&] { TestComponent parent; TestComponent childA; TestComponent childB; GlowEffect effect; childB.setComponentEffect (&effect); childB.setAlpha (0.5f); const Rectangle bounds { 0, 0, 100, 100 }; parent.setBounds (bounds); childA.setBounds (bounds); childB.setBounds (bounds); parent.addAndMakeVisible (childA); parent.addAndMakeVisible (childB); paintComponentBounds (childB); expectEquals (parent.numPaintCalls, 1); expectEquals (childA.numPaintCalls, 1); expectEquals (childB.numPaintCalls, 1); }); testCase ("A mouse event retargeted to a surviving ancestor has its positions converted into that ancestor's space", [&] { const Rectangle parentBounds { 50, 50, 100, 100 }; const Rectangle childBounds { 20, 20, 40, 40 }; const Point positionInChild { 5.0f, 7.0f }; const Point mouseDownPositionInChild { 1.0f, 2.0f }; auto parent = std::make_unique(); auto child = std::make_unique(); parent->setBounds (parentBounds); child->setBounds (childBounds); parent->addAndMakeVisible (*child); const auto time = Time::getCurrentTime(); const MouseEvent event { Desktop::getInstance().getMainMouseSource(), positionInChild, ModifierKeys::leftButtonModifier, MouseInputSource::defaultPressure, MouseInputSource::defaultOrientation, MouseInputSource::defaultRotation, MouseInputSource::defaultTiltX, MouseInputSource::defaultTiltY, child.get(), child.get(), time, mouseDownPositionInChild, time, 1, false }; Component::SafePointer target { child.get() }; HierarchyChecker checker (&target, event); expect (! checker.shouldBailOut()); expect (target == child.get()); const auto unchanged = checker.eventWithNearestParent(); expect (unchanged.eventComponent == child.get()); expect (unchanged.position == positionInChild); expect (unchanged.mouseDownPosition == mouseDownPositionInChild); child.reset(); expect (! checker.shouldBailOut()); expect (target == parent.get()); const auto retargeted = checker.eventWithNearestParent(); expect (retargeted.eventComponent == parent.get()); expect (retargeted.originalComponent == parent.get()); expect (retargeted.position == positionInChild + childBounds.getPosition().toFloat()); expect (retargeted.mouseDownPosition == mouseDownPositionInChild + childBounds.getPosition().toFloat()); parent.reset(); expect (checker.shouldBailOut()); expect (target == nullptr); }); } }; static ComponentTests componentTests; #endif } // namespace juce