diff --git a/abstract_client.h b/abstract_client.h index 1b7cbb746..078021b3f 100644 --- a/abstract_client.h +++ b/abstract_client.h @@ -1,1263 +1,1263 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_ABSTRACT_CLIENT_H #define KWIN_ABSTRACT_CLIENT_H #include "toplevel.h" #include "options.h" #include "rules.h" #include "tabgroup.h" #include "cursor.h" #include #include #include namespace KWayland { namespace Server { class PlasmaWindowInterface; } } namespace KDecoration2 { class Decoration; } namespace KWin { namespace TabBox { class TabBoxClientImpl; } namespace Decoration { class DecoratedClientImpl; class DecorationPalette; } class KWIN_EXPORT AbstractClient : public Toplevel { Q_OBJECT /** * Whether this Client is fullScreen. A Client might either be fullScreen due to the _NET_WM property * or through a legacy support hack. The fullScreen state can only be changed if the Client does not * use the legacy hack. To be sure whether the state changed, connect to the notify signal. **/ Q_PROPERTY(bool fullScreen READ isFullScreen WRITE setFullScreen NOTIFY fullScreenChanged) /** * Whether the Client can be set to fullScreen. The property is evaluated each time it is invoked. * Because of that there is no notify signal. **/ Q_PROPERTY(bool fullScreenable READ isFullScreenable) /** * Whether this Client is the currently visible Client in its Client Group (Window Tabs). * For change connect to the visibleChanged signal on the Client's Group. **/ Q_PROPERTY(bool isCurrentTab READ isCurrentTab) /** * Whether this Client is active or not. Use Workspace::activateClient() to activate a Client. * @see Workspace::activateClient **/ Q_PROPERTY(bool active READ isActive NOTIFY activeChanged) /** * The desktop this Client is on. If the Client is on all desktops the property has value -1. * This is a legacy property, use x11DesktopIds instead **/ Q_PROPERTY(int desktop READ desktop WRITE setDesktop NOTIFY desktopChanged) /** * Whether the Client is on all desktops. That is desktop is -1. **/ Q_PROPERTY(bool onAllDesktops READ isOnAllDesktops WRITE setOnAllDesktops NOTIFY desktopChanged) /** * The x11 ids for all desktops this client is in. On X11 this list will always have a length of 1 **/ Q_PROPERTY(QVector x11DesktopIds READ x11DesktopIds NOTIFY x11DesktopIdsChanged) /** * Indicates that the window should not be included on a taskbar. **/ Q_PROPERTY(bool skipTaskbar READ skipTaskbar WRITE setSkipTaskbar NOTIFY skipTaskbarChanged) /** * Indicates that the window should not be included on a Pager. **/ Q_PROPERTY(bool skipPager READ skipPager WRITE setSkipPager NOTIFY skipPagerChanged) /** * Whether the Client should be excluded from window switching effects. **/ Q_PROPERTY(bool skipSwitcher READ skipSwitcher WRITE setSkipSwitcher NOTIFY skipSwitcherChanged) /** * Whether the window can be closed by the user. The value is evaluated each time the getter is called. * Because of that no changed signal is provided. **/ Q_PROPERTY(bool closeable READ isCloseable) Q_PROPERTY(QIcon icon READ icon NOTIFY iconChanged) /** * Whether the Client is set to be kept above other windows. **/ Q_PROPERTY(bool keepAbove READ keepAbove WRITE setKeepAbove NOTIFY keepAboveChanged) /** * Whether the Client is set to be kept below other windows. **/ Q_PROPERTY(bool keepBelow READ keepBelow WRITE setKeepBelow NOTIFY keepBelowChanged) /** * Whether the Client can be shaded. The property is evaluated each time it is invoked. * Because of that there is no notify signal. **/ Q_PROPERTY(bool shadeable READ isShadeable) /** * Whether the Client is shaded. **/ Q_PROPERTY(bool shade READ isShade WRITE setShade NOTIFY shadeChanged) /** * Whether the Client can be minimized. The property is evaluated each time it is invoked. * Because of that there is no notify signal. **/ Q_PROPERTY(bool minimizable READ isMinimizable) /** * Whether the Client is minimized. **/ Q_PROPERTY(bool minimized READ isMinimized WRITE setMinimized NOTIFY minimizedChanged) /** * The optional geometry representing the minimized Client in e.g a taskbar. * See _NET_WM_ICON_GEOMETRY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . * The value is evaluated each time the getter is called. * Because of that no changed signal is provided. **/ Q_PROPERTY(QRect iconGeometry READ iconGeometry) /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. * The value is evaluated each time the getter is called. * Because of that no changed signal is provided. **/ Q_PROPERTY(bool specialWindow READ isSpecialWindow) /** * Whether window state _NET_WM_STATE_DEMANDS_ATTENTION is set. This state indicates that some * action in or with the window happened. For example, it may be set by the Window Manager if * the window requested activation but the Window Manager refused it, or the application may set * it if it finished some work. This state may be set by both the Client and the Window Manager. * It should be unset by the Window Manager when it decides the window got the required attention * (usually, that it got activated). **/ Q_PROPERTY(bool demandsAttention READ isDemandingAttention WRITE demandAttention NOTIFY demandsAttentionChanged) /** * The Caption of the Client. Read from WM_NAME property together with a suffix for hostname and shortcut. * To read only the caption as provided by WM_NAME, use the getter with an additional @c false value. **/ Q_PROPERTY(QString caption READ caption NOTIFY captionChanged) /** * Minimum size as specified in WM_NORMAL_HINTS **/ Q_PROPERTY(QSize minSize READ minSize) /** * Maximum size as specified in WM_NORMAL_HINTS **/ Q_PROPERTY(QSize maxSize READ maxSize) /** * Whether the Client can accept keyboard focus. * The value is evaluated each time the getter is called. * Because of that no changed signal is provided. **/ Q_PROPERTY(bool wantsInput READ wantsInput) /** * Whether the Client is a transient Window to another Window. * @see transientFor **/ Q_PROPERTY(bool transient READ isTransient NOTIFY transientChanged) /** * The Client to which this Client is a transient if any. **/ Q_PROPERTY(KWin::AbstractClient *transientFor READ transientFor NOTIFY transientChanged) /** * Whether the Client represents a modal window. **/ Q_PROPERTY(bool modal READ isModal NOTIFY modalChanged) /** * The geometry of this Client. Be aware that depending on resize mode the geometryChanged signal * might be emitted at each resize step or only at the end of the resize operation. **/ Q_PROPERTY(QRect geometry READ geometry WRITE setGeometry) /** * Whether the Client is currently being moved by the user. * Notify signal is emitted when the Client starts or ends move/resize mode. **/ Q_PROPERTY(bool move READ isMove NOTIFY moveResizedChanged) /** * Whether the Client is currently being resized by the user. * Notify signal is emitted when the Client starts or ends move/resize mode. **/ Q_PROPERTY(bool resize READ isResize NOTIFY moveResizedChanged) /** * Whether the decoration is currently using an alpha channel. **/ Q_PROPERTY(bool decorationHasAlpha READ decorationHasAlpha) /** * Whether the window has a decoration or not. * This property is not allowed to be set by applications themselves. * The decision whether a window has a border or not belongs to the window manager. * If this property gets abused by application developers, it will be removed again. **/ Q_PROPERTY(bool noBorder READ noBorder WRITE setNoBorder) /** * Whether the Client provides context help. Mostly needed by decorations to decide whether to * show the help button or not. **/ Q_PROPERTY(bool providesContextHelp READ providesContextHelp CONSTANT) /** * Whether the Client can be maximized both horizontally and vertically. * The property is evaluated each time it is invoked. * Because of that there is no notify signal. **/ Q_PROPERTY(bool maximizable READ isMaximizable) /** * Whether the Client is moveable. Even if it is not moveable, it might be possible to move * it to another screen. The property is evaluated each time it is invoked. * Because of that there is no notify signal. * @see moveableAcrossScreens **/ Q_PROPERTY(bool moveable READ isMovable) /** * Whether the Client can be moved to another screen. The property is evaluated each time it is invoked. * Because of that there is no notify signal. * @see moveable **/ Q_PROPERTY(bool moveableAcrossScreens READ isMovableAcrossScreens) /** * Whether the Client can be resized. The property is evaluated each time it is invoked. * Because of that there is no notify signal. **/ Q_PROPERTY(bool resizeable READ isResizable) /** * The desktop file name of the application this AbstractClient belongs to. * * This is either the base name without full path and without file extension of the * desktop file for the window's application (e.g. "org.kde.foo"). * * The application's desktop file name can also be the full path to the desktop file * (e.g. "/opt/kde/share/org.kde.foo.desktop") in case it's not in a standard location. **/ Q_PROPERTY(QByteArray desktopFileName READ desktopFileName NOTIFY desktopFileNameChanged) /** * Whether an application menu is available for this Client */ Q_PROPERTY(bool hasApplicationMenu READ hasApplicationMenu NOTIFY hasApplicationMenuChanged) /** * Whether the application menu for this Client is currently opened */ Q_PROPERTY(bool applicationMenuActive READ applicationMenuActive NOTIFY applicationMenuActiveChanged) /** * Whether this client is unresponsive. * * When an application failed to react on a ping request in time, it is * considered unresponsive. This usually indicates that the application froze or crashed. */ Q_PROPERTY(bool unresponsive READ unresponsive NOTIFY unresponsiveChanged) /** * The "Window Tabs" Group this Client belongs to. **/ Q_PROPERTY(KWin::TabGroup* tabGroup READ tabGroup NOTIFY tabGroupChanged SCRIPTABLE false) /** * The color scheme set on this client * Absolute file path, or name of palette in the user's config directory following KColorSchemes format. * An empty string indicates the default palette from kdeglobals is used. - * @Note this indicates the colour scheme requested, which might differ from the theme applied if the colorScheme cannot be found + * @note this indicates the colour scheme requested, which might differ from the theme applied if the colorScheme cannot be found */ Q_PROPERTY(QString colorScheme READ colorScheme NOTIFY colorSchemeChanged) public: virtual ~AbstractClient(); QWeakPointer tabBoxClient() const { return m_tabBoxClient.toWeakRef(); } bool isFirstInTabBox() const { return m_firstInTabBox; } bool skipSwitcher() const { return m_skipSwitcher; } void setSkipSwitcher(bool set); bool skipTaskbar() const { return m_skipTaskbar; } void setSkipTaskbar(bool set); void setOriginalSkipTaskbar(bool set); bool originalSkipTaskbar() const { return m_originalSkipTaskbar; } bool skipPager() const { return m_skipPager; } void setSkipPager(bool set); const QIcon &icon() const { return m_icon; } bool isActive() const { return m_active; } /** * Sets the client's active state to \a act. * * This function does only change the visual appearance of the client, * it does not change the focus setting. Use * Workspace::activateClient() or Workspace::requestFocus() instead. * * If a client receives or looses the focus, it calls setActive() on * its own. **/ void setActive(bool); bool keepAbove() const { return m_keepAbove; } void setKeepAbove(bool); bool keepBelow() const { return m_keepBelow; } void setKeepBelow(bool); void demandAttention(bool set = true); bool isDemandingAttention() const { return m_demandsAttention; } void cancelAutoRaise(); bool wantsTabFocus() const; QPoint clientPos() const override { return QPoint(borderLeft(), borderTop()); } virtual void updateMouseGrab(); /** * @returns The caption consisting of @link{captionNormal} and @link{captionSuffix} * @see captionNormal * @see captionSuffix **/ QString caption() const; /** * @returns The caption as set by the AbstractClient without any suffix. * @see caption * @see captionSuffix **/ virtual QString captionNormal() const = 0; /** * @returns The suffix added to the caption (e.g. shortcut, machine name, etc.) * @see caption * @see captionNormal **/ virtual QString captionSuffix() const = 0; virtual bool isCloseable() const = 0; // TODO: remove boolean trap virtual bool isShown(bool shaded_is_shown) const = 0; virtual bool isHiddenInternal() const = 0; // TODO: remove boolean trap virtual void hideClient(bool hide) = 0; bool isFullScreenable() const; bool isFullScreenable(bool fullscreen_hack) const; virtual bool isFullScreen() const = 0; // TODO: remove boolean trap virtual AbstractClient *findModal(bool allow_itself = false) = 0; virtual bool isTransient() const; /** * @returns Whether there is a hint available to place the AbstractClient on it's parent, default @c false. * @see transientPlacementHint **/ virtual bool hasTransientPlacementHint() const; /** * Only valid id hasTransientPlacementHint is true * @returns The position the transient wishes to position itself **/ virtual QRect transientPlacement(const QRect &bounds) const; const AbstractClient* transientFor() const; AbstractClient* transientFor(); /** * @returns @c true if c is the transient_for window for this client, * or recursively the transient_for window * @todo: remove boolean trap **/ virtual bool hasTransient(const AbstractClient* c, bool indirect) const; const QList& transients() const; // Is not indirect virtual void removeTransient(AbstractClient* cl); virtual QList mainClients() const; // Call once before loop , is not indirect QList allMainClients() const; // Call once before loop , is indirect /** * Returns true for "special" windows and false for windows which are "normal" * (normal=window which has a border, can be moved by the user, can be closed, etc.) * true for Desktop, Dock, Splash, Override and TopMenu (and Toolbar??? - for now) * false for Normal, Dialog, Utility and Menu (and Toolbar??? - not yet) TODO */ bool isSpecialWindow() const; void sendToScreen(int screen); const QKeySequence &shortcut() const { return _shortcut; } void setShortcut(const QString &cut); virtual bool performMouseCommand(Options::MouseCommand, const QPoint &globalPos); void setOnAllDesktops(bool set); void setDesktop(int); void enterDesktop(VirtualDesktop *desktop); void leaveDesktop(VirtualDesktop *desktop); void setDesktops(QVector desktops); int desktop() const override { return m_desktops.isEmpty() ? (int)NET::OnAllDesktops : m_desktops.last()->x11DesktopNumber(); } virtual QVector desktops() const { return m_desktops; } QVector x11DesktopIds() const; void setMinimized(bool set); /** * Minimizes this client plus its transients */ void minimize(bool avoid_animation = false); void unminimize(bool avoid_animation = false); bool isMinimized() const { return m_minimized; } virtual void setFullScreen(bool set, bool user = true) = 0; // Tabbing functions Q_INVOKABLE inline bool tabBefore(AbstractClient *other, bool activate) { return tabTo(other, false, activate); } Q_INVOKABLE inline bool tabBehind(AbstractClient *other, bool activate) { return tabTo(other, true, activate); } /** - * Syncs the *dynamic* @param property @param fromThisClient or the @link currentTab() to - * all members of the @link tabGroup() (if there is one) + * Syncs the *dynamic* @param property @param fromThisClient or the currentTab() to + * all members of the tabGroup() (if there is one) * * eg. if you call: * client->setProperty("kwin_tiling_floats", true); * client->syncTabGroupFor("kwin_tiling_floats", true) * all clients in this tabGroup will have ::property("kwin_tiling_floats").toBool() == true * * WARNING: non dynamic properties are ignored - you're not supposed to alter/update such explicitly */ Q_INVOKABLE void syncTabGroupFor(QString property, bool fromThisClient = false); TabGroup *tabGroup() const; /** * Set tab group - this is to be invoked by TabGroup::add/remove(client) and NO ONE ELSE */ void setTabGroup(TabGroup* group); virtual void setClientShown(bool shown); Q_INVOKABLE bool untab(const QRect &toGeometry = QRect(), bool clientRemoved = false); /* * When a click is done in the decoration and it calls the group * to change the visible client it starts to move-resize the new * client, this function stops it. */ bool isCurrentTab() const; virtual QRect geometryRestore() const = 0; /** * The currently applied maximize mode */ virtual MaximizeMode maximizeMode() const = 0; /** * The maximise mode requested by the server. * For X this always matches maximizeMode, for wayland clients it * is asyncronous */ virtual MaximizeMode requestedMaximizeMode() const; void maximize(MaximizeMode); void setMaximize(bool vertically, bool horizontally); virtual bool noBorder() const = 0; virtual void setNoBorder(bool set) = 0; virtual void blockActivityUpdates(bool b = true) = 0; QPalette palette() const; const Decoration::DecorationPalette *decorationPalette() const; virtual bool isResizable() const = 0; virtual bool isMovable() const = 0; virtual bool isMovableAcrossScreens() const = 0; /** * @c true only for @c ShadeNormal **/ bool isShade() const { return shadeMode() == ShadeNormal; } /** * Default implementation returns @c ShadeNone **/ virtual ShadeMode shadeMode() const; // Prefer isShade() void setShade(bool set); /** * Default implementation does nothing **/ virtual void setShade(ShadeMode mode); /** * Whether the Client can be shaded. Default implementation returns @c false. **/ virtual bool isShadeable() const; virtual bool isMaximizable() const = 0; virtual bool isMinimizable() const = 0; virtual QRect iconGeometry() const; virtual bool userCanSetFullScreen() const = 0; virtual bool userCanSetNoBorder() const = 0; virtual void checkNoBorder(); virtual void setOnActivities(QStringList newActivitiesList); virtual void setOnAllActivities(bool set) = 0; const WindowRules* rules() const { return &m_rules; } void removeRule(Rules* r); void setupWindowRules(bool ignore_temporary); void evaluateWindowRules(); void applyWindowRules(); virtual void takeFocus() = 0; virtual bool wantsInput() const = 0; /** * Whether a dock window wants input. * * By default KWin doesn't pass focus to a dock window unless a force activate * request is provided. * * This method allows to have dock windows take focus also through flags set on * the window. * * The default implementation returns @c false. **/ virtual bool dockWantsInput() const; void checkWorkspacePosition(QRect oldGeometry = QRect(), int oldDesktop = -2, QRect oldClientGeometry = QRect()); virtual xcb_timestamp_t userTime() const; virtual void updateWindowRules(Rules::Types selection); void growHorizontal(); void shrinkHorizontal(); void growVertical(); void shrinkVertical(); void updateMoveResize(const QPointF ¤tGlobalCursor); /** * Ends move resize when all pointer buttons are up again. **/ void endMoveResize(); void keyPressEvent(uint key_code); void enterEvent(const QPoint &globalPos); void leaveEvent(); /** * These values represent positions inside an area */ enum Position { // without prefix, they'd conflict with Qt::TopLeftCorner etc. :( PositionCenter = 0x00, PositionLeft = 0x01, PositionRight = 0x02, PositionTop = 0x04, PositionBottom = 0x08, PositionTopLeft = PositionLeft | PositionTop, PositionTopRight = PositionRight | PositionTop, PositionBottomLeft = PositionLeft | PositionBottom, PositionBottomRight = PositionRight | PositionBottom }; Position titlebarPosition() const; bool titlebarPositionUnderMouse() const; // a helper for the workspace window packing. tests for screen validity and updates since in maximization case as with normal moving void packTo(int left, int top); /** Set the quick tile mode ("snap") of this window. * This will also handle preserving and restoring of window geometry as necessary. * @param mode The tile mode (left/right) to give this window. */ void setQuickTileMode(QuickTileMode mode, bool keyboard = false); QuickTileMode quickTileMode() const { return QuickTileMode(m_quickTileMode); } Layer layer() const override; void updateLayer(); enum ForceGeometry_t { NormalGeometrySet, ForceGeometrySet }; void move(int x, int y, ForceGeometry_t force = NormalGeometrySet); void move(const QPoint &p, ForceGeometry_t force = NormalGeometrySet); virtual void resizeWithChecks(int w, int h, ForceGeometry_t force = NormalGeometrySet) = 0; void resizeWithChecks(const QSize& s, ForceGeometry_t force = NormalGeometrySet); void keepInArea(QRect area, bool partial = false); virtual QSize minSize() const; virtual QSize maxSize() const; virtual void setGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) = 0; void setGeometry(const QRect& r, ForceGeometry_t force = NormalGeometrySet); /// How to resize the window in order to obey constains (mainly aspect ratios) enum Sizemode { SizemodeAny, SizemodeFixedW, ///< Try not to affect width SizemodeFixedH, ///< Try not to affect height SizemodeMax ///< Try not to make it larger in either direction }; /** *Calculate the appropriate frame size for the given client size @p wsize. * * @p wsize is adapted according to the window's size hints (minimum, maximum and incremental size changes). * * Default implementation returns the passed in @p wsize. */ virtual QSize sizeForClientSize(const QSize &wsize, Sizemode mode = SizemodeAny, bool noframe = false) const; QSize adjustedSize(const QSize&, Sizemode mode = SizemodeAny) const; QSize adjustedSize() const; bool isMove() const { return isMoveResize() && moveResizePointerMode() == PositionCenter; } bool isResize() const { return isMoveResize() && moveResizePointerMode() != PositionCenter; } /** * Cursor shape for move/resize mode. **/ CursorShape cursor() const { return m_moveResize.cursor; } virtual bool hasStrut() const; void setModal(bool modal); bool isModal() const; /** * Determines the mouse command for the given @p button in the current state. * * The @p handled argument specifies whether the button was handled or not. * This value should be used to determine whether the mouse button should be * passed to the AbstractClient or being filtered out. **/ Options::MouseCommand getMouseCommand(Qt::MouseButton button, bool *handled) const; Options::MouseCommand getWheelCommand(Qt::Orientation orientation, bool *handled) const; // decoration related KDecoration2::Decoration *decoration() { return m_decoration.decoration; } const KDecoration2::Decoration *decoration() const { return m_decoration.decoration; } bool isDecorated() const { return m_decoration.decoration != nullptr; } QPointer decoratedClient() const; void setDecoratedClient(QPointer client); bool decorationHasAlpha() const; void triggerDecorationRepaint(); virtual void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const; void processDecorationMove(const QPoint &localPos, const QPoint &globalPos); bool processDecorationButtonPress(QMouseEvent *event, bool ignoreMenu = false); void processDecorationButtonRelease(QMouseEvent *event); /** * TODO: fix boolean traps **/ virtual void updateDecoration(bool check_workspace_pos, bool force = false) = 0; /** * Returns whether the window provides context help or not. If it does, * you should show a help menu item or a help button like '?' and call * contextHelp() if this is invoked. * * Default implementation returns @c false. * @see showContextHelp; */ virtual bool providesContextHelp() const; /** * Invokes context help on the window. Only works if the window * actually provides context help. * * Default implementation does nothing. * * @see providesContextHelp() */ virtual void showContextHelp(); QRect inputGeometry() const override; /** * Restores the AbstractClient after it had been hidden due to show on screen edge functionality. * The AbstractClient also gets raised (e.g. Panel mode windows can cover) and the AbstractClient * gets informed in a window specific way that it is shown and raised again. **/ virtual void showOnScreenEdge() = 0; QByteArray desktopFileName() const { return m_desktopFileName; } /** * Tries to terminate the process of this AbstractClient. * * Implementing subclasses can perform a windowing system solution for terminating. **/ virtual void killWindow() = 0; enum class SameApplicationCheck { RelaxedForActive = 1 << 0, AllowCrossProcesses = 1 << 1 }; Q_DECLARE_FLAGS(SameApplicationChecks, SameApplicationCheck) static bool belongToSameApplication(const AbstractClient* c1, const AbstractClient* c2, SameApplicationChecks checks = SameApplicationChecks()); bool hasApplicationMenu() const; bool applicationMenuActive() const { return m_applicationMenuActive; } void setApplicationMenuActive(bool applicationMenuActive); QString applicationMenuServiceName() const { return m_applicationMenuServiceName; } QString applicationMenuObjectPath() const { return m_applicationMenuObjectPath; } QString colorScheme() const { return m_colorScheme; } /** * Request showing the application menu bar * @param actionId The DBus menu ID of the action that should be highlighted, 0 for the root menu */ void showApplicationMenu(int actionId); bool unresponsive() const; virtual bool isInitialPositionSet() const { return false; } public Q_SLOTS: virtual void closeWindow() = 0; Q_SIGNALS: void fullScreenChanged(); void skipTaskbarChanged(); void skipPagerChanged(); void skipSwitcherChanged(); void iconChanged(); void activeChanged(); void keepAboveChanged(bool); void keepBelowChanged(bool); /** * Emitted whenever the demands attention state changes. **/ void demandsAttentionChanged(); void desktopPresenceChanged(KWin::AbstractClient*, int); // to be forwarded by Workspace void desktopChanged(); void x11DesktopIdsChanged(); void shadeChanged(); void minimizedChanged(); void clientMinimized(KWin::AbstractClient* client, bool animate); void clientUnminimized(KWin::AbstractClient* client, bool animate); void paletteChanged(const QPalette &p); void colorSchemeChanged(); void captionChanged(); void clientMaximizedStateChanged(KWin::AbstractClient*, MaximizeMode); void clientMaximizedStateChanged(KWin::AbstractClient* c, bool h, bool v); void transientChanged(); void modalChanged(); void quickTileModeChanged(); void moveResizedChanged(); void moveResizeCursorChanged(CursorShape); void clientStartUserMovedResized(KWin::AbstractClient*); void clientStepUserMovedResized(KWin::AbstractClient *, const QRect&); void clientFinishUserMovedResized(KWin::AbstractClient*); void closeableChanged(bool); void minimizeableChanged(bool); void shadeableChanged(bool); void maximizeableChanged(bool); void desktopFileNameChanged(); void hasApplicationMenuChanged(bool); void applicationMenuActiveChanged(bool); void unresponsiveChanged(bool); /** * Emitted whenever the Client's TabGroup changed. That is whenever the Client is moved to * another group, but not when a Client gets added or removed to the Client's ClientGroup. **/ void tabGroupChanged(); protected: AbstractClient(); void setFirstInTabBox(bool enable) { m_firstInTabBox = enable; } void setIcon(const QIcon &icon); void startAutoRaise(); void autoRaise(); /** * Whether the window accepts focus. * The difference to wantsInput is that the implementation should not check rules and return * what the window effectively supports. **/ virtual bool acceptsFocus() const = 0; /** - * Called from ::setActive once the active value got updated, but before the changed signal + * Called from setActive once the active value got updated, but before the changed signal * is emitted. * * Default implementation does nothing. **/ virtual void doSetActive(); /** - * Called from ::setKeepAbove once the keepBelow value got updated, but before the changed signal + * Called from setKeepAbove once the keepBelow value got updated, but before the changed signal * is emitted. * * Default implementation does nothing. **/ virtual void doSetKeepAbove(); /** - * Called from ::setKeepBelow once the keepBelow value got updated, but before the changed signal + * Called from setKeepBelow once the keepBelow value got updated, but before the changed signal * is emitted. * * Default implementation does nothing. **/ virtual void doSetKeepBelow(); /** - * Called from ::setDeskop once the desktop value got updated, but before the changed signal + * Called from setDeskop once the desktop value got updated, but before the changed signal * is emitted. * * Default implementation does nothing. * @param desktop The new desktop the Client is on * @param was_desk The desktop the Client was on before **/ virtual void doSetDesktop(int desktop, int was_desk); /** - * Called from ::minimize and ::unminimize once the minimized value got updated, but before the + * Called from @ref minimize and @ref unminimize once the minimized value got updated, but before the * changed signal is emitted. * * Default implementation does nothig. **/ virtual void doMinimize(); virtual bool belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const = 0; virtual void doSetSkipTaskbar(); virtual void doSetSkipPager(); virtual void doSetSkipSwitcher(); void setupWindowManagementInterface(); void destroyWindowManagementInterface(); void updateColorScheme(QString path); virtual void updateColorScheme() = 0; void setTransientFor(AbstractClient *transientFor); virtual void addTransient(AbstractClient* cl); /** * Just removes the @p cl from the transients without any further checks. **/ void removeTransientFromList(AbstractClient* cl); Layer belongsToLayer() const; virtual bool belongsToDesktop() const; void invalidateLayer(); bool isActiveFullScreen() const; virtual Layer layerForDock() const; // electric border / quick tiling void setElectricBorderMode(QuickTileMode mode); QuickTileMode electricBorderMode() const { return m_electricMode; } void setElectricBorderMaximizing(bool maximizing); bool isElectricBorderMaximizing() const { return m_electricMaximizing; } QRect electricBorderMaximizeGeometry(QPoint pos, int desktop); void updateQuickTileMode(QuickTileMode newMode) { m_quickTileMode = newMode; } KWayland::Server::PlasmaWindowInterface *windowManagementInterface() const { return m_windowManagementInterface; } // geometry handling void checkOffscreenPosition(QRect *geom, const QRect &screenArea); int borderLeft() const; int borderRight() const; int borderTop() const; int borderBottom() const; virtual void changeMaximize(bool horizontal, bool vertical, bool adjust) = 0; virtual void setGeometryRestore(const QRect &geo) = 0; /** * Called from move after updating the geometry. Can be reimplemented to perform specific tasks. * The base implementation does nothing. **/ virtual void doMove(int x, int y); void blockGeometryUpdates(bool block); void blockGeometryUpdates(); void unblockGeometryUpdates(); bool areGeometryUpdatesBlocked() const; enum PendingGeometry_t { PendingGeometryNone, PendingGeometryNormal, PendingGeometryForced }; PendingGeometry_t pendingGeometryUpdate() const; void setPendingGeometryUpdate(PendingGeometry_t update); QRect geometryBeforeUpdateBlocking() const { return m_geometryBeforeUpdateBlocking; } void updateGeometryBeforeUpdateBlocking(); /** * Schedules a repaint for the visibleRect before and after a * geometry update. The current visibleRect is stored for the * next time this method is called as the before geometry. **/ void addRepaintDuringGeometryUpdates(); /** * Convenient method to update the TabGroup states if there is one present. * Marked as virtual as TabGroup does not yet handle AbstractClient, but only * subclasses of AbstractClient. Given that the default implementation does nothing. **/ virtual void updateTabGroupStates(TabGroup::States states); /** * @returns whether the Client is currently in move resize mode **/ bool isMoveResize() const { return m_moveResize.enabled; } /** * Sets whether the Client is in move resize mode to @p enabled. **/ void setMoveResize(bool enabled) { m_moveResize.enabled = enabled; } /** * @returns whether the move resize mode is unrestricted. **/ bool isUnrestrictedMoveResize() const { return m_moveResize.unrestricted; } /** * Sets whether move resize mode is unrestricted to @p set. **/ void setUnrestrictedMoveResize(bool set) { m_moveResize.unrestricted = set; } QPoint moveOffset() const { return m_moveResize.offset; } void setMoveOffset(const QPoint &offset) { m_moveResize.offset = offset; } QPoint invertedMoveOffset() const { return m_moveResize.invertedOffset; } void setInvertedMoveOffset(const QPoint &offset) { m_moveResize.invertedOffset = offset; } QRect initialMoveResizeGeometry() const { return m_moveResize.initialGeometry; } /** * Sets the initial move resize geometry to the current geometry. **/ void updateInitialMoveResizeGeometry(); QRect moveResizeGeometry() const { return m_moveResize.geometry; } void setMoveResizeGeometry(const QRect &geo) { m_moveResize.geometry = geo; } Position moveResizePointerMode() const { return m_moveResize.pointer; } void setMoveResizePointerMode(Position mode) { m_moveResize.pointer = mode; } bool isMoveResizePointerButtonDown() const { return m_moveResize.buttonDown; } void setMoveResizePointerButtonDown(bool down) { m_moveResize.buttonDown = down; } int moveResizeStartScreen() const { return m_moveResize.startScreen; } void checkUnrestrictedMoveResize(); /** * Sets an appropriate cursor shape for the logical mouse position. */ void updateCursor(); void startDelayedMoveResize(); void stopDelayedMoveResize(); bool startMoveResize(); /** - * Called from @link startMoveResize. + * Called from startMoveResize. * * Implementing classes should return @c false if starting move resize should * get aborted. In that case @link startMoveResize will also return @c false. * * Base implementation returns @c true. **/ virtual bool doStartMoveResize(); void finishMoveResize(bool cancel); /** * Leaves the move resize mode. * * Inheriting classes must invoke the base implementation which * ensures that the internal mode is properly ended. **/ virtual void leaveMoveResize(); virtual void positionGeometryTip(); void performMoveResize(); /** * Called from performMoveResize() after actually performing the change of geometry. * Implementing subclasses can perform windowing system specific handling here. * * Default implementation does nothing. **/ virtual void doPerformMoveResize(); /* * Checks if the mouse cursor is near the edge of the screen and if so * activates quick tiling or maximization */ void checkQuickTilingMaximizationZones(int xroot, int yroot); /** * Whether a sync request is still pending. * Default implementation returns @c false. **/ virtual bool isWaitingForMoveResizeSync() const; /** * Called during handling a resize. Implementing subclasses can use this * method to perform windowing system specific syncing. * * Default implementation does nothing. **/ virtual void doResizeSync(); void handleMoveResize(int x, int y, int x_root, int y_root); void handleMoveResize(const QPoint &local, const QPoint &global); void dontMoveResize(); virtual QSize resizeIncrements() const; /** * Returns the position depending on the Decoration's section under mouse. * If no decoration it returns PositionCenter. **/ Position mousePosition() const; static bool haveResizeEffect() { return s_haveResizeEffect; } static void updateHaveResizeEffect(); static void resetHaveResizeEffect() { s_haveResizeEffect = false; } void setDecoration(KDecoration2::Decoration *decoration) { m_decoration.decoration = decoration; } virtual void destroyDecoration(); void startDecorationDoubleClickTimer(); void invalidateDecorationDoubleClickTimer(); void setDesktopFileName(QByteArray name); QString iconFromDesktopFile() const; void updateApplicationMenuServiceName(const QString &serviceName); void updateApplicationMenuObjectPath(const QString &objectPath); void setUnresponsive(bool unresponsive); virtual void setShortcutInternal(); QString shortcutCaptionSuffix() const; virtual void updateCaption() = 0; /** * Looks for another AbstractClient with same @link{captionNormal} and @link{captionSuffix}. * If no such AbstractClient exists @c nullptr is returned. **/ AbstractClient *findClientWithSameCaption() const; void finishWindowRules(); void discardTemporaryRules(); bool tabTo(AbstractClient *other, bool behind, bool activate); private: void handlePaletteChange(); QSharedPointer m_tabBoxClient; bool m_firstInTabBox = false; bool m_skipTaskbar = false; /** * Unaffected by KWin **/ bool m_originalSkipTaskbar = false; bool m_skipPager = false; bool m_skipSwitcher = false; QIcon m_icon; bool m_active = false; bool m_keepAbove = false; bool m_keepBelow = false; bool m_demandsAttention = false; bool m_minimized = false; QTimer *m_autoRaiseTimer = nullptr; QVector m_desktops; QString m_colorScheme; std::shared_ptr m_palette; static QHash> s_palettes; static std::shared_ptr s_defaultPalette; KWayland::Server::PlasmaWindowInterface *m_windowManagementInterface = nullptr; AbstractClient *m_transientFor = nullptr; QList m_transients; bool m_modal = false; Layer m_layer = UnknownLayer; // electric border/quick tiling QuickTileMode m_electricMode = QuickTileFlag::None; bool m_electricMaximizing = false; /** The quick tile mode of this window. */ int m_quickTileMode = int(QuickTileFlag::None); QTimer *m_electricMaximizingDelay = nullptr; // geometry int m_blockGeometryUpdates = 0; // > 0 = New geometry is remembered, but not actually set PendingGeometry_t m_pendingGeometryUpdate = PendingGeometryNone; friend class GeometryUpdatesBlocker; QRect m_visibleRectBeforeGeometryUpdate; QRect m_geometryBeforeUpdateBlocking; struct { bool enabled = false; bool unrestricted = false; QPoint offset; QPoint invertedOffset; QRect initialGeometry; QRect geometry; Position pointer = PositionCenter; bool buttonDown = false; CursorShape cursor = Qt::ArrowCursor; int startScreen = 0; QTimer *delayedTimer = nullptr; } m_moveResize; struct { KDecoration2::Decoration *decoration = nullptr; QPointer client; QElapsedTimer doubleClickTimer; } m_decoration; QByteArray m_desktopFileName; bool m_applicationMenuActive = false; QString m_applicationMenuServiceName; QString m_applicationMenuObjectPath; bool m_unresponsive = false; QKeySequence _shortcut; WindowRules m_rules; TabGroup* tab_group = nullptr; static bool s_haveResizeEffect; }; /** * Helper for AbstractClient::blockGeometryUpdates() being called in pairs (true/false) */ class GeometryUpdatesBlocker { public: explicit GeometryUpdatesBlocker(AbstractClient* c) : cl(c) { cl->blockGeometryUpdates(true); } ~GeometryUpdatesBlocker() { cl->blockGeometryUpdates(false); } private: AbstractClient* cl; }; inline void AbstractClient::move(const QPoint& p, ForceGeometry_t force) { move(p.x(), p.y(), force); } inline void AbstractClient::resizeWithChecks(const QSize& s, AbstractClient::ForceGeometry_t force) { resizeWithChecks(s.width(), s.height(), force); } inline void AbstractClient::setGeometry(const QRect& r, ForceGeometry_t force) { setGeometry(r.x(), r.y(), r.width(), r.height(), force); } inline const QList& AbstractClient::transients() const { return m_transients; } inline bool AbstractClient::areGeometryUpdatesBlocked() const { return m_blockGeometryUpdates != 0; } inline void AbstractClient::blockGeometryUpdates() { m_blockGeometryUpdates++; } inline void AbstractClient::unblockGeometryUpdates() { m_blockGeometryUpdates--; } inline AbstractClient::PendingGeometry_t AbstractClient::pendingGeometryUpdate() const { return m_pendingGeometryUpdate; } inline void AbstractClient::setPendingGeometryUpdate(PendingGeometry_t update) { m_pendingGeometryUpdate = update; } inline TabGroup* AbstractClient::tabGroup() const { return tab_group; } } Q_DECLARE_METATYPE(KWin::AbstractClient*) Q_DECLARE_METATYPE(QList) Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::AbstractClient::SameApplicationChecks) #endif diff --git a/cursor.h b/cursor.h index 90a4c7a36..447912087 100644 --- a/cursor.h +++ b/cursor.h @@ -1,306 +1,306 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_CURSOR_H #define KWIN_CURSOR_H // kwin #include // Qt #include #include #include // xcb #include class QTimer; namespace KWin { namespace ExtendedCursor { enum Shape { SizeNorthWest = 0x100 + 0, SizeNorth = 0x100 + 1, SizeNorthEast = 0x100 + 2, SizeEast = 0x100 + 3, SizeWest = 0x100 + 4, SizeSouthEast = 0x100 + 5, SizeSouth = 0x100 + 6, SizeSouthWest = 0x100 + 7 }; } /** * Extension of Qt::CursorShape with values not currently present there */ /** * @brief Wrapper round Qt::CursorShape with extensions enums into a single entity */ class KWIN_EXPORT CursorShape { public: CursorShape() = default; CursorShape(Qt::CursorShape qtShape) { m_shape = qtShape; } CursorShape(KWin::ExtendedCursor::Shape kwinShape) { m_shape = kwinShape; } bool operator==(const CursorShape &o) const { return m_shape == o.m_shape; } operator int() const { return m_shape; } /** * @brief The name of a cursor shape in the theme. */ QByteArray name() const; private: int m_shape = Qt::ArrowCursor; }; /** * @short Replacement for QCursor. * * This class provides a similar API to QCursor and should be preferred inside KWin. It allows to * get the position and warp the mouse cursor with static methods just like QCursor. It also provides * the possibility to get an X11 cursor for a Qt::CursorShape - a functionality lost in Qt 5's QCursor * implementation. * * In addition the class provides a mouse polling facility as required by e.g. Effects and ScreenEdges * and emits signals when the mouse position changes. In opposite to QCursor this class is a QObject * and cannot be constructed. Instead it provides a singleton getter, though the most important * methods are wrapped in a static method, just like QCursor. * * The actual implementation is split into two parts: a system independent interface and a windowing * system specific subclass. So far only an X11 backend is implemented which uses query pointer to * fetch the position and warp pointer to set the position. It uses a timer based mouse polling and * can provide X11 cursors through the XCursor library. **/ class KWIN_EXPORT Cursor : public QObject { Q_OBJECT public: virtual ~Cursor(); void startMousePolling(); void stopMousePolling(); /** * @brief Enables tracking changes of cursor images. * * After enabling cursor change tracking the signal @link cursorChanged will be emitted * whenever a change to the cursor image is recognized. * * Use @link stopCursorTracking to no longer emit this signal. Note: the signal will be * emitted until each call of this method has been matched with a call to stopCursorTracking. * * This tracking is not about pointer position tracking. * @see stopCursorTracking * @see cursorChanged */ void startCursorTracking(); /** * @brief Disables tracking changes of cursor images. * - * Only call after using @link startCursorTracking. + * Only call after using startCursorTracking. * * @see startCursorTracking */ void stopCursorTracking(); /** * @brief The name of the currently used Cursor theme. * * @return const QString& */ const QString &themeName() const; /** * @brief The size of the currently used Cursor theme. * * @return int */ int themeSize() const; /** * @return list of alternative names for the cursor with @p name **/ QVector cursorAlternativeNames(const QByteArray &name) const; /** * Returns the current cursor position. This method does an update of the mouse position if * needed. It's save to call it multiple times. * * Implementing subclasses should prefer to use @link currentPos which is not performing a check * for update. **/ static QPoint pos(); /** * Warps the mouse cursor to new @p pos. **/ static void setPos(const QPoint &pos); static void setPos(int x, int y); static xcb_cursor_t x11Cursor(CursorShape shape); /** * Notice: if available always use the CursorShape variant to avoid cache duplicates for * ambiguous cursor names in the non existing cursor name spcification **/ static xcb_cursor_t x11Cursor(const QByteArray &name); Q_SIGNALS: void posChanged(QPoint pos); void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); /** * @brief Signal emitted when the cursor image changes. * - * To enable these signals use @link startCursorTracking. + * To enable these signals use startCursorTracking. * * @see startCursorTracking * @see stopCursorTracking */ void cursorChanged(); void themeChanged(); protected: /** * Called from @link x11Cursor to actually retrieve the X11 cursor. Base implementation returns * a null cursor, an implementing subclass should implement this method if it can provide X11 * mouse cursors. **/ virtual xcb_cursor_t getX11Cursor(CursorShape shape); /** * Called from @link x11Cursor to actually retrieve the X11 cursor. Base implementation returns * a null cursor, an implementing subclass should implement this method if it can provide X11 * mouse cursors. **/ virtual xcb_cursor_t getX11Cursor(const QByteArray &name); /** * Performs the actual warping of the cursor. **/ virtual void doSetPos(); /** * Called from @link pos() to allow syncing the internal position with the underlying * system's cursor position. **/ virtual void doGetPos(); /** * Called from @link startMousePolling when the mouse polling gets activated. Base implementation * does nothing, inheriting classes can overwrite to e.g. start a timer. **/ virtual void doStartMousePolling(); /** * Called from @link stopMousePolling when the mouse polling gets deactivated. Base implementation * does nothing, inheriting classes can overwrite to e.g. stop a timer. **/ virtual void doStopMousePolling(); /** * Called from @link startCursorTracking when cursor image tracking gets activated. Inheriting class needs * to overwrite to enable platform specific code for the tracking. */ virtual void doStartCursorTracking(); /** * Called from @link stopCursorTracking when cursor image tracking gets deactivated. Inheriting class needs * to overwrite to disable platform specific code for the tracking. */ virtual void doStopCursorTracking(); bool isCursorTracking() const; /** * Provides the actual internal cursor position to inheriting classes. If an inheriting class needs - * access to the cursor position this method should be used instead of the static @link pos, as + * access to the cursor position this method should be used instead of the static @ref pos, as * the static method syncs with the underlying system's cursor. **/ const QPoint ¤tPos() const; /** * Updates the internal position to @p pos without warping the pointer as * @link setPos does. **/ void updatePos(const QPoint &pos); void updatePos(int x, int y); private Q_SLOTS: void loadThemeSettings(); void slotKGlobalSettingsNotifyChange(int type, int arg); private: void updateTheme(const QString &name, int size); void loadThemeFromKConfig(); QPoint m_pos; int m_mousePollingCounter; int m_cursorTrackingCounter; QString m_themeName; int m_themeSize; KWIN_SINGLETON(Cursor) }; /** * @brief Implementation using the InputRedirection framework to get pointer positions. * * Does not support warping of cursor. * */ class InputRedirectionCursor : public Cursor { Q_OBJECT public: explicit InputRedirectionCursor(QObject *parent); virtual ~InputRedirectionCursor(); protected: virtual void doSetPos(); virtual void doStartCursorTracking(); virtual void doStopCursorTracking(); private Q_SLOTS: void slotPosChanged(const QPointF &pos); void slotPointerButtonChanged(); void slotModifiersChanged(Qt::KeyboardModifiers mods, Qt::KeyboardModifiers oldMods); private: Qt::MouseButtons m_currentButtons; friend class Cursor; }; inline const QPoint &Cursor::currentPos() const { return m_pos; } inline void Cursor::updatePos(int x, int y) { updatePos(QPoint(x, y)); } inline const QString& Cursor::themeName() const { return m_themeName; } inline int Cursor::themeSize() const { return m_themeSize; } inline bool Cursor::isCursorTracking() const { return m_cursorTrackingCounter > 0; } } Q_DECLARE_METATYPE(KWin::CursorShape) #endif // KWIN_CURSOR_H diff --git a/input.h b/input.h index ad66ad141..d32f814bf 100644 --- a/input.h +++ b/input.h @@ -1,482 +1,482 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin Copyright (C) 2018 Roman Gilg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_INPUT_H #define KWIN_INPUT_H #include #include #include #include #include #include #include #include class KGlobalAccelInterface; class QKeySequence; class QMouseEvent; class QKeyEvent; class QWheelEvent; namespace KWin { class GlobalShortcutsManager; class Toplevel; class InputEventFilter; class InputEventSpy; class KeyboardInputRedirection; class PointerInputRedirection; class TouchInputRedirection; class WindowSelectorFilter; class SwitchEvent; namespace Decoration { class DecoratedClientImpl; } namespace LibInput { class Connection; } /** * @brief This class is responsible for redirecting incoming input to the surface which currently * has input or send enter/leave events. * * In addition input is intercepted before passed to the surfaces to have KWin internal areas * getting input first (e.g. screen edges) and filter the input event out if we currently have * a full input grab. * */ class KWIN_EXPORT InputRedirection : public QObject { Q_OBJECT public: enum PointerButtonState { PointerButtonReleased, PointerButtonPressed }; enum PointerAxis { PointerAxisVertical, PointerAxisHorizontal }; enum KeyboardKeyState { KeyboardKeyReleased, KeyboardKeyPressed, KeyboardKeyAutoRepeat }; virtual ~InputRedirection(); void init(); /** * @return const QPointF& The current global pointer position */ QPointF globalPointer() const; Qt::MouseButtons qtButtonStates() const; Qt::KeyboardModifiers keyboardModifiers() const; Qt::KeyboardModifiers modifiersRelevantForGlobalShortcuts() const; void registerShortcut(const QKeySequence &shortcut, QAction *action); /** * @overload * * Like registerShortcut, but also connects QAction::triggered to the @p slot on @p receiver. * It's recommended to use this method as it ensures that the X11 timestamp is updated prior * to the @p slot being invoked. If not using this overload it's required to ensure that * registerShortcut is called before connecting to QAction's triggered signal. **/ template void registerShortcut(const QKeySequence &shortcut, QAction *action, T *receiver, Slot slot); void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action); void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action); void registerTouchpadSwipeShortcut(SwipeDirection direction, QAction *action); void registerGlobalAccel(KGlobalAccelInterface *interface); /** * @internal */ void processPointerMotion(const QPointF &pos, uint32_t time); /** * @internal */ void processPointerButton(uint32_t button, PointerButtonState state, uint32_t time); /** * @internal */ void processPointerAxis(PointerAxis axis, qreal delta, uint32_t time); /** * @internal */ void processKeyboardKey(uint32_t key, KeyboardKeyState state, uint32_t time); /** * @internal */ void processKeyboardModifiers(uint32_t modsDepressed, uint32_t modsLatched, uint32_t modsLocked, uint32_t group); /** * @internal **/ void processKeymapChange(int fd, uint32_t size); void processTouchDown(qint32 id, const QPointF &pos, quint32 time); void processTouchUp(qint32 id, quint32 time); void processTouchMotion(qint32 id, const QPointF &pos, quint32 time); void cancelTouch(); void touchFrame(); bool supportsPointerWarping() const; void warpPointer(const QPointF &pos); /** * Adds the @p filter to the list of event filters and makes it the first * event filter in processing. * * Note: the event filter will get events before the lock screen can get them, thus * this is a security relevant method. **/ void prependInputEventFilter(InputEventFilter *filter); void uninstallInputEventFilter(InputEventFilter *filter); /** * Installs the @p spy for spying on events. **/ void installInputEventSpy(InputEventSpy *spy); /** * Uninstalls the @p spy. This happens automatically when deleting an InputEventSpy. **/ void uninstallInputEventSpy(InputEventSpy *spy); Toplevel *findToplevel(const QPoint &pos); GlobalShortcutsManager *shortcuts() const { return m_shortcuts; } /** * Sends an event through all InputFilters. * The method @p function is invoked on each input filter. Processing is stopped if * a filter returns @c true for @p function. * * The UnaryPredicate is defined like the UnaryPredicate of std::any_of. * The signature of the function should be equivalent to the following: * @code * bool function(const InputEventFilter *spy); * @endcode * * The intended usage is to std::bind the method to invoke on the filter with all arguments * bind. **/ template void processFilters(UnaryPredicate function) { std::any_of(m_filters.constBegin(), m_filters.constEnd(), function); } /** * Sends an event through all input event spies. * The @p function is invoked on each InputEventSpy. * * The UnaryFunction is defined like the UnaryFunction of std::for_each. * The signature of the function should be equivalent to the following: * @code * void function(const InputEventSpy *spy); * @endcode * * The intended usage is to std::bind the method to invoke on the spies with all arguments * bind. **/ template void processSpies(UnaryFunction function) { std::for_each(m_spies.constBegin(), m_spies.constEnd(), function); } KeyboardInputRedirection *keyboard() const { return m_keyboard; } PointerInputRedirection *pointer() const { return m_pointer; } TouchInputRedirection *touch() const { return m_touch; } bool hasAlphaNumericKeyboard(); bool hasTabletModeSwitch(); void startInteractiveWindowSelection(std::function callback, const QByteArray &cursorName); void startInteractivePositionSelection(std::function callback); bool isSelectingWindow() const; Q_SIGNALS: /** * @brief Emitted when the global pointer position changed * * @param pos The new global pointer position. */ void globalPointerChanged(const QPointF &pos); /** * @brief Emitted when the state of a pointer button changed. * * @param button The button which changed * @param state The new button state */ void pointerButtonStateChanged(uint32_t button, InputRedirection::PointerButtonState state); /** * @brief Emitted when a pointer axis changed * * @param axis The axis on which the even occurred * @param delta The delta of the event. */ void pointerAxisChanged(InputRedirection::PointerAxis axis, qreal delta); /** * @brief Emitted when the modifiers changes. * * Only emitted for the mask which is provided by Qt::KeyboardModifiers, if other modifiers * change signal is not emitted * * @param newMods The new modifiers state * @param oldMods The previous modifiers state */ void keyboardModifiersChanged(Qt::KeyboardModifiers newMods, Qt::KeyboardModifiers oldMods); /** * @brief Emitted when the state of a key changed. * * @param keyCode The keycode of the key which changed - * @param oldMods The new key state + * @param state The new key state */ void keyStateChanged(quint32 keyCode, InputRedirection::KeyboardKeyState state); void hasAlphaNumericKeyboardChanged(bool set); void hasTabletModeSwitchChanged(bool set); private: void setupLibInput(); void setupTouchpadShortcuts(); void setupLibInputWithScreens(); void setupWorkspace(); void reconfigure(); void setupInputFilters(); void installInputEventFilter(InputEventFilter *filter); KeyboardInputRedirection *m_keyboard; PointerInputRedirection *m_pointer; TouchInputRedirection *m_touch; GlobalShortcutsManager *m_shortcuts; LibInput::Connection *m_libInput = nullptr; WindowSelectorFilter *m_windowSelector = nullptr; QVector m_filters; QVector m_spies; KWIN_SINGLETON(InputRedirection) friend InputRedirection *input(); friend class DecorationEventFilter; friend class InternalWindowEventFilter; friend class ForwardInputFilter; }; /** * Base class for filtering input events inside InputRedirection. * * The idea behind the InputEventFilter is to have task oriented * filters. E.g. there is one filter taking care of a locked screen, * one to take care of interacting with window decorations, etc. * * A concrete subclass can reimplement the virtual methods and decide * whether an event should be filtered out or not by returning either * @c true or @c false. E.g. the lock screen filter can easily ensure * that all events are filtered out. * * As soon as a filter returns @c true the processing is stopped. If * a filter returns @c false the next one is invoked. This means a filter * installed early gets to see more events than a filter installed later on. * * Deleting an instance of InputEventFilter automatically uninstalls it from * InputRedirection. **/ class KWIN_EXPORT InputEventFilter { public: InputEventFilter(); virtual ~InputEventFilter(); /** * Event filter for pointer events which can be described by a QMouseEvent. * * Please note that the button translation in QMouseEvent cannot cover all * possible buttons. Because of that also the @p nativeButton code is passed * through the filter. For internal areas it's fine to use @p event, but for * passing to client windows the @p nativeButton should be used. * * @param event The event information about the move or button press/release * @param nativeButton The native key code of the button, for move events 0 * @return @c true to stop further event processing, @c false to pass to next filter **/ virtual bool pointerEvent(QMouseEvent *event, quint32 nativeButton); /** * Event filter for pointer axis events. * * @param event The event information about the axis event * @return @c true to stop further event processing, @c false to pass to next filter **/ virtual bool wheelEvent(QWheelEvent *event); /** * Event filter for keyboard events. * * @param event The event information about the key event * @return @c tru to stop further event processing, @c false to pass to next filter. **/ virtual bool keyEvent(QKeyEvent *event); virtual bool touchDown(quint32 id, const QPointF &pos, quint32 time); virtual bool touchMotion(quint32 id, const QPointF &pos, quint32 time); virtual bool touchUp(quint32 id, quint32 time); virtual bool pinchGestureBegin(int fingerCount, quint32 time); virtual bool pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time); virtual bool pinchGestureEnd(quint32 time); virtual bool pinchGestureCancelled(quint32 time); virtual bool swipeGestureBegin(int fingerCount, quint32 time); virtual bool swipeGestureUpdate(const QSizeF &delta, quint32 time); virtual bool swipeGestureEnd(quint32 time); virtual bool swipeGestureCancelled(quint32 time); virtual bool switchEvent(SwitchEvent *event); protected: void passToWaylandServer(QKeyEvent *event); }; class KWIN_EXPORT InputDeviceHandler : public QObject { Q_OBJECT public: virtual ~InputDeviceHandler(); virtual void init(); void update(); /** * @brief First Toplevel currently at the position of the input device * according to the stacking order. * @return Toplevel* at device position. */ QPointer at() const { return m_at; } /** * @brief Toplevel currently having pointer input focus (this might * be different from the Toplevel at the position of the pointer). * @return Toplevel* with pointer focus. */ QPointer focus() const { return m_focus.focus; } /** * @brief The Decoration currently receiving events. * @return decoration with pointer focus. **/ QPointer decoration() const { return m_focus.decoration; } /** * @brief The internal window currently receiving events. * @return QWindow with pointer focus. **/ QPointer internalWindow() const { return m_focus.internalWindow; } virtual QPointF position() const = 0; void setFocus(Toplevel *toplevel); void setDecoration(QPointer decoration); void setInternalWindow(QWindow *window); Q_SIGNALS: void atChanged(Toplevel *old, Toplevel *now); void decorationChanged(); protected: explicit InputDeviceHandler(InputRedirection *parent); virtual void cleanupInternalWindow(QWindow *old, QWindow *now) = 0; virtual void cleanupDecoration(Decoration::DecoratedClientImpl *old, Decoration::DecoratedClientImpl *now) = 0; virtual void focusUpdate(Toplevel *old, Toplevel *now) = 0; /* Certain input devices can be in a state of having no valid * position. An example are touch screens when no finger/pen * is resting on the surface (no touch point). */ virtual bool positionValid() const { return false; } virtual bool focusUpdatesBlocked() { return false; } inline bool inited() const { return m_inited; } inline void setInited(bool set) { m_inited = set; } private: bool setAt(Toplevel *toplevel); void updateFocus(); bool updateDecoration(); void updateInternalWindow(QWindow *window); QWindow* findInternalWindow(const QPoint &pos) const; QPointer m_at; struct { QPointer focus; QPointer decoration; QPointer internalWindow; } m_focus; bool m_inited = false; }; inline InputRedirection *input() { return InputRedirection::s_self; } template inline void InputRedirection::registerShortcut(const QKeySequence &shortcut, QAction *action, T *receiver, Slot slot) { registerShortcut(shortcut, action); connect(action, &QAction::triggered, receiver, slot); } } // namespace KWin Q_DECLARE_METATYPE(KWin::InputRedirection::KeyboardKeyState) Q_DECLARE_METATYPE(KWin::InputRedirection::PointerButtonState) Q_DECLARE_METATYPE(KWin::InputRedirection::PointerAxis) #endif // KWIN_INPUT_H diff --git a/libkwineffects/kwinanimationeffect.h b/libkwineffects/kwinanimationeffect.h index 1efe4eb62..a1c904f8b 100644 --- a/libkwineffects/kwinanimationeffect.h +++ b/libkwineffects/kwinanimationeffect.h @@ -1,411 +1,411 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Thomas Lübking Copyright (C) 2018 Vlad Zagorodniy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef ANIMATION_EFFECT_H #define ANIMATION_EFFECT_H #include #include #include #include #include namespace KWin { class KWINEFFECTS_EXPORT FPx2 { public: FPx2() { f[0] = f[1] = 0.0; valid = false; } explicit FPx2(float v) { f[0] = f[1] = v; valid = true; } FPx2(float v1, float v2) { f[0] = v1; f[1] = v2; valid = true; } FPx2(const FPx2 &other) { f[0] = other.f[0]; f[1] = other.f[1]; valid = other.valid; } explicit FPx2(const QPoint &other) { f[0] = other.x(); f[1] = other.y(); valid = true; } explicit FPx2(const QPointF &other) { f[0] = other.x(); f[1] = other.y(); valid = true; } explicit FPx2(const QSize &other) { f[0] = other.width(); f[1] = other.height(); valid = true; } explicit FPx2(const QSizeF &other) { f[0] = other.width(); f[1] = other.height(); valid = true; } inline void invalidate() { valid = false; } inline bool isValid() const { return valid; } inline float operator[](int n) const { return f[n]; } inline QString toString() const { QString ret; if (valid) ret = QString::number(f[0]) + QLatin1Char(',') + QString::number(f[1]); else ret = QString(); return ret; } inline FPx2 &operator+=(const FPx2 &other) { f[0] += other[0]; f[1] += other[1]; return *this; } inline FPx2 &operator-=(const FPx2 &other) { f[0] -= other[0]; f[1] -= other[1]; return *this; } inline FPx2 &operator*=(float fl) { f[0] *= fl; f[1] *= fl; return *this; } inline FPx2 &operator/=(float fl) { f[0] /= fl; f[1] /= fl; return *this; } friend inline bool operator==(const FPx2 &f1, const FPx2 &f2) { return f1[0] == f2[0] && f1[1] == f2[1]; } friend inline bool operator!=(const FPx2 &f1, const FPx2 &f2) { return f1[0] != f2[0] || f1[1] != f2[1]; } friend inline const FPx2 operator+(const FPx2 &f1, const FPx2 &f2) { return FPx2( f1[0] + f2[0], f1[1] + f2[1] ); } friend inline const FPx2 operator-(const FPx2 &f1, const FPx2 &f2) { return FPx2( f1[0] - f2[0], f1[1] - f2[1] ); } friend inline const FPx2 operator*(const FPx2 &f, float fl) { return FPx2( f[0] * fl, f[1] * fl ); } friend inline const FPx2 operator*(float fl, const FPx2 &f) { return FPx2( f[0] * fl, f[1] *fl ); } friend inline const FPx2 operator-(const FPx2 &f) { return FPx2( -f[0], -f[1] ); } friend inline const FPx2 operator/(const FPx2 &f, float fl) { return FPx2( f[0] / fl, f[1] / fl ); } inline void set(float v) { f[0] = v; valid = true; } inline void set(float v1, float v2) { f[0] = v1; f[1] = v2; valid = true; } private: float f[2]; bool valid; }; class AniData; class AnimationEffectPrivate; /** * Base class for animation effects. * * AnimationEffect serves as a base class for animation effects. It makes easier * implementing animated transitions, without having to worry about low-level * specific stuff, e.g. referencing and unreferencing deleted windows, scheduling * repaints for the next frame, etc. * * Each animation animates one specific attribute, e.g. size, position, scale, etc. * You can provide your own implementation of the Generic attribute if none of the * standard attributes(e.g. size, position, etc) satisfy your requirements. * * @since 4.8 **/ class KWINEFFECTS_EXPORT AnimationEffect : public Effect { Q_OBJECT public: typedef QMap< EffectWindow*, QPair, QRect> > AniMap; enum Anchor { Left = 1<<0, Top = 1<<1, Right = 1<<2, Bottom = 1<<3, Horizontal = Left|Right, Vertical = Top|Bottom, Mouse = 1<<4 }; Q_ENUM(Anchor) enum Attribute { Opacity = 0, Brightness, Saturation, Scale, Rotation, Position, Size, Translation, Clip, Generic, CrossFadePrevious, NonFloatBase = Position }; Q_ENUM(Attribute) enum MetaType { SourceAnchor, TargetAnchor, RelativeSourceX, RelativeSourceY, RelativeTargetX, RelativeTargetY, Axis }; Q_ENUM(MetaType) /** * This enum type is used to specify the direction of the animation. * * @since 5.15 **/ enum Direction { Forward, ///< The animation goes from source to target. Backward ///< The animation goes from target to source. }; Q_ENUM(Direction) /** * This enum type is used to specify when the animation should be terminated. * * @since 5.15 **/ enum TerminationFlag { /** * Don't terminate the animation when it reaches source or target position. **/ DontTerminate = 0x00, /** * Terminate the animation when it reaches the source position. An animation * can reach the source position if its direction was changed to go backward * (from target to source). **/ TerminateAtSource = 0x01, /** * Terminate the animation when it reaches the target position. If this flag * is not set, then the animation will be persistent. **/ TerminateAtTarget = 0x02 }; Q_FLAGS(TerminationFlag) Q_DECLARE_FLAGS(TerminationFlags, TerminationFlag) /** * Constructs AnimationEffect. * * Whenever you intend to connect to the EffectsHandler::windowClosed() signal, * do so when reimplementing the constructor. Do not add private slots named * _windowClosed or _windowDeleted! The AnimationEffect connects them right after * the construction. * * If you shadow the _windowDeleted slot (it doesn't matter that it's a private * slot), this will lead to segfaults. * * If you shadow _windowClosed or connect your slot to EffectsHandler::windowClosed() * after _windowClosed was connected, animations for closing windows will fail. **/ AnimationEffect(); ~AnimationEffect(); bool isActive() const; /** * Gets stored metadata. * * Metadata can be used to store some extra information, for example rotation axis, * etc. The first 24 bits are reserved for the AnimationEffect class, you can use * the last 8 bits for custom hints. In case when you transform a Generic attribute, * all 32 bits are yours and you can use them as you want and read them in your * genericAnimation() implementation. * * @param type The type of the metadata. * @param meta Where the metadata is stored. * @returns Stored metadata. * @since 4.8 **/ static int metaData(MetaType type, uint meta ); /** * Sets metadata. * * @param type The type of the metadata. * @param value The data to be stored. * @param meta Where the metadata will be stored. * @since 4.8 **/ static void setMetaData(MetaType type, uint value, uint &meta ); // Reimplemented from KWin::Effect. QString debug(const QString ¶meter) const; virtual void prePaintScreen( ScreenPrePaintData& data, int time ); virtual void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ); virtual void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ); virtual void postPaintScreen(); /** * Gaussian (bumper) animation curve for QEasingCurve. * * @since 4.8 **/ static qreal qecGaussian(qreal progress) { progress = 2*progress - 1; progress *= -5*progress; return qExp(progress); } /** * @since 4.8 **/ static inline qint64 clock() { return s_clock.elapsed(); } protected: /** * Starts an animated transition of any supported attribute. * * @param w The animated window. * @param a The animated attribute. * @param meta Basically a wildcard to carry various extra information, e.g. * the anchor, relativity or rotation axis. You will probably use it when * performing Generic animations. * @param ms How long the transition will last. * @param to The target value. FPx2 is an agnostic two component float type * (like QPointF or QSizeF, but without requiring to be either and supporting * an invalid state). - * @param shape How the animation progresses, e.g. Linear progresses constantly + * @param curve How the animation progresses, e.g. Linear progresses constantly * while Exponential start slow and becomes very fast in the end. * @param delay When the animation will start compared to "now" (the window will * remain at the "from" position until then). * @param from The starting value, the default is invalid, ie. the attribute for * the window is not transformed in the beginning. * @param fullScreen Sets this effect as the active full screen effect for the * duration of the animation. * @param keepAlive Whether closed windows should be kept alive during animation. * @returns An ID that you can use to cancel a running animation. * @since 4.8 **/ quint64 animate( EffectWindow *w, Attribute a, uint meta, int ms, FPx2 to, QEasingCurve curve = QEasingCurve(), int delay = 0, FPx2 from = FPx2(), bool fullScreen = false, bool keepAlive = true) { return p_animate(w, a, meta, ms, to, curve, delay, from, false, fullScreen, keepAlive); } /** * Starts a persistent animated transition of any supported attribute. * * This method is equal to animate() with one important difference: * the target value for the attribute is kept until you call cancel(). * * @param w The animated window. * @param a The animated attribute. * @param meta Basically a wildcard to carry various extra information, e.g. * the anchor, relativity or rotation axis. You will probably use it when * performing Generic animations. * @param ms How long the transition will last. * @param to The target value. FPx2 is an agnostic two component float type * (like QPointF or QSizeF, but without requiring to be either and supporting * an invalid state). - * @param shape How the animation progresses, e.g. Linear progresses constantly + * @param curve How the animation progresses, e.g. Linear progresses constantly * while Exponential start slow and becomes very fast in the end. * @param delay When the animation will start compared to "now" (the window will * remain at the "from" position until then). * @param from The starting value, the default is invalid, ie. the attribute for * the window is not transformed in the beginning. * @param fullScreen Sets this effect as the active full screen effect for the * duration of the animation. * @param keepAlive Whether closed windows should be kept alive during animation. * @returns An ID that you need to use to cancel this manipulation. * @since 4.11 **/ quint64 set( EffectWindow *w, Attribute a, uint meta, int ms, FPx2 to, QEasingCurve curve = QEasingCurve(), int delay = 0, FPx2 from = FPx2(), bool fullScreen = false, bool keepAlive = true) { return p_animate(w, a, meta, ms, to, curve, delay, from, true, fullScreen, keepAlive); } /** * Changes the target (but not type or curve) of a running animation. * * Please use cancel() to cancel an animation rather than altering it. * * @param animationId The id of the animation to be retargetted. * @param newTarget The new target. * @param newRemainingTime The new duration of the transition. By default (-1), * the remaining time remains unchanged. * @returns @c true if the animation was retargetted successfully, @c false otherwise. * @note You can NOT retarget an animation that just has just ended! * @since 5.6 **/ bool retarget(quint64 animationId, FPx2 newTarget, int newRemainingTime = -1); /** * Changes the direction of the animation. * * @param animationId The id of the animation. * @param direction The new direction of the animation. - * @param terminationPolicy Whether the animation should be terminated when it + * @param terminationFlags Whether the animation should be terminated when it * reaches the source position after its direction was changed to go backward. * Currently, TerminationFlag::TerminateAtTarget has no effect. * @returns @c true if the direction of the animation was changed successfully, * otherwise @c false. * @since 5.15 **/ bool redirect(quint64 animationId, Direction direction, TerminationFlags terminationFlags = TerminateAtSource); /** * Fast-forwards the animation to the target position. * * @param animationId The id of the animation. * @returns @c true if the animation was fast-forwarded successfully, otherwise * @c false. * @since 5.15 **/ bool complete(quint64 animationId); /** * Called whenever an animation ends. * * You can reimplement this method to keep a constant transformation for the window * (i.e. keep it at some opacity or position) or to start another animation. * * @param w The animated window. * @param a The animated attribute. * @param meta Originally supplied metadata to animate() or set(). * @since 4.8 **/ virtual void animationEnded(EffectWindow *w, Attribute a, uint meta) {Q_UNUSED(w); Q_UNUSED(a); Q_UNUSED(meta);} /** * Cancels a running animation. * * @param animationId The id of the animation. * @returns @c true if the animation was found (and canceled), @c false otherwise. * @note There is NO animated reset of the original value. You'll have to provide * that with a second animation. * @note This will eventually release a Deleted window as well. * @note If you intend to run another animation on the (Deleted) window, you have * to do that before cancelling the old animation (to keep the window around). * @since 4.11 **/ bool cancel(quint64 animationId); /** * Called whenever animation that transforms Generic attribute needs to be painted. * * You should reimplement this method if you transform Generic attribute. @p meta * can be used to support more than one additional animations. * * @param w The animated window. * @param data The paint data. * @param progress Current progress value. * @param meta The metadata. * @since 4.8 **/ virtual void genericAnimation( EffectWindow *w, WindowPaintData &data, float progress, uint meta ) {Q_UNUSED(w); Q_UNUSED(data); Q_UNUSED(progress); Q_UNUSED(meta);} //Internal for unit tests AniMap state() const; private: quint64 p_animate(EffectWindow *w, Attribute a, uint meta, int ms, FPx2 to, QEasingCurve curve, int delay, FPx2 from, bool keepAtTarget, bool fullScreenEffect, bool keepAlive); QRect clipRect(const QRect &windowRect, const AniData&) const; void clipWindow(const EffectWindow *, const AniData &, WindowQuadList &) const; float interpolated( const AniData&, int i = 0 ) const; float progress( const AniData& ) const; void disconnectGeometryChanges(); void updateLayerRepaints(); void validate(Attribute a, uint &meta, FPx2 *from, FPx2 *to, const EffectWindow *w) const; private Q_SLOTS: void init(); void triggerRepaint(); void _windowClosed( KWin::EffectWindow* w ); void _windowDeleted( KWin::EffectWindow* w ); void _expandedGeometryChanged(KWin::EffectWindow *w, const QRect &old); private: static QElapsedTimer s_clock; AnimationEffectPrivate * const d_ptr; Q_DECLARE_PRIVATE(AnimationEffect) }; } // namespace QDebug operator<<(QDebug dbg, const KWin::FPx2 &fpx2); Q_DECLARE_METATYPE(KWin::FPx2) Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::AnimationEffect::TerminationFlags) #endif // ANIMATION_EFFECT_H diff --git a/libkwineffects/kwineffects.h b/libkwineffects/kwineffects.h index a2364be52..26373201a 100644 --- a/libkwineffects/kwineffects.h +++ b/libkwineffects/kwineffects.h @@ -1,3891 +1,3891 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009 Lucas Murray Copyright (C) 2010, 2011 Martin Gräßlin Copyright (C) 2018 Vlad Zagorodniy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWINEFFECTS_H #define KWINEFFECTS_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class KConfigGroup; class QFont; class QGraphicsScale; class QKeyEvent; class QMatrix4x4; class QAction; /** * Logging category to be used inside the KWin effects. * Do not use in this library. **/ Q_DECLARE_LOGGING_CATEGORY(KWINEFFECTS) namespace KWayland { namespace Server { class SurfaceInterface; class Display; } } namespace KWin { class PaintDataPrivate; class WindowPaintDataPrivate; class EffectWindow; class EffectWindowGroup; class EffectFrame; class EffectFramePrivate; class Effect; class WindowQuad; class GLShader; class XRenderPicture; class WindowQuadList; class WindowPrePaintData; class WindowPaintData; class ScreenPrePaintData; class ScreenPaintData; typedef QPair< QString, Effect* > EffectPair; typedef QList< KWin::EffectWindow* > EffectWindowList; /** @defgroup kwineffects KWin effects library * KWin effects library contains necessary classes for creating new KWin * compositing effects. * * @section creating Creating new effects * This example will demonstrate the basics of creating an effect. We'll use * CoolEffect as the class name, cooleffect as internal name and * "Cool Effect" as user-visible name of the effect. * * This example doesn't demonstrate how to write the effect's code. For that, * see the documentation of the Effect class. * * @subsection creating-class CoolEffect class * First you need to create CoolEffect class which has to be a subclass of * @ref KWin::Effect. In that class you can reimplement various virtual * methods to control how and where the windows are drawn. * * @subsection creating-macro KWIN_EFFECT_FACTORY macro * This library provides a specialized KPluginFactory subclass and macros to * create a sub class. This subclass of KPluginFactory has to be used, otherwise * KWin won't load the plugin. Use the @ref KWIN_EFFECT_FACTORY macro to create the * plugin factory. * * @subsection creating-buildsystem Buildsystem * To build the effect, you can use the KWIN_ADD_EFFECT() cmake macro which * can be found in effects/CMakeLists.txt file in KWin's source. First * argument of the macro is the name of the library that will contain * your effect. Although not strictly required, it is usually a good idea to * use the same name as your effect's internal name there. Following arguments * to the macro are the files containing your effect's source. If our effect's * source is in cooleffect.cpp, we'd use following: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * @endcode * * This macro takes care of compiling your effect. You'll also need to install * your effect's .desktop file, so the example CMakeLists.txt file would be * as follows: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * install( FILES cooleffect.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kwin ) * @endcode * * @subsection creating-desktop Effect's .desktop file * You will also need to create .desktop file to set name, description, icon * and other properties of your effect. Important fields of the .desktop file * are: * @li Name User-visible name of your effect * @li Icon Name of the icon of the effect * @li Comment Short description of the effect * @li Type must be "Service" * @li X-KDE-ServiceTypes must be "KWin/Effect" * @li X-KDE-PluginInfo-Name effect's internal name as passed to the KWIN_EFFECT macro plus "kwin4_effect_" prefix * @li X-KDE-PluginInfo-Category effect's category. Should be one of Appearance, Accessibility, Window Management, Demos, Tests, Misc * @li X-KDE-PluginInfo-EnabledByDefault whether the effect should be enabled by default (use sparingly). Default is false * @li X-KDE-Library name of the library containing the effect. This is the first argument passed to the KWIN_ADD_EFFECT macro in cmake file plus "kwin4_effect_" prefix. * * Example cooleffect.desktop file follows: * @code [Desktop Entry] Name=Cool Effect Comment=The coolest effect you've ever seen Icon=preferences-system-windows-effect-cooleffect Type=Service X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-Author=My Name X-KDE-PluginInfo-Email=my@email.here X-KDE-PluginInfo-Name=kwin4_effect_cooleffect X-KDE-PluginInfo-Category=Misc X-KDE-Library=kwin4_effect_cooleffect * @endcode * * * @section accessing Accessing windows and workspace * Effects can gain access to the properties of windows and workspace via * EffectWindow and EffectsHandler classes. * * There is one global EffectsHandler object which you can access using the * @ref effects pointer. * For each window, there is an EffectWindow object which can be used to read * window properties such as position and also to change them. * * For more information about this, see the documentation of the corresponding * classes. * * @{ **/ #define KWIN_EFFECT_API_MAKE_VERSION( major, minor ) (( major ) << 8 | ( minor )) #define KWIN_EFFECT_API_VERSION_MAJOR 0 #define KWIN_EFFECT_API_VERSION_MINOR 227 #define KWIN_EFFECT_API_VERSION KWIN_EFFECT_API_MAKE_VERSION( \ KWIN_EFFECT_API_VERSION_MAJOR, KWIN_EFFECT_API_VERSION_MINOR ) enum WindowQuadType { WindowQuadError, // for the stupid default ctor WindowQuadContents, WindowQuadDecoration, // Shadow Quad types WindowQuadShadow, // OpenGL only. The other shadow types are only used by Xrender WindowQuadShadowTop, WindowQuadShadowTopRight, WindowQuadShadowRight, WindowQuadShadowBottomRight, WindowQuadShadowBottom, WindowQuadShadowBottomLeft, WindowQuadShadowLeft, WindowQuadShadowTopLeft, EFFECT_QUAD_TYPE_START = 100 ///< @internal }; /** * EffectWindow::setData() and EffectWindow::data() global roles. * All values between 0 and 999 are reserved for global roles. */ enum DataRole { // Grab roles are used to force all other animations to ignore the window. // The value of the data is set to the Effect's `this` value. WindowAddedGrabRole = 1, WindowClosedGrabRole, WindowMinimizedGrabRole, WindowUnminimizedGrabRole, WindowForceBlurRole, ///< For fullscreen effects to enforce blurring of windows, WindowBlurBehindRole, ///< For single windows to blur behind WindowForceBackgroundContrastRole, ///< For fullscreen effects to enforce the background contrast, WindowBackgroundContrastRole, ///< For single windows to enable Background contrast LanczosCacheRole }; /** * Style types used by @ref EffectFrame. * @since 4.6 */ enum EffectFrameStyle { EffectFrameNone, ///< Displays no frame around the contents. EffectFrameUnstyled, ///< Displays a basic box around the contents. EffectFrameStyled ///< Displays a Plasma-styled frame around the contents. }; /** * Infinite region (i.e. a special region type saying that everything needs to be painted). */ KWINEFFECTS_EXPORT inline QRect infiniteRegion() { // INT_MIN / 2 because width/height is used (INT_MIN+INT_MAX==-1) return QRect(INT_MIN / 2, INT_MIN / 2, INT_MAX, INT_MAX); } /** * @short Base class for all KWin effects * * This is the base class for all effects. By reimplementing virtual methods * of this class, you can customize how the windows are painted. * * The virtual methods are used for painting and need to be implemented for * custom painting. * * In order to react to state changes (e.g. a window gets closed) the effect * should provide slots for the signals emitted by the EffectsHandler. * * @section Chaining * Most methods of this class are called in chain style. This means that when * effects A and B area active then first e.g. A::paintWindow() is called and * then from within that method B::paintWindow() is called (although * indirectly). To achieve this, you need to make sure to call corresponding * method in EffectsHandler class from each such method (using @ref effects * pointer): * @code * void MyEffect::postPaintScreen() * { * // Do your own processing here * ... * // Call corresponding EffectsHandler method * effects->postPaintScreen(); * } * @endcode * * @section Effectsptr Effects pointer * @ref effects pointer points to the global EffectsHandler object that you can * use to interact with the windows. * * @section painting Painting stages * Painting of windows is done in three stages: * @li First, the prepaint pass.
* Here you can specify how the windows will be painted, e.g. that they will * be translucent and transformed. * @li Second, the paint pass.
* Here the actual painting takes place. You can change attributes such as * opacity of windows as well as apply transformations to them. You can also * paint something onto the screen yourself. * @li Finally, the postpaint pass.
* Here you can mark windows, part of windows or even the entire screen for * repainting to create animations. * * For each stage there are *Screen() and *Window() methods. The window method * is called for every window which the screen method is usually called just * once. * * @section OpenGL * Effects can use OpenGL if EffectsHandler::isOpenGLCompositing() returns @c true. * The OpenGL context may not always be current when code inside the effect is * executed. The framework ensures that the OpenGL context is current when the Effect * gets created, destroyed or reconfigured and during the painting stages. All virtual * methods which have the OpenGL context current are documented. * * If OpenGL code is going to be executed outside the painting stages, e.g. in reaction * to a global shortcut, it is the task of the Effect to make the OpenGL context current: * @code * effects->makeOpenGLContextCurrent(); * @endcode * * There is in general no need to call the matching doneCurrent method. **/ class KWINEFFECTS_EXPORT Effect : public QObject { Q_OBJECT public: /** Flags controlling how painting is done. */ // TODO: is that ok here? enum { /** * Window (or at least part of it) will be painted opaque. **/ PAINT_WINDOW_OPAQUE = 1 << 0, /** * Window (or at least part of it) will be painted translucent. **/ PAINT_WINDOW_TRANSLUCENT = 1 << 1, /** * Window will be painted with transformed geometry. **/ PAINT_WINDOW_TRANSFORMED = 1 << 2, /** * Paint only a region of the screen (can be optimized, cannot * be used together with TRANSFORMED flags). **/ PAINT_SCREEN_REGION = 1 << 3, /** * The whole screen will be painted with transformed geometry. * Forces the entire screen to be painted. **/ PAINT_SCREEN_TRANSFORMED = 1 << 4, /** * At least one window will be painted with transformed geometry. * Forces the entire screen to be painted. **/ PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS = 1 << 5, /** * Clear whole background as the very first step, without optimizing it **/ PAINT_SCREEN_BACKGROUND_FIRST = 1 << 6, // PAINT_DECORATION_ONLY = 1 << 7 has been deprecated /** * Window will be painted with a lanczos filter. **/ PAINT_WINDOW_LANCZOS = 1 << 8 // PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS = 1 << 9 has been removed }; enum Feature { Nothing = 0, Resize, GeometryTip, Outline, /**< @deprecated */ ScreenInversion, Blur, Contrast, HighlightWindows }; /** * Constructs new Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is constructed. **/ Effect(); /** * Destructs the Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is destroyed. **/ virtual ~Effect(); /** * Flags describing which parts of configuration have changed. */ enum ReconfigureFlag { ReconfigureAll = 1 << 0 /// Everything needs to be reconfigured. }; Q_DECLARE_FLAGS(ReconfigureFlags, ReconfigureFlag) /** * Called when configuration changes (either the effect's or KWin's global). * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is reconfigured. If this method is called from within the Effect it is * required to ensure that the context is current if the implementation does OpenGL calls. */ virtual void reconfigure(ReconfigureFlags flags); /** * Called when another effect requests the proxy for this effect. */ virtual void* proxy(); /** * Called before starting to paint the screen. * In this method you can: * @li set whether the windows or the entire screen will be transformed * @li change the region of the screen that will be painted * @li do various housekeeping tasks such as initing your effect's variables for the upcoming paint pass or updating animation's progress * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintScreen(ScreenPrePaintData& data, int time); /** * In this method you can: * @li paint something on top of the windows (by painting after calling * effects->paintScreen()) * @li paint multiple desktops and/or multiple copies of the same desktop * by calling effects->paintScreen() multiple times * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); /** * Called after all the painting has been finished. * In this method you can: * @li schedule next repaint in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintScreen(); /** * Called for every window before the actual paint pass * In this method you can: * @li enable or disable painting of the window (e.g. enable paiting of minimized window) * @li set window to be painted with translucency * @li set window to be transformed * @li request the window to be divided into multiple parts * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); /** * This is the main method for painting windows. * In this method you can: * @li do various transformations * @li change opacity of the window * @li change brightness and/or saturation, if it's supported * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Called for every window after all painting has been finished. * In this method you can: * @li schedule next repaint for individual window(s) in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintWindow(EffectWindow* w); /** * This method is called directly before painting an @ref EffectFrame. * You can implement this method if you need to bind a shader or perform * other operations before the frame is rendered. * @param frame The EffectFrame which will be rendered * @param region Region to restrict painting to * @param opacity Opacity of text/icon * @param frameOpacity Opacity of background * @since 4.6 * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity); /** * Called on Transparent resizes. * return true if your effect substitutes questioned feature */ virtual bool provides(Feature); /** * Performs the @p feature with the @p arguments. * * This allows to have specific protocols between KWin core and an Effect. * * The method is supposed to return @c true if it performed the features, * @c false otherwise. * * The default implementation returns @c false. * @since 5.8 **/ virtual bool perform(Feature feature, const QVariantList &arguments); /** * Can be called to draw multiple copies (e.g. thumbnails) of a window. * You can change window's opacity/brightness/etc here, but you can't * do any transformations. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Define new window quads so that they can be transformed by other effects. * It's up to the effect to keep track of them. **/ virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList); virtual void windowInputMouseEvent(QEvent* e); virtual void grabbedKeyboardEvent(QKeyEvent* e); /** * Overwrite this method to indicate whether your effect will be doing something in * the next frame to be rendered. If the method returns @c false the effect will be * excluded from the chained methods in the next rendered frame. * * This method is called always directly before the paint loop begins. So it is totally * fine to e.g. react on a window event, issue a repaint to trigger an animation and * change a flag to indicate that this method returns @c true. * * As the method is called each frame, you should not perform complex calculations. * Best use just a boolean flag. * * The default implementation of this method returns @c true. * @since 4.8 **/ virtual bool isActive() const; /** * Reimplement this method to provide online debugging. * This could be as trivial as printing specific detail information about the effect state * but could also be used to move the effect in and out of a special debug modes, clear bogus * data, etc. * Notice that the functions is const by intent! Whenever you alter the state of the object * due to random user input, you should do so with greatest care, hence const_cast<> your * object - signalling "let me alone, i know what i'm doing" * @param parameter A freeform string user input for your effect to interpret. * @since 4.11 */ virtual QString debug(const QString ¶meter) const; /** * Reimplement this method to indicate where in the Effect chain the Effect should be placed. * * A low number indicates early chain position, thus before other Effects got called, a high * number indicates a late position. The returned number should be in the interval [0, 100]. * The default value is 0. * * In KWin4 this information was provided in the Effect's desktop file as property * X-KDE-Ordering. In the case of Scripted Effects this property is still used. * * @since 5.0 **/ virtual int requestedEffectChainPosition() const; /** * A touch point was pressed. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param pos The position of the touch point in global coordinates * @param time Timestamp * * @see touchMotion * @see touchUp * @since 5.8 **/ virtual bool touchDown(quint32 id, const QPointF &pos, quint32 time); /** * A touch point moved. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param pos The position of the touch point in global coordinates * @param time Timestamp * * @see touchDown * @see touchUp * @since 5.8 **/ virtual bool touchMotion(quint32 id, const QPointF &pos, quint32 time); /** * A touch point was released. * * If the effect wants to exclusively use the touch event it should return @c true. * If @c false is returned the touch event is passed to further effects. * * In general an Effect should only return @c true if it is the exclusive effect getting * input events. E.g. has grabbed mouse events. * * Default implementation returns @c false. * * @param id The unique id of the touch point * @param time Timestamp * * @see touchDown * @see touchMotion * @since 5.8 **/ virtual bool touchUp(quint32 id, quint32 time); static QPoint cursorPos(); /** * Read animation time from the configuration and possibly adjust using animationTimeFactor(). * The configuration value in the effect should also have special value 'default' (set using * QSpinBox::setSpecialValueText()) with the value 0. This special value is adjusted * using the global animation speed, otherwise the exact time configured is returned. * @param cfg configuration group to read value from * @param key configuration key to read value from * @param defaultTime default animation time in milliseconds */ // return type is intentionally double so that one can divide using it without losing data static double animationTime(const KConfigGroup& cfg, const QString& key, int defaultTime); /** * @overload Use this variant if the animation time is hardcoded and not configurable * in the effect itself. */ static double animationTime(int defaultTime); /** * @overload Use this variant if animation time is provided through a KConfigXT generated class * having a property called "duration". **/ template int animationTime(int defaultDuration); /** * Linearly interpolates between @p x and @p y. * * Returns @p x when @p a = 0; returns @p y when @p a = 1. **/ static double interpolate(double x, double y, double a) { return x * (1 - a) + y * a; } /** Helper to set WindowPaintData and QRegion to necessary transformations so that * a following drawWindow() would put the window at the requested geometry (useful for thumbnails) **/ static void setPositionTransformations(WindowPaintData& data, QRect& region, EffectWindow* w, const QRect& r, Qt::AspectRatioMode aspect); public Q_SLOTS: virtual bool borderActivated(ElectricBorder border); protected: xcb_connection_t *xcbConnection() const; xcb_window_t x11RootWindow() const; /** * An implementing class can call this with it's kconfig compiled singleton class. * This method will perform the instance on the class. * @since 5.9 **/ template void initConfig(); }; /** * Prefer the KWIN_EFFECT_FACTORY macros. */ class KWINEFFECTS_EXPORT EffectPluginFactory : public KPluginFactory { Q_OBJECT public: EffectPluginFactory(); virtual ~EffectPluginFactory(); /** * Returns whether the Effect is supported. * * An Effect can implement this method to determine at runtime whether the Effect is supported. * * If the current compositing backend is not supported it should return @c false. * * This method is optional, by default @c true is returned. */ virtual bool isSupported() const; /** * Returns whether the Effect should get enabled by default. * * This function provides a way for an effect to override the default at runtime, * e.g. based on the capabilities of the hardware. * * This method is optional; the effect doesn't have to provide it. * * Note that this function is only called if the supported() function returns true, * and if X-KDE-PluginInfo-EnabledByDefault is set to true in the .desktop file. * * This method is optional, by default @c true is returned. */ virtual bool enabledByDefault() const; /** * This method returns the created Effect. */ virtual KWin::Effect *createEffect() const = 0; }; /** * Defines an EffectPluginFactory sub class with customized isSupported and enabledByDefault methods. * * If the Effect to be created does not need the isSupported or enabledByDefault methods prefer * the simplified KWIN_EFFECT_FACTORY, KWIN_EFFECT_FACTORY_SUPPORTED or KWIN_EFFECT_FACTORY_ENABLED * macros which create an EffectPluginFactory with a useable default value. * * The macro also adds a useable K_EXPORT_PLUGIN_VERSION to the definition. KWin will not load * any Effect with a non-matching plugin version. This API is not providing binary compatibility * and thus the effect plugin must be compiled against the same kwineffects library version as * KWin. * * @param factoryName The name to be used for the EffectPluginFactory * @param className The class name of the Effect sub class which is to be created by the factory * @param jsonFile Name of the json file to be compiled into the plugin as metadata * @param supported Source code to go into the isSupported() method, must return a boolean * @param enabled Source code to go into the enabledByDefault() method, must return a boolean **/ #define KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, enabled ) \ class factoryName : public KWin::EffectPluginFactory \ { \ Q_OBJECT \ Q_PLUGIN_METADATA(IID KPluginFactory_iid FILE jsonFile) \ Q_INTERFACES(KPluginFactory) \ public: \ explicit factoryName() {} \ ~factoryName() {} \ bool isSupported() const override { \ supported \ } \ bool enabledByDefault() const override { \ enabled \ } \ KWin::Effect *createEffect() const override { \ return new className(); \ } \ }; \ K_EXPORT_PLUGIN_VERSION(quint32(KWIN_EFFECT_API_VERSION)) #define KWIN_EFFECT_FACTORY_ENABLED( factoryName, className, jsonFile, enabled ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, enabled ) #define KWIN_EFFECT_FACTORY_SUPPORTED( factoryName, classname, jsonFile, supported ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, return true; ) #define KWIN_EFFECT_FACTORY( factoryName, classname, jsonFile ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, return true; ) /** * @short Manager class that handles all the effects. * * This class creates Effect objects and calls it's appropriate methods. * * Effect objects can call methods of this class to interact with the * workspace, e.g. to activate or move a specific window, change current * desktop or create a special input window to receive mouse and keyboard * events. **/ class KWINEFFECTS_EXPORT EffectsHandler : public QObject { Q_OBJECT Q_PROPERTY(int currentDesktop READ currentDesktop WRITE setCurrentDesktop NOTIFY desktopChanged) Q_PROPERTY(QString currentActivity READ currentActivity NOTIFY currentActivityChanged) Q_PROPERTY(KWin::EffectWindow *activeWindow READ activeWindow WRITE activateWindow NOTIFY windowActivated) Q_PROPERTY(QSize desktopGridSize READ desktopGridSize) Q_PROPERTY(int desktopGridWidth READ desktopGridWidth) Q_PROPERTY(int desktopGridHeight READ desktopGridHeight) Q_PROPERTY(int workspaceWidth READ workspaceWidth) Q_PROPERTY(int workspaceHeight READ workspaceHeight) /** * The number of desktops currently used. Minimum number of desktops is 1, maximum 20. **/ Q_PROPERTY(int desktops READ numberOfDesktops WRITE setNumberOfDesktops NOTIFY numberDesktopsChanged) Q_PROPERTY(bool optionRollOverDesktops READ optionRollOverDesktops) Q_PROPERTY(int activeScreen READ activeScreen) Q_PROPERTY(int numScreens READ numScreens NOTIFY numberScreensChanged) /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ Q_PROPERTY(qreal animationTimeFactor READ animationTimeFactor) Q_PROPERTY(QList< KWin::EffectWindow* > stackingOrder READ stackingOrder) /** * Whether window decorations use the alpha channel. **/ Q_PROPERTY(bool decorationsHaveAlpha READ decorationsHaveAlpha) /** * Whether the window decorations support blurring behind the decoration. **/ Q_PROPERTY(bool decorationSupportsBlurBehind READ decorationSupportsBlurBehind) Q_PROPERTY(CompositingType compositingType READ compositingType CONSTANT) Q_PROPERTY(QPoint cursorPos READ cursorPos) Q_PROPERTY(QSize virtualScreenSize READ virtualScreenSize NOTIFY virtualScreenSizeChanged) Q_PROPERTY(QRect virtualScreenGeometry READ virtualScreenGeometry NOTIFY virtualScreenGeometryChanged) Q_PROPERTY(bool hasActiveFullScreenEffect READ hasActiveFullScreenEffect NOTIFY hasActiveFullScreenEffectChanged) friend class Effect; public: explicit EffectsHandler(CompositingType type); virtual ~EffectsHandler(); // for use by effects virtual void prePaintScreen(ScreenPrePaintData& data, int time) = 0; virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data) = 0; virtual void postPaintScreen() = 0; virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) = 0; virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void postPaintWindow(EffectWindow* w) = 0; virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) = 0; virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList) = 0; virtual QVariant kwinOption(KWinOption kwopt) = 0; /** * Sets the cursor while the mouse is intercepted. * @see startMouseInterception * @since 4.11 **/ virtual void defineCursor(Qt::CursorShape shape) = 0; virtual QPoint cursorPos() const = 0; virtual bool grabKeyboard(Effect* effect) = 0; virtual void ungrabKeyboard() = 0; /** * Ensures that all mouse events are sent to the @p effect. * No window will get the mouse events. Only fullscreen effects providing a custom user interface should * be using this method. The input events are delivered to Effect::windowInputMouseEvent. * * NOTE: this method does not perform an X11 mouse grab. On X11 a fullscreen input window is raised above * all other windows, but no grab is performed. * * @param shape Sets the cursor to be used while the mouse is intercepted * @see stopMouseInterception * @see Effect::windowInputMouseEvent * @since 4.11 **/ virtual void startMouseInterception(Effect *effect, Qt::CursorShape shape) = 0; /** * Releases the hold mouse interception for @p effect * @see startMouseInterception * @since 4.11 **/ virtual void stopMouseInterception(Effect *effect) = 0; /** * @brief Registers a global shortcut with the provided @p action. * * @param shortcut The global shortcut which should trigger the action * @param action The action which gets triggered when the shortcut matches */ virtual void registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) = 0; /** * @brief Registers a global pointer shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param pointerButtons The pointer buttons which need to be pressed * @param action The action which gets triggered when the shortcut matches **/ virtual void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) = 0; /** * @brief Registers a global axis shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param axis The direction in which the axis needs to be moved * @param action The action which gets triggered when the shortcut matches **/ virtual void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) = 0; /** * @brief Registers a global touchpad swipe gesture shortcut with the provided @p action. * * @param direction The direction for the swipe * @param action The action which gets triggered when the gesture triggers * @since 5.10 **/ virtual void registerTouchpadSwipeShortcut(SwipeDirection direction, QAction *action) = 0; /** * Retrieve the proxy class for an effect if it has one. Will return NULL if * the effect isn't loaded or doesn't have a proxy class. */ virtual void* getProxy(QString name) = 0; // Mouse polling virtual void startMousePolling() = 0; virtual void stopMousePolling() = 0; virtual void reserveElectricBorder(ElectricBorder border, Effect *effect) = 0; virtual void unreserveElectricBorder(ElectricBorder border, Effect *effect) = 0; /** * Registers the given @p action for the given @p border to be activated through * a touch swipe gesture. * * If the @p border gets triggered through a touch swipe gesture the @link{QAction::triggered} * signal gets invoked. * * To unregister the touch screen action either delete the @p action or * invoke @link{unregisterTouchBorder}. * * @see unregisterTouchBorder * @since 5.10 **/ virtual void registerTouchBorder(ElectricBorder border, QAction *action) = 0; /** * Unregisters the given @p action for the given touch @p border. * * @see registerTouchBorder * @since 5.10 **/ virtual void unregisterTouchBorder(ElectricBorder border, QAction *action) = 0; // functions that allow controlling windows/desktop virtual void activateWindow(KWin::EffectWindow* c) = 0; virtual KWin::EffectWindow* activeWindow() const = 0 ; Q_SCRIPTABLE virtual void moveWindow(KWin::EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0) = 0; /** * Moves the window to the specific desktop * Setting desktop to NET::OnAllDesktops will set the window on all desktops */ Q_SCRIPTABLE virtual void windowToDesktop(KWin::EffectWindow* w, int desktop) = 0; /** * Moves a window to the given desktops * On X11, the window will end up on the last window in the list * Setting this to an empty list will set the window on all desktops * * @arg desktopIds a list of desktops the window should be placed on. NET::OnAllDesktops is not a valid desktop X11Id */ Q_SCRIPTABLE virtual void windowToDesktops(KWin::EffectWindow* w, const QVector &desktopIds) = 0; Q_SCRIPTABLE virtual void windowToScreen(KWin::EffectWindow* w, int screen) = 0; virtual void setShowingDesktop(bool showing) = 0; // Activities /** * @returns The ID of the current activity. */ virtual QString currentActivity() const = 0; // Desktops /** * @returns The ID of the current desktop. */ virtual int currentDesktop() const = 0; /** * @returns Total number of desktops currently in existence. */ virtual int numberOfDesktops() const = 0; /** * Set the current desktop to @a desktop. */ virtual void setCurrentDesktop(int desktop) = 0; /** * Sets the total number of desktops to @a desktops. */ virtual void setNumberOfDesktops(int desktops) = 0; /** * @returns The size of desktop layout in grid units. */ virtual QSize desktopGridSize() const = 0; /** * @returns The width of desktop layout in grid units. */ virtual int desktopGridWidth() const = 0; /** * @returns The height of desktop layout in grid units. */ virtual int desktopGridHeight() const = 0; /** * @returns The width of desktop layout in pixels. */ virtual int workspaceWidth() const = 0; /** * @returns The height of desktop layout in pixels. */ virtual int workspaceHeight() const = 0; /** * @returns The ID of the desktop at the point @a coords or 0 if no desktop exists at that * point. @a coords is to be in grid units. */ virtual int desktopAtCoords(QPoint coords) const = 0; /** * @returns The coords of desktop @a id in grid units. */ virtual QPoint desktopGridCoords(int id) const = 0; /** * @returns The coords of the top-left corner of desktop @a id in pixels. */ virtual QPoint desktopCoords(int id) const = 0; /** * @returns The ID of the desktop above desktop @a id. Wraps around to the bottom of * the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopAbove(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the right of desktop @a id. Wraps around to the * left of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToRight(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop below desktop @a id. Wraps around to the top of the * layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopBelow(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the left of desktop @a id. Wraps around to the * right of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToLeft(int desktop = 0, bool wrap = true) const = 0; Q_SCRIPTABLE virtual QString desktopName(int desktop) const = 0; virtual bool optionRollOverDesktops() const = 0; virtual int activeScreen() const = 0; // Xinerama virtual int numScreens() const = 0; // Xinerama Q_SCRIPTABLE virtual int screenNumber(const QPoint& pos) const = 0; // Xinerama virtual QRect clientArea(clientAreaOption, int screen, int desktop) const = 0; virtual QRect clientArea(clientAreaOption, const EffectWindow* c) const = 0; virtual QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const = 0; /** * The bounding size of all screens combined. Overlapping areas * are not counted multiple times. * * @see virtualScreenGeometry() * @see virtualScreenSizeChanged() * @since 5.0 **/ virtual QSize virtualScreenSize() const = 0; /** * The bounding geometry of all outputs combined. Always starts at (0,0) and has * virtualScreenSize as it's size. * * @see virtualScreenSize() * @see virtualScreenGeometryChanged() * @since 5.0 **/ virtual QRect virtualScreenGeometry() const = 0; /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ virtual double animationTimeFactor() const = 0; virtual WindowQuadType newWindowQuadType() = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(WId id) const = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(KWayland::Server::SurfaceInterface *surf) const = 0; virtual EffectWindowList stackingOrder() const = 0; // window will be temporarily painted as if being at the top of the stack Q_SCRIPTABLE virtual void setElevatedWindow(KWin::EffectWindow* w, bool set) = 0; virtual void setTabBoxWindow(EffectWindow*) = 0; virtual void setTabBoxDesktop(int) = 0; virtual EffectWindowList currentTabBoxWindowList() const = 0; virtual void refTabBox() = 0; virtual void unrefTabBox() = 0; virtual void closeTabBox() = 0; virtual QList< int > currentTabBoxDesktopList() const = 0; virtual int currentTabBoxDesktop() const = 0; virtual EffectWindow* currentTabBoxWindow() const = 0; virtual void setActiveFullScreenEffect(Effect* e) = 0; virtual Effect* activeFullScreenEffect() const = 0; /** * Schedules the entire workspace to be repainted next time. * If you call it during painting (including prepaint) then it does not * affect the current painting. **/ Q_SCRIPTABLE virtual void addRepaintFull() = 0; Q_SCRIPTABLE virtual void addRepaint(const QRect& r) = 0; Q_SCRIPTABLE virtual void addRepaint(const QRegion& r) = 0; Q_SCRIPTABLE virtual void addRepaint(int x, int y, int w, int h) = 0; CompositingType compositingType() const; /** * @brief Whether the Compositor is OpenGL based (either GL 1 or 2). * * @return bool @c true in case of OpenGL based Compositor, @c false otherwise **/ bool isOpenGLCompositing() const; virtual unsigned long xrenderBufferPicture() = 0; /** * @brief Provides access to the QPainter which is rendering to the back buffer. * * Only relevant for CompositingType QPainterCompositing. For all other compositing types * @c null is returned. * * @return QPainter* The Scene's QPainter or @c null. */ virtual QPainter *scenePainter() = 0; virtual void reconfigure() = 0; virtual QByteArray readRootProperty(long atom, long type, int format) const = 0; /** * @brief Announces support for the feature with the given name. If no other Effect * has announced support for this feature yet, an X11 property will be installed on * the root window. * * The Effect will be notified for events through the signal propertyNotify(). * * To remove the support again use @link removeSupportProperty. When an Effect is * destroyed it is automatically taken care of removing the support. It is not * required to call @link removeSupportProperty in the Effect's cleanup handling. * * @param propertyName The name of the property to announce support for * @param effect The effect which announces support * @return xcb_atom_t The created X11 atom * @see removeSupportProperty * @since 4.11 **/ virtual xcb_atom_t announceSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * @brief Removes support for the feature with the given name. If there is no other Effect left * which has announced support for the given property, the property will be removed from the * root window. * * In case the Effect had not registered support, calling this function does not change anything. * * @param propertyName The name of the property to remove support for * @param effect The effect which had registered the property. * @see announceSupportProperty * @since 4.11 **/ virtual void removeSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * Returns @a true if the active window decoration has shadow API hooks. */ virtual bool hasDecorationShadows() const = 0; /** * Returns @a true if the window decorations use the alpha channel, and @a false otherwise. * @since 4.5 */ virtual bool decorationsHaveAlpha() const = 0; /** * Returns @a true if the window decorations support blurring behind the decoration, and @a false otherwise * @since 4.6 */ virtual bool decorationSupportsBlurBehind() const = 0; /** * Creates a new frame object. If the frame does not have a static size * then it will be located at @a position with @a alignment. A * non-static frame will automatically adjust its size to fit the contents. * @returns A new @ref EffectFrame. It is the responsibility of the caller to delete the * EffectFrame. * @since 4.6 */ virtual EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize = true, const QPoint& position = QPoint(-1, -1), Qt::Alignment alignment = Qt::AlignCenter) const = 0; /** * Allows an effect to trigger a reload of itself. * This can be used by an effect which needs to be reloaded when screen geometry changes. * It is possible that the effect cannot be loaded again as it's supported method does no longer * hold. * @param effect The effect to reload * @since 4.8 **/ virtual void reloadEffect(Effect *effect) = 0; /** * Whether the screen is currently considered as locked. * Note for technical reasons this is not always possible to detect. The screen will only * be considered as locked if the screen locking process implements the * org.freedesktop.ScreenSaver interface. * * @returns @c true if the screen is currently locked, @c false otherwise * @see screenLockingChanged * @since 4.11 **/ virtual bool isScreenLocked() const = 0; /** * @brief Makes the OpenGL compositing context current. * * If the compositing backend is not using OpenGL, this method returns @c false. * * @return bool @c true if the context became current, @c false otherwise. */ virtual bool makeOpenGLContextCurrent() = 0; /** * @brief Makes a null OpenGL context current resulting in no context * being current. * * If the compositing backend is not OpenGL based, this method is a noop. * * There is normally no reason for an Effect to call this method. */ virtual void doneOpenGLContextCurrent() = 0; virtual xcb_connection_t *xcbConnection() const = 0; virtual xcb_window_t x11RootWindow() const = 0; /** * Interface to the Wayland display: this is relevant only * on Wayland, on X11 it will be nullptr * @since 5.5 */ virtual KWayland::Server::Display *waylandDisplay() const = 0; /** * Whether animations are supported by the Scene. * If this method returns @c false Effects are supposed to not * animate transitions. * * @returns Whether the Scene can drive animations * @since 5.8 **/ virtual bool animationsSupported() const = 0; /** * The current cursor image of the Platform. * @see cursorPos * @since 5.9 **/ virtual PlatformCursorImage cursorImage() const = 0; /** * The cursor image should be hidden. * @see showCursor * @since 5.9 **/ virtual void hideCursor() = 0; /** - * The cursor image should be shown again after having been hidden.. + * The cursor image should be shown again after having been hidden. * @see hideCursor * @since 5.9 **/ virtual void showCursor() = 0; /** * Starts an interactive window selection process. * * Once the user selected a window the @p callback is invoked with the selected EffectWindow as * argument. In case the user cancels the interactive window selection or selecting a window is currently * not possible (e.g. screen locked) the @p callback is invoked with a @c nullptr argument. * * During the interactive window selection the cursor is turned into a crosshair cursor. * * @param callback The function to invoke once the interactive window selection ends * @since 5.9 **/ virtual void startInteractiveWindowSelection(std::function callback) = 0; /** * Starts an interactive position selection process. * * Once the user selected a position on the screen the @p callback is invoked with * the selected point as argument. In case the user cancels the interactive position selection * or selecting a position is currently not possible (e.g. screen locked) the @p callback * is invoked with a point at @c -1 as x and y argument. * * During the interactive window selection the cursor is turned into a crosshair cursor. * * @param callback The function to invoke once the interactive position selection ends * @since 5.9 **/ virtual void startInteractivePositionSelection(std::function callback) = 0; /** * Shows an on-screen-message. To hide it again use @link{hideOnScreenMessage}. * * @param message The message to show * @param iconName The optional themed icon name * @see hideOnScreenMessage * @since 5.9 **/ virtual void showOnScreenMessage(const QString &message, const QString &iconName = QString()) = 0; /** * Flags for how to hide a shown on-screen-message * @see hideOnScreenMessage * @since 5.9 **/ enum class OnScreenMessageHideFlag { /** * The on-screen-message should skip the close window animation. * @see EffectWindow::skipsCloseAnimation **/ SkipsCloseAnimation = 1 }; Q_DECLARE_FLAGS(OnScreenMessageHideFlags, OnScreenMessageHideFlag) /** * Hides a previously shown on-screen-message again. * @param flags The flags for how to hide the message * @see showOnScreenMessage * @since 5.9 **/ virtual void hideOnScreenMessage(OnScreenMessageHideFlags flags = OnScreenMessageHideFlags()) = 0; /* * @returns The configuration used by the EffectsHandler. * @since 5.10 **/ virtual KSharedConfigPtr config() const = 0; /** * @returns The global input configuration (kcminputrc) * @since 5.10 **/ virtual KSharedConfigPtr inputConfig() const = 0; /** * Returns if activeFullScreenEffect is set */ virtual bool hasActiveFullScreenEffect() const = 0; Q_SIGNALS: /** * Signal emitted when the current desktop changed. * @param oldDesktop The previously current desktop * @param newDesktop The new current desktop * @param with The window which is taken over to the new desktop, can be NULL * @since 4.9 */ void desktopChanged(int oldDesktop, int newDesktop, KWin::EffectWindow *with); /** * @since 4.7 * @deprecated */ void desktopChanged(int oldDesktop, int newDesktop); /** * Signal emitted when a window moved to another desktop * NOTICE that this does NOT imply that the desktop has changed * The @param window which is moved to the new desktop * @param oldDesktop The previous desktop of the window * @param newDesktop The new desktop of the window * @since 4.11.4 */ void desktopPresenceChanged(KWin::EffectWindow *window, int oldDesktop, int newDesktop); /** * Signal emitted when the number of currently existing desktops is changed. * @param old The previous number of desktops in used. * @see EffectsHandler::numberOfDesktops. * @since 4.7 */ void numberDesktopsChanged(uint old); /** * Signal emitted when the number of screens changed. * @since 5.0 **/ void numberScreensChanged(); /** * Signal emitted when the desktop showing ("dashboard") state changed * The desktop is risen to the keepAbove layer, you may want to elevate * windows or such. * @since 5.3 **/ void showingDesktopChanged(bool); /** * Signal emitted when a new window has been added to the Workspace. * @param w The added window * @since 4.7 **/ void windowAdded(KWin::EffectWindow *w); /** * Signal emitted when a window is being removed from the Workspace. * An effect which wants to animate the window closing should connect * to this signal and reference the window by using - * @link EffectWindow::refWindow + * @ref EffectWindow::refWindow * @param w The window which is being closed * @since 4.7 **/ void windowClosed(KWin::EffectWindow *w); /** * Signal emitted when a window get's activated. * @param w The new active window, or @c NULL if there is no active window. * @since 4.7 **/ void windowActivated(KWin::EffectWindow *w); /** * Signal emitted when a window is deleted. * This means that a closed window is not referenced any more. * An effect bookkeeping the closed windows should connect to this * signal to clean up the internal references. * @param w The window which is going to be deleted. * @see EffectWindow::refWindow * @see EffectWindow::unrefWindow * @see windowClosed * @since 4.7 **/ void windowDeleted(KWin::EffectWindow *w); /** * Signal emitted when a user begins a window move or resize operation. * To figure out whether the user resizes or moves the window use - * @link EffectWindow::isUserMove or @link EffectWindow::isUserResize. + * @ref EffectWindow::isUserMove or @link EffectWindow::isUserResize. * Whenever the geometry is updated the signal @link windowStepUserMovedResized * is emitted with the current geometry. * The move/resize operation ends with the signal @link windowFinishUserMovedResized. * Only one window can be moved/resized by the user at the same time! * @param w The window which is being moved/resized * @see windowStepUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStartUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted during a move/resize operation when the user changed the geometry. * Please note: KWin supports two operation modes. In one mode all changes are applied * instantly. This means the window's geometry matches the passed in @p geometry. In the * other mode the geometry is changed after the user ended the move/resize mode. * The @p geometry differs from the window's geometry. Also the window's pixmap still has * the same size as before. Depending what the effect wants to do it would be recommended * to scale/translate the window. * @param w The window which is being moved/resized * @param geometry The geometry of the window in the current move/resize step. * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStepUserMovedResized(KWin::EffectWindow *w, const QRect &geometry); /** * Signal emitted when the user finishes move/resize of window @p w. * @param w The window which has been moved/resized * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @since 4.7 **/ void windowFinishUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted when the maximized state of the window @p w changed. * A window can be in one of four states: * @li restored: both @p horizontal and @p vertical are @c false * @li horizontally maximized: @p horizontal is @c true and @p vertical is @c false * @li vertically maximized: @p horizontal is @c false and @p vertical is @c true - * @li completely maximized: both @p horizontal and @p vertical are @C true + * @li completely maximized: both @p horizontal and @p vertical are @c true * @param w The window whose maximized state changed * @param horizontal If @c true maximized horizontally * @param vertical If @c true maximized vertically * @since 4.7 **/ void windowMaximizedStateChanged(KWin::EffectWindow *w, bool horizontal, bool vertical); /** * Signal emitted when the geometry or shape of a window changed. * This is caused if the window changes geometry without user interaction. * E.g. the decoration is changed. This is in opposite to windowUserMovedResized * which is caused by direct user interaction. * @param w The window whose geometry changed * @param old The previous geometry * @see windowUserMovedResized * @since 4.7 **/ void windowGeometryShapeChanged(KWin::EffectWindow *w, const QRect &old); /** * Signal emitted when the padding of a window changed. (eg. shadow size) * @param w The window whose geometry changed * @param old The previous expandedGeometry() * @since 4.9 **/ void windowPaddingChanged(KWin::EffectWindow *w, const QRect &old); /** * Signal emitted when the windows opacity is changed. * @param w The window whose opacity level is changed. * @param oldOpacity The previous opacity level * @param newOpacity The new opacity level * @since 4.7 **/ void windowOpacityChanged(KWin::EffectWindow *w, qreal oldOpacity, qreal newOpacity); /** * Signal emitted when a window got minimized. * @param w The window which was minimized * @since 4.7 **/ void windowMinimized(KWin::EffectWindow *w); /** * Signal emitted when a window got unminimized. * @param w The window which was unminimized * @since 4.7 **/ void windowUnminimized(KWin::EffectWindow *w); /** * Signal emitted when a window either becomes modal (ie. blocking for its main client) or looses that state. * @param w The window which was unminimized * @since 4.11 **/ void windowModalityChanged(KWin::EffectWindow *w); /** * Signal emitted when a window either became unresponsive (eg. app froze or crashed) * or respoonsive * @param w The window that became (un)responsive * @param unresponsive Whether the window is responsive or unresponsive * @since 5.10 */ void windowUnresponsiveChanged(KWin::EffectWindow *w, bool unresponsive); /** * Signal emitted when an area of a window is scheduled for repainting. * Use this signal in an effect if another area needs to be synced as well. * @param w The window which is scheduled for repainting * @param r Always empty. * @since 4.7 **/ void windowDamaged(KWin::EffectWindow *w, const QRect &r); /** * Signal emitted when a tabbox is added. - * An effect who wants to replace the tabbox with itself should use @link refTabBox. + * An effect who wants to replace the tabbox with itself should use refTabBox. * @param mode The TabBoxMode. * @see refTabBox * @see tabBoxClosed * @see tabBoxUpdated * @see tabBoxKeyEvent * @since 4.7 **/ void tabBoxAdded(int mode); /** * Signal emitted when the TabBox was closed by KWin core. * An effect which referenced the TabBox should use @link unrefTabBox to unref again. * @see unrefTabBox * @see tabBoxAdded * @since 4.7 **/ void tabBoxClosed(); /** * Signal emitted when the selected TabBox window changed or the TabBox List changed. - * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. + * An effect should only response to this signal if it referenced the TabBox with refTabBox. * @see refTabBox * @see currentTabBoxWindowList * @see currentTabBoxDesktopList * @see currentTabBoxWindow * @see currentTabBoxDesktop * @since 4.7 **/ void tabBoxUpdated(); /** * Signal emitted when a key event, which is not handled by TabBox directly is, happens while * TabBox is active. An effect might use the key event to e.g. change the selected window. * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. * @param event The key event not handled by TabBox directly * @see refTabBox * @since 4.7 **/ void tabBoxKeyEvent(QKeyEvent* event); void currentTabAboutToChange(KWin::EffectWindow* from, KWin::EffectWindow* to); void tabAdded(KWin::EffectWindow* from, KWin::EffectWindow* to); // from merged with to void tabRemoved(KWin::EffectWindow* c, KWin::EffectWindow* group); // c removed from group /** * Signal emitted when mouse changed. - * If an effect needs to get updated mouse positions, it needs to first call @link startMousePolling. - * For a fullscreen effect it is better to use an input window and react on @link windowInputMouseEvent. + * If an effect needs to get updated mouse positions, it needs to first call startMousePolling. + * For a fullscreen effect it is better to use an input window and react on windowInputMouseEvent. * @param pos The new mouse position * @param oldpos The previously mouse position * @param buttons The pressed mouse buttons * @param oldbuttons The previously pressed mouse buttons * @param modifiers Pressed keyboard modifiers * @param oldmodifiers Previously pressed keyboard modifiers. * @see startMousePolling * @since 4.7 **/ void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); /** * Signal emitted when the cursor shape changed. * You'll likely want to query the current cursor as reaction: xcb_xfixes_get_cursor_image_unchecked * Connection to this signal is tracked, so if you don't need it anymore, disconnect from it to stop cursor event filtering */ void cursorShapeChanged(); /** - * Receives events registered for using @link registerPropertyType. + * Receives events registered for using registerPropertyType. * Use readProperty() to get the property data. * Note that the property may be already set on the window, so doing the same * processing from windowAdded() (e.g. simply calling propertyNotify() from it) * is usually needed. * @param w The window whose property changed, is @c null if it is a root window property * @param atom The property * @since 4.7 */ void propertyNotify(KWin::EffectWindow* w, long atom); /** * Signal emitted after the screen geometry changed (e.g. add of a monitor). * Effects using displayWidth()/displayHeight() to cache information should * react on this signal and update the caches. * @param size The new screen size * @since 4.8 **/ void screenGeometryChanged(const QSize &size); /** * This signal is emitted when the global * activity is changed * @param id id of the new current activity * @since 4.9 **/ void currentActivityChanged(const QString &id); /** * This signal is emitted when a new activity is added * @param id id of the new activity * @since 4.9 */ void activityAdded(const QString &id); /** * This signal is emitted when the activity * is removed * @param id id of the removed activity * @since 4.9 */ void activityRemoved(const QString &id); /** * This signal is emitted when the screen got locked or unlocked. * @param locked @c true if the screen is now locked, @c false if it is now unlocked * @since 4.11 **/ void screenLockingChanged(bool locked); /** * This signels is emitted when ever the stacking order is change, ie. a window is risen * or lowered * @since 4.10 */ void stackingOrderChanged(); /** * This signal is emitted when the user starts to approach the @p border with the mouse. * The @p factor describes how far away the mouse is in a relative mean. The values are in * [0.0, 1.0] with 0.0 being emitted when first entered and on leaving. The value 1.0 means that * the @p border is reached with the mouse. So the values are well suited for animations. * The signal is always emitted when the mouse cursor position changes. * @param border The screen edge which is being approached * @param factor Value in range [0.0,1.0] to describe how close the mouse is to the border * @param geometry The geometry of the edge which is being approached * @since 4.11 **/ void screenEdgeApproaching(ElectricBorder border, qreal factor, const QRect &geometry); /** * Emitted whenever the virtualScreenSize changes. * @see virtualScreenSize() * @since 5.0 **/ void virtualScreenSizeChanged(); /** * Emitted whenever the virtualScreenGeometry changes. * @see virtualScreenGeometry() * @since 5.0 **/ void virtualScreenGeometryChanged(); /** * The window @p w gets shown again. The window was previously * initially shown with @link{windowAdded} and hidden with @link{windowHidden}. * * @see windowHidden * @see windowAdded * @since 5.8 **/ void windowShown(KWin::EffectWindow *w); /** * The window @p w got hidden but not yet closed. * This can happen when a window is still being used and is supposed to be shown again * with @link{windowShown}. On X11 an example is autohiding panels. On Wayland every * window first goes through the window hidden state and might get shown again, or might * get closed the normal way. * * @see windowShown * @see windowClosed * @since 5.8 **/ void windowHidden(KWin::EffectWindow *w); /** * This signal gets emitted when the data on EffectWindow @p w for @p role changed. * * An Effect can connect to this signal to read the new value and react on it. * E.g. an Effect which does not operate on windows grabbed by another Effect wants * to cancel the already scheduled animation if another Effect adds a grab. * * @param w The EffectWindow for which the data changed * @param role The data role which changed * @see EffectWindow::setData * @see EffectWindow::data * @since 5.8.4 **/ void windowDataChanged(KWin::EffectWindow *w, int role); /** * The xcb connection changed, either a new xcbConnection got created or the existing one * got destroyed. * Effects can use this to refetch the properties they want to set. * * When the xcbConnection changes also the @link{x11RootWindow} becomes invalid. * @see xcbConnection * @see x11RootWindow * @since 5.11 **/ void xcbConnectionChanged(); /** * This signal is emitted when active fullscreen effect changed. * * @see activeFullScreenEffect * @see setActiveFullScreenEffect * @since 5.14 **/ void activeFullScreenEffectChanged(); /** * This signal is emitted when active fullscreen effect changed to being * set or unset * * @see activeFullScreenEffect * @see setActiveFullScreenEffect * @since 5.15 **/ void hasActiveFullScreenEffectChanged(); /** * This signal is emitted when the keep above state of @p w was changed. * * @param w The window whose the keep above state was changed. * @since 5.15 **/ void windowKeepAboveChanged(EffectWindow *w); /** * This signal is emitted when the keep below state of @p was changed. * * @param w The window whose the keep below state was changed. * @since 5.15 **/ void windowKeepBelowChanged(EffectWindow *w); /** * This signal is emitted when the full screen state of @p w was changed. * * @param w The window whose the full screen state was changed. * @since 5.15 **/ void windowFullScreenChanged(EffectWindow *w); protected: QVector< EffectPair > loaded_effects; //QHash< QString, EffectFactory* > effect_factories; CompositingType compositing_type; }; /** * @short Representation of a window used by/for Effect classes. * * The purpose is to hide internal data and also to serve as a single * representation for the case when Client/Unmanaged becomes Deleted. **/ class KWINEFFECTS_EXPORT EffectWindow : public QObject { Q_OBJECT Q_PROPERTY(bool alpha READ hasAlpha CONSTANT) Q_PROPERTY(QRect geometry READ geometry) Q_PROPERTY(QRect expandedGeometry READ expandedGeometry) Q_PROPERTY(int height READ height) Q_PROPERTY(qreal opacity READ opacity) Q_PROPERTY(QPoint pos READ pos) Q_PROPERTY(int screen READ screen) Q_PROPERTY(QSize size READ size) Q_PROPERTY(int width READ width) Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int desktop READ desktop) Q_PROPERTY(bool onAllDesktops READ isOnAllDesktops) Q_PROPERTY(bool onCurrentDesktop READ isOnCurrentDesktop) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QString windowClass READ windowClass) Q_PROPERTY(QString windowRole READ windowRole) /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool desktopWindow READ isDesktop) /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dock READ isDock) /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool toolbar READ isToolbar) /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool menu READ isMenu) /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool normalWindow READ isNormalWindow) /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dialog READ isDialog) /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool splash READ isSplash) /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool utility READ isUtility) /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dropdownMenu READ isDropdownMenu) /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool popupMenu READ isPopupMenu) /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool tooltip READ isTooltip) /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ Q_PROPERTY(bool onScreenDisplay READ isOnScreenDisplay) /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool comboBox READ isComboBox) /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(int windowType READ windowType) /** * Whether this EffectWindow is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). **/ Q_PROPERTY(bool managed READ isManaged) /** * Whether this EffectWindow represents an already deleted window and only kept for the compositor for animations. **/ Q_PROPERTY(bool deleted READ isDeleted) /** * Whether the window has an own shape **/ Q_PROPERTY(bool shaped READ hasOwnShape) /** * The Window's shape **/ Q_PROPERTY(QRegion shape READ shape) /** * The Caption of the window. Read from WM_NAME property together with a suffix for hostname and shortcut. **/ Q_PROPERTY(QString caption READ caption) /** * Whether the window is set to be kept above other windows. **/ Q_PROPERTY(bool keepAbove READ keepAbove) /** * Whether the window is set to be kept below other windows. **/ Q_PROPERTY(bool keepBelow READ keepBelow) /** * Whether the window is minimized. **/ Q_PROPERTY(bool minimized READ isMinimized WRITE setMinimized) /** * Whether the window represents a modal window. **/ Q_PROPERTY(bool modal READ isModal) /** * Whether the window is moveable. Even if it is not moveable, it might be possible to move * it to another screen. * @see moveableAcrossScreens **/ Q_PROPERTY(bool moveable READ isMovable) /** * Whether the window can be moved to another screen. * @see moveable **/ Q_PROPERTY(bool moveableAcrossScreens READ isMovableAcrossScreens) /** * By how much the window wishes to grow/shrink at least. Usually QSize(1,1). * MAY BE DISOBEYED BY THE WM! It's only for information, do NOT rely on it at all. */ Q_PROPERTY(QSize basicUnit READ basicUnit) /** * Whether the window is currently being moved by the user. **/ Q_PROPERTY(bool move READ isUserMove) /** * Whether the window is currently being resized by the user. **/ Q_PROPERTY(bool resize READ isUserResize) /** * The optional geometry representing the minimized Client in e.g a taskbar. * See _NET_WM_ICON_GEOMETRY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . **/ Q_PROPERTY(QRect iconGeometry READ iconGeometry) /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. **/ Q_PROPERTY(bool specialWindow READ isSpecialWindow) Q_PROPERTY(QIcon icon READ icon) /** * Whether the window should be excluded from window switching effects. **/ Q_PROPERTY(bool skipSwitcher READ isSkipSwitcher) /** * Geometry of the actual window contents inside the whole (including decorations) window. */ Q_PROPERTY(QRect contentsRect READ contentsRect) /** * Geometry of the transparent rect in the decoration. * May be different from contentsRect if the decoration is extended into the client area. */ Q_PROPERTY(QRect decorationInnerRect READ decorationInnerRect) Q_PROPERTY(bool hasDecoration READ hasDecoration) Q_PROPERTY(QStringList activities READ activities) Q_PROPERTY(bool onCurrentActivity READ isOnCurrentActivity) Q_PROPERTY(bool onAllActivities READ isOnAllActivities) /** * Whether the decoration currently uses an alpha channel. * @since 4.10 **/ Q_PROPERTY(bool decorationHasAlpha READ decorationHasAlpha) /** * Whether the window is currently visible to the user, that is: *
    *
  • Not minimized
  • *
  • On current desktop
  • *
  • On current activity
  • *
* @since 4.11 **/ Q_PROPERTY(bool visible READ isVisible) /** * Whether the window does not want to be animated on window close. * In case this property is @c true it is not useful to start an animation on window close. * The window will not be visible, but the animation hooks are executed. * @since 5.0 **/ Q_PROPERTY(bool skipsCloseAnimation READ skipsCloseAnimation) /** * Interface to the corresponding wayland surface. * relevant only in Wayland, on X11 it will be nullptr */ Q_PROPERTY(KWayland::Server::SurfaceInterface *surface READ surface) /** * Whether the window is fullscreen. * @since 5.6 **/ Q_PROPERTY(bool fullScreen READ isFullScreen) /** * Whether this client is unresponsive. * * When an application failed to react on a ping request in time, it is * considered unresponsive. This usually indicates that the application froze or crashed. * * @since 5.10 */ Q_PROPERTY(bool unresponsive READ isUnresponsive) /** * Whether this is a Wayland client. * @since 5.15 **/ Q_PROPERTY(bool waylandClient READ isWaylandClient CONSTANT) /** * Whether this is an X11 client. * @since 5.15 **/ Q_PROPERTY(bool x11Client READ isX11Client CONSTANT) /** * Whether the window is a popup. * * A popup is a window that can be used to implement tooltips, combo box popups, * popup menus and other similar user interface concepts. * * @since 5.15 **/ Q_PROPERTY(bool popupWindow READ isPopupWindow CONSTANT) public: /** Flags explaining why painting should be disabled */ enum { /** Window will not be painted */ PAINT_DISABLED = 1 << 0, /** Window will not be painted because it is deleted */ PAINT_DISABLED_BY_DELETE = 1 << 1, /** Window will not be painted because of which desktop it's on */ PAINT_DISABLED_BY_DESKTOP = 1 << 2, /** Window will not be painted because it is minimized */ PAINT_DISABLED_BY_MINIMIZE = 1 << 3, /** Window will not be painted because it is not the active window in a client group */ PAINT_DISABLED_BY_TAB_GROUP = 1 << 4, /** Window will not be painted because it's not on the current activity */ PAINT_DISABLED_BY_ACTIVITY = 1 << 5 }; explicit EffectWindow(QObject *parent = nullptr); virtual ~EffectWindow(); virtual void enablePainting(int reason) = 0; virtual void disablePainting(int reason) = 0; virtual bool isPaintingEnabled() = 0; Q_SCRIPTABLE virtual void addRepaint(const QRect &r) = 0; Q_SCRIPTABLE virtual void addRepaint(int x, int y, int w, int h) = 0; Q_SCRIPTABLE virtual void addRepaintFull() = 0; Q_SCRIPTABLE virtual void addLayerRepaint(const QRect &r) = 0; Q_SCRIPTABLE virtual void addLayerRepaint(int x, int y, int w, int h) = 0; virtual void refWindow() = 0; virtual void unrefWindow() = 0; virtual bool isDeleted() const = 0; virtual bool isMinimized() const = 0; virtual double opacity() const = 0; virtual bool hasAlpha() const = 0; bool isOnCurrentActivity() const; Q_SCRIPTABLE bool isOnActivity(QString id) const; bool isOnAllActivities() const; virtual QStringList activities() const = 0; Q_SCRIPTABLE bool isOnDesktop(int d) const; bool isOnCurrentDesktop() const; bool isOnAllDesktops() const; /** * The desktop this window is in. This mkaes sense only on X11 * where desktops are mutually exclusive, on Wayland it's the last * desktop the window has been added to. * use desktops() instead. * @see desktops() * @deprecated */ #ifndef KWIN_NO_DEPRECATED virtual int KWIN_DEPRECATED desktop() const = 0; // prefer isOnXXX() #endif /** * All the desktops by number that the window is in. On X11 this list will always have * a length of 1, on Wayland can be any subset. * If the list is empty it means the window is on all desktops */ virtual QVector desktops() const = 0; virtual int x() const = 0; virtual int y() const = 0; virtual int width() const = 0; virtual int height() const = 0; /** * By how much the window wishes to grow/shrink at least. Usually QSize(1,1). * MAY BE DISOBEYED BY THE WM! It's only for information, do NOT rely on it at all. */ virtual QSize basicUnit() const = 0; virtual QRect geometry() const = 0; /** * Geometry of the window including decoration and potentially shadows. * May be different from geometry() if the window has a shadow. * @since 4.9 */ virtual QRect expandedGeometry() const = 0; virtual QRegion shape() const = 0; virtual int screen() const = 0; /** @internal Do not use */ virtual bool hasOwnShape() const = 0; // only for shadow effect, for now virtual QPoint pos() const = 0; virtual QSize size() const = 0; virtual QRect rect() const = 0; virtual bool isMovable() const = 0; virtual bool isMovableAcrossScreens() const = 0; virtual bool isUserMove() const = 0; virtual bool isUserResize() const = 0; virtual QRect iconGeometry() const = 0; /** * Geometry of the actual window contents inside the whole (including decorations) window. */ virtual QRect contentsRect() const = 0; /** * Geometry of the transparent rect in the decoration. * May be different from contentsRect() if the decoration is extended into the client area. * @since 4.5 */ virtual QRect decorationInnerRect() const = 0; bool hasDecoration() const; virtual bool decorationHasAlpha() const = 0; virtual QByteArray readProperty(long atom, long type, int format) const = 0; virtual void deleteProperty(long atom) const = 0; virtual QString caption() const = 0; virtual QIcon icon() const = 0; virtual QString windowClass() const = 0; virtual QString windowRole() const = 0; virtual const EffectWindowGroup* group() const = 0; /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isDesktop() const = 0; /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isDock() const = 0; /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isToolbar() const = 0; /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isMenu() const = 0; /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isNormalWindow() const = 0; // normal as in 'NET::Normal or NET::Unknown non-transient' /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. */ virtual bool isSpecialWindow() const = 0; /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isDialog() const = 0; /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isSplash() const = 0; /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isUtility() const = 0; /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isDropdownMenu() const = 0; /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isPopupMenu() const = 0; // a context popup, not dropdown, not torn-off /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isTooltip() const = 0; /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isNotification() const = 0; /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ virtual bool isOnScreenDisplay() const = 0; /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isComboBox() const = 0; /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual bool isDNDIcon() const = 0; /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ virtual NET::WindowType windowType() const = 0; /** * Returns whether the window is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). */ virtual bool isManaged() const = 0; // whether it's managed or override-redirect /** * Returns whether or not the window can accept keyboard focus. */ virtual bool acceptsFocus() const = 0; /** * Returns whether or not the window is kept above all other windows. */ virtual bool keepAbove() const = 0; /** * Returns whether the window is kept below all other windows. */ virtual bool keepBelow() const = 0; virtual bool isModal() const = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findModal() = 0; Q_SCRIPTABLE virtual QList mainWindows() const = 0; /** * Returns whether the window should be excluded from window switching effects. * @since 4.5 */ virtual bool isSkipSwitcher() const = 0; /** * Returns the unmodified window quad list. Can also be used to force rebuilding. */ virtual WindowQuadList buildQuads(bool force = false) const = 0; void setMinimized(bool minimize); virtual void minimize() = 0; virtual void unminimize() = 0; Q_SCRIPTABLE virtual void closeWindow() = 0; virtual bool isCurrentTab() const = 0; /** * @since 4.11 **/ bool isVisible() const; /** * @since 5.0 **/ virtual bool skipsCloseAnimation() const = 0; /** * @since 5.5 */ virtual KWayland::Server::SurfaceInterface *surface() const = 0; /** * @since 5.6 **/ virtual bool isFullScreen() const = 0; /** * @since 5.10 */ virtual bool isUnresponsive() const = 0; /** * @since 5.15 **/ virtual bool isWaylandClient() const = 0; /** * @since 5.15 **/ virtual bool isX11Client() const = 0; /** * @since 5.15 **/ virtual bool isPopupWindow() const = 0; /** * Can be used to by effects to store arbitrary data in the EffectWindow. * * Invoking this method will emit the signal EffectsHandler::windowDataChanged. * @see EffectsHandler::windowDataChanged */ Q_SCRIPTABLE virtual void setData(int role, const QVariant &data) = 0; Q_SCRIPTABLE virtual QVariant data(int role) const = 0; /** * @brief References the previous window pixmap to prevent discarding. * * This method allows to reference the previous window pixmap in case that a window changed * its size, which requires a new window pixmap. By referencing the previous (and then outdated) * window pixmap an effect can for example cross fade the current window pixmap with the previous * one. This allows for smoother transitions for window geometry changes. * - * If an effect calls this method on a window it also needs to call @link unreferencePreviousWindowPixmap + * If an effect calls this method on a window it also needs to call unreferencePreviousWindowPixmap * once it does no longer need the previous window pixmap. * * Note: the window pixmap is not kept forever even when referenced. If the geometry changes again, so that * a new window pixmap is created, the previous window pixmap will be exchanged with the current one. This * means it's still possible to have rendering glitches. An effect is supposed to track for itself the changes * to the window's geometry and decide how the transition should continue in such a situation. * * @see unreferencePreviousWindowPixmap * @since 4.11 */ virtual void referencePreviousWindowPixmap() = 0; /** - * @brief Unreferences the previous window pixmap. Only relevant after @link referencePreviousWindowPixmap had + * @brief Unreferences the previous window pixmap. Only relevant after referencePreviousWindowPixmap had * been called. * * @see referencePreviousWindowPixmap * @since 4.11 */ virtual void unreferencePreviousWindowPixmap() = 0; private: class Private; QScopedPointer d; }; class KWINEFFECTS_EXPORT EffectWindowGroup { public: virtual ~EffectWindowGroup(); virtual EffectWindowList members() const = 0; }; struct GLVertex2D { QVector2D position; QVector2D texcoord; }; struct GLVertex3D { QVector3D position; QVector2D texcoord; }; /** * @short Vertex class * * A vertex is one position in a window. WindowQuad consists of four WindowVertex objects * and represents one part of a window. **/ class KWINEFFECTS_EXPORT WindowVertex { public: WindowVertex(); WindowVertex(const QPointF &position, const QPointF &textureCoordinate); WindowVertex(double x, double y, double tx, double ty); double x() const { return px; } double y() const { return py; } double u() const { return tx; } double v() const { return ty; } double originalX() const { return ox; } double originalY() const { return oy; } double textureX() const { return tx; } double textureY() const { return ty; } void move(double x, double y); void setX(double x); void setY(double y); private: friend class WindowQuad; friend class WindowQuadList; double px, py; // position double ox, oy; // origional position double tx, ty; // texture coords }; /** * @short Class representing one area of a window. * * WindowQuads consists of four WindowVertex objects and represents one part of a window. */ // NOTE: This class expects the (original) vertices to be in the clockwise order starting from topleft. class KWINEFFECTS_EXPORT WindowQuad { public: explicit WindowQuad(WindowQuadType type, int id = -1); WindowQuad makeSubQuad(double x1, double y1, double x2, double y2) const; WindowVertex& operator[](int index); const WindowVertex& operator[](int index) const; WindowQuadType type() const; void setUVAxisSwapped(bool value) { uvSwapped = value; } bool uvAxisSwapped() const { return uvSwapped; } int id() const; bool decoration() const; bool effect() const; double left() const; double right() const; double top() const; double bottom() const; double originalLeft() const; double originalRight() const; double originalTop() const; double originalBottom() const; bool smoothNeeded() const; bool isTransformed() const; private: friend class WindowQuadList; WindowVertex verts[ 4 ]; WindowQuadType quadType; // 0 - contents, 1 - decoration bool uvSwapped; int quadID; }; class KWINEFFECTS_EXPORT WindowQuadList : public QList< WindowQuad > { public: WindowQuadList splitAtX(double x) const; WindowQuadList splitAtY(double y) const; WindowQuadList makeGrid(int maxquadsize) const; WindowQuadList makeRegularGrid(int xSubdivisions, int ySubdivisions) const; WindowQuadList select(WindowQuadType type) const; WindowQuadList filterOut(WindowQuadType type) const; bool smoothNeeded() const; void makeInterleavedArrays(unsigned int type, GLVertex2D *vertices, const QMatrix4x4 &matrix) const; void makeArrays(float** vertices, float** texcoords, const QSizeF &size, bool yInverted) const; bool isTransformed() const; }; class KWINEFFECTS_EXPORT WindowPrePaintData { public: int mask; /** * Region that will be painted, in screen coordinates. **/ QRegion paint; /** * The clip region will be subtracted from paint region of following windows. * I.e. window will definitely cover it's clip region **/ QRegion clip; WindowQuadList quads; /** * Simple helper that sets data to say the window will be painted as non-opaque. * Takes also care of changing the regions. */ void setTranslucent(); /** * Helper to mark that this window will be transformed **/ void setTransformed(); }; class KWINEFFECTS_EXPORT PaintData { public: virtual ~PaintData(); /** * @returns scale factor in X direction. * @since 4.10 **/ qreal xScale() const; /** * @returns scale factor in Y direction. * @since 4.10 **/ qreal yScale() const; /** * @returns scale factor in Z direction. * @since 4.10 **/ qreal zScale() const; /** * Sets the scale factor in X direction to @p scale * @param scale The scale factor in X direction * @since 4.10 **/ void setXScale(qreal scale); /** * Sets the scale factor in Y direction to @p scale * @param scale The scale factor in Y direction * @since 4.10 **/ void setYScale(qreal scale); /** * Sets the scale factor in Z direction to @p scale * @param scale The scale factor in Z direction * @since 4.10 **/ void setZScale(qreal scale); /** * Sets the scale factor in X and Y direction. * @param scale The scale factor for X and Y direction * @since 4.10 **/ void setScale(const QVector2D &scale); /** * Sets the scale factor in X, Y and Z direction * @param scale The scale factor for X, Y and Z direction * @since 4.10 **/ void setScale(const QVector3D &scale); const QGraphicsScale &scale() const; const QVector3D &translation() const; /** * @returns the translation in X direction. * @since 4.10 **/ qreal xTranslation() const; /** * @returns the translation in Y direction. * @since 4.10 **/ qreal yTranslation() const; /** * @returns the translation in Z direction. * @since 4.10 **/ qreal zTranslation() const; /** * Sets the translation in X direction to @p translate. * @since 4.10 **/ void setXTranslation(qreal translate); /** * Sets the translation in Y direction to @p translate. * @since 4.10 **/ void setYTranslation(qreal translate); /** * Sets the translation in Z direction to @p translate. * @since 4.10 **/ void setZTranslation(qreal translate); /** * Performs a translation by adding the values component wise. * @param x Translation in X direction * @param y Translation in Y direction * @param z Translation in Z direction * @since 4.10 **/ void translate(qreal x, qreal y = 0.0, qreal z = 0.0); /** * Performs a translation by adding the values component wise. * Overloaded method for convenience. * @param translate The translation * @since 4.10 **/ void translate(const QVector3D &translate); /** * Sets the rotation angle. * @param angle The new rotation angle. * @since 4.10 * @see rotationAngle() **/ void setRotationAngle(qreal angle); /** * Returns the rotation angle. * Initially 0.0. * @returns The current rotation angle. * @since 4.10 * @see setRotationAngle **/ qreal rotationAngle() const; /** * Sets the rotation origin. * @param origin The new rotation origin. * @since 4.10 * @see rotationOrigin() **/ void setRotationOrigin(const QVector3D &origin); /** * Returns the rotation origin. That is the point in space which is fixed during the rotation. * Initially this is 0/0/0. * @returns The rotation's origin * @since 4.10 * @see setRotationOrigin() **/ QVector3D rotationOrigin() const; /** * Sets the rotation axis. * Set a component to 1.0 to rotate around this axis and to 0.0 to disable rotation around the * axis. * @param axis A vector holding information on which axis to rotate * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(const QVector3D &axis); /** * Sets the rotation axis. * Overloaded method for convenience. * @param axis The axis around which should be rotated. * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(Qt::Axis axis); /** * The current rotation axis. * By default the rotation is (0/0/1) which means a rotation around the z axis. * @returns The current rotation axis. * @since 4.10 * @see setRotationAxis **/ QVector3D rotationAxis() const; protected: PaintData(); PaintData(const PaintData &other); private: PaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT WindowPaintData : public PaintData { public: explicit WindowPaintData(EffectWindow* w); explicit WindowPaintData(EffectWindow* w, const QMatrix4x4 &screenProjectionMatrix); WindowPaintData(const WindowPaintData &other); virtual ~WindowPaintData(); /** * Scales the window by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ WindowPaintData& operator*=(qreal scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ WindowPaintData& operator*=(const QVector2D &scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ WindowPaintData& operator*=(const QVector3D &scale); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ WindowPaintData& operator+=(const QPointF &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QPoint &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector2D &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector3D &translation); /** * Window opacity, in range 0 = transparent to 1 = fully opaque * @see setOpacity * @since 4.10 */ qreal opacity() const; /** * Sets the window opacity to the new @p opacity. * If you want to modify the existing opacity level consider using multiplyOpacity. * @param opacity The new opacity level * @since 4.10 **/ void setOpacity(qreal opacity); /** * Multiplies the current opacity with the @p factor. * @param factor Factor with which the opacity should be multiplied * @return New opacity level * @since 4.10 **/ qreal multiplyOpacity(qreal factor); /** * Saturation of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * unsaturated (greyscale). 0.5 would make the colors less intense, * but not completely grey * Use EffectsHandler::saturationSupported() to find out whether saturation * is supported by the system, otherwise this value has no effect. * @return The current saturation * @see setSaturation() * @since 4.10 **/ qreal saturation() const; /** * Sets the window saturation level to @p saturation. * If you want to modify the existing saturation level consider using multiplySaturation. * @param saturation The new saturation level * @since 4.10 **/ void setSaturation(qreal saturation) const; /** * Multiplies the current saturation with @p factor. * @param factor with which the saturation should be multiplied * @return New saturation level * @since 4.10 **/ qreal multiplySaturation(qreal factor); /** * Brightness of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * black. 0.5 would make it 50% darker than usual **/ qreal brightness() const; /** * Sets the window brightness level to @p brightness. * If you want to modify the existing brightness level consider using multiplyBrightness. * @param brightness The new brightness level **/ void setBrightness(qreal brightness); /** * Multiplies the current brightness level with @p factor. * @param factor with which the brightness should be multiplied. * @return New brightness level * @since 4.10 **/ qreal multiplyBrightness(qreal factor); /** * The screen number for which the painting should be done. * This affects color correction (different screens may need different * color correction lookup tables because they have different ICC profiles). * @return screen for which painting should be done */ int screen() const; /** * @param screen New screen number * A value less than 0 will indicate that a default profile should be done. */ void setScreen(int screen) const; /** * @brief Sets the cross fading @p factor to fade over with previously sized window. * If @c 1.0 only the current window is used, if @c 0.0 only the previous window is used. * * By default only the current window is used. This factor can only make any visual difference * if the previous window get referenced. * * @param factor The cross fade factor between @c 0.0 (previous window) and @c 1.0 (current window) * @see crossFadeProgress */ void setCrossFadeProgress(qreal factor); /** * @see setCrossFadeProgress */ qreal crossFadeProgress() const; /** * Sets the projection matrix that will be used when painting the window. * * The default projection matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setProjectionMatrix(const QMatrix4x4 &matrix); /** * Returns the current projection matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 projectionMatrix() const; /** * Returns a reference to the projection matrix. */ QMatrix4x4 &rprojectionMatrix(); /** * Sets the model-view matrix that will be used when painting the window. * * The default model-view matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setModelViewMatrix(const QMatrix4x4 &matrix); /** * Returns the current model-view matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 modelViewMatrix() const; /** * Returns a reference to the model-view matrix. */ QMatrix4x4 &rmodelViewMatrix(); /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * @since 5.6 **/ QMatrix4x4 screenProjectionMatrix() const; WindowQuadList quads; /** * Shader to be used for rendering, if any. */ GLShader* shader; private: WindowPaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT ScreenPaintData : public PaintData { public: ScreenPaintData(); ScreenPaintData(const QMatrix4x4 &projectionMatrix, const QRect &outputGeometry = QRect()); ScreenPaintData(const ScreenPaintData &other); virtual ~ScreenPaintData(); /** * Scales the screen by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ ScreenPaintData& operator*=(qreal scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector2D &scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector3D &scale); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ ScreenPaintData& operator+=(const QPointF &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QPoint &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector2D &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector3D &translation); ScreenPaintData& operator=(const ScreenPaintData &rhs); /** * The projection matrix used by the scene for the current rendering pass. * On non-OpenGL compositors it's set to Identity matrix. * @since 5.6 **/ QMatrix4x4 projectionMatrix() const; /** * The geometry of the currently rendered output. * Only set for per-output rendering (e.g. Wayland). * * This geometry can be used as a hint about the native window the OpenGL context * is bound. OpenGL calls need to be translated to this geometry. * @since 5.9 **/ QRect outputGeometry() const; private: class Private; QScopedPointer d; }; class KWINEFFECTS_EXPORT ScreenPrePaintData { public: int mask; QRegion paint; }; /** * @short Helper class for restricting painting area only to allowed area. * * This helper class helps specifying areas that should be painted, clipping * out the rest. The simplest usage is creating an object on the stack * and giving it the area that is allowed to be painted to. When the object * is destroyed, the restriction will be removed. * Note that all painting code must use paintArea() to actually perform the clipping. */ class KWINEFFECTS_EXPORT PaintClipper { public: /** * Calls push(). */ explicit PaintClipper(const QRegion& allowed_area); /** * Calls pop(). */ ~PaintClipper(); /** * Allows painting only in the given area. When areas have been already * specified, painting is allowed only in the intersection of all areas. */ static void push(const QRegion& allowed_area); /** * Removes the given area. It must match the top item in the stack. */ static void pop(const QRegion& allowed_area); /** * Returns true if any clipping should be performed. */ static bool clip(); /** * If clip() returns true, this function gives the resulting area in which * painting is allowed. It is usually simpler to use the helper Iterator class. */ static QRegion paintArea(); /** * Helper class to perform the clipped painting. The usage is: * @code * for ( PaintClipper::Iterator iterator; * !iterator.isDone(); * iterator.next()) * { // do the painting, possibly use iterator.boundingRect() * } * @endcode */ class KWINEFFECTS_EXPORT Iterator { public: Iterator(); ~Iterator(); bool isDone(); void next(); QRect boundingRect() const; private: struct Data; Data* data; }; private: QRegion area; static QStack< QRegion >* areas; }; /** * @internal */ template class KWINEFFECTS_EXPORT Motion { public: /** * Creates a new motion object. "Strength" is the amount of * acceleration that is applied to the object when the target * changes and "smoothness" relates to how fast the object * can change its direction and speed. */ explicit Motion(T initial, double strength, double smoothness); /** * Creates an exact copy of another motion object, including * position, target and velocity. */ Motion(const Motion &other); ~Motion(); inline T value() const { return m_value; } inline void setValue(const T value) { m_value = value; } inline T target() const { return m_target; } inline void setTarget(const T target) { m_start = m_value; m_target = target; } inline T velocity() const { return m_velocity; } inline void setVelocity(const T velocity) { m_velocity = velocity; } inline double strength() const { return m_strength; } inline void setStrength(const double strength) { m_strength = strength; } inline double smoothness() const { return m_smoothness; } inline void setSmoothness(const double smoothness) { m_smoothness = smoothness; } inline T startValue() { return m_start; } /** * The distance between the current position and the target. */ inline T distance() const { return m_target - m_value; } /** * Calculates the new position if not at the target. Called * once per frame only. */ void calculate(const int msec); /** * Place the object on top of the target immediately, * bypassing all movement calculation. */ void finish(); private: T m_value; T m_start; T m_target; T m_velocity; double m_strength; double m_smoothness; }; /** * @short A single 1D motion dynamics object. * * This class represents a single object that can be moved around a * 1D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion1D : public Motion { public: explicit Motion1D(double initial = 0.0, double strength = 0.08, double smoothness = 4.0); Motion1D(const Motion1D &other); ~Motion1D(); }; /** * @short A single 2D motion dynamics object. * * This class represents a single object that can be moved around a * 2D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion2D : public Motion { public: explicit Motion2D(QPointF initial = QPointF(), double strength = 0.08, double smoothness = 4.0); Motion2D(const Motion2D &other); ~Motion2D(); }; /** * @short Helper class for motion dynamics in KWin effects. * * This motion manager class is intended to help KWin effect authors * move windows across the screen smoothly and naturally. Once * windows are registered by the manager the effect can issue move * commands with the moveWindow() methods. The position of any * managed window can be determined in realtime by the * transformedGeometry() method. As the manager knows if any windows * are moving at any given time it can also be used as a notifier as * to see whether the effect is active or not. */ class KWINEFFECTS_EXPORT WindowMotionManager { public: /** * Creates a new window manager object. */ explicit WindowMotionManager(bool useGlobalAnimationModifier = true); ~WindowMotionManager(); /** * Register a window for managing. */ void manage(EffectWindow *w); /** * Register a list of windows for managing. */ inline void manage(EffectWindowList list) { for (int i = 0; i < list.size(); i++) manage(list.at(i)); } /** * Deregister a window. All transformations applied to the * window will be permanently removed and cannot be recovered. */ void unmanage(EffectWindow *w); /** * Deregister all windows, returning the manager to its * originally initiated state. */ void unmanageAll(); /** * Determine the new positions for windows that have not * reached their target. Called once per frame, usually in * prePaintScreen(). Remember to set the * Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS flag. */ void calculate(int time); /** * Modify a registered window's paint data to make it appear * at its real location on the screen. Usually called in * paintWindow(). Remember to flag the window as having been * transformed in prePaintWindow() by calling * WindowPrePaintData::setTransformed() */ void apply(EffectWindow *w, WindowPaintData &data); /** * Set all motion targets and values back to where the * windows were before transformations. The same as * unmanaging then remanaging all windows. */ void reset(); /** * Resets the motion target and current value of a single * window. */ void reset(EffectWindow *w); /** * Ask the manager to move the window to the target position * with the specified scale. If `yScale` is not provided or * set to 0.0, `scale` will be used as the scale in the * vertical direction as well as in the horizontal direction. */ void moveWindow(EffectWindow *w, QPoint target, double scale = 1.0, double yScale = 0.0); /** * This is an overloaded method, provided for convenience. * * Ask the manager to move the window to the target rectangle. * Automatically determines scale. */ inline void moveWindow(EffectWindow *w, QRect target) { // TODO: Scale might be slightly different in the comparison due to rounding moveWindow(w, target.topLeft(), target.width() / double(w->width()), target.height() / double(w->height())); } /** * Retrieve the current tranformed geometry of a registered * window. */ QRectF transformedGeometry(EffectWindow *w) const; /** * Sets the current transformed geometry of a registered window to the given geometry. * @see transformedGeometry * @since 4.5 */ void setTransformedGeometry(EffectWindow *w, const QRectF &geometry); /** * Retrieve the current target geometry of a registered * window. */ QRectF targetGeometry(EffectWindow *w) const; /** * Return the window that has its transformed geometry under * the specified point. It is recommended to use the stacking * order as it's what the user sees, but it is slightly * slower to process. */ EffectWindow* windowAtPoint(QPoint point, bool useStackingOrder = true) const; /** * Return a list of all currently registered windows. */ inline EffectWindowList managedWindows() const { return m_managedWindows.keys(); } /** * Returns whether or not a specified window is being managed * by this manager object. */ inline bool isManaging(EffectWindow *w) const { return m_managedWindows.contains(w); } /** * Returns whether or not this manager object is actually * managing any windows or not. */ inline bool managingWindows() const { return !m_managedWindows.empty(); } /** * Returns whether all windows have reached their targets yet * or not. Can be used to see if an effect should be * processed and displayed or not. */ inline bool areWindowsMoving() const { return !m_movingWindowsSet.isEmpty(); } /** * Returns whether a window has reached its targets yet * or not. */ inline bool isWindowMoving(EffectWindow *w) const { return m_movingWindowsSet.contains(w); } private: bool m_useGlobalAnimationModifier; struct WindowMotion { // TODO: Rotation, etc? Motion2D translation; // Absolute position Motion2D scale; // xScale and yScale }; QHash m_managedWindows; QSet m_movingWindowsSet; }; /** * @short Helper class for displaying text and icons in frames. * * Paints text and/or and icon with an optional frame around them. The * available frames includes one that follows the default Plasma theme and * another that doesn't. * It is recommended to use this class whenever displaying text. */ class KWINEFFECTS_EXPORT EffectFrame { public: EffectFrame(); virtual ~EffectFrame(); /** * Delete any existing textures to free up graphics memory. They will * be automatically recreated the next time they are required. */ virtual void free() = 0; /** * Render the frame. */ virtual void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0) = 0; virtual void setPosition(const QPoint& point) = 0; /** * Set the text alignment for static frames and the position alignment * for non-static. */ virtual void setAlignment(Qt::Alignment alignment) = 0; virtual Qt::Alignment alignment() const = 0; virtual void setGeometry(const QRect& geometry, bool force = false) = 0; virtual const QRect& geometry() const = 0; virtual void setText(const QString& text) = 0; virtual const QString& text() const = 0; virtual void setFont(const QFont& font) = 0; virtual const QFont& font() const = 0; /** * Set the icon that will appear on the left-hand size of the frame. */ virtual void setIcon(const QIcon& icon) = 0; virtual const QIcon& icon() const = 0; virtual void setIconSize(const QSize& size) = 0; virtual const QSize& iconSize() const = 0; /** * Sets the geometry of a selection. * To remove the selection set a null rect. * @param selection The geometry of the selection in screen coordinates. **/ virtual void setSelection(const QRect& selection) = 0; /** * @param shader The GLShader for rendering. **/ virtual void setShader(GLShader* shader) = 0; /** * @returns The GLShader used for rendering or null if none. **/ virtual GLShader* shader() const = 0; /** * @returns The style of this EffectFrame. **/ virtual EffectFrameStyle style() const = 0; /** * If @p enable is @c true cross fading between icons and text is enabled * By default disabled. Use setCrossFadeProgress to cross fade. * Cross Fading is currently only available if OpenGL is used. * @param enable @c true enables cross fading, @c false disables it again * @see isCrossFade * @see setCrossFadeProgress * @since 4.6 **/ void enableCrossFade(bool enable); /** * @returns @c true if cross fading is enabled, @c false otherwise * @see enableCrossFade * @since 4.6 **/ bool isCrossFade() const; /** * Sets the current progress for cross fading the last used icon/text * with current icon/text to @p progress. * A value of 0.0 means completely old icon/text, a value of 1.0 means * completely current icon/text. * Default value is 1.0. You have to enable cross fade before using it. * Cross Fading is currently only available if OpenGL is used. * @see enableCrossFade * @see isCrossFade * @see crossFadeProgress * @since 4.6 **/ void setCrossFadeProgress(qreal progress); /** * @returns The current progress for cross fading * @see setCrossFadeProgress * @see enableCrossFade * @see isCrossFade * @since 4.6 **/ qreal crossFadeProgress() const; /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * This matrix is only valid during a rendering pass started by render. * * @since 5.6 * @see render * @see EffectsHandler::paintEffectFrame * @see Effect::paintEffectFrame **/ QMatrix4x4 screenProjectionMatrix() const; protected: void setScreenProjectionMatrix(const QMatrix4x4 &projection); private: EffectFramePrivate* const d; }; /** * The TimeLine class is a helper for controlling animations. **/ class KWINEFFECTS_EXPORT TimeLine { public: /** * Direction of the timeline. * * When the direction of the timeline is Forward, the progress * value will go from 0.0 to 1.0. * * When the direction of the timeline is Backward, the progress * value will go from 1.0 to 0.0. **/ enum Direction { Forward, Backward }; /** * Constructs a new instance of TimeLine. * * @param duration Duration of the timeline, in milliseconds * @param direction Direction of the timeline * @since 5.14 **/ explicit TimeLine(std::chrono::milliseconds duration = std::chrono::milliseconds(1000), Direction direction = Forward); TimeLine(const TimeLine &other); ~TimeLine(); /** * Returns the current value of the timeline. * * @since 5.14 **/ qreal value() const; /** * Updates the progress of the timeline. * * @note The delta value should be a non-negative number, i.e. it * should be greater or equal to 0. * * @param delta The number milliseconds passed since last frame * @since 5.14 **/ void update(std::chrono::milliseconds delta); /** * Returns the number of elapsed milliseconds. * * @see setElapsed * @since 5.14 **/ std::chrono::milliseconds elapsed() const; /** * Sets the number of elapsed milliseconds. * * This method overwrites previous value of elapsed milliseconds. * If the new value of elapsed milliseconds is greater or equal * to duration of the timeline, the timeline will be finished, i.e. * proceeding TimeLine::done method calls will return @c true. * Please don't use it. Instead, use TimeLine::update. * * @note The new number of elapsed milliseconds should be a non-negative * number, i.e. it should be greater or equal to 0. * * @param elapsed The new number of elapsed milliseconds * @see elapsed * @since 5.14 **/ void setElapsed(std::chrono::milliseconds elapsed); /** * Returns the duration of the timeline. * * @returns Duration of the timeline, in milliseconds * @see setDuration * @since 5.14 **/ std::chrono::milliseconds duration() const; /** * Sets the duration of the timeline. * * In addition to setting new value of duration, the timeline will * try to retarget the number of elapsed milliseconds to match * as close as possible old progress value. If the new duration * is much smaller than old duration, there is a big chance that * the timeline will be finished after setting new duration. * * @note The new duration should be a positive number, i.e. it * should be greater or equal to 1. * * @param duration The new duration of the timeline, in milliseconds * @see duration * @since 5.14 **/ void setDuration(std::chrono::milliseconds duration); /** * Returns the direction of the timeline. * * @returns Direction of the timeline(TimeLine::Forward or TimeLine::Backward) * @see setDirection * @see toggleDirection * @since 5.14 **/ Direction direction() const; /** * Sets the direction of the timeline. * * @param direction The new direction of the timeline * @see direction * @see toggleDirection * @since 5.14 **/ void setDirection(Direction direction); /** * Toggles the direction of the timeline. * * If the direction of the timeline was TimeLine::Forward, it becomes * TimeLine::Backward, and vice verca. * * @see direction * @see setDirection * @since 5.14 **/ void toggleDirection(); /** * Returns the easing curve of the timeline. * * @see setEasingCurve * @since 5.14 **/ QEasingCurve easingCurve() const; /** * Sets new easing curve. * * @param easingCurve An easing curve to be set * @see easingCurve * @since 5.14 **/ void setEasingCurve(const QEasingCurve &easingCurve); /** * Sets new easing curve by providing its type. * * @param type Type of the easing curve(e.g. QEasingCurve::InQuad, etc) * @see easingCurve * @since 5.14 **/ void setEasingCurve(QEasingCurve::Type type); /** * Returns whether the timeline is currently in progress. * * @see done * @since 5.14 **/ bool running() const; /** * Returns whether the timeline is finished. * * @see reset * @since 5.14 **/ bool done() const; /** * Resets the timeline to initial state. * * @since 5.14 **/ void reset(); enum class RedirectMode { Strict, Relaxed }; /** * Returns the redirect mode for the source position. * * The redirect mode controls behavior of the timeline when its direction is * changed at the source position, e.g. what should we do when the timeline * initially goes forward and we change its direction to go backward. * * In the strict mode, the timeline will stop. * * In the relaxed mode, the timeline will go in the new direction. For example, * if the timeline goes forward(from 0 to 1), then with the new direction it * will go backward(from 1 to 0). * * The default is RedirectMode::Relaxed. * * @see targetRedirectMode * @since 5.15 **/ RedirectMode sourceRedirectMode() const; /** * Sets the redirect mode for the source position. * * @param mode The new mode. * @since 5.15 **/ void setSourceRedirectMode(RedirectMode mode); /** * Returns the redirect mode for the target position. * * The redirect mode controls behavior of the timeline when its direction is * changed at the target position. * * In the strict mode, subsequent update calls won't have any effect on the * current value of the timeline. * * In the relaxed mode, the timeline will go in the new direction. * * The default is RedirectMode::Strict. * * @see sourceRedirectMode * @since 5.15 **/ RedirectMode targetRedirectMode() const; /** * Sets the redirect mode for the target position. * * @param mode The new mode. * @since 5.15 **/ void setTargetRedirectMode(RedirectMode mode); TimeLine &operator=(const TimeLine &other); private: qreal progress() const; private: class Data; QSharedDataPointer d; }; /** * Pointer to the global EffectsHandler object. **/ extern KWINEFFECTS_EXPORT EffectsHandler* effects; /*************************************************************** WindowVertex ***************************************************************/ inline WindowVertex::WindowVertex() : px(0), py(0), ox(0), oy(0), tx(0), ty(0) { } inline WindowVertex::WindowVertex(double _x, double _y, double _tx, double _ty) : px(_x), py(_y), ox(_x), oy(_y), tx(_tx), ty(_ty) { } inline WindowVertex::WindowVertex(const QPointF &position, const QPointF &texturePosition) : px(position.x()), py(position.y()), ox(position.x()), oy(position.y()), tx(texturePosition.x()), ty(texturePosition.y()) { } inline void WindowVertex::move(double x, double y) { px = x; py = y; } inline void WindowVertex::setX(double x) { px = x; } inline void WindowVertex::setY(double y) { py = y; } /*************************************************************** WindowQuad ***************************************************************/ inline WindowQuad::WindowQuad(WindowQuadType t, int id) : quadType(t) , uvSwapped(false) , quadID(id) { } inline WindowVertex& WindowQuad::operator[](int index) { assert(index >= 0 && index < 4); return verts[ index ]; } inline const WindowVertex& WindowQuad::operator[](int index) const { assert(index >= 0 && index < 4); return verts[ index ]; } inline WindowQuadType WindowQuad::type() const { assert(quadType != WindowQuadError); return quadType; } inline int WindowQuad::id() const { return quadID; } inline bool WindowQuad::decoration() const { assert(quadType != WindowQuadError); return quadType == WindowQuadDecoration; } inline bool WindowQuad::effect() const { assert(quadType != WindowQuadError); return quadType >= EFFECT_QUAD_TYPE_START; } inline bool WindowQuad::isTransformed() const { return !(verts[ 0 ].px == verts[ 0 ].ox && verts[ 0 ].py == verts[ 0 ].oy && verts[ 1 ].px == verts[ 1 ].ox && verts[ 1 ].py == verts[ 1 ].oy && verts[ 2 ].px == verts[ 2 ].ox && verts[ 2 ].py == verts[ 2 ].oy && verts[ 3 ].px == verts[ 3 ].ox && verts[ 3 ].py == verts[ 3 ].oy); } inline double WindowQuad::left() const { return qMin(verts[ 0 ].px, qMin(verts[ 1 ].px, qMin(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::right() const { return qMax(verts[ 0 ].px, qMax(verts[ 1 ].px, qMax(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::top() const { return qMin(verts[ 0 ].py, qMin(verts[ 1 ].py, qMin(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::bottom() const { return qMax(verts[ 0 ].py, qMax(verts[ 1 ].py, qMax(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::originalLeft() const { return verts[ 0 ].ox; } inline double WindowQuad::originalRight() const { return verts[ 2 ].ox; } inline double WindowQuad::originalTop() const { return verts[ 0 ].oy; } inline double WindowQuad::originalBottom() const { return verts[ 2 ].oy; } /*************************************************************** Motion ***************************************************************/ template Motion::Motion(T initial, double strength, double smoothness) : m_value(initial) , m_start(initial) , m_target(initial) , m_velocity() , m_strength(strength) , m_smoothness(smoothness) { } template Motion::Motion(const Motion &other) : m_value(other.value()) , m_start(other.target()) , m_target(other.target()) , m_velocity(other.velocity()) , m_strength(other.strength()) , m_smoothness(other.smoothness()) { } template Motion::~Motion() { } template void Motion::calculate(const int msec) { if (m_value == m_target && m_velocity == T()) // At target and not moving return; // Poor man's time independent calculation int steps = qMax(1, msec / 5); for (int i = 0; i < steps; i++) { T diff = m_target - m_value; T strength = diff * m_strength; m_velocity = (m_smoothness * m_velocity + strength) / (m_smoothness + 1.0); m_value += m_velocity; } } template void Motion::finish() { m_value = m_target; m_velocity = T(); } /*************************************************************** Effect ***************************************************************/ template int Effect::animationTime(int defaultDuration) { return animationTime(T::duration() != 0 ? T::duration() : defaultDuration); } template void Effect::initConfig() { T::instance(effects->config()); } } // namespace Q_DECLARE_METATYPE(KWin::EffectWindow*) Q_DECLARE_METATYPE(QList) Q_DECLARE_METATYPE(KWin::TimeLine) Q_DECLARE_METATYPE(KWin::TimeLine::Direction) /** @} */ #endif // KWINEFFECTS_H diff --git a/libkwineffects/kwinglutils.h b/libkwineffects/kwinglutils.h index b0045115b..7bafb400f 100644 --- a/libkwineffects/kwinglutils.h +++ b/libkwineffects/kwinglutils.h @@ -1,825 +1,825 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006-2007 Rivo Laks Copyright (C) 2010, 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_GLUTILS_H #define KWIN_GLUTILS_H // kwin #include #include "kwinglutils_funcs.h" #include "kwingltexture.h" // Qt #include #include /** @addtogroup kwineffects */ /** @{ */ class QVector2D; class QVector3D; class QVector4D; class QMatrix4x4; template< class K, class V > class QHash; namespace KWin { class GLVertexBuffer; class GLVertexBufferPrivate; // Initializes OpenGL stuff. This includes resolving function pointers as // well as checking for GL version and extensions // Note that GL context has to be created by the time this function is called typedef void (*resolveFuncPtr)(); void KWINGLUTILS_EXPORT initGL(std::function resolveFunction); // Cleans up all resources hold by the GL Context void KWINGLUTILS_EXPORT cleanupGL(); bool KWINGLUTILS_EXPORT hasGLVersion(int major, int minor, int release = 0); // use for both OpenGL and GLX extensions bool KWINGLUTILS_EXPORT hasGLExtension(const QByteArray &extension); // detect OpenGL error (add to various places in code to pinpoint the place) bool KWINGLUTILS_EXPORT checkGLError(const char* txt); QList KWINGLUTILS_EXPORT openGLExtensions(); class KWINGLUTILS_EXPORT GLShader { public: enum Flags { NoFlags = 0, ExplicitLinking = (1 << 0) }; GLShader(const QString &vertexfile, const QString &fragmentfile, unsigned int flags = NoFlags); ~GLShader(); bool isValid() const { return mValid; } void bindAttributeLocation(const char *name, int index); void bindFragDataLocation(const char *name, int index); bool link(); int uniformLocation(const char* name); bool setUniform(const char* name, float value); bool setUniform(const char* name, int value); bool setUniform(const char* name, const QVector2D& value); bool setUniform(const char* name, const QVector3D& value); bool setUniform(const char* name, const QVector4D& value); bool setUniform(const char* name, const QMatrix4x4& value); bool setUniform(const char* name, const QColor& color); bool setUniform(int location, float value); bool setUniform(int location, int value); bool setUniform(int location, const QVector2D &value); bool setUniform(int location, const QVector3D &value); bool setUniform(int location, const QVector4D &value); bool setUniform(int location, const QMatrix4x4 &value); bool setUniform(int location, const QColor &value); int attributeLocation(const char* name); bool setAttribute(const char* name, float value); /** * @return The value of the uniform as a matrix * @since 4.7 **/ QMatrix4x4 getUniformMatrix4x4(const char* name); enum MatrixUniform { TextureMatrix = 0, ProjectionMatrix, ModelViewMatrix, ModelViewProjectionMatrix, WindowTransformation, ScreenTransformation, MatrixCount }; enum Vec2Uniform { Offset, Vec2UniformCount }; enum Vec4Uniform { ModulationConstant, Vec4UniformCount }; enum FloatUniform { Saturation, FloatUniformCount }; enum IntUniform { AlphaToOne, ///< @deprecated no longer used IntUniformCount }; enum ColorUniform { Color, ColorUniformCount }; bool setUniform(MatrixUniform uniform, const QMatrix4x4 &matrix); bool setUniform(Vec2Uniform uniform, const QVector2D &value); bool setUniform(Vec4Uniform uniform, const QVector4D &value); bool setUniform(FloatUniform uniform, float value); bool setUniform(IntUniform uniform, int value); bool setUniform(ColorUniform uniform, const QVector4D &value); bool setUniform(ColorUniform uniform, const QColor &value); protected: GLShader(unsigned int flags = NoFlags); bool loadFromFiles(const QString& vertexfile, const QString& fragmentfile); bool load(const QByteArray &vertexSource, const QByteArray &fragmentSource); const QByteArray prepareSource(GLenum shaderType, const QByteArray &sourceCode) const; bool compile(GLuint program, GLenum shaderType, const QByteArray &sourceCode) const; void bind(); void unbind(); void resolveLocations(); private: unsigned int mProgram; bool mValid:1; bool mLocationsResolved:1; bool mExplicitLinking:1; int mMatrixLocation[MatrixCount]; int mVec2Location[Vec2UniformCount]; int mVec4Location[Vec4UniformCount]; int mFloatLocation[FloatUniformCount]; int mIntLocation[IntUniformCount]; int mColorLocation[ColorUniformCount]; friend class ShaderManager; }; enum class ShaderTrait { MapTexture = (1 << 0), UniformColor = (1 << 1), Modulate = (1 << 2), AdjustSaturation = (1 << 3), }; Q_DECLARE_FLAGS(ShaderTraits, ShaderTrait) /** * @short Manager for Shaders. * * This class provides some built-in shaders to be used by both compositing scene and effects. * The ShaderManager provides methods to bind a built-in or a custom shader and keeps track of * the shaders which have been bound. When a shader is unbound the previously bound shader * will be rebound. * * @author Martin Gräßlin * @since 4.7 **/ class KWINGLUTILS_EXPORT ShaderManager { public: /** * Returns a shader with the given traits, creating it if necessary. */ GLShader *shader(ShaderTraits traits); /** * @return The currently bound shader or @c null if no shader is bound. **/ GLShader *getBoundShader() const; /** * @return @c true if a shader is bound, @c false otherwise **/ bool isShaderBound() const; /** * Is @c true if the environment variable KWIN_GL_DEBUG is set to 1. * In that case shaders are compiled with KWIN_SHADER_DEBUG defined. * @returns @c true if shaders are compiled with debug information * @since 4.8 **/ bool isShaderDebug() const; /** * Pushes the current shader onto the stack and binds a shader * with the given traits. */ GLShader *pushShader(ShaderTraits traits); /** * Binds the @p shader. - * To unbind the shader use @link popShader. A previous bound shader will be rebound. + * To unbind the shader use popShader. A previous bound shader will be rebound. * To bind a built-in shader use the more specific method. * @param shader The shader to be bound * @see popShader **/ void pushShader(GLShader *shader); /** * Unbinds the currently bound shader and rebinds a previous stored shader. * If there is no previous shader, no shader will be rebound. * It is not safe to call this method if there is no bound shader. * @see pushShader * @see getBoundShader **/ void popShader(); /** * Creates a GLShader with the specified sources. * The difference to GLShader is that it does not need to be loaded from files. * @param vertexSource The source code of the vertex shader * @param fragmentSource The source code of the fragment shader. * @return The created shader **/ GLShader *loadShaderFromCode(const QByteArray &vertexSource, const QByteArray &fragmentSource); /** * Creates a custom shader with the given @p traits and custom @p vertexSource and or @p fragmentSource. * If the @p vertexSource is empty a vertex shader with the given @p traits is generated. * If it is not empty the @p vertexSource is used as the source for the vertex shader. * * The same applies for argument @p fragmentSource just for the fragment shader. * * So if both @p vertesSource and @p fragmentSource are provided the @p traits are ignored. * If neither are provided a new shader following the @p traits is generated. * * @param traits The shader traits for generating the shader - * @param vertesSource optional vertex shader source code to be used instead of shader traits + * @param vertexSource optional vertex shader source code to be used instead of shader traits * @param fragmentSource optional fragment shader source code to be used instead of shader traits * @return new generated shader * @since 5.6 **/ GLShader *generateCustomShader(ShaderTraits traits, const QByteArray &vertexSource = QByteArray(), const QByteArray &fragmentSource = QByteArray()); /** * Creates a custom shader with the given @p traits and custom @p vertexFile and or @p fragmentFile. * The file names specified in @p vertexFile and @p fragmentFile are relative paths to the shaders * resource file shipped together with KWin. This means this method can only be used for built-in * effects, for 3rd party effects @link {generateCustomShader} should be used. * * If the @p vertexFile is empty a vertex shader with the given @p traits is generated. * If it is not empty the @p vertexFile is used as the source for the vertex shader. * * The same applies for argument @p fragmentFile just for the fragment shader. * * So if both @p vertexFile and @p fragmentFile are provided the @p traits are ignored. * If neither are provided a new shader following the @p traits is generated. * * @param traits The shader traits for generating the shader * @param vertexFile optional vertex shader source code to be used instead of shader traits * @param fragmentFile optional fragment shader source code to be used instead of shader traits * @return new generated shader * @see generateCustomShader * @since 5.6 **/ GLShader *generateShaderFromResources(ShaderTraits traits, const QString &vertexFile = QString(), const QString &fragmentFile = QString()); /** * Compiles and tests the dynamically generated shaders. * Returns true if successful and false otherwise. */ bool selfTest(); /** * @return a pointer to the ShaderManager instance **/ static ShaderManager *instance(); /** * @internal **/ static void cleanup(); private: ShaderManager(); ~ShaderManager(); void bindFragDataLocations(GLShader *shader); void bindAttributeLocations(GLShader *shader) const; QByteArray generateVertexSource(ShaderTraits traits) const; QByteArray generateFragmentSource(ShaderTraits traits) const; GLShader *generateShader(ShaderTraits traits); QStack m_boundShaders; QHash m_shaderHash; bool m_debug; QString m_resourcePath; static ShaderManager *s_shaderManager; }; /** * An helper class to push a Shader on to ShaderManager's stack and ensuring that the Shader * gets popped again from the stack automatically once the object goes out of life. * * How to use: * @code * { * GLShader *myCustomShaderIWantToPush; * ShaderBinder binder(myCustomShaderIWantToPush); * // do stuff with the shader being pushed on the stack * } * // here the Shader is automatically popped as helper does no longer exist. * @endcode * * @since 4.10 **/ class KWINGLUTILS_EXPORT ShaderBinder { public: /** * @brief Pushes the given @p shader to the ShaderManager's stack. * * @param shader The Shader to push on the stack * @see ShaderManager::pushShader **/ explicit ShaderBinder(GLShader *shader); /** * @brief Pushes the Shader with the given @p traits to the ShaderManager's stack. * * @param traits The traits describing the shader * @see ShaderManager::pushShader * @since 5.6 **/ explicit ShaderBinder(ShaderTraits traits); ~ShaderBinder(); /** * @return The Shader pushed to the Stack. **/ GLShader *shader(); private: GLShader *m_shader; }; inline ShaderBinder::ShaderBinder(GLShader *shader) : m_shader(shader) { ShaderManager::instance()->pushShader(shader); } inline ShaderBinder::ShaderBinder(ShaderTraits traits) : m_shader(nullptr) { m_shader = ShaderManager::instance()->pushShader(traits); } inline ShaderBinder::~ShaderBinder() { ShaderManager::instance()->popShader(); } inline GLShader* ShaderBinder::shader() { return m_shader; } /** * @short Render target object * * Render target object enables you to render onto a texture. This texture can * later be used to e.g. do post-processing of the scene. * * @author Rivo Laks **/ class KWINGLUTILS_EXPORT GLRenderTarget { public: /** * Constructs a GLRenderTarget * @since 5.13 **/ explicit GLRenderTarget(); /** * Constructs a GLRenderTarget * @param color texture where the scene will be rendered onto **/ explicit GLRenderTarget(const GLTexture& color); ~GLRenderTarget(); /** * Enables this render target. * All OpenGL commands from now on affect this render target until the * @ref disable method is called **/ bool enable(); /** * Disables this render target, activating whichever target was active * when @ref enable was called. **/ bool disable(); /** * Sets the target texture * @param target texture where the scene will be rendered on * @since 4.8 **/ void attachTexture(const GLTexture& target); /** * Detaches the texture that is currently attached to this framebuffer object. * @since 5.13 **/ void detachTexture(); bool valid() const { return mValid; } void setTextureDirty() { mTexture.setDirty(); } static void initStatic(); static bool supported() { return sSupported; } /** * Pushes the render target stack of the input parameter in reverse order. * @param targets The stack of GLRenderTargets * @since 5.13 **/ static void pushRenderTargets(QStack targets); static void pushRenderTarget(GLRenderTarget *target); static GLRenderTarget *popRenderTarget(); static bool isRenderTargetBound(); /** * Whether the GL_EXT_framebuffer_blit extension is supported. * This functionality is not available in OpenGL ES 2.0. * * @returns whether framebuffer blitting is supported. * @since 4.8 **/ static bool blitSupported(); /** * Blits the content of the current draw framebuffer into the texture attached to this FBO. * * Be aware that framebuffer blitting may not be supported on all hardware. Use @link blitSupported to check whether * it is supported. * @param source Geometry in screen coordinates which should be blitted, if not specified complete framebuffer is used * @param destination Geometry in attached texture, if not specified complete texture is used as destination * @param filter The filter to use if blitted content needs to be scaled. * @see blitSupported * @since 4.8 **/ void blitFromFramebuffer(const QRect &source = QRect(), const QRect &destination = QRect(), GLenum filter = GL_LINEAR); /** * Sets the virtual screen size to @p s. * @since 5.2 **/ static void setVirtualScreenSize(const QSize &s) { s_virtualScreenSize = s; } /** * Sets the virtual screen geometry to @p g. * This is the geometry of the OpenGL window currently being rendered to * in the virtual geometry space the rendering geometries use. * @see virtualScreenGeometry * @since 5.9 **/ static void setVirtualScreenGeometry(const QRect &g) { s_virtualScreenGeometry = g; } /** * The geometry of the OpenGL window currently being rendered to * in the virtual geometry space the rendering system uses. * @see setVirtualScreenGeometry * @since 5.9 **/ static QRect virtualScreenGeometry() { return s_virtualScreenGeometry; } /** * The scale of the OpenGL window currently being rendered to * * @returns the ratio between the virtual geometry space the rendering * system uses and the target * @since 5.10 */ static void setVirtualScreenScale(qreal scale) { s_virtualScreenScale = scale; } static qreal virtualScreenScale() { return s_virtualScreenScale; } protected: void initFBO(); private: friend void KWin::cleanupGL(); static void cleanup(); static bool sSupported; static bool s_blitSupported; static QStack s_renderTargets; static QSize s_virtualScreenSize; static QRect s_virtualScreenGeometry; static qreal s_virtualScreenScale; static GLint s_virtualScreenViewport[4]; GLTexture mTexture; bool mValid; GLuint mFramebuffer; }; enum VertexAttributeType { VA_Position = 0, VA_TexCoord = 1, VertexAttributeCount = 2 }; /** * Describes the format of a vertex attribute stored in a buffer object. * * The attribute format consists of the attribute index, the number of * vector components, the data type, and the offset of the first element * relative to the start of the vertex data. */ struct GLVertexAttrib { int index; /** The attribute index */ int size; /** The number of components [1..4] */ GLenum type; /** The type (e.g. GL_FLOAT) */ int relativeOffset; /** The relative offset of the attribute */ }; /** * @short Vertex Buffer Object * * This is a short helper class to use vertex buffer objects (VBO). A VBO can be used to buffer * vertex data and to store them on graphics memory. It is the only allowed way to pass vertex * data to the GPU in OpenGL ES 2 and OpenGL 3 with forward compatible mode. * * If VBOs are not supported on the used OpenGL profile this class falls back to legacy * rendering using client arrays. Therefore this class should always be used for rendering geometries. * * @author Martin Gräßlin * @since 4.6 */ class KWINGLUTILS_EXPORT GLVertexBuffer { public: /** * Enum to define how often the vertex data in the buffer object changes. */ enum UsageHint { Dynamic, ///< frequent changes, but used several times for rendering Static, ///< No changes to data Stream ///< Data only used once for rendering, updated very frequently }; explicit GLVertexBuffer(UsageHint hint); ~GLVertexBuffer(); /** * Specifies how interleaved vertex attributes are laid out in * the buffer object. * * Note that the attributes and the stride should be 32 bit aligned * or a performance penalty may be incurred. * * For some hardware the optimal stride is a multiple of 32 bytes. * * Example: * * struct Vertex { * QVector3D position; * QVector2D texcoord; * }; * * const GLVertexAttrib attribs[] = { * { VA_Position, 3, GL_FLOAT, offsetof(Vertex, position) }, * { VA_TexCoord, 2, GL_FLOAT, offsetof(Vertex, texcoord) } * }; * * Vertex vertices[6]; * vbo->setAttribLayout(attribs, 2, sizeof(Vertex)); * vbo->setData(vertices, sizeof(vertices)); */ void setAttribLayout(const GLVertexAttrib *attribs, int count, int stride); /** * Uploads data into the buffer object's data store. */ void setData(const void *data, size_t sizeInBytes); /** * Sets the number of vertices that will be drawn by the render() method. */ void setVertexCount(int count); /** * Sets the vertex data. * @param numberVertices The number of vertices in the arrays * @param dim The dimension of the vertices: 2 for x/y, 3 for x/y/z * @param vertices The vertices, size must equal @a numberVertices * @a dim * @param texcoords The texture coordinates for each vertex. * Size must equal 2 * @a numberVertices. */ void setData(int numberVertices, int dim, const float* vertices, const float* texcoords); /** * Maps an unused range of the data store into the client's address space. * * The data store will be reallocated if it is smaller than the given size. * * The buffer object is mapped for writing, not reading. Attempts to read from * the mapped buffer range may result in system errors, including program * termination. The data in the mapped region is undefined until it has been * written to. If subsequent GL calls access unwritten memory, the results are * undefined and system errors, including program termination, may occur. * * No GL calls that access the buffer object must be made while the buffer * object is mapped. The returned pointer must not be passed as a parameter * value to any GL function. * * It is assumed that the GL_ARRAY_BUFFER_BINDING will not be changed while * the buffer object is mapped. */ GLvoid *map(size_t size); /** * Flushes the mapped buffer range and unmaps the buffer. */ void unmap(); /** * Binds the vertex arrays to the context. */ void bindArrays(); /** * Disables the vertex arrays. */ void unbindArrays(); /** * Draws count vertices beginning with first. */ void draw(GLenum primitiveMode, int first, int count); /** * Draws count vertices beginning with first. */ void draw(const QRegion ®ion, GLenum primitiveMode, int first, int count, bool hardwareClipping = false); /** * Renders the vertex data in given @a primitiveMode. * Please refer to OpenGL documentation of glDrawArrays or glDrawElements for allowed * values for @a primitiveMode. Best is to use GL_TRIANGLES or similar to be future * compatible. */ void render(GLenum primitiveMode); /** * Same as above restricting painting to @a region if @a hardwareClipping is true. * It's within the caller's responsibility to enable GL_SCISSOR_TEST. */ void render(const QRegion& region, GLenum primitiveMode, bool hardwareClipping = false); /** * Sets the color the geometry will be rendered with. * For legacy rendering glColor is used before rendering the geometry. * For core shader a uniform "geometryColor" is expected and is set. * @param color The color to render the geometry * @param enableColor Whether the geometry should be rendered with a color or not * @see setUseColor * @see isUseColor * @since 4.7 **/ void setColor(const QColor& color, bool enableColor = true); /** * @return @c true if geometry will be painted with a color, @c false otherwise * @see setUseColor * @see setColor * @since 4.7 **/ bool isUseColor() const; /** * Enables/Disables rendering the geometry with a color. * If no color is set an opaque, black color is used. * @param enable Enable/Disable rendering with color * @see isUseColor * @see setColor * @since 4.7 **/ void setUseColor(bool enable); /** * Resets the instance to default values. * Useful for shared buffers. * @since 4.7 **/ void reset(); /** * Notifies the vertex buffer that we are done painting the frame. * * @internal */ void endOfFrame(); /** * Notifies the vertex buffer that we have posted the frame. * * @internal */ void framePosted(); /** * @internal */ static void initStatic(); /** * @internal */ static void cleanup(); /** * Returns true if indexed quad mode is supported, and false otherwise. */ static bool supportsIndexedQuads(); /** * @return A shared VBO for streaming data * @since 4.7 **/ static GLVertexBuffer *streamingBuffer(); /** * Sets the virtual screen geometry to @p g. * This is the geometry of the OpenGL window currently being rendered to * in the virtual geometry space the rendering geometries use. * @since 5.9 **/ static void setVirtualScreenGeometry(const QRect &g) { s_virtualScreenGeometry = g; } /** * The scale of the OpenGL window currently being rendered to * * @returns the ratio between the virtual geometry space the rendering * system uses and the target * @since 5.11.3 */ static void setVirtualScreenScale(qreal s) { s_virtualScreenScale = s; } private: GLVertexBufferPrivate* const d; static QRect s_virtualScreenGeometry; static qreal s_virtualScreenScale; }; } // namespace Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::ShaderTraits) /** @} */ #endif diff --git a/outline.h b/outline.h index 982c97f11..163216bf8 100644 --- a/outline.h +++ b/outline.h @@ -1,194 +1,194 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Arthur Arlt This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_OUTLINE_H #define KWIN_OUTLINE_H #include #include #include #include class QQmlContext; class QQmlComponent; namespace KWin { class OutlineVisual; /** * @short This class is used to show the outline of a given geometry. * * The class renders an outline by using four windows. One for each border of * the geometry. It is possible to replace the outline with an effect. If an * effect is available the effect will be used, otherwise the outline will be * rendered by using the X implementation. * * @author Arthur Arlt * @since 4.7 */ class Outline : public QObject { Q_OBJECT Q_PROPERTY(QRect geometry READ geometry NOTIFY geometryChanged) Q_PROPERTY(QRect visualParentGeometry READ visualParentGeometry NOTIFY visualParentGeometryChanged) Q_PROPERTY(QRect unifiedGeometry READ unifiedGeometry NOTIFY unifiedGeometryChanged) Q_PROPERTY(bool active READ isActive NOTIFY activeChanged) public: ~Outline(); /** * Set the outline geometry. - * To show the outline use @link showOutline. + * To show the outline use showOutline. * @param outlineGeometry The geometry of the outline to be shown * @see showOutline */ void setGeometry(const QRect &outlineGeometry); /** * Set the visual parent geometry. * This is the geometry from which the will emerge. * @param visualParentGeometry The visual geometry of the visual parent * @see showOutline */ void setVisualParentGeometry(const QRect &visualParentGeometry); /** * Shows the outline of a window using either an effect or the X implementation. - * To stop the outline process use @link hideOutline. + * To stop the outline process use hideOutline. * @see hideOutline */ void show(); /** * Shows the outline for the given @p outlineGeometry. * This is the same as setOutlineGeometry followed by showOutline directly. - * To stop the outline process use @link hideOutline. + * To stop the outline process use hideOutline. * @param outlineGeometry The geometry of the outline to be shown * @see hideOutline */ void show(const QRect &outlineGeometry); /** * Shows the outline for the given @p outlineGeometry animated from @p visualParentGeometry. * This is the same as setOutlineGeometry followed by setVisualParentGeometry * and then showOutline. - * To stop the outline process use @link hideOutline. + * To stop the outline process use hideOutline. * @param outlineGeometry The geometry of the outline to be shown * @param visualParentGeometry The geometry from where the outline should emerge * @see hideOutline * @since 5.10 */ void show(const QRect &outlineGeometry, const QRect &visualParentGeometry); /** * Hides shown outline. * @see showOutline */ void hide(); const QRect &geometry() const; const QRect &visualParentGeometry() const; QRect unifiedGeometry() const; bool isActive() const; private Q_SLOTS: void compositingChanged(); Q_SIGNALS: void activeChanged(); void geometryChanged(); void unifiedGeometryChanged(); void visualParentGeometryChanged(); private: void createHelper(); QScopedPointer m_visual; QRect m_outlineGeometry; QRect m_visualParentGeometry; bool m_active; KWIN_SINGLETON(Outline) }; class KWIN_EXPORT OutlineVisual { public: OutlineVisual(Outline *outline); virtual ~OutlineVisual(); virtual void show() = 0; virtual void hide() = 0; protected: Outline *outline(); const Outline *outline() const; private: Outline *m_outline; }; class CompositedOutlineVisual : public OutlineVisual { public: CompositedOutlineVisual(Outline *outline); virtual ~CompositedOutlineVisual(); virtual void show(); virtual void hide(); private: QScopedPointer m_qmlContext; QScopedPointer m_qmlComponent; QScopedPointer m_mainItem; }; inline bool Outline::isActive() const { return m_active; } inline const QRect &Outline::geometry() const { return m_outlineGeometry; } inline const QRect &Outline::visualParentGeometry() const { return m_visualParentGeometry; } inline Outline *OutlineVisual::outline() { return m_outline; } inline const Outline *OutlineVisual::outline() const { return m_outline; } inline Outline *outline() { return Outline::self(); } } #endif diff --git a/scene.h b/scene.h index 5f05829cd..892fb5878 100644 --- a/scene.h +++ b/scene.h @@ -1,683 +1,683 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCENE_H #define KWIN_SCENE_H #include "toplevel.h" #include "utils.h" #include "kwineffects.h" #include #include class QOpenGLFramebufferObject; namespace KWayland { namespace Server { class BufferInterface; class SubSurfaceInterface; } } namespace KWin { namespace Decoration { class DecoratedClientImpl; class Renderer; } class AbstractThumbnailItem; class Deleted; class EffectFrameImpl; class EffectWindowImpl; class OverlayWindow; class Shadow; class WindowPixmap; // The base class for compositing backends. class KWIN_EXPORT Scene : public QObject { Q_OBJECT public: explicit Scene(QObject *parent = nullptr); virtual ~Scene() = 0; class EffectFrame; class Window; // Returns true if the ctor failed to properly initialize. virtual bool initFailed() const = 0; virtual CompositingType compositingType() const = 0; virtual bool hasPendingFlush() const { return false; } // Repaints the given screen areas, windows provides the stacking order. // The entry point for the main part of the painting pass. // returns the time since the last vblank signal - if there's one // ie. "what of this frame is lost to painting" virtual qint64 paint(QRegion damage, ToplevelList windows) = 0; // Notification function - KWin core informs about changes. // Used to mainly discard cached data. // a new window has been created void windowAdded(Toplevel*); /** * @brief Creates the Scene backend of an EffectFrame. * * @param frame The EffectFrame this Scene::EffectFrame belongs to. */ virtual Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame) = 0; /** * @brief Creates the Scene specific Shadow subclass. * * An implementing class has to create a proper instance. It is not allowed to * return @c null. * * @param toplevel The Toplevel for which the Shadow needs to be created. */ virtual Shadow *createShadow(Toplevel *toplevel) = 0; /** * Method invoked when the screen geometry is changed. * Reimplementing classes should also invoke the parent method * as it takes care of resizing the overlay window. * @param size The new screen geometry size **/ virtual void screenGeometryChanged(const QSize &size); // Flags controlling how painting is done. enum { // Window (or at least part of it) will be painted opaque. PAINT_WINDOW_OPAQUE = 1 << 0, // Window (or at least part of it) will be painted translucent. PAINT_WINDOW_TRANSLUCENT = 1 << 1, // Window will be painted with transformed geometry. PAINT_WINDOW_TRANSFORMED = 1 << 2, // Paint only a region of the screen (can be optimized, cannot // be used together with TRANSFORMED flags). PAINT_SCREEN_REGION = 1 << 3, // Whole screen will be painted with transformed geometry. PAINT_SCREEN_TRANSFORMED = 1 << 4, // At least one window will be painted with transformed geometry. PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS = 1 << 5, // Clear whole background as the very first step, without optimizing it PAINT_SCREEN_BACKGROUND_FIRST = 1 << 6, // PAINT_DECORATION_ONLY = 1 << 7 has been removed // Window will be painted with a lanczos filter. PAINT_WINDOW_LANCZOS = 1 << 8 // PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS = 1 << 9 has been removed }; // types of filtering available enum ImageFilterType { ImageFilterFast, ImageFilterGood }; // there's nothing to paint (adjust time_diff later) virtual void idle(); virtual bool blocksForRetrace() const; virtual bool syncsToVBlank() const; virtual OverlayWindow* overlayWindow() = 0; virtual bool makeOpenGLContextCurrent(); virtual void doneOpenGLContextCurrent(); virtual QMatrix4x4 screenProjectionMatrix() const; /** * Whether the Scene uses an X11 overlay window to perform compositing. */ virtual bool usesOverlayWindow() const = 0; virtual void triggerFence(); virtual Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *) = 0; /** * Whether the Scene is able to drive animations. * This is used as a hint to the effects system which effects can be supported. * If the Scene performs software rendering it is supposed to return @c false, * if rendering is hardware accelerated it should return @c true. **/ virtual bool animationsSupported() const = 0; /** * The render buffer used by an XRender based compositor scene. * Default implementation returns XCB_RENDER_PICTURE_NONE **/ virtual xcb_render_picture_t xrenderBufferPicture() const; /** * The QPainter used by a QPainter based compositor scene. * Default implementation returns @c nullptr; **/ virtual QPainter *scenePainter() const; /** * The render buffer used by a QPainter based compositor. * Default implementation returns @c nullptr. **/ virtual QImage *qpainterRenderBuffer() const; /** * The backend specific extensions (e.g. EGL/GLX extensions). * * Not the OpenGL (ES) extension! * * Default implementation returns empty list **/ virtual QVector openGLPlatformInterfaceExtensions() const; Q_SIGNALS: void frameRendered(); void resetCompositing(); public Q_SLOTS: // a window has been destroyed void windowDeleted(KWin::Deleted*); // shape/size of a window changed void windowGeometryShapeChanged(KWin::Toplevel* c); // a window has been closed void windowClosed(KWin::Toplevel* c, KWin::Deleted* deleted); protected: virtual Window *createWindow(Toplevel *toplevel) = 0; void createStackingOrder(ToplevelList toplevels); void clearStackingOrder(); // shared implementation, starts painting the screen void paintScreen(int *mask, const QRegion &damage, const QRegion &repaint, QRegion *updateRegion, QRegion *validRegion, const QMatrix4x4 &projection = QMatrix4x4(), const QRect &outputGeometry = QRect()); // Render cursor texture in case hardware cursor is disabled/non-applicable virtual void paintCursor() = 0; friend class EffectsHandlerImpl; // called after all effects had their paintScreen() called void finalPaintScreen(int mask, QRegion region, ScreenPaintData& data); // shared implementation of painting the screen in the generic // (unoptimized) way virtual void paintGenericScreen(int mask, ScreenPaintData data); // shared implementation of painting the screen in an optimized way virtual void paintSimpleScreen(int mask, QRegion region); // paint the background (not the desktop background - the whole background) virtual void paintBackground(QRegion region) = 0; // called after all effects had their paintWindow() called void finalPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); // shared implementation, starts painting the window virtual void paintWindow(Window* w, int mask, QRegion region, WindowQuadList quads); // called after all effects had their drawWindow() called virtual void finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); // let the scene decide whether it's better to paint more of the screen, eg. in order to allow a buffer swap // the default is NOOP virtual void extendPaintRegion(QRegion ®ion, bool opaqueFullscreen); virtual void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data); // compute time since the last repaint void updateTimeDiff(); // saved data for 2nd pass of optimized screen painting struct Phase2Data { Phase2Data(Window* w, QRegion r, QRegion c, int m, const WindowQuadList& q) : window(w), region(r), clip(c), mask(m), quads(q) {} Phase2Data() { window = 0; mask = 0; } Window* window; QRegion region; QRegion clip; int mask; WindowQuadList quads; }; // The region which actually has been painted by paintScreen() and should be // copied from the buffer to the screen. I.e. the region returned from Scene::paintScreen(). // Since prePaintWindow() can extend areas to paint, these changes would have to propagate // up all the way from paintSimpleScreen() up to paintScreen(), so save them here rather // than propagate them up in arguments. QRegion painted_region; // Additional damage that needs to be repaired to bring a reused back buffer up to date QRegion repaint_region; // The dirty region before it was unioned with repaint_region QRegion damaged_region; // time since last repaint int time_diff; QElapsedTimer last_time; private: void paintWindowThumbnails(Scene::Window *w, QRegion region, qreal opacity, qreal brightness, qreal saturation); void paintDesktopThumbnails(Scene::Window *w); QHash< Toplevel*, Window* > m_windows; // windows in their stacking order QVector< Window* > stacking_order; }; /** * Factory class to create a Scene. Needs to be implemented by the plugins. **/ class KWIN_EXPORT SceneFactory : public QObject { Q_OBJECT public: virtual ~SceneFactory(); /** * @returns The created Scene, may be @c nullptr. **/ virtual Scene *create(QObject *parent = nullptr) const = 0; protected: explicit SceneFactory(QObject *parent); }; // The base class for windows representations in composite backends class Scene::Window { public: Window(Toplevel* c); virtual ~Window(); // perform the actual painting of the window virtual void performPaint(int mask, QRegion region, WindowPaintData data) = 0; // do any cleanup needed when the window's composite pixmap is discarded void pixmapDiscarded(); int x() const; int y() const; int width() const; int height() const; QRect geometry() const; QPoint pos() const; QSize size() const; QRect rect() const; // access to the internal window class // TODO eventually get rid of this Toplevel* window() const; // should the window be painted bool isPaintingEnabled() const; void resetPaintingEnabled(); // Flags explaining why painting should be disabled enum { // Window will not be painted PAINT_DISABLED = 1 << 0, // Window will not be painted because it is deleted PAINT_DISABLED_BY_DELETE = 1 << 1, // Window will not be painted because of which desktop it's on PAINT_DISABLED_BY_DESKTOP = 1 << 2, // Window will not be painted because it is minimized PAINT_DISABLED_BY_MINIMIZE = 1 << 3, // Window will not be painted because it is not the active window in a client group PAINT_DISABLED_BY_TAB_GROUP = 1 << 4, // Window will not be painted because it's not on the current activity PAINT_DISABLED_BY_ACTIVITY = 1 << 5 }; void enablePainting(int reason); void disablePainting(int reason); // is the window visible at all bool isVisible() const; // is the window fully opaque bool isOpaque() const; // shape of the window const QRegion &shape() const; QRegion clientShape() const; void discardShape(); void updateToplevel(Toplevel* c); // creates initial quad list for the window virtual WindowQuadList buildQuads(bool force = false) const; void updateShadow(Shadow* shadow); const Shadow* shadow() const; Shadow* shadow(); void referencePreviousPixmap(); void unreferencePreviousPixmap(); void invalidateQuadsCache(); protected: WindowQuadList makeQuads(WindowQuadType type, const QRegion& reg, const QPoint &textureOffset = QPoint(0, 0), qreal textureScale = 1.0) const; WindowQuadList makeDecorationQuads(const QRect *rects, const QRegion ®ion, qreal textureScale = 1.0) const; /** * @brief Returns the WindowPixmap for this Window. * - * If the WindowPixmap does not yet exist, this method will invoke @link createWindowPixmap. + * If the WindowPixmap does not yet exist, this method will invoke createWindowPixmap. * If the WindowPixmap is not valid it tries to create it, in case this succeeds the WindowPixmap is * returned. In case it fails, the previous (and still valid) WindowPixmap is returned. * - * Note: this method can return @c NULL as there might neither be a valid previous nor current WindowPixmap + * @note This method can return @c NULL as there might neither be a valid previous nor current WindowPixmap * around. * * The WindowPixmap gets casted to the type passed in as a template parameter. That way this class does not * need to know the actual WindowPixmap subclass used by the concrete Scene implementations. * * @return The WindowPixmap casted to T* or @c NULL if there is no valid window pixmap. */ template T *windowPixmap(); template T *previousWindowPixmap(); /** * @brief Factory method to create a WindowPixmap. * * The inheriting classes need to implement this method to create a new instance of their WindowPixmap subclass. - * Note: do not use @link WindowPixmap::create on the created instance. The Scene will take care of that. + * @note Do not use WindowPixmap::create on the created instance. The Scene will take care of that. */ virtual WindowPixmap *createWindowPixmap() = 0; Toplevel* toplevel; ImageFilterType filter; Shadow *m_shadow; private: QScopedPointer m_currentPixmap; QScopedPointer m_previousPixmap; int m_referencePixmapCounter; int disable_painting; mutable QRegion shape_region; mutable bool shape_valid; mutable QScopedPointer cached_quad_list; Q_DISABLE_COPY(Window) }; /** * @brief Wrapper for a pixmap of the @link Scene::Window. * * This class encapsulates the functionality to get the pixmap for a window. When initialized the pixmap is not yet * mapped to the window and @link isValid will return @c false. The pixmap mapping to the window can be established * through @link create. If it succeeds @link isValid will return @c true, otherwise it will keep in the non valid * state and it can be tried to create the pixmap mapping again (e.g. in the next frame). * * This class is not intended to be updated when the pixmap is no longer valid due to e.g. resizing the window. * Instead a new instance of this class should be instantiated. The idea behind this is that a valid pixmap does not * get destroyed, but can continue to be used. To indicate that a newer pixmap should in generally be around, one can * use @link markAsDiscarded. * * This class is intended to be inherited for the needs of the compositor backends which need further mapping from * the native pixmap to the respective rendering format. */ class KWIN_EXPORT WindowPixmap { public: virtual ~WindowPixmap(); /** * @brief Tries to create the mapping between the Window and the pixmap. * * In case this method succeeds in creating the pixmap for the window, @link isValid will return @c true otherwise * @c false. * * Inheriting classes should re-implement this method in case they need to add further functionality for mapping the * native pixmap to the rendering format. */ virtual void create(); /** * @return @c true if the pixmap has been created and is valid, @c false otherwise */ virtual bool isValid() const; /** * @return The native X11 pixmap handle */ xcb_pixmap_t pixmap() const; /** * @return The Wayland BufferInterface for this WindowPixmap. **/ QPointer buffer() const; const QSharedPointer &fbo() const; /** * @brief Whether this WindowPixmap is considered as discarded. This means the window has changed in a way that a new * WindowPixmap should have been created already. * * @return @c true if this WindowPixmap is considered as discarded, @c false otherwise. * @see markAsDiscarded */ bool isDiscarded() const; /** * @brief Marks this WindowPixmap as discarded. From now on @link isDiscarded will return @c true. This method should * only be used by the Window when it changes in a way that a new pixmap is required. * * @see isDiscarded */ void markAsDiscarded(); /** * The size of the pixmap. */ const QSize &size() const; /** * The geometry of the Client's content inside the pixmap. In case of a decorated Client the * pixmap also contains the decoration which is not rendered into this pixmap, though. This * contentsRect tells where inside the complete pixmap the real content is. */ const QRect &contentsRect() const; /** * @brief Returns the Toplevel this WindowPixmap belongs to. * Note: the Toplevel can change over the lifetime of the WindowPixmap in case the Toplevel is copied to Deleted. */ Toplevel *toplevel() const; /** * @returns the parent WindowPixmap in the sub-surface tree **/ WindowPixmap *parent() const { return m_parent; } /** * @returns the current sub-surface tree **/ QVector children() const { return m_children; } /** * @returns the subsurface this WindowPixmap is for if it is not for a root window **/ QPointer subSurface() const { return m_subSurface; } /** * @returns the surface this WindowPixmap references, might be @c null. **/ KWayland::Server::SurfaceInterface *surface() const; protected: explicit WindowPixmap(Scene::Window *window); explicit WindowPixmap(const QPointer &subSurface, WindowPixmap *parent); virtual WindowPixmap *createChild(const QPointer &subSurface); /** * @return The Window this WindowPixmap belongs to */ Scene::Window *window(); /** * Should be called by the implementing subclasses when the Wayland Buffer changed and needs * updating. **/ virtual void updateBuffer(); /** * Sets the sub-surface tree to @p children. **/ void setChildren(const QVector &children) { m_children = children; } private: Scene::Window *m_window; xcb_pixmap_t m_pixmap; QSize m_pixmapSize; bool m_discarded; QRect m_contentsRect; QPointer m_buffer; QSharedPointer m_fbo; WindowPixmap *m_parent = nullptr; QVector m_children; QPointer m_subSurface; }; class Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame); virtual ~EffectFrame(); virtual void render(QRegion region, double opacity, double frameOpacity) = 0; virtual void free() = 0; virtual void freeIconFrame() = 0; virtual void freeTextFrame() = 0; virtual void freeSelection() = 0; virtual void crossFadeIcon() = 0; virtual void crossFadeText() = 0; protected: EffectFrameImpl* m_effectFrame; }; inline int Scene::Window::x() const { return toplevel->x(); } inline int Scene::Window::y() const { return toplevel->y(); } inline int Scene::Window::width() const { return toplevel->width(); } inline int Scene::Window::height() const { return toplevel->height(); } inline QRect Scene::Window::geometry() const { return toplevel->geometry(); } inline QSize Scene::Window::size() const { return toplevel->size(); } inline QPoint Scene::Window::pos() const { return toplevel->pos(); } inline QRect Scene::Window::rect() const { return toplevel->rect(); } inline Toplevel* Scene::Window::window() const { return toplevel; } inline void Scene::Window::updateToplevel(Toplevel* c) { toplevel = c; } inline const Shadow* Scene::Window::shadow() const { return m_shadow; } inline Shadow* Scene::Window::shadow() { return m_shadow; } inline QPointer WindowPixmap::buffer() const { return m_buffer; } inline const QSharedPointer &WindowPixmap::fbo() const { return m_fbo; } template inline T* Scene::Window::windowPixmap() { if (m_currentPixmap.isNull()) { m_currentPixmap.reset(createWindowPixmap()); } if (m_currentPixmap->isValid()) { return static_cast(m_currentPixmap.data()); } m_currentPixmap->create(); if (m_currentPixmap->isValid()) { return static_cast(m_currentPixmap.data()); } else { return static_cast(m_previousPixmap.data()); } } template inline T* Scene::Window::previousWindowPixmap() { return static_cast(m_previousPixmap.data()); } inline Toplevel* WindowPixmap::toplevel() const { return m_window->window(); } inline xcb_pixmap_t WindowPixmap::pixmap() const { return m_pixmap; } inline bool WindowPixmap::isDiscarded() const { return m_discarded; } inline void WindowPixmap::markAsDiscarded() { m_discarded = true; m_window->referencePreviousPixmap(); } inline const QRect &WindowPixmap::contentsRect() const { return m_contentsRect; } inline const QSize &WindowPixmap::size() const { return m_pixmapSize; } } // namespace Q_DECLARE_INTERFACE(KWin::SceneFactory, "org.kde.kwin.Scene") #endif diff --git a/screenedge.h b/screenedge.h index 8157e1f6d..a14e9dcea 100644 --- a/screenedge.h +++ b/screenedge.h @@ -1,590 +1,590 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Arthur Arlt Copyright (C) 2013 Martin Gräßlin Since the functionality provided in this class has been moved from class Workspace, it is not clear who exactly has written the code. The list below contains the copyright holders of the class Workspace. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 Lucas Murray This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCREENEDGE_H #define KWIN_SCREENEDGE_H // KWin #include "kwinglobals.h" // KDE includes #include // Qt #include #include #include #include class QAction; class QMouseEvent; namespace KWin { class AbstractClient; class GestureRecognizer; class ScreenEdges; class SwipeGesture; class KWIN_EXPORT Edge : public QObject { Q_OBJECT public: explicit Edge(ScreenEdges *parent); virtual ~Edge(); bool isLeft() const; bool isTop() const; bool isRight() const; bool isBottom() const; bool isCorner() const; bool isScreenEdge() const; bool triggersFor(const QPoint &cursorPos) const; bool check(const QPoint &cursorPos, const QDateTime &triggerTime, bool forceNoPushBack = false); void markAsTriggered(const QPoint &cursorPos, const QDateTime &triggerTime); bool isReserved() const; const QRect &approachGeometry() const; ElectricBorder border() const; void reserve(QObject *object, const char *slot); const QHash &callBacks() const; void reserveTouchCallBack(QAction *action); void unreserveTouchCallBack(QAction *action); QVector touchCallBacks() const { return m_touchActions; } void startApproaching(); void stopApproaching(); bool isApproaching() const; void setClient(AbstractClient *client); AbstractClient *client() const; const QRect &geometry() const; void setTouchAction(ElectricBorderAction action); bool activatesForPointer() const; bool activatesForTouchGesture() const; /** * The window id of the native window representing the edge. * Default implementation returns @c 0, which means no window. **/ virtual quint32 window() const; /** * The approach window is a special window to notice when get close to the screen border but * not yet triggering the border. * * The default implementation returns @c 0, which means no window. **/ virtual quint32 approachWindow() const; public Q_SLOTS: void reserve(); void unreserve(); void unreserve(QObject *object); void setBorder(ElectricBorder border); void setAction(ElectricBorderAction action); void setGeometry(const QRect &geometry); void updateApproaching(const QPoint &point); void checkBlocking(); Q_SIGNALS: void approaching(ElectricBorder border, qreal factor, const QRect &geometry); void activatesForTouchGestureChanged(); protected: ScreenEdges *edges(); const ScreenEdges *edges() const; bool isBlocked() const; virtual void doGeometryUpdate(); virtual void doActivate(); virtual void doDeactivate(); virtual void doStartApproaching(); virtual void doStopApproaching(); virtual void doUpdateBlocking(); private: void activate(); void deactivate(); bool canActivate(const QPoint &cursorPos, const QDateTime &triggerTime); void handle(const QPoint &cursorPos); bool handleAction(ElectricBorderAction action); bool handlePointerAction() { return handleAction(m_action); } bool handleTouchAction() { return handleAction(m_touchAction); } bool handleByCallback(); void handleTouchCallback(); void switchDesktop(const QPoint &cursorPos); void pushCursorBack(const QPoint &cursorPos); ScreenEdges *m_edges; ElectricBorder m_border; ElectricBorderAction m_action; ElectricBorderAction m_touchAction = ElectricActionNone; int m_reserved; QRect m_geometry; QRect m_approachGeometry; QDateTime m_lastTrigger; QDateTime m_lastReset; QPoint m_triggeredPoint; QHash m_callBacks; bool m_approaching; int m_lastApproachingFactor; bool m_blocked; bool m_pushBackBlocked; AbstractClient *m_client; SwipeGesture *m_gesture; QVector m_touchActions; }; /** * @short Class for controlling screen edges. * * The screen edge functionality is split into three parts: * @li This manager class ScreenEdges * @li abstract class @ref Edge - * @li specific implementation of @ref Edge, e.g. @ref WindowBasedEdge + * @li specific implementation of @ref Edge, e.g. WindowBasedEdge * * The ScreenEdges creates an @ref Edge for each screen edge which is also an edge in the * combination of all screens. E.g. if there are two screens, no Edge is created between the screens, * but at all other edges even if the screens have a different dimension. * * In addition at each corner of the overall display geometry an one-pixel large @ref Edge is * created. No matter how many screens there are, there will only be exactly four of these corner * edges. This is motivated by Fitts's Law which show that it's easy to trigger such a corner, but * it would be very difficult to trigger a corner between two screens (one pixel target not visually * outlined). * * The ScreenEdges are used for one of the following functionality: * @li switch virtual desktop (see property @ref desktopSwitching) * @li switch virtual desktop when moving a window (see property @ref desktopSwitchingMovingClients) * @li trigger a pre-defined action (see properties @ref actionTop and similar) * @li trigger an externally configured action (e.g. Effect, Script, see @ref reserve, @ref unreserve) * * An @ref Edge is only active if there is at least one of the possible actions "reserved" for this * edge. The idea is to not block the screen edge if nothing could be triggered there, so that the * user e.g. can configure nothing on the top edge, which tends to interfere with full screen apps * having a hidden panel there. On X11 (currently only supported backend) the @ref Edge is * represented by a @ref WindowBasedEdge which creates an input only window for the geometry and * reacts on enter notify events. If the edge gets reserved for the first time a window is created * and mapped, once the edge gets unreserved again, the window gets destroyed. * * When the mouse enters one of the screen edges the following values are used to determine whether * the action should be triggered or the cursor be pushed back * @li Time difference between two entering events is not larger than a certain threshold * @li Time difference between two entering events is larger than @ref timeThreshold * @li Time difference between two activations is larger than @ref reActivateThreshold * @li Distance between two enter events is not larger than a defined pixel distance * These checks are performed in @ref Edge * * @todo change way how Effects/Scripts can reserve an edge and are notified. */ class KWIN_EXPORT ScreenEdges : public QObject { Q_OBJECT Q_PROPERTY(bool desktopSwitching READ isDesktopSwitching) Q_PROPERTY(bool desktopSwitchingMovingClients READ isDesktopSwitchingMovingClients) Q_PROPERTY(QSize cursorPushBackDistance READ cursorPushBackDistance) Q_PROPERTY(int timeThreshold READ timeThreshold) Q_PROPERTY(int reActivateThreshold READ reActivationThreshold) Q_PROPERTY(int actionTopLeft READ actionTopLeft) Q_PROPERTY(int actionTop READ actionTop) Q_PROPERTY(int actionTopRight READ actionTopRight) Q_PROPERTY(int actionRight READ actionRight) Q_PROPERTY(int actionBottomRight READ actionBottomRight) Q_PROPERTY(int actionBottom READ actionBottom) Q_PROPERTY(int actionBottomLeft READ actionBottomLeft) Q_PROPERTY(int actionLeft READ actionLeft) public: virtual ~ScreenEdges(); /** * @internal **/ void setConfig(KSharedConfig::Ptr config); /** * Initialize the screen edges. * @internal */ void init(); /** * Check, if a screen edge is entered and trigger the appropriate action * if one is enabled for the current region and the timeout is satisfied * @param pos the position of the mouse pointer * @param now the time when the function is called * @param forceNoPushBack needs to be called to workaround some DnD clients, don't use unless you want to chek on a DnD event */ void check(const QPoint& pos, const QDateTime &now, bool forceNoPushBack = false); /** * The (dpi dependent) length, reserved for the active corners of each edge - 1/3" */ int cornerOffset() const; /** * Mark the specified screen edge as reserved. This method is provided for external activation * like effects and scripts. When the effect/script does no longer need the edge it is supposed * to call @ref unreserve. * @param border the screen edge to mark as reserved * @param object The object on which the @p callback needs to be invoked * @param callback The method name to be invoked - uses QMetaObject::invokeMethod * @see unreserve * @todo: add pointer to script/effect */ void reserve(ElectricBorder border, QObject *object, const char *callback); /** * Mark the specified screen edge as unreserved. This method is provided for external activation * like effects and scripts. This method is only allowed to be called if @ref reserve had been * called before for the same @p border. An unbalanced calling of reserve/unreserve leads to the * edge never being active or never being able to deactivate again. * @param border the screen edge to mark as unreserved * @param object the object on which the callback had been invoked * @see reserve * @todo: add pointer to script/effect */ void unreserve(ElectricBorder border, QObject *object); /** * Reserves an edge for the @p client. The idea behind this is to show the @p client if the * screen edge which the @p client borders gets triggered. * * When first called it is tried to create an Edge for the client. This is only done if the * client borders with a screen edge specified by @p border. If the client doesn't border the * screen edge, no Edge gets created and the client is shown again. Otherwise there would not * be a possibility to show the client again. * * On subsequent calls for the client no new Edge is created, but the existing one gets reused * and if the client is already hidden, the Edge gets reserved. * * Once the Edge for the client triggers, the client gets shown again and the Edge unreserved. * The idea is that the Edge can only get activated if the client is currently hidden. * * To make sure that the client can always be shown again the implementation also starts to * track geometry changes and shows the Client again. The same for screen geometry changes. * * The Edge gets automatically destroyed if the client gets released. * @param client The Client for which an Edge should be reserved * @param border The border which the client wants to use, only proper borders are supported (no corners) **/ void reserve(KWin::AbstractClient *client, ElectricBorder border); /** * Mark the specified screen edge as reserved for touch gestures. This method is provided for * external activation like effects and scripts. * When the effect/script does no longer need the edge it is supposed * to call @ref unreserveTouch. * @param border the screen edge to mark as reserved * @param action The action which gets triggered * @see unreserveTouch * @since 5.10 **/ void reserveTouch(ElectricBorder border, QAction *action); /** * Unreserves the specified @p border from activating the @p action for touch gestures. * @see reserveTouch * @since 5.10 **/ void unreserveTouch(ElectricBorder border, QAction *action); /** * Reserve desktop switching for screen edges, if @p isToReserve is @c true. Unreserve otherwise. * @param isToReserve indicated whether desktop switching should be reserved or unreseved */ void reserveDesktopSwitching(bool isToReserve, Qt::Orientations o); /** * Raise electric border windows to the real top of the screen. We only need * to do this if an effect input window is active. */ void ensureOnTop(); bool isEntered(QMouseEvent *event); /** * Returns a QVector of all existing screen edge windows * @return all existing screen edge windows in a QVector */ QVector< xcb_window_t > windows() const; bool isDesktopSwitching() const; bool isDesktopSwitchingMovingClients() const; const QSize &cursorPushBackDistance() const; /** * Minimum time between the push back of the cursor and the activation by re-entering the edge. **/ int timeThreshold() const; /** * Minimum time between triggers **/ int reActivationThreshold() const; ElectricBorderAction actionTopLeft() const; ElectricBorderAction actionTop() const; ElectricBorderAction actionTopRight() const; ElectricBorderAction actionRight() const; ElectricBorderAction actionBottomRight() const; ElectricBorderAction actionBottom() const; ElectricBorderAction actionBottomLeft() const; ElectricBorderAction actionLeft() const; GestureRecognizer *gestureRecognizer() const { return m_gestureRecognizer; } bool handleDndNotify(xcb_window_t window, const QPoint &point); bool handleEnterNotifiy(xcb_window_t window, const QPoint &point, const QDateTime ×tamp); public Q_SLOTS: void reconfigure(); /** * Updates the layout of virtual desktops and adjust the reserved borders in case of * virtual desktop switching on edges. **/ void updateLayout(); /** * Recreates all edges e.g. after the screen size changes. **/ void recreateEdges(); Q_SIGNALS: /** * Signal emitted during approaching of mouse towards @p border. The @p factor indicates how * far away the mouse is from the approaching area. The values are clamped into [0.0,1.0] with * @c 0.0 meaning far away from the border, @c 1.0 in trigger distance. **/ void approaching(ElectricBorder border, qreal factor, const QRect &geometry); void checkBlocking(); private: enum { ElectricDisabled = 0, ElectricMoveOnly = 1, ElectricAlways = 2 }; void setDesktopSwitching(bool enable); void setDesktopSwitchingMovingClients(bool enable); void setCursorPushBackDistance(const QSize &distance); void setTimeThreshold(int threshold); void setReActivationThreshold(int threshold); void createHorizontalEdge(ElectricBorder border, const QRect &screen, const QRect &fullArea); void createVerticalEdge(ElectricBorder border, const QRect &screen, const QRect &fullArea); Edge *createEdge(ElectricBorder border, int x, int y, int width, int height, bool createAction = true); void setActionForBorder(ElectricBorder border, ElectricBorderAction *oldValue, ElectricBorderAction newValue); void setActionForTouchBorder(ElectricBorder border, ElectricBorderAction newValue); ElectricBorderAction actionForEdge(Edge *edge) const; ElectricBorderAction actionForTouchEdge(Edge *edge) const; void createEdgeForClient(AbstractClient *client, ElectricBorder border); void deleteEdgeForClient(AbstractClient *client); bool m_desktopSwitching; bool m_desktopSwitchingMovingClients; QSize m_cursorPushBackDistance; int m_timeThreshold; int m_reactivateThreshold; Qt::Orientations m_virtualDesktopLayout; QList m_edges; KSharedConfig::Ptr m_config; ElectricBorderAction m_actionTopLeft; ElectricBorderAction m_actionTop; ElectricBorderAction m_actionTopRight; ElectricBorderAction m_actionRight; ElectricBorderAction m_actionBottomRight; ElectricBorderAction m_actionBottom; ElectricBorderAction m_actionBottomLeft; ElectricBorderAction m_actionLeft; QMap m_touchActions; int m_cornerOffset; GestureRecognizer *m_gestureRecognizer; KWIN_SINGLETON(ScreenEdges) }; /********************************************************** * Inlines Edge *********************************************************/ inline bool Edge::isBottom() const { return m_border == ElectricBottom || m_border == ElectricBottomLeft || m_border == ElectricBottomRight; } inline bool Edge::isLeft() const { return m_border == ElectricLeft || m_border == ElectricTopLeft || m_border == ElectricBottomLeft; } inline bool Edge::isRight() const { return m_border == ElectricRight || m_border == ElectricTopRight || m_border == ElectricBottomRight; } inline bool Edge::isTop() const { return m_border == ElectricTop || m_border == ElectricTopLeft || m_border == ElectricTopRight; } inline bool Edge::isCorner() const { return m_border == ElectricTopLeft || m_border == ElectricTopRight || m_border == ElectricBottomRight || m_border == ElectricBottomLeft; } inline bool Edge::isScreenEdge() const { return m_border == ElectricLeft || m_border == ElectricRight || m_border == ElectricTop || m_border == ElectricBottom; } inline bool Edge::isReserved() const { return m_reserved != 0; } inline void Edge::setAction(ElectricBorderAction action) { m_action = action; } inline ScreenEdges *Edge::edges() { return m_edges; } inline const ScreenEdges *Edge::edges() const { return m_edges; } inline const QRect &Edge::geometry() const { return m_geometry; } inline const QRect &Edge::approachGeometry() const { return m_approachGeometry; } inline ElectricBorder Edge::border() const { return m_border; } inline const QHash< QObject *, QByteArray > &Edge::callBacks() const { return m_callBacks; } inline bool Edge::isBlocked() const { return m_blocked; } inline AbstractClient *Edge::client() const { return m_client; } inline bool Edge::isApproaching() const { return m_approaching; } /********************************************************** * Inlines ScreenEdges *********************************************************/ inline void ScreenEdges::setConfig(KSharedConfig::Ptr config) { m_config = config; } inline int ScreenEdges::cornerOffset() const { return m_cornerOffset; } inline const QSize &ScreenEdges::cursorPushBackDistance() const { return m_cursorPushBackDistance; } inline bool ScreenEdges::isDesktopSwitching() const { return m_desktopSwitching; } inline bool ScreenEdges::isDesktopSwitchingMovingClients() const { return m_desktopSwitchingMovingClients; } inline int ScreenEdges::reActivationThreshold() const { return m_reactivateThreshold; } inline int ScreenEdges::timeThreshold() const { return m_timeThreshold; } inline void ScreenEdges::setCursorPushBackDistance(const QSize &distance) { m_cursorPushBackDistance = distance; } inline void ScreenEdges::setDesktopSwitching(bool enable) { if (enable == m_desktopSwitching) { return; } m_desktopSwitching = enable; reserveDesktopSwitching(enable, m_virtualDesktopLayout); } inline void ScreenEdges::setDesktopSwitchingMovingClients(bool enable) { m_desktopSwitchingMovingClients = enable; } inline void ScreenEdges::setReActivationThreshold(int threshold) { Q_ASSERT(threshold >= m_timeThreshold); m_reactivateThreshold = threshold; } inline void ScreenEdges::setTimeThreshold(int threshold) { m_timeThreshold = threshold; } #define ACTION( name ) \ inline ElectricBorderAction ScreenEdges::name() const \ { \ return m_##name; \ } ACTION(actionTopLeft) ACTION(actionTop) ACTION(actionTopRight) ACTION(actionRight) ACTION(actionBottomRight) ACTION(actionBottom) ACTION(actionBottomLeft) ACTION(actionLeft) #undef ACTION } #endif // KWIN_SCREENEDGE_H diff --git a/toplevel.h b/toplevel.h index 23bf1fda9..7d535aa7d 100644 --- a/toplevel.h +++ b/toplevel.h @@ -1,910 +1,910 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_TOPLEVEL_H #define KWIN_TOPLEVEL_H // kwin #include "input.h" #include "utils.h" #include "virtualdesktops.h" #include "xcbutils.h" // KDE #include // Qt #include #include #include // xcb #include #include // XLib #include #include // system #include // c++ #include class QOpenGLFramebufferObject; namespace KWayland { namespace Server { class SurfaceInterface; } } namespace KWin { class ClientMachine; class EffectWindowImpl; class Shadow; /** * Enum to describe the reason why a Toplevel has to be released. */ enum class ReleaseReason { Release, ///< Normal Release after e.g. an Unmap notify event (window still valid) Destroyed, ///< Release after an Destroy notify event (window no longer valid) KWinShutsDown ///< Release on KWin Shutdown (window still valid) }; class KWIN_EXPORT Toplevel : public QObject { Q_OBJECT Q_PROPERTY(bool alpha READ hasAlpha NOTIFY hasAlphaChanged) Q_PROPERTY(qulonglong frameId READ frameId) Q_PROPERTY(QRect geometry READ geometry NOTIFY geometryChanged) Q_PROPERTY(QRect visibleRect READ visibleRect) Q_PROPERTY(int height READ height) Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged) Q_PROPERTY(QPoint pos READ pos) Q_PROPERTY(int screen READ screen NOTIFY screenChanged) Q_PROPERTY(QSize size READ size) Q_PROPERTY(int width READ width) Q_PROPERTY(qulonglong windowId READ windowId CONSTANT) Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int desktop READ desktop) /** * Whether the window is on all desktops. That is desktop is -1. **/ Q_PROPERTY(bool onAllDesktops READ isOnAllDesktops) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QPoint clientPos READ clientPos) Q_PROPERTY(QSize clientSize READ clientSize) Q_PROPERTY(QByteArray resourceName READ resourceName NOTIFY windowClassChanged) Q_PROPERTY(QByteArray resourceClass READ resourceClass NOTIFY windowClassChanged) Q_PROPERTY(QByteArray windowRole READ windowRole NOTIFY windowRoleChanged) /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool desktopWindow READ isDesktop) /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dock READ isDock) /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool toolbar READ isToolbar) /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool menu READ isMenu) /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool normalWindow READ isNormalWindow) /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dialog READ isDialog) /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool splash READ isSplash) /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool utility READ isUtility) /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dropdownMenu READ isDropdownMenu) /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool popupMenu READ isPopupMenu) /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool tooltip READ isTooltip) /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is an On Screen Display. */ Q_PROPERTY(bool onScreenDisplay READ isOnScreenDisplay) /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool comboBox READ isComboBox) /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(int windowType READ windowType) Q_PROPERTY(QStringList activities READ activities NOTIFY activitiesChanged) /** * Whether this Toplevel is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). **/ Q_PROPERTY(bool managed READ isClient CONSTANT) /** * Whether this Toplevel represents an already deleted window and only kept for the compositor for animations. **/ Q_PROPERTY(bool deleted READ isDeleted CONSTANT) /** * Whether the window has an own shape **/ Q_PROPERTY(bool shaped READ shape NOTIFY shapedChanged) /** * Whether the window does not want to be animated on window close. * There are legit reasons for this like a screenshot application which does not want it's * window being captured. **/ Q_PROPERTY(bool skipsCloseAnimation READ skipsCloseAnimation WRITE setSkipCloseAnimation NOTIFY skipCloseAnimationChanged) /** * The Id of the Wayland Surface associated with this Toplevel. * On X11 only setups the value is @c 0. **/ Q_PROPERTY(quint32 surfaceId READ surfaceId NOTIFY surfaceIdChanged) /** * Interface to the Wayland Surface. * Relevant only in Wayland, in X11 it will be nullptr */ Q_PROPERTY(KWayland::Server::SurfaceInterface *surface READ surface) /** * Whether the window is a popup. **/ Q_PROPERTY(bool popupWindow READ isPopupWindow) public: explicit Toplevel(); virtual xcb_window_t frameId() const; xcb_window_t window() const; /** * @return a unique identifier for the Toplevel. On X11 same as @link {window} **/ virtual quint32 windowId() const; QRect geometry() const; /** * The geometry of the Toplevel which accepts input events. This might be larger * than the actual geometry, e.g. to support resizing outside the window. * * Default implementation returns same as geometry. **/ virtual QRect inputGeometry() const; QSize size() const; QPoint pos() const; QRect rect() const; int x() const; int y() const; int width() const; int height() const; bool isOnScreen(int screen) const; // true if it's at least partially there bool isOnActiveScreen() const; int screen() const; // the screen where the center is /** * The scale of the screen this window is currently on - * @Note: The buffer scale can be different. + * @note The buffer scale can be different. * @since 5.12 */ qreal screenScale() const; // virtual QPoint clientPos() const = 0; // inside of geometry() /** * Describes how the client's content maps to the window geometry including the frame. * The default implementation is a 1:1 mapping meaning the frame is part of the content. **/ virtual QPoint clientContentPos() const; virtual QSize clientSize() const = 0; virtual QRect visibleRect() const; // the area the window occupies on the screen virtual QRect decorationRect() const; // rect including the decoration shadows virtual QRect transparentRect() const = 0; virtual bool isClient() const; virtual bool isDeleted() const; // prefer isXXX() instead // 0 for supported types means default for managed/unmanaged types virtual NET::WindowType windowType(bool direct = false, int supported_types = 0) const = 0; bool hasNETSupport() const; bool isDesktop() const; bool isDock() const; bool isToolbar() const; bool isMenu() const; bool isNormalWindow() const; // normal as in 'NET::Normal or NET::Unknown non-transient' bool isDialog() const; bool isSplash() const; bool isUtility() const; bool isDropdownMenu() const; bool isPopupMenu() const; // a context popup, not dropdown, not torn-off bool isTooltip() const; bool isNotification() const; bool isOnScreenDisplay() const; bool isComboBox() const; bool isDNDIcon() const; virtual bool isLockScreen() const; virtual bool isInputMethod() const; /** * Returns the virtual desktop within the workspace() the client window * is located in, 0 if it isn't located on any special desktop (not mapped yet), * or NET::OnAllDesktops. Do not use desktop() directly, use * isOnDesktop() instead. */ virtual int desktop() const = 0; virtual QVector desktops() const = 0; virtual QStringList activities() const = 0; bool isOnDesktop(int d) const; bool isOnActivity(const QString &activity) const; bool isOnCurrentDesktop() const; bool isOnCurrentActivity() const; bool isOnAllDesktops() const; bool isOnAllActivities() const; virtual QByteArray windowRole() const; QByteArray sessionId() const; QByteArray resourceName() const; QByteArray resourceClass() const; QByteArray wmCommand(); QByteArray wmClientMachine(bool use_localhost) const; const ClientMachine *clientMachine() const; virtual bool isLocalhost() const; Window wmClientLeader() const; virtual pid_t pid() const; static bool resourceMatch(const Toplevel* c1, const Toplevel* c2); bool readyForPainting() const; // true if the window has been already painted its contents xcb_visualid_t visual() const; bool shape() const; QRegion inputShape() const; virtual void setOpacity(double opacity); virtual double opacity() const; int depth() const; bool hasAlpha() const; virtual bool setupCompositing(); virtual void finishCompositing(ReleaseReason releaseReason = ReleaseReason::Release); Q_INVOKABLE void addRepaint(const QRect& r); Q_INVOKABLE void addRepaint(const QRegion& r); Q_INVOKABLE void addRepaint(int x, int y, int w, int h); Q_INVOKABLE void addLayerRepaint(const QRect& r); Q_INVOKABLE void addLayerRepaint(const QRegion& r); Q_INVOKABLE void addLayerRepaint(int x, int y, int w, int h); Q_INVOKABLE virtual void addRepaintFull(); // these call workspace->addRepaint(), but first transform the damage if needed void addWorkspaceRepaint(const QRect& r); void addWorkspaceRepaint(int x, int y, int w, int h); QRegion repaints() const; void resetRepaints(); QRegion damage() const; void resetDamage(); EffectWindowImpl* effectWindow(); const EffectWindowImpl* effectWindow() const; /** * Window will be temporarily painted as if being at the top of the stack. * Only available if Compositor is active, if not active, this method is a no-op. **/ void elevate(bool elevate); /** * @returns Whether the Toplevel has a Shadow or not * @see shadow **/ bool hasShadow() const; /** * Returns the pointer to the Toplevel's Shadow. A Shadow * is only available if Compositing is enabled and the corresponding X window * has the Shadow property set. * If a shadow is available @link hasShadow returns @c true. * @returns The Shadow belonging to this Toplevel, may be @c NULL. * @see hasShadow **/ const Shadow *shadow() const; Shadow *shadow(); /** * Updates the Shadow associated with this Toplevel from X11 Property. * Call this method when the Property changes or Compositing is started. **/ void getShadow(); /** * Whether the Toplevel currently wants the shadow to be rendered. Default * implementation always returns @c true. **/ virtual bool wantsShadowToBeRendered() const; /** * This method returns the area that the Toplevel window reports to be opaque. * It is supposed to only provide valuable information if @link hasAlpha is @c true . * @see hasAlpha **/ const QRegion& opaqueRegion() const; virtual Layer layer() const = 0; /** * Resets the damage state and sends a request for the damage region. * A call to this function must be followed by a call to getDamageRegionReply(), * or the reply will be leaked. * * Returns true if the window was damaged, and false otherwise. */ bool resetAndFetchDamage(); /** * Gets the reply from a previous call to resetAndFetchDamage(). * Calling this function is a no-op if there is no pending reply. * Call damage() to return the fetched region. */ void getDamageRegionReply(); bool skipsCloseAnimation() const; void setSkipCloseAnimation(bool set); quint32 surfaceId() const; KWayland::Server::SurfaceInterface *surface() const; void setSurface(KWayland::Server::SurfaceInterface *surface); virtual void setInternalFramebufferObject(const QSharedPointer &fbo); const QSharedPointer &internalFramebufferObject() const; /** * @returns Transformation to map from global to window coordinates. * * Default implementation returns a translation on negative pos(). * @see pos **/ virtual QMatrix4x4 inputTransformation() const; /** * The window has a popup grab. This means that when it got mapped the * parent window had an implicit (pointer) grab. * * Normally this is only relevant for transient windows. * * Once the popup grab ends (e.g. pointer press outside of any Toplevel of * the client), the method popupDone should be invoked. * * The default implementation returns @c false. * @see popupDone * @since 5.10 **/ virtual bool hasPopupGrab() const { return false; } /** * This method should be invoked for Toplevels with a popup grab when * the grab ends. * * The default implementation does nothing. * @see hasPopupGrab * @since 5.10 **/ virtual void popupDone() {}; /** * @brief Finds the Toplevel matching the condition expressed in @p func in @p list. * * The method is templated to operate on either a list of Toplevels or on a list of * a subclass type of Toplevel. * @param list The list to search in * @param func The condition function (compare std::find_if) * @return T* The found Toplevel or @c null if there is no matching Toplevel */ template static T *findInList(const QList &list, std::function func); /** * Whether the window is a popup. * * Popups can be used to implement popup menus, tooltips, combo boxes, etc. * * @since 5.15 **/ virtual bool isPopupWindow() const; /** * A UUID to uniquely identify this Toplevel independent of windowing system. **/ QUuid internalId() const { return m_internalId; } Q_SIGNALS: void opacityChanged(KWin::Toplevel* toplevel, qreal oldOpacity); void damaged(KWin::Toplevel* toplevel, const QRect& damage); void geometryChanged(); void geometryShapeChanged(KWin::Toplevel* toplevel, const QRect& old); void paddingChanged(KWin::Toplevel* toplevel, const QRect& old); void windowClosed(KWin::Toplevel* toplevel, KWin::Deleted* deleted); void windowShown(KWin::Toplevel* toplevel); void windowHidden(KWin::Toplevel* toplevel); /** * Signal emitted when the window's shape state changed. That is if it did not have a shape * and received one or if the shape was withdrawn. Think of Chromium enabling/disabling KWin's * decoration. **/ void shapedChanged(); /** * Emitted whenever the state changes in a way, that the Compositor should * schedule a repaint of the scene. **/ void needsRepaint(); void activitiesChanged(KWin::Toplevel* toplevel); /** * Emitted whenever the Toplevel's screen changes. This can happen either in consequence to * a screen being removed/added or if the Toplevel's geometry changes. * @since 4.11 **/ void screenChanged(); void skipCloseAnimationChanged(); /** * Emitted whenever the window role of the window changes. * @since 5.0 **/ void windowRoleChanged(); /** * Emitted whenever the window class name or resource name of the window changes. * @since 5.0 **/ void windowClassChanged(); /** * Emitted when a Wayland Surface gets associated with this Toplevel. * @since 5.3 **/ void surfaceIdChanged(quint32); /** * @since 5.4 **/ void hasAlphaChanged(); /** * Emitted whenever the Surface for this Toplevel changes. **/ void surfaceChanged(); /* * Emitted when the client's screen changes onto a screen of a different scale * or the screen we're on changes * @since 5.12 */ void screenScaleChanged(); /** * Emitted whenever the client's shadow changes. * @since 5.15 **/ void shadowChanged(); protected Q_SLOTS: /** * Checks whether the screen number for this Toplevel changed and updates if needed. * Any method changing the geometry of the Toplevel should call this method. **/ void checkScreen(); void setupCheckScreenConnection(); void removeCheckScreenConnection(); void setReadyForPainting(); protected: virtual ~Toplevel(); void setWindowHandles(xcb_window_t client); void detectShape(Window id); virtual void propertyNotifyEvent(xcb_property_notify_event_t *e); virtual void damageNotifyEvent(); virtual void clientMessageEvent(xcb_client_message_event_t *e); void discardWindowPixmap(); void addDamageFull(); virtual void addDamage(const QRegion &damage); Xcb::Property fetchWmClientLeader() const; void readWmClientLeader(Xcb::Property &p); void getWmClientLeader(); void getWmClientMachine(); /** * @returns Whether there is a compositor and it is active. **/ bool compositing() const; /** * This function fetches the opaque region from this Toplevel. * Will only be called on corresponding property changes and for initialization. **/ void getWmOpaqueRegion(); void getResourceClass(); void setResourceClass(const QByteArray &name, const QByteArray &className = QByteArray()); Xcb::Property fetchSkipCloseAnimation() const; void readSkipCloseAnimation(Xcb::Property &prop); void getSkipCloseAnimation(); virtual void debug(QDebug& stream) const = 0; void copyToDeleted(Toplevel* c); void disownDataPassedToDeleted(); friend QDebug& operator<<(QDebug& stream, const Toplevel*); void deleteEffectWindow(); void setDepth(int depth); QRect geom; xcb_visualid_t m_visual; int bit_depth; NETWinInfo* info; bool ready_for_painting; QRegion repaints_region; // updating, repaint just requires repaint of that area QRegion layer_repaints_region; protected: bool m_isDamaged; private: // when adding new data members, check also copyToDeleted() QUuid m_internalId; Xcb::Window m_client; xcb_damage_damage_t damage_handle; QRegion damage_region; // damage is really damaged window (XDamage) and texture needs bool is_shape; EffectWindowImpl* effect_window; QByteArray resource_name; QByteArray resource_class; ClientMachine *m_clientMachine; WId wmClientLeaderWin; bool m_damageReplyPending; QRegion opaque_region; xcb_xfixes_fetch_region_cookie_t m_regionCookie; int m_screen; bool m_skipCloseAnimation; quint32 m_surfaceId = 0; KWayland::Server::SurfaceInterface *m_surface = nullptr; /** * An FBO object KWin internal windows might render to. **/ QSharedPointer m_internalFBO; // when adding new data members, check also copyToDeleted() qreal m_screenScale = 1.0; }; inline xcb_window_t Toplevel::window() const { return m_client; } inline void Toplevel::setWindowHandles(xcb_window_t w) { assert(!m_client.isValid() && w != XCB_WINDOW_NONE); m_client.reset(w, false); } inline QRect Toplevel::geometry() const { return geom; } inline QSize Toplevel::size() const { return geom.size(); } inline QPoint Toplevel::pos() const { return geom.topLeft(); } inline int Toplevel::x() const { return geom.x(); } inline int Toplevel::y() const { return geom.y(); } inline int Toplevel::width() const { return geom.width(); } inline int Toplevel::height() const { return geom.height(); } inline QRect Toplevel::rect() const { return QRect(0, 0, width(), height()); } inline bool Toplevel::readyForPainting() const { return ready_for_painting; } inline xcb_visualid_t Toplevel::visual() const { return m_visual; } inline bool Toplevel::isDesktop() const { return windowType() == NET::Desktop; } inline bool Toplevel::isDock() const { return windowType() == NET::Dock; } inline bool Toplevel::isMenu() const { return windowType() == NET::Menu; } inline bool Toplevel::isToolbar() const { return windowType() == NET::Toolbar; } inline bool Toplevel::isSplash() const { return windowType() == NET::Splash; } inline bool Toplevel::isUtility() const { return windowType() == NET::Utility; } inline bool Toplevel::isDialog() const { return windowType() == NET::Dialog; } inline bool Toplevel::isNormalWindow() const { return windowType() == NET::Normal; } inline bool Toplevel::isDropdownMenu() const { return windowType() == NET::DropdownMenu; } inline bool Toplevel::isPopupMenu() const { return windowType() == NET::PopupMenu; } inline bool Toplevel::isTooltip() const { return windowType() == NET::Tooltip; } inline bool Toplevel::isNotification() const { return windowType() == NET::Notification; } inline bool Toplevel::isOnScreenDisplay() const { return windowType() == NET::OnScreenDisplay; } inline bool Toplevel::isComboBox() const { return windowType() == NET::ComboBox; } inline bool Toplevel::isDNDIcon() const { return windowType() == NET::DNDIcon; } inline bool Toplevel::isLockScreen() const { return false; } inline bool Toplevel::isInputMethod() const { return false; } inline QRegion Toplevel::damage() const { return damage_region; } inline QRegion Toplevel::repaints() const { return repaints_region.translated(pos()) | layer_repaints_region; } inline bool Toplevel::shape() const { return is_shape; } inline int Toplevel::depth() const { return bit_depth; } inline bool Toplevel::hasAlpha() const { return depth() == 32; } inline const QRegion& Toplevel::opaqueRegion() const { return opaque_region; } inline EffectWindowImpl* Toplevel::effectWindow() { return effect_window; } inline const EffectWindowImpl* Toplevel::effectWindow() const { return effect_window; } inline bool Toplevel::isOnAllDesktops() const { return kwinApp()->operationMode() == Application::OperationModeWaylandOnly || kwinApp()->operationMode() == Application::OperationModeXwayland //Wayland ? desktops().isEmpty() //X11 : desktop() == NET::OnAllDesktops; } inline bool Toplevel::isOnAllActivities() const { return activities().isEmpty(); } inline bool Toplevel::isOnDesktop(int d) const { return (kwinApp()->operationMode() == Application::OperationModeWaylandOnly || kwinApp()->operationMode() == Application::OperationModeXwayland ? desktops().contains(VirtualDesktopManager::self()->desktopForX11Id(d)) : desktop() == d ) || isOnAllDesktops(); } inline bool Toplevel::isOnActivity(const QString &activity) const { return activities().isEmpty() || activities().contains(activity); } inline bool Toplevel::isOnCurrentDesktop() const { return isOnDesktop(VirtualDesktopManager::self()->current()); } inline QByteArray Toplevel::resourceName() const { return resource_name; // it is always lowercase } inline QByteArray Toplevel::resourceClass() const { return resource_class; // it is always lowercase } inline const ClientMachine *Toplevel::clientMachine() const { return m_clientMachine; } inline quint32 Toplevel::surfaceId() const { return m_surfaceId; } inline KWayland::Server::SurfaceInterface *Toplevel::surface() const { return m_surface; } inline const QSharedPointer &Toplevel::internalFramebufferObject() const { return m_internalFBO; } inline QPoint Toplevel::clientContentPos() const { return QPoint(0, 0); } template inline T *Toplevel::findInList(const QList &list, std::function func) { static_assert(std::is_base_of::value, "U must be derived from T"); const auto it = std::find_if(list.begin(), list.end(), func); if (it == list.end()) { return nullptr; } return *it; } inline bool Toplevel::isPopupWindow() const { switch (windowType()) { case NET::ComboBox: case NET::DropdownMenu: case NET::PopupMenu: case NET::Tooltip: return true; default: return false; } } QDebug& operator<<(QDebug& stream, const Toplevel*); QDebug& operator<<(QDebug& stream, const ToplevelList&); } // namespace Q_DECLARE_METATYPE(KWin::Toplevel*) #endif diff --git a/virtualdesktops.h b/virtualdesktops.h index f19a25cac..61d239e30 100644 --- a/virtualdesktops.h +++ b/virtualdesktops.h @@ -1,732 +1,732 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2012 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_VIRTUAL_DESKTOPS_H #define KWIN_VIRTUAL_DESKTOPS_H // KWin #include #include // Qt includes #include #include #include #include // KDE includes #include #include class KLocalizedString; class NETRootInfo; class QAction; namespace KWayland { namespace Server { class PlasmaVirtualDesktopManagementInterface; } } namespace KWin { class KWIN_EXPORT VirtualDesktop : public QObject { Q_OBJECT Q_PROPERTY(QByteArray id READ id CONSTANT) Q_PROPERTY(uint x11DesktopNumber READ x11DesktopNumber NOTIFY x11DesktopNumberChanged) Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) public: explicit VirtualDesktop(QObject *parent = nullptr); virtual ~VirtualDesktop(); void setId(const QByteArray &id); QByteArray id() const { return m_id; } void setName(const QString &name); QString name() const { return m_name; } void setX11DesktopNumber(uint number); uint x11DesktopNumber() const { return m_x11DesktopNumber; } Q_SIGNALS: void nameChanged(); void x11DesktopNumberChanged(); /** * Emitted just before the desktop gets destroyed. **/ void aboutToBeDestroyed(); private: QByteArray m_id; QString m_name; int m_x11DesktopNumber = 0; }; /** * @brief Two dimensional grid containing the ID of the virtual desktop at a specific position * in the grid. * * The VirtualDesktopGrid represents a visual layout of the Virtual Desktops as they are in e.g. * a Pager. This grid is used for getting a desktop next to a given desktop in any direction by * making use of the layout information. This allows navigation like move to desktop on left. **/ class VirtualDesktopGrid { public: VirtualDesktopGrid(); ~VirtualDesktopGrid(); void update(const QSize &size, Qt::Orientation orientation, const QVector &desktops); /** * @returns The coords of desktop @a id in grid units. */ QPoint gridCoords(uint id) const; /** * @returns The coords of desktop @a vd in grid units. */ QPoint gridCoords(VirtualDesktop *vd) const; /** * @returns The desktop at the point @a coords or 0 if no desktop exists at that * point. @a coords is to be in grid units. */ VirtualDesktop *at(const QPoint &coords) const; int width() const; int height() const; const QSize &size() const; private: QSize m_size; QVector> m_grid; }; /** * @brief Manages the number of available virtual desktops, the layout of those and which virtual * desktop is the current one. * * This manager is responsible for Virtual Desktop handling inside KWin. It has a property for the * count of available virtual desktops and a property for the currently active virtual desktop. All * changes to the number of virtual desktops and the current virtual desktop need to go through this * manager. * * On all changes a signal is emitted and interested parties should connect to the signal. The manager * itself does not interact with other parts of the system. E.g. it does not hide/show windows of * desktop changes. This is outside the scope of this manager. * * Internally the manager organizes the virtual desktops in a grid allowing to navigate over the * virtual desktops. For this a set of convenient methods are available which allow to get the id * of an adjacent desktop or to switch to an adjacent desktop. Interested parties should make use of * these methods and not replicate the logic to switch to the next desktop. **/ class KWIN_EXPORT VirtualDesktopManager : public QObject { Q_OBJECT /** * The number of virtual desktops currently available. * The ids of the virtual desktops are in the range [1, VirtualDesktopManager::maximum()]. **/ Q_PROPERTY(uint count READ count WRITE setCount NOTIFY countChanged) /** * The id of the virtual desktop which is currently in use. **/ Q_PROPERTY(uint current READ current WRITE setCurrent NOTIFY currentChanged) /** * Whether navigation in the desktop layout wraps around at the borders. **/ Q_PROPERTY(bool navigationWrappingAround READ isNavigationWrappingAround WRITE setNavigationWrappingAround NOTIFY navigationWrappingAroundChanged) public: virtual ~VirtualDesktopManager(); /** * @internal, for X11 case **/ void setRootInfo(NETRootInfo *info); /** * @internal, for Wayland case **/ void setVirtualDesktopManagement(KWayland::Server::PlasmaVirtualDesktopManagementInterface *management); /** * @internal **/ void setConfig(KSharedConfig::Ptr config); /** * @returns Total number of desktops currently in existence. * @see setCount * @see countChanged */ uint count() const; /** * @returns the number of rows the layout has. * @see setRows * @see rowsChanged */ uint rows() const; /** * @returns The ID of the current desktop. * @see setCurrent * @see currentChanged */ uint current() const; /** * @returns The current desktop * @see setCurrent * @see currentChanged **/ VirtualDesktop *currentDesktop() const; /** * Moves to the desktop through the algorithm described by Direction. * @param wrap If @c true wraps around to the other side of the layout * @see setCurrent **/ template void moveTo(bool wrap = false); /** * @returns The name of the @p desktop **/ QString name(uint desktop) const; /** * @returns @c true if navigation at borders of layout wraps around, @c false otherwise * @see setNavigationWrappingAround * @see navigationWrappingAroundChanged **/ bool isNavigationWrappingAround() const; /** * @returns The layout aware virtual desktop grid used by this manager. **/ const VirtualDesktopGrid &grid() const; /** * @returns The ID of the desktop above desktop @a id. Wraps around to the bottom of * the layout if @a wrap is set. If @a id is not set use the current one. */ uint above(uint id = 0, bool wrap = true) const; /** * @returns The desktop above desktop @a desktop. Wraps around to the bottom of * the layout if @a wrap is set. If @a desktop is @c null use the current one. */ VirtualDesktop *above(VirtualDesktop *desktop, bool wrap = true) const; /** * @returns The ID of the desktop to the right of desktop @a id. Wraps around to the * left of the layout if @a wrap is set. If @a id is not set use the current one. */ uint toRight(uint id = 0, bool wrap = true) const; /** * @returns The desktop to the right of desktop @a desktop. Wraps around to the * left of the layout if @a wrap is set. If @a desktop is @c null use the current one. */ VirtualDesktop *toRight(VirtualDesktop *desktop, bool wrap = true) const; /** * @returns The ID of the desktop below desktop @a id. Wraps around to the top of the * layout if @a wrap is set. If @a id is not set use the current one. */ uint below(uint id = 0, bool wrap = true) const; /** * @returns The desktop below desktop @a desktop. Wraps around to the top of the * layout if @a wrap is set. If @a desktop is @c null use the current one. */ VirtualDesktop *below(VirtualDesktop *desktop, bool wrap = true) const; /** * @returns The ID of the desktop to the left of desktop @a id. Wraps around to the * right of the layout if @a wrap is set. If @a id is not set use the current one. */ uint toLeft(uint id = 0, bool wrap = true) const; /** * @returns The desktop to the left of desktop @a desktop. Wraps around to the * right of the layout if @a wrap is set. If @a desktop is @c null use the current one. */ VirtualDesktop *toLeft(VirtualDesktop *desktop, bool wrap = true) const; /** * @returns The desktop after the desktop @a desktop. Wraps around to the first * desktop if @a wrap is set. If @a desktop is @c null use the current desktop. **/ VirtualDesktop *next(VirtualDesktop *desktop = nullptr, bool wrap = true) const; /** * @returns The desktop in front of the desktop @a desktop. Wraps around to the * last desktop if @a wrap is set. If @a desktop is @c null use the current desktop. **/ VirtualDesktop *previous(VirtualDesktop *desktop = nullptr, bool wrap = true) const; void initShortcuts(); /** * @returns all currently managed VirtualDesktops **/ QVector desktops() const { return m_desktops; } /** * @returns The VirtualDesktop for the x11 @p id, if no such VirtualDesktop @c null is returned **/ VirtualDesktop *desktopForX11Id(uint id) const; /** * @returns The VirtualDesktop for the internal desktop string @p id, if no such VirtualDesktop @c null is returned **/ VirtualDesktop *desktopForId(const QByteArray &id) const; /** * Create a new virtual desktop at the requested position. * The difference with setCount is that setCount always adds new desktops at the end of the chain. The Id is automatically generated. * @param x11DesktopNumber number for the desktop. The desktop created will have an * x11DesktopNumber guaranteed to be between 1 and numberOfDesktops(). * Existing desktops will eventually have their x11DesktopNumber increased. * @param name The name for the new desktop, if empty the default name will be used. * @returns the new VirtualDesktop, nullptr if we reached the maximum number of desktops */ VirtualDesktop *createVirtualDesktop(uint x11DesktopNumber, const QString &name = QString()); /** * Remove the virtual desktop identified by id, if it exists * difference with setCount is that is possible to remove an arbitrary desktop, * not only the last one. * @param id the string id of the desktop to remove */ void removeVirtualDesktop(const QByteArray &id); /** * Updates the net root info for new number of desktops **/ void updateRootInfo(); /** * @returns The maximum number of desktops that KWin supports. */ static uint maximum(); public Q_SLOTS: /** * Set the number of available desktops to @a count. This function overrides any previous * grid layout. * There needs to be at least one virtual desktop and the new value is capped at the maximum * number of desktops. A caller of this function cannot expect that the change has been applied. * It is the callers responsibility to either check the @link numberOfDesktops or connect to the - * @link countChanged signal. + * countChanged signal. * * In case the @link current desktop is on a desktop higher than the new count, the current desktop - * is changed to be the new desktop with highest id. In that situation the signal @link desktopRemoved + * is changed to be the new desktop with highest id. In that situation the signal desktopRemoved * is emitted. * @param count The new number of desktops to use * @see count * @see maximum * @see countChanged * @see desktopCreated * @see desktopRemoved */ void setCount(uint count); /** * Set the current desktop to @a current. * @returns True on success, false otherwise. * @see current * @see currentChanged * @see moveTo */ bool setCurrent(uint current); /** * Set the current desktop to @a current. * @returns True on success, false otherwise. * @see current * @see currentChanged * @see moveTo **/ bool setCurrent(VirtualDesktop *current); /** * Updates the layout to a new number of rows. The number of columns will be calculated accordingly */ void setRows(uint rows); /** * Called from within setCount() to ensure the desktop layout is still valid. */ void updateLayout(); /** * @param enabled wrapping around borders for navigation in desktop layout * @see isNavigationWrappingAround * @see navigationWrappingAroundChanged **/ void setNavigationWrappingAround(bool enabled); /** * Loads number of desktops and names from configuration file **/ void load(); /** * Saves number of desktops and names to configuration file **/ void save(); Q_SIGNALS: /** * Signal emitted whenever the number of virtual desktops changes. * @param previousCount The number of desktops prior to the change * @param newCount The new current number of desktops **/ void countChanged(uint previousCount, uint newCount); /** * Signal when the number of rows in the layout changes - * @param new number of rows + * @param rows number of rows */ void rowsChanged(uint rows); /** * A new desktop has been created * @param desktop the new just crated desktop */ void desktopCreated(KWin::VirtualDesktop *desktop); /** * A desktop has been removed and is about to be deleted * @param desktop the desktop that has been removed. * It's guaranteed to stil la valid pointer when the signal arrives, * but it's about to be deleted. */ void desktopRemoved(KWin::VirtualDesktop *desktop); /** * Signal emitted whenever the current desktop changes. * @param previousDesktop The virtual desktop changed from * @param newDesktop The virtual desktop changed to **/ void currentChanged(uint previousDesktop, uint newDesktop); /** * Signal emitted whenever the desktop layout changes. * @param columns The new number of columns in the layout * @param rows The new number of rows in the layout **/ void layoutChanged(int columns, int rows); /** * Signal emitted whenever the navigationWrappingAround property changes. **/ void navigationWrappingAroundChanged(); private Q_SLOTS: /** * Common slot for all "Switch to Desktop n" shortcuts. * This method uses the sender() method to access some data. * DO NOT CALL DIRECTLY! ONLY TO BE USED FROM AN ACTION! **/ void slotSwitchTo(); /** * Slot for switch to next desktop action. **/ void slotNext(); /** * Slot for switch to previous desktop action. **/ void slotPrevious(); /** * Slot for switch to right desktop action. **/ void slotRight(); /** * Slot for switch to left desktop action. **/ void slotLeft(); /** * Slot for switch to desktop above action. **/ void slotUp(); /** * Slot for switch to desktop below action. **/ void slotDown(); private: /** * Generate a desktop layout from EWMH _NET_DESKTOP_LAYOUT property parameters. */ void setNETDesktopLayout(Qt::Orientation orientation, uint width, uint height, int startingCorner); /** * @returns A default name for the given @p desktop **/ QString defaultName(int desktop) const; /** * Creates all the global keyboard shortcuts for "Switch To Desktop n" actions. **/ void initSwitchToShortcuts(); /** * Creates an action and connects it to the @p slot in this Manager. This method is * meant to be used for the case that an additional information needs to be stored in * the action and the label. * @param name The name of the action to be created * @param label The localized name for the action to be created * @param value An additional value added to the label and to the created action * @param key The global shortcut for the action * @param slot The slot to invoke when the action is triggered **/ QAction *addAction(const QString &name, const KLocalizedString &label, uint value, const QKeySequence &key, void (VirtualDesktopManager::*slot)()); /** * Creates an action and connects it to the @p slot in this Manager. * Overloaded method for the case that no additional value needs to be passed to the action and * no global shortcut is defined by default. * @param name The name of the action to be created * @param label The localized name for the action to be created * @param slot The slot to invoke when the action is triggered **/ QAction *addAction(const QString &name, const QString &label, void (VirtualDesktopManager::*slot)()); QVector m_desktops; QPointer m_current; quint32 m_rows = 2; bool m_navigationWrapsAround; VirtualDesktopGrid m_grid; // TODO: QPointer NETRootInfo *m_rootInfo; KWayland::Server::PlasmaVirtualDesktopManagementInterface *m_virtualDesktopManagement = nullptr; KSharedConfig::Ptr m_config; KWIN_SINGLETON_VARIABLE(VirtualDesktopManager, s_manager) }; /** * Function object to select the desktop above in the layout. * Note: does not switch to the desktop! **/ class DesktopAbove { public: DesktopAbove() {} /** * @param desktop The desktop from which the desktop above should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already topmost desktop * @returns Id of the desktop above @p desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the desktop above should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already topmost desktop * @returns the desktop above @p desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->above(desktop, wrap); } }; /** * Function object to select the desktop below in the layout. * Note: does not switch to the desktop! **/ class DesktopBelow { public: DesktopBelow() {} /** * @param desktop The desktop from which the desktop below should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already lowest desktop * @returns Id of the desktop below @p desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the desktop below should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already lowest desktop * @returns the desktop below @p desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->below(desktop, wrap); } }; /** * Function object to select the desktop to the left in the layout. * Note: does not switch to the desktop! **/ class DesktopLeft { public: DesktopLeft() {} /** * @param desktop The desktop from which the desktop on the left should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already leftmost desktop * @returns Id of the desktop left of @p desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the desktop on the left should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already leftmost desktop * @returns the desktop left of @p desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->toLeft(desktop, wrap); } }; /** * Function object to select the desktop to the right in the layout. * Note: does not switch to the desktop! **/ class DesktopRight { public: DesktopRight() {} /** * @param desktop The desktop from which the desktop on the right should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already rightmost desktop * @returns Id of the desktop right of @p desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the desktop on the right should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already rightmost desktop * @returns the desktop right of @p desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->toRight(desktop, wrap); } }; /** * Function object to select the next desktop in the layout. * Note: does not switch to the desktop! **/ class DesktopNext { public: DesktopNext() {} /** * @param desktop The desktop from which the next desktop should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already last desktop * @returns Id of the next desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the next desktop should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already last desktop * @returns the next desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->next(desktop, wrap); } }; /** * Function object to select the previous desktop in the layout. * Note: does not switch to the desktop! **/ class DesktopPrevious { public: DesktopPrevious() {} /** * @param desktop The desktop from which the previous desktop should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already first desktop * @returns Id of the previous desktop **/ uint operator() (uint desktop, bool wrap) { return (*this)(VirtualDesktopManager::self()->desktopForX11Id(desktop), wrap)->x11DesktopNumber(); } /** * @param desktop The desktop from which the previous desktop should be selected. If @c 0 the current desktop is used * @param wrap Whether to wrap around if already first desktop * @returns the previous desktop **/ VirtualDesktop *operator() (VirtualDesktop *desktop, bool wrap) { return VirtualDesktopManager::self()->previous(desktop, wrap); } }; /** * Helper function to get the ID of a virtual desktop in the direction from * the given @p desktop. If @c 0 the current desktop is used as a starting point. * @param desktop The desktop from which the desktop in given Direction should be selected. * @param wrap Whether desktop navigation wraps around at the borders of the layout * @returns The next desktop in specified direction **/ template uint getDesktop(int desktop = 0, bool wrap = true); template uint getDesktop(int d, bool wrap) { Direction direction; return direction(d, wrap); } inline int VirtualDesktopGrid::width() const { return m_size.width(); } inline int VirtualDesktopGrid::height() const { return m_size.height(); } inline const QSize &VirtualDesktopGrid::size() const { return m_size; } inline uint VirtualDesktopManager::maximum() { return 20; } inline uint VirtualDesktopManager::count() const { return m_desktops.count(); } inline bool VirtualDesktopManager::isNavigationWrappingAround() const { return m_navigationWrapsAround; } inline void VirtualDesktopManager::setConfig(KSharedConfig::Ptr config) { m_config = config; } inline const VirtualDesktopGrid &VirtualDesktopManager::grid() const { return m_grid; } template void VirtualDesktopManager::moveTo(bool wrap) { Direction functor; setCurrent(functor(nullptr, wrap)); } } // namespace KWin #endif diff --git a/xcbutils.h b/xcbutils.h index 011af83de..0adc0f9bd 100644 --- a/xcbutils.h +++ b/xcbutils.h @@ -1,1887 +1,1887 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2012, 2013 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_XCB_UTILS_H #define KWIN_XCB_UTILS_H #include #include "main.h" #include #include #include #include #include #include #include #include class TestXcbSizeHints; namespace KWin { template using ScopedCPointer = QScopedPointer; namespace Xcb { typedef xcb_window_t WindowId; // forward declaration of methods static void defineCursor(xcb_window_t window, xcb_cursor_t cursor); static void setInputFocus(xcb_window_t window, uint8_t revertTo = XCB_INPUT_FOCUS_POINTER_ROOT, xcb_timestamp_t time = xTime()); static void moveWindow(xcb_window_t window, const QPoint &pos); static void moveWindow(xcb_window_t window, uint32_t x, uint32_t y); static void lowerWindow(xcb_window_t window); static void selectInput(xcb_window_t window, uint32_t events); /** * @brief Variadic template to wrap an xcb request. * * This struct is part of the generic implementation to wrap xcb requests * and fetching their reply. Each request is represented by two templated * elements: WrapperData and Wrapper. * * The WrapperData defines the following types: * @li reply_type of the xcb request * @li cookie_type of the xcb request * @li function pointer type for the xcb request * @li function pointer type for the reply * This uses variadic template arguments thus it can be used to specify any * xcb request. * * As the WrapperData does not specify the actual function pointers one needs * to derive another struct which specifies the function pointer requestFunc and * the function pointer replyFunc as static constexpr of type reply_func and * reply_type respectively. E.g. for the command xcb_get_geometry: * @code * struct GeometryData : public WrapperData< xcb_get_geometry_reply_t, xcb_get_geometry_cookie_t, xcb_drawable_t > * { * static constexpr request_func requestFunc = &xcb_get_geometry_unchecked; * static constexpr reply_func replyFunc = &xcb_get_geometry_reply; * }; * @endcode * * To simplify this definition the macro XCB_WRAPPER_DATA is provided. * For the same xcb command this looks like this: * @code * XCB_WRAPPER_DATA(GeometryData, xcb_get_geometry, xcb_drawable_t) * @endcode * * The derived WrapperData has to be passed as first template argument to Wrapper. The other * template arguments of Wrapper are the same variadic template arguments as passed into * WrapperData. This is ensured at compile time and will cause a compile error in case there * is a mismatch of the variadic template arguments passed to WrapperData and Wrapper. * Passing another type than a struct derived from WrapperData to Wrapper will result in a * compile error. The following code snippets won't compile: * @code * XCB_WRAPPER_DATA(GeometryData, xcb_get_geometry, xcb_drawable_t) * // fails with "static assertion failed: Argument miss-match between Wrapper and WrapperData" * class IncorrectArguments : public Wrapper * { * public: * IncorrectArguments() = default; * IncorrectArguments(xcb_window_t window) : Wrapper(window) {} * }; * * // fails with "static assertion failed: Data template argument must be derived from WrapperData" * class WrapperDataDirectly : public Wrapper, xcb_drawable_t> * { * public: * WrapperDataDirectly() = default; * WrapperDataDirectly(xcb_window_t window) : Wrapper, xcb_drawable_t>(window) {} * }; * * // fails with "static assertion failed: Data template argument must be derived from WrapperData" * struct FakeWrapperData * { * typedef xcb_get_geometry_reply_t reply_type; * typedef xcb_get_geometry_cookie_t cookie_type; * typedef std::tuple argument_types; * typedef cookie_type (*request_func)(xcb_connection_t*, xcb_drawable_t); * typedef reply_type *(*reply_func)(xcb_connection_t*, cookie_type, xcb_generic_error_t**); * static constexpr std::size_t argumentCount = 1; * static constexpr request_func requestFunc = &xcb_get_geometry_unchecked; * static constexpr reply_func replyFunc = &xcb_get_geometry_reply; * }; * class NotDerivedFromWrapperData : public Wrapper * { * public: * NotDerivedFromWrapperData() = default; * NotDerivedFromWrapperData(xcb_window_t window) : Wrapper(window) {} * }; * @endcode * * The Wrapper provides an easy to use RAII API which calls the WrapperData's requestFunc in * the ctor and fetches the reply the first time it is used. In addition the dtor takes care * of freeing the reply if it got fetched, otherwise it discards the reply. The Wrapper can * be used as if it were the reply_type directly. * * There are several command wrappers defined which either subclass Wrapper to add methods to * simplify the usage of the result_type or use a typedef. To add a new typedef one can use the * macro XCB_WRAPPER which creates the WrapperData struct as XCB_WRAPPER_DATA does and the * typedef. E.g: * @code * XCB_WRAPPER(Geometry, xcb_get_geometry, xcb_drawable_t) * @endcode * * creates a typedef Geometry and the struct GeometryData. * * Overall this allows to simplify the Xcb usage. For example consider the * following xcb code snippet: * @code * xcb_window_t w; // some window * xcb_connection_t *c = connection(); * const xcb_get_geometry_cookie_t cookie = xcb_get_geometry_unchecked(c, w); * // do other stuff * xcb_get_geometry_reply_t *reply = xcb_get_geometry_reply(c, cookie, nullptr); * if (reply) { * reply->x; // do something with the geometry * } * free(reply); * @endcode * * With the help of the Wrapper class this can be simplified to: * @code * xcb_window_t w; // some window * Xcb::Geometry geo(w); * if (!geo.isNull()) { * geo->x; // do something with the geometry * } * @endcode * * @see XCB_WRAPPER_DATA * @see XCB_WRAPPER * @see Wrapper * @see WindowAttributes * @see OverlayWindow * @see WindowGeometry * @see Tree * @see CurrentInput * @see TransientFor */ template struct WrapperData { /** * @brief The type returned by the xcb reply function. */ typedef Reply reply_type; /** * @brief The type returned by the xcb request function. */ typedef Cookie cookie_type; /** * @brief Variadic arguments combined as a std::tuple. * @internal Used for verifying the arguments. */ typedef std::tuple argument_types; /** * @brief The function pointer definition for the xcb request function. */ typedef Cookie (*request_func)(xcb_connection_t*, Args...); /** * @brief The function pointer definition for the xcb reply function. */ typedef Reply *(*reply_func)(xcb_connection_t*, Cookie, xcb_generic_error_t**); /** * @brief Number of variadic arguments. * @internal Used for verifying the arguments. */ static constexpr std::size_t argumentCount = sizeof...(Args); }; /** * @brief Partial template specialization for WrapperData with no further arguments. * * This will be used for xcb requests just taking the xcb_connection_t* argument. **/ template struct WrapperData { typedef Reply reply_type; typedef Cookie cookie_type; typedef std::tuple<> argument_types; typedef Cookie (*request_func)(xcb_connection_t*); typedef Reply *(*reply_func)(xcb_connection_t*, Cookie, xcb_generic_error_t**); static constexpr std::size_t argumentCount = 0; }; /** * @brief Abstract base class for the wrapper. * * This class contains the complete functionality of the Wrapper. It's only an abstract * base class to provide partial template specialization for more specific constructors. */ template class AbstractWrapper { public: typedef typename Data::cookie_type Cookie; typedef typename Data::reply_type Reply; virtual ~AbstractWrapper() { cleanup(); } inline AbstractWrapper &operator=(const AbstractWrapper &other) { if (this != &other) { // if we had managed a reply, free it cleanup(); // copy members m_retrieved = other.m_retrieved; m_cookie = other.m_cookie; m_window = other.m_window; m_reply = other.m_reply; // take over the responsibility for the reply pointer takeFromOther(const_cast(other)); } return *this; } inline const Reply *operator->() { getReply(); return m_reply; } inline bool isNull() { getReply(); return m_reply == NULL; } inline bool isNull() const { const_cast(this)->getReply(); return m_reply == NULL; } inline operator bool() { return !isNull(); } inline operator bool() const { return !isNull(); } inline const Reply *data() { getReply(); return m_reply; } inline const Reply *data() const { const_cast(this)->getReply(); return m_reply; } inline WindowId window() const { return m_window; } inline bool isRetrieved() const { return m_retrieved; } /** * Returns the value of the reply pointer referenced by this object. The reply pointer of * this object will be reset to null. Calling any method which requires the reply to be valid * will crash. * * Callers of this function take ownership of the pointer. **/ inline Reply *take() { getReply(); Reply *ret = m_reply; m_reply = NULL; m_window = XCB_WINDOW_NONE; return ret; } protected: AbstractWrapper() : m_retrieved(false) , m_window(XCB_WINDOW_NONE) , m_reply(NULL) { m_cookie.sequence = 0; } explicit AbstractWrapper(WindowId window, Cookie cookie) : m_retrieved(false) , m_cookie(cookie) , m_window(window) , m_reply(NULL) { } explicit AbstractWrapper(const AbstractWrapper &other) : m_retrieved(other.m_retrieved) , m_cookie(other.m_cookie) , m_window(other.m_window) , m_reply(NULL) { takeFromOther(const_cast(other)); } void getReply() { if (m_retrieved || !m_cookie.sequence) { return; } m_reply = Data::replyFunc(connection(), m_cookie, nullptr); m_retrieved = true; } private: inline void cleanup() { if (!m_retrieved && m_cookie.sequence) { xcb_discard_reply(connection(), m_cookie.sequence); } else if (m_reply) { free(m_reply); } } inline void takeFromOther(AbstractWrapper &other) { if (m_retrieved) { m_reply = other.take(); } else { //ensure that other object doesn't try to get the reply or discards it in the dtor other.m_retrieved = true; other.m_window = XCB_WINDOW_NONE; } } bool m_retrieved; Cookie m_cookie; WindowId m_window; Reply *m_reply; }; /** * @brief Template to compare the arguments of two std::tuple. * * @internal Used by static_assert in Wrapper */ template struct tupleCompare { typedef typename std::tuple_element::type tuple1Type; typedef typename std::tuple_element::type tuple2Type; /** * @c true if both tuple have the same arguments, @c false otherwise. * */ static constexpr bool value = std::is_same< tuple1Type, tuple2Type >::value && tupleCompare::value; }; /** * @brief Recursive template case for first tuple element. */ template struct tupleCompare { typedef typename std::tuple_element<0, T1>::type tuple1Type; typedef typename std::tuple_element<0, T2>::type tuple2Type; static constexpr bool value = std::is_same< tuple1Type, tuple2Type >::value; }; /** * @brief Wrapper taking a WrapperData as first template argument and xcb request args as variadic args. */ template class Wrapper : public AbstractWrapper { public: static_assert(!std::is_same >::value, "Data template argument must be derived from WrapperData"); static_assert(std::is_base_of, Data>::value, "Data template argument must be derived from WrapperData"); static_assert(sizeof...(Args) == Data::argumentCount, "Wrapper and WrapperData need to have same template argument count"); static_assert(tupleCompare, typename Data::argument_types, sizeof...(Args) - 1>::value, "Argument miss-match between Wrapper and WrapperData"); Wrapper() = default; explicit Wrapper(Args... args) : AbstractWrapper(XCB_WINDOW_NONE, Data::requestFunc(connection(), args...)) { } explicit Wrapper(xcb_window_t w, Args... args) : AbstractWrapper(w, Data::requestFunc(connection(), args...)) { } }; /** * @brief Template specialization for xcb_window_t being first variadic argument. **/ template class Wrapper : public AbstractWrapper { public: static_assert(!std::is_same >::value, "Data template argument must be derived from WrapperData"); static_assert(std::is_base_of, Data>::value, "Data template argument must be derived from WrapperData"); static_assert(sizeof...(Args) + 1 == Data::argumentCount, "Wrapper and WrapperData need to have same template argument count"); static_assert(tupleCompare, typename Data::argument_types, sizeof...(Args)>::value, "Argument miss-match between Wrapper and WrapperData"); Wrapper() = default; explicit Wrapper(xcb_window_t w, Args... args) : AbstractWrapper(w, Data::requestFunc(connection(), w, args...)) { } }; /** * @brief Template specialization for no variadic arguments. * * It's needed to prevent ambiguous constructors being generated. **/ template class Wrapper : public AbstractWrapper { public: static_assert(!std::is_same >::value, "Data template argument must be derived from WrapperData"); static_assert(std::is_base_of, Data>::value, "Data template argument must be derived from WrapperData"); static_assert(Data::argumentCount == 0, "Wrapper for no arguments constructed with WrapperData with arguments"); explicit Wrapper() : AbstractWrapper(XCB_WINDOW_NONE, Data::requestFunc(connection())) { } }; class Atom { public: explicit Atom(const QByteArray &name, bool onlyIfExists = false, xcb_connection_t *c = connection()) : m_connection(c) , m_retrieved(false) , m_cookie(xcb_intern_atom_unchecked(m_connection, onlyIfExists, name.length(), name.constData())) , m_atom(XCB_ATOM_NONE) , m_name(name) { } Atom() = delete; Atom(const Atom &) = delete; ~Atom() { if (!m_retrieved && m_cookie.sequence) { xcb_discard_reply(m_connection, m_cookie.sequence); } } operator xcb_atom_t() const { (const_cast(this))->getReply(); return m_atom; } bool isValid() { getReply(); return m_atom != XCB_ATOM_NONE; } bool isValid() const { (const_cast(this))->getReply(); return m_atom != XCB_ATOM_NONE; } inline const QByteArray &name() const { return m_name; } private: void getReply() { if (m_retrieved || !m_cookie.sequence) { return; } ScopedCPointer reply(xcb_intern_atom_reply(m_connection, m_cookie, nullptr)); if (!reply.isNull()) { m_atom = reply->atom; } m_retrieved = true; } xcb_connection_t *m_connection; bool m_retrieved; xcb_intern_atom_cookie_t m_cookie; xcb_atom_t m_atom; QByteArray m_name; }; /** * @brief Macro to create the WrapperData subclass. * * Creates a struct with name @p __NAME__ for the xcb request identified by @p __REQUEST__. * The variadic arguments are used to pass as template arguments to the WrapperData. * * The @p __REQUEST__ is the common prefix of the cookie type, reply type, request function and * reply function. E.g. "xcb_get_geometry" is used to create: * @li cookie type xcb_get_geometry_cookie_t * @li reply type xcb_get_geometry_reply_t * @li request function pointer xcb_get_geometry_unchecked * @li reply function pointer xcb_get_geometry_reply * * @param __NAME__ The name of the WrapperData subclass * @param __REQUEST__ The name of the xcb request, e.g. xcb_get_geometry * @param __VA_ARGS__ The variadic template arguments, e.g. xcb_drawable_t * @see XCB_WRAPPER **/ #define XCB_WRAPPER_DATA( __NAME__, __REQUEST__, ... ) \ struct __NAME__ : public WrapperData< __REQUEST__##_reply_t, __REQUEST__##_cookie_t, __VA_ARGS__ > \ { \ static constexpr request_func requestFunc = &__REQUEST__##_unchecked; \ static constexpr reply_func replyFunc = &__REQUEST__##_reply; \ }; /** * @brief Macro to create Wrapper typedef and WrapperData. * * This macro expands the XCB_WRAPPER_DATA macro and creates an additional * typedef for Wrapper with name @p __NAME__. The created WrapperData is also derived * from @p __NAME__ with "Data" as suffix. * * @param __NAME__ The name for the Wrapper typedef * @param __REQUEST__ The name of the xcb request, passed to XCB_WRAPPER_DATA * @param __VA_ARGS__ The variadic template arguments for Wrapper and WrapperData * @see XCB_WRAPPER_DATA **/ #define XCB_WRAPPER( __NAME__, __REQUEST__, ... ) \ XCB_WRAPPER_DATA( __NAME__##Data, __REQUEST__, __VA_ARGS__ ) \ typedef Wrapper< __NAME__##Data, __VA_ARGS__ > __NAME__; XCB_WRAPPER(WindowAttributes, xcb_get_window_attributes, xcb_window_t) XCB_WRAPPER(OverlayWindow, xcb_composite_get_overlay_window, xcb_window_t) XCB_WRAPPER_DATA(GeometryData, xcb_get_geometry, xcb_drawable_t) class WindowGeometry : public Wrapper { public: WindowGeometry() : Wrapper() {} explicit WindowGeometry(xcb_window_t window) : Wrapper(window) {} inline QRect rect() { const xcb_get_geometry_reply_t *geometry = data(); if (!geometry) { return QRect(); } return QRect(geometry->x, geometry->y, geometry->width, geometry->height); } }; XCB_WRAPPER_DATA(TreeData, xcb_query_tree, xcb_window_t) class Tree : public Wrapper { public: explicit Tree(WindowId window) : Wrapper(window) {} inline WindowId *children() { if (isNull() || data()->children_len == 0) { return nullptr; } return xcb_query_tree_children(data()); } inline xcb_window_t parent() { if (isNull()) return XCB_WINDOW_NONE; return (*this)->parent; } }; XCB_WRAPPER(Pointer, xcb_query_pointer, xcb_window_t) struct CurrentInputData : public WrapperData< xcb_get_input_focus_reply_t, xcb_get_input_focus_cookie_t > { static constexpr request_func requestFunc = &xcb_get_input_focus_unchecked; static constexpr reply_func replyFunc = &xcb_get_input_focus_reply; }; class CurrentInput : public Wrapper { public: CurrentInput() : Wrapper() {} inline xcb_window_t window() { if (isNull()) return XCB_WINDOW_NONE; return (*this)->focus; } }; struct QueryKeymapData : public WrapperData< xcb_query_keymap_reply_t, xcb_query_keymap_cookie_t > { static constexpr request_func requestFunc = &xcb_query_keymap_unchecked; static constexpr reply_func replyFunc = &xcb_query_keymap_reply; }; class QueryKeymap : public Wrapper { public: QueryKeymap() : Wrapper() {} }; struct ModifierMappingData : public WrapperData< xcb_get_modifier_mapping_reply_t, xcb_get_modifier_mapping_cookie_t > { static constexpr request_func requestFunc = &xcb_get_modifier_mapping_unchecked; static constexpr reply_func replyFunc = &xcb_get_modifier_mapping_reply; }; class ModifierMapping : public Wrapper { public: ModifierMapping() : Wrapper() {} inline xcb_keycode_t *keycodes() { if (isNull()) { return nullptr; } return xcb_get_modifier_mapping_keycodes(data()); } inline int size() { if (isNull()) { return 0; } return xcb_get_modifier_mapping_keycodes_length(data()); } }; XCB_WRAPPER_DATA(PropertyData, xcb_get_property, uint8_t, xcb_window_t, xcb_atom_t, xcb_atom_t, uint32_t, uint32_t) class Property : public Wrapper { public: Property() : Wrapper() , m_type(XCB_ATOM_NONE) { } Property(const Property &other) : Wrapper(other) , m_type(other.m_type) { } explicit Property(uint8_t _delete, xcb_window_t window, xcb_atom_t property, xcb_atom_t type, uint32_t long_offset, uint32_t long_length) : Wrapper(window, _delete, window, property, type, long_offset, long_length) , m_type(type) { } Property &operator=(const Property &other) { Wrapper::operator=(other); m_type = other.m_type; return *this; } /** * @brief Overloaded method for convenience. * * Uses the type which got passed into the ctor and derives the format from the sizeof(T). * Note: for the automatic format detection the size of the type T may not vary between * architectures. Thus one needs to use e.g. uint32_t instead of long. In general all xcb * data types can be used, all Xlib data types can not be used. * * @param defaultValue The default value to return in case of error * @param ok Set to @c false in case of error, @c true in case of success * @return The read value or @p defaultValue in error case */ template inline typename std::enable_if::value, T>::type value(T defaultValue = T(), bool *ok = nullptr) { return value(sizeof(T) * 8, m_type, defaultValue, ok); } /** * @brief Reads the property as a POD type. * * Returns the first value of the property data. In case of @p format or @p type mismatch * the @p defaultValue is returned. The optional argument @p ok is set * to @c false in case of error and to @c true in case of successful reading of * the property. * * @param format The expected format of the property value, e.g. 32 for XCB_ATOM_CARDINAL * @param type The expected type of the property value, e.g. XCB_ATOM_CARDINAL * @param defaultValue The default value to return in case of error * @param ok Set to @c false in case of error, @c true in case of success * @return The read value or @p defaultValue in error case **/ template inline typename std::enable_if::value, T>::type value(uint8_t format, xcb_atom_t type, T defaultValue = T(), bool *ok = nullptr) { T *reply = value(format, type, nullptr, ok); if (!reply) { return defaultValue; } return reply[0]; } /** * @brief Overloaded method for convenience. * * Uses the type which got passed into the ctor and derives the format from the sizeof(T). * Note: for the automatic format detection the size of the type T may not vary between * architectures. Thus one needs to use e.g. uint32_t instead of long. In general all xcb * data types can be used, all Xlib data types can not be used. * * @param defaultValue The default value to return in case of error * @param ok Set to @c false in case of error, @c true in case of success * @return The read value or @p defaultValue in error case */ template inline typename std::enable_if::value, T>::type value(T defaultValue = nullptr, bool *ok = nullptr) { return value(sizeof(typename std::remove_pointer::type) * 8, m_type, defaultValue, ok); } /** * @brief Reads the property as an array of T. * * This method is an overload for the case that T is a pointer type. * * Return the property value casted to the pointer type T. In case of @p format * or @p type mismatch the @p defaultValue is returned. Also if the value length * is @c 0 the @p defaultValue is returned. The optional argument @p ok is set * to @c false in case of error and to @c true in case of successful reading of * the property. Ok will always be true if the property exists and has been * successfully read, even in the case the property is empty and its length is 0 * * @param format The expected format of the property value, e.g. 32 for XCB_ATOM_CARDINAL * @param type The expected type of the property value, e.g. XCB_ATOM_CARDINAL * @param defaultValue The default value to return in case of error * @param ok Set to @c false in case of error, @c true in case of success * @return The read value or @p defaultValue in error case **/ template inline typename std::enable_if::value, T>::type value(uint8_t format, xcb_atom_t type, T defaultValue = nullptr, bool *ok = nullptr) { if (ok) { *ok = false; } const PropertyData::reply_type *reply = data(); if (!reply) { return defaultValue; } if (reply->type != type) { return defaultValue; } if (reply->format != format) { return defaultValue; } if (ok) { *ok = true; } if (xcb_get_property_value_length(reply) == 0) { return defaultValue; } return reinterpret_cast(xcb_get_property_value(reply)); } /** * @brief Reads the property as string and returns a QByteArray. * * In case of error this method returns a null QByteArray. **/ inline QByteArray toByteArray(uint8_t format = 8, xcb_atom_t type = XCB_ATOM_STRING, bool *ok = nullptr) { bool valueOk = false; const char *reply = value(format, type, nullptr, &valueOk); if (ok) { *ok = valueOk; } if (valueOk && !reply) { return QByteArray("", 0); // valid, not null, but empty data } else if (!valueOk) { return QByteArray(); // Property not found, data empty and null } return QByteArray(reply, xcb_get_property_value_length(data())); } /** * @brief Overloaded method for convenience. **/ inline QByteArray toByteArray(bool *ok) { return toByteArray(8, m_type, ok); } /** * @brief Reads the property as a boolean value. * * If the property reply length is @c 1 the first element is interpreted as a boolean * value returning @c true for any value unequal to @c 0 and @c false otherwise. * * In case of error this method returns @c false. Thus it is not possible to distinguish * between error case and a read @c false value. Use the optional argument @p ok to * distinguish the error case. * * @param format Expected format. Defaults to 32. * @param type Expected type Defaults to XCB_ATOM_CARDINAL. * @param ok Set to @c false in case of error, @c true in case of success * @return bool The first element interpreted as a boolean value or @c false in error case * @see value */ inline bool toBool(uint8_t format = 32, xcb_atom_t type = XCB_ATOM_CARDINAL, bool *ok = nullptr) { bool *reply = value(format, type, nullptr, ok); if (!reply) { return false; } if (data()->value_len != 1) { if (ok) { *ok = false; } return false; } return reply[0] != 0; } /** * @brief Overloaded method for convenience. **/ inline bool toBool(bool *ok) { return toBool(32, m_type, ok); } private: xcb_atom_t m_type; }; class StringProperty : public Property { public: StringProperty() = default; explicit StringProperty(xcb_window_t w, xcb_atom_t p) : Property(false, w, p, XCB_ATOM_STRING, 0, 10000) { } operator QByteArray() { return toByteArray(); } }; class TransientFor : public Property { public: explicit TransientFor(WindowId window) : Property(0, window, XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 0, 1) { } /** * @brief Fill given window pointer with the WM_TRANSIENT_FOR property of a window. * @param prop WM_TRANSIENT_FOR property value. * @returns @c true on success, @c false otherwise **/ inline bool getTransientFor(WindowId *prop) { WindowId *windows = value(); if (!windows) { return false; } *prop = *windows; return true; } }; class GeometryHints { public: GeometryHints() = default; void init(xcb_window_t window) { Q_ASSERT(window); if (m_window) { // already initialized return; } m_window = window; fetch(); } void fetch() { if (!m_window) { return; } m_sizeHints = nullptr; m_hints = NormalHints(m_window); } void read() { m_sizeHints = m_hints.sizeHints(); } bool hasPosition() const { return testFlag(NormalHints::SizeHints::UserPosition) || testFlag(NormalHints::SizeHints::ProgramPosition); } bool hasSize() const { return testFlag(NormalHints::SizeHints::UserSize) || testFlag(NormalHints::SizeHints::ProgramSize); } bool hasMinSize() const { return testFlag(NormalHints::SizeHints::MinSize); } bool hasMaxSize() const { return testFlag(NormalHints::SizeHints::MaxSize); } bool hasResizeIncrements() const { return testFlag(NormalHints::SizeHints::ResizeIncrements); } bool hasAspect() const { return testFlag(NormalHints::SizeHints::Aspect); } bool hasBaseSize() const { return testFlag(NormalHints::SizeHints::BaseSize); } bool hasWindowGravity() const { return testFlag(NormalHints::SizeHints::WindowGravity); } QSize maxSize() const { if (!hasMaxSize()) { return QSize(INT_MAX, INT_MAX); } return QSize(qMax(m_sizeHints->maxWidth, 1), qMax(m_sizeHints->maxHeight, 1)); } QSize minSize() const { if (!hasMinSize()) { // according to ICCCM 4.1.23 base size should be used as a fallback return baseSize(); } return QSize(m_sizeHints->minWidth, m_sizeHints->minHeight); } QSize baseSize() const { // Note: not using minSize as fallback if (!hasBaseSize()) { return QSize(0, 0); } return QSize(m_sizeHints->baseWidth, m_sizeHints->baseHeight); } QSize resizeIncrements() const { if (!hasResizeIncrements()) { return QSize(1, 1); } return QSize(qMax(m_sizeHints->widthInc, 1), qMax(m_sizeHints->heightInc, 1)); } xcb_gravity_t windowGravity() const { if (!hasWindowGravity()) { return XCB_GRAVITY_NORTH_WEST; } return xcb_gravity_t(m_sizeHints->winGravity); } QSize minAspect() const { if (!hasAspect()) { return QSize(1, INT_MAX); } // prevent devision by zero return QSize(m_sizeHints->minAspect[0], qMax(m_sizeHints->minAspect[1], 1)); } QSize maxAspect() const { if (!hasAspect()) { return QSize(INT_MAX, 1); } // prevent devision by zero return QSize(m_sizeHints->maxAspect[0], qMax(m_sizeHints->maxAspect[1], 1)); } private: /** * NormalHints as specified in ICCCM 4.1.2.3. **/ class NormalHints : public Property { public: struct SizeHints { enum Flags { UserPosition = 1, UserSize = 2, ProgramPosition = 4, ProgramSize = 8, MinSize = 16, MaxSize = 32, ResizeIncrements = 64, Aspect = 128, BaseSize = 256, WindowGravity = 512 }; qint32 flags = 0; qint32 pad[4] = {0, 0, 0, 0}; qint32 minWidth = 0; qint32 minHeight = 0; qint32 maxWidth = 0; qint32 maxHeight = 0; qint32 widthInc = 0; qint32 heightInc = 0; qint32 minAspect[2] = {0, 0}; qint32 maxAspect[2] = {0, 0}; qint32 baseWidth = 0; qint32 baseHeight = 0; qint32 winGravity = 0; }; explicit NormalHints() : Property() {}; explicit NormalHints(WindowId window) : Property(0, window, XCB_ATOM_WM_NORMAL_HINTS, XCB_ATOM_WM_SIZE_HINTS, 0, 18) { } inline SizeHints *sizeHints() { return value(32, XCB_ATOM_WM_SIZE_HINTS, nullptr); } }; friend TestXcbSizeHints; bool testFlag(NormalHints::SizeHints::Flags flag) const { if (!m_window || !m_sizeHints) { return false; } return m_sizeHints->flags & flag; } xcb_window_t m_window = XCB_WINDOW_NONE; NormalHints m_hints; NormalHints::SizeHints *m_sizeHints = nullptr; }; class MotifHints { public: MotifHints(xcb_atom_t atom) : m_atom(atom) {} void init(xcb_window_t window) { Q_ASSERT(window); if (m_window) { // already initialized return; } m_window = window; fetch(); } void fetch() { if (!m_window) { return; } m_hints = nullptr; m_prop = Property(0, m_window, m_atom, m_atom, 0, 5); } void read() { m_hints = m_prop.value(32, m_atom, nullptr); } bool hasDecoration() const { if (!m_window || !m_hints) { return false; } return m_hints->flags & uint32_t(Hints::Decorations); } bool noBorder() const { if (!hasDecoration()) { return false; } return !m_hints->decorations; } bool resize() const { return testFunction(Functions::Resize); } bool move() const { return testFunction(Functions::Move); } bool minimize() const { return testFunction(Functions::Minimize); } bool maximize() const { return testFunction(Functions::Maximize); } bool close() const { return testFunction(Functions::Close); } private: struct MwmHints { uint32_t flags; uint32_t functions; uint32_t decorations; int32_t input_mode; uint32_t status; }; enum class Hints { Functions = (1L << 0), Decorations = (1L << 1) }; enum class Functions { All = (1L << 0), Resize = (1L << 1), Move = (1L << 2), Minimize = (1L << 3), Maximize = (1L << 4), Close = (1L << 5) }; bool testFunction(Functions flag) const { if (!m_window || !m_hints) { return true; } if (!(m_hints->flags & uint32_t(Hints::Functions))) { return true; } // if MWM_FUNC_ALL is set, other flags say what to turn _off_ const bool set_value = ((m_hints->functions & uint32_t(Functions::All)) == 0); if (m_hints->functions & uint32_t(flag)) { return set_value; } return !set_value; } xcb_window_t m_window = XCB_WINDOW_NONE; Property m_prop; xcb_atom_t m_atom; MwmHints *m_hints = nullptr; }; namespace RandR { XCB_WRAPPER(ScreenInfo, xcb_randr_get_screen_info, xcb_window_t) XCB_WRAPPER_DATA(ScreenResourcesData, xcb_randr_get_screen_resources, xcb_window_t) class ScreenResources : public Wrapper { public: explicit ScreenResources(WindowId window) : Wrapper(window) {} inline xcb_randr_crtc_t *crtcs() { if (isNull()) { return nullptr; } return xcb_randr_get_screen_resources_crtcs(data()); } inline xcb_randr_mode_info_t *modes() { if (isNull()) { return nullptr; } return xcb_randr_get_screen_resources_modes(data()); } inline uint8_t *names() { if (isNull()) { return nullptr; } return xcb_randr_get_screen_resources_names(data()); } }; XCB_WRAPPER_DATA(CrtcGammaData, xcb_randr_get_crtc_gamma, xcb_randr_crtc_t) class CrtcGamma : public Wrapper { public: explicit CrtcGamma(xcb_randr_crtc_t c) : Wrapper(c) {} inline uint16_t *red() { return xcb_randr_get_crtc_gamma_red(data()); } inline uint16_t *green() { return xcb_randr_get_crtc_gamma_green(data()); } inline uint16_t *blue() { return xcb_randr_get_crtc_gamma_blue(data()); } }; XCB_WRAPPER_DATA(CrtcInfoData, xcb_randr_get_crtc_info, xcb_randr_crtc_t, xcb_timestamp_t) class CrtcInfo : public Wrapper { public: CrtcInfo() = default; CrtcInfo(const CrtcInfo&) = default; explicit CrtcInfo(xcb_randr_crtc_t c, xcb_timestamp_t t) : Wrapper(c, t) {} inline QRect rect() { const CrtcInfoData::reply_type *info = data(); if (!info || info->num_outputs == 0 || info->mode == XCB_NONE || info->status != XCB_RANDR_SET_CONFIG_SUCCESS) { return QRect(); } return QRect(info->x, info->y, info->width, info->height); } inline xcb_randr_output_t *outputs() { const CrtcInfoData::reply_type *info = data(); if (!info || info->num_outputs == 0 || info->mode == XCB_NONE || info->status != XCB_RANDR_SET_CONFIG_SUCCESS) { return nullptr; } return xcb_randr_get_crtc_info_outputs(info); } }; XCB_WRAPPER_DATA(OutputInfoData, xcb_randr_get_output_info, xcb_randr_output_t, xcb_timestamp_t) class OutputInfo : public Wrapper { public: OutputInfo() = default; OutputInfo(const OutputInfo&) = default; explicit OutputInfo(xcb_randr_output_t c, xcb_timestamp_t t) : Wrapper(c, t) {} inline QString name() { const OutputInfoData::reply_type *info = data(); if (!info || info->num_crtcs == 0 || info->num_modes == 0 || info->status != XCB_RANDR_SET_CONFIG_SUCCESS) { return QString(); } return QString::fromUtf8(reinterpret_cast(xcb_randr_get_output_info_name(info)), info->name_len); } }; XCB_WRAPPER_DATA(CurrentResourcesData, xcb_randr_get_screen_resources_current, xcb_window_t) class CurrentResources : public Wrapper { public: explicit CurrentResources(WindowId window) : Wrapper(window) {} inline xcb_randr_crtc_t *crtcs() { if (isNull()) { return nullptr; } return xcb_randr_get_screen_resources_current_crtcs(data()); } inline xcb_randr_mode_info_t *modes() { if (isNull()) { return nullptr; } return xcb_randr_get_screen_resources_current_modes(data()); } }; XCB_WRAPPER(SetCrtcConfig, xcb_randr_set_crtc_config, xcb_randr_crtc_t, xcb_timestamp_t, xcb_timestamp_t, int16_t, int16_t, xcb_randr_mode_t, uint16_t, uint32_t, const xcb_randr_output_t*) } class ExtensionData { public: ExtensionData(); int version; int eventBase; int errorBase; int majorOpcode; bool present; QByteArray name; QVector opCodes; QVector errorCodes; }; class KWIN_EXPORT Extensions { public: bool isShapeAvailable() const { return m_shape.version > 0; } bool isShapeInputAvailable() const; int shapeNotifyEvent() const; bool hasShape(xcb_window_t w) const; bool isRandrAvailable() const { return m_randr.present; } int randrNotifyEvent() const; bool isDamageAvailable() const { return m_damage.present; } int damageNotifyEvent() const; bool isCompositeAvailable() const { return m_composite.version > 0; } bool isCompositeOverlayAvailable() const; bool isRenderAvailable() const { return m_render.version > 0; } bool isFixesAvailable() const { return m_fixes.version > 0; } int fixesCursorNotifyEvent() const; bool isFixesRegionAvailable() const; bool isSyncAvailable() const { return m_sync.present; } int syncAlarmNotifyEvent() const; QVector extensions() const; bool hasGlx() const { return m_glx.present; } int glxEventBase() const { return m_glx.eventBase; } int glxMajorOpcode() const { return m_glx.majorOpcode; } static Extensions *self(); static void destroy(); private: Extensions(); ~Extensions(); void init(); template void initVersion(T cookie, F f, ExtensionData *dataToFill); void extensionQueryReply(const xcb_query_extension_reply_t *extension, ExtensionData *dataToFill); ExtensionData m_shape; ExtensionData m_randr; ExtensionData m_damage; ExtensionData m_composite; ExtensionData m_render; ExtensionData m_fixes; ExtensionData m_sync; ExtensionData m_glx; static Extensions *s_self; }; /** * This class is an RAII wrapper for an xcb_window_t. An xcb_window_t hold by an instance of this class * will be freed when the instance gets destroyed. * * Furthermore the class provides wrappers around some xcb methods operating on an xcb_window_t. * * For the cases that one is more interested in wrapping the xcb methods the constructor which takes * an existing window and the @link reset method allow to disable the RAII functionality. **/ class Window { public: /** * Takes over responsibility of @p window. If @p window is not provided an invalid Window is * created. Use @link create to set an xcb_window_t later on. * * If @p destroy is @c true the window will be destroyed together with this object, if @c false * the window will be kept around. This is useful if you are not interested in the RAII capabilities * but still want to use a window like an object. * * @param window The window to manage. * @param destroy Whether the window should be destroyed together with the object. * @see reset **/ Window(xcb_window_t window = XCB_WINDOW_NONE, bool destroy = true); /** * Creates an xcb_window_t and manages it. It's a convenient method to create a window with * depth, class and visual being copied from parent and border being @c 0. * @param geometry The geometry for the window to be created * @param mask The mask for the values * @param values The values to be passed to xcb_create_window * @param parent The parent window **/ Window(const QRect &geometry, uint32_t mask = 0, const uint32_t *values = NULL, xcb_window_t parent = rootWindow()); /** * Creates an xcb_window_t and manages it. It's a convenient method to create a window with * depth and visual being copied from parent and border being @c 0. * @param geometry The geometry for the window to be created - * @param class The window class + * @param windowClass The window class * @param mask The mask for the values * @param values The values to be passed to xcb_create_window * @param parent The parent window **/ Window(const QRect &geometry, uint16_t windowClass, uint32_t mask = 0, const uint32_t *values = NULL, xcb_window_t parent = rootWindow()); Window(const Window &other) = delete; ~Window(); /** * Creates a new window for which the responsibility is taken over. If a window had been managed * before it is freed. * * Depth, class and visual are being copied from parent and border is @c 0. * @param geometry The geometry for the window to be created * @param mask The mask for the values * @param values The values to be passed to xcb_create_window * @param parent The parent window **/ void create(const QRect &geometry, uint32_t mask = 0, const uint32_t *values = NULL, xcb_window_t parent = rootWindow()); /** * Creates a new window for which the responsibility is taken over. If a window had been managed * before it is freed. * * Depth and visual are being copied from parent and border is @c 0. * @param geometry The geometry for the window to be created - * @param class The window class + * @param windowClass The window class * @param mask The mask for the values * @param values The values to be passed to xcb_create_window * @param parent The parent window **/ void create(const QRect &geometry, uint16_t windowClass, uint32_t mask = 0, const uint32_t *values = NULL, xcb_window_t parent = rootWindow()); /** * Frees the existing window and starts to manage the new @p window. * If @p destroy is @c true the new managed window will be destroyed together with this * object or when reset is called again. If @p destroy is @c false the window will not * be destroyed. It is then the responsibility of the caller to destroy the window. **/ void reset(xcb_window_t window = XCB_WINDOW_NONE, bool destroy = true); /** * @returns @c true if a window is managed, @c false otherwise. **/ bool isValid() const; + inline const QRect &geometry() const { return m_logicGeometry; } /** * Configures the window with a new geometry. * @param geometry The new window geometry to be used **/ - inline const QRect &geometry() const { return m_logicGeometry; } void setGeometry(const QRect &geometry); void setGeometry(uint32_t x, uint32_t y, uint32_t width, uint32_t height); void move(const QPoint &pos); void move(uint32_t x, uint32_t y); void resize(const QSize &size); void resize(uint32_t width, uint32_t height); void raise(); void lower(); void map(); void unmap(); void reparent(xcb_window_t parent, int x = 0, int y = 0); void changeProperty(xcb_atom_t property, xcb_atom_t type, uint8_t format, uint32_t length, const void *data, uint8_t mode = XCB_PROP_MODE_REPLACE); void deleteProperty(xcb_atom_t property); void setBorderWidth(uint32_t width); void grabButton(uint8_t pointerMode, uint8_t keyboardmode, uint16_t modifiers = XCB_MOD_MASK_ANY, uint8_t button = XCB_BUTTON_INDEX_ANY, uint16_t eventMask = XCB_EVENT_MASK_BUTTON_PRESS, xcb_window_t confineTo = XCB_WINDOW_NONE, xcb_cursor_t cursor = XCB_CURSOR_NONE, bool ownerEvents = false); void ungrabButton(uint16_t modifiers = XCB_MOD_MASK_ANY, uint8_t button = XCB_BUTTON_INDEX_ANY); /** * Clears the window area. Same as xcb_clear_area with x, y, width, height being @c 0. **/ void clear(); void setBackgroundPixmap(xcb_pixmap_t pixmap); void defineCursor(xcb_cursor_t cursor); void focus(uint8_t revertTo = XCB_INPUT_FOCUS_POINTER_ROOT, xcb_timestamp_t time = XCB_TIME_CURRENT_TIME); void selectInput(uint32_t events); void kill(); operator xcb_window_t() const; private: xcb_window_t doCreate(const QRect &geometry, uint16_t windowClass, uint32_t mask = 0, const uint32_t *values = NULL, xcb_window_t parent = rootWindow()); void destroy(); xcb_window_t m_window; bool m_destroy; QRect m_logicGeometry; }; inline Window::Window(xcb_window_t window, bool destroy) : m_window(window) , m_destroy(destroy) { } inline Window::Window(const QRect &geometry, uint32_t mask, const uint32_t *values, xcb_window_t parent) : m_window(doCreate(geometry, XCB_COPY_FROM_PARENT, mask, values, parent)) , m_destroy(true) { } inline Window::Window(const QRect &geometry, uint16_t windowClass, uint32_t mask, const uint32_t *values, xcb_window_t parent) : m_window(doCreate(geometry, windowClass, mask, values, parent)) , m_destroy(true) { } inline Window::~Window() { destroy(); } inline void Window::destroy() { if (!isValid() || !m_destroy) { return; } xcb_destroy_window(connection(), m_window); m_window = XCB_WINDOW_NONE; } inline bool Window::isValid() const { return m_window != XCB_WINDOW_NONE; } inline Window::operator xcb_window_t() const { return m_window; } inline void Window::create(const QRect &geometry, uint16_t windowClass, uint32_t mask, const uint32_t *values, xcb_window_t parent) { destroy(); m_window = doCreate(geometry, windowClass, mask, values, parent); } inline void Window::create(const QRect &geometry, uint32_t mask, const uint32_t *values, xcb_window_t parent) { create(geometry, XCB_COPY_FROM_PARENT, mask, values, parent); } inline xcb_window_t Window::doCreate(const QRect &geometry, uint16_t windowClass, uint32_t mask, const uint32_t *values, xcb_window_t parent) { m_logicGeometry = geometry; xcb_window_t w = xcb_generate_id(connection()); xcb_create_window(connection(), XCB_COPY_FROM_PARENT, w, parent, geometry.x(), geometry.y(), geometry.width(), geometry.height(), 0, windowClass, XCB_COPY_FROM_PARENT, mask, values); return w; } inline void Window::reset(xcb_window_t window, bool shouldDestroy) { destroy(); m_window = window; m_destroy = shouldDestroy; } inline void Window::setGeometry(const QRect &geometry) { setGeometry(geometry.x(), geometry.y(), geometry.width(), geometry.height()); } inline void Window::setGeometry(uint32_t x, uint32_t y, uint32_t width, uint32_t height) { m_logicGeometry.setRect(x, y, width, height); if (!isValid()) { return; } const uint16_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT; const uint32_t values[] = { x, y, width, height }; xcb_configure_window(connection(), m_window, mask, values); } inline void Window::move(const QPoint &pos) { move(pos.x(), pos.y()); } inline void Window::move(uint32_t x, uint32_t y) { m_logicGeometry.moveTo(x, y); if (!isValid()) { return; } moveWindow(m_window, x, y); } inline void Window::resize(const QSize &size) { resize(size.width(), size.height()); } inline void Window::resize(uint32_t width, uint32_t height) { m_logicGeometry.setSize(QSize(width, height)); if (!isValid()) { return; } const uint16_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT; const uint32_t values[] = { width, height }; xcb_configure_window(connection(), m_window, mask, values); } inline void Window::raise() { const uint32_t values[] = { XCB_STACK_MODE_ABOVE }; xcb_configure_window(connection(), m_window, XCB_CONFIG_WINDOW_STACK_MODE, values); } inline void Window::lower() { lowerWindow(m_window); } inline void Window::map() { if (!isValid()) { return; } xcb_map_window(connection(), m_window); } inline void Window::unmap() { if (!isValid()) { return; } xcb_unmap_window(connection(), m_window); } inline void Window::reparent(xcb_window_t parent, int x, int y) { if (!isValid()) { return; } xcb_reparent_window(connection(), m_window, parent, x, y); } inline void Window::changeProperty(xcb_atom_t property, xcb_atom_t type, uint8_t format, uint32_t length, const void *data, uint8_t mode) { if (!isValid()) { return; } xcb_change_property(connection(), mode, m_window, property, type, format, length, data); } inline void Window::deleteProperty(xcb_atom_t property) { if (!isValid()) { return; } xcb_delete_property(connection(), m_window, property); } inline void Window::setBorderWidth(uint32_t width) { if (!isValid()) { return; } xcb_configure_window(connection(), m_window, XCB_CONFIG_WINDOW_BORDER_WIDTH, &width); } inline void Window::grabButton(uint8_t pointerMode, uint8_t keyboardmode, uint16_t modifiers, uint8_t button, uint16_t eventMask, xcb_window_t confineTo, xcb_cursor_t cursor, bool ownerEvents) { if (!isValid()) { return; } xcb_grab_button(connection(), ownerEvents, m_window, eventMask, pointerMode, keyboardmode, confineTo, cursor, button, modifiers); } inline void Window::ungrabButton(uint16_t modifiers, uint8_t button) { if (!isValid()) { return; } xcb_ungrab_button(connection(), button, m_window, modifiers); } inline void Window::clear() { if (!isValid()) { return; } xcb_clear_area(connection(), false, m_window, 0, 0, 0, 0); } inline void Window::setBackgroundPixmap(xcb_pixmap_t pixmap) { if (!isValid()) { return; } const uint32_t values[] = {pixmap}; xcb_change_window_attributes(connection(), m_window, XCB_CW_BACK_PIXMAP, values); } inline void Window::defineCursor(xcb_cursor_t cursor) { Xcb::defineCursor(m_window, cursor); } inline void Window::focus(uint8_t revertTo, xcb_timestamp_t time) { setInputFocus(m_window, revertTo, time); } inline void Window::selectInput(uint32_t events) { Xcb::selectInput(m_window, events); } inline void Window::kill() { xcb_kill_client(connection(), m_window); } // helper functions static inline void moveResizeWindow(WindowId window, const QRect &geometry) { const uint16_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT; const uint32_t values[] = { static_cast(geometry.x()), static_cast(geometry.y()), static_cast(geometry.width()), static_cast(geometry.height()) }; xcb_configure_window(connection(), window, mask, values); } static inline void moveWindow(xcb_window_t window, const QPoint& pos) { moveWindow(window, pos.x(), pos.y()); } static inline void moveWindow(xcb_window_t window, uint32_t x, uint32_t y) { const uint16_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y; const uint32_t values[] = { x, y }; xcb_configure_window(connection(), window, mask, values); } static inline void lowerWindow(xcb_window_t window) { const uint32_t values[] = { XCB_STACK_MODE_BELOW }; xcb_configure_window(connection(), window, XCB_CONFIG_WINDOW_STACK_MODE, values); } static inline WindowId createInputWindow(const QRect &geometry, uint32_t mask, const uint32_t *values) { WindowId window = xcb_generate_id(connection()); xcb_create_window(connection(), 0, window, rootWindow(), geometry.x(), geometry.y(), geometry.width(), geometry.height(), 0, XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, mask, values); return window; } static inline void restackWindows(const QVector &windows) { if (windows.count() < 2) { // only one window, nothing to do return; } for (int i=1; i &windows) { if (windows.isEmpty()) { return; } const uint32_t values[] = { XCB_STACK_MODE_ABOVE }; xcb_configure_window(connection(), windows.first(), XCB_CONFIG_WINDOW_STACK_MODE, values); restackWindows(windows); } static inline int defaultDepth() { static int depth = 0; if (depth != 0) { return depth; } int screen = Application::x11ScreenNumber(); for (xcb_screen_iterator_t it = xcb_setup_roots_iterator(xcb_get_setup(connection())); it.rem; --screen, xcb_screen_next(&it)) { if (screen == 0) { depth = it.data->root_depth; break; } } return depth; } static inline xcb_rectangle_t fromQt(const QRect &rect) { xcb_rectangle_t rectangle; rectangle.x = rect.x(); rectangle.y = rect.y(); rectangle.width = rect.width(); rectangle.height = rect.height(); return rectangle; } static inline QVector regionToRects(const QRegion ®ion) { const QVector regionRects = region.rects(); QVector rects(regionRects.count()); for (int i=0; i sync(xcb_get_input_focus_reply(c, cookie, &error)); if (error) { free(error); } } void selectInput(xcb_window_t window, uint32_t events) { xcb_change_window_attributes(connection(), window, XCB_CW_EVENT_MASK, &events); } /** * @brief Small helper class to encapsulate SHM related functionality. * */ class Shm { public: Shm(); ~Shm(); int shmId() const; void *buffer() const; xcb_shm_seg_t segment() const; bool isValid() const; uint8_t pixmapFormat() const; private: bool init(); int m_shmId; void *m_buffer; xcb_shm_seg_t m_segment; bool m_valid; uint8_t m_pixmapFormat; }; inline void *Shm::buffer() const { return m_buffer; } inline bool Shm::isValid() const { return m_valid; } inline xcb_shm_seg_t Shm::segment() const { return m_segment; } inline int Shm::shmId() const { return m_shmId; } inline uint8_t Shm::pixmapFormat() const { return m_pixmapFormat; } } // namespace X11 } // namespace KWin #endif // KWIN_X11_UTILS_H