diff --git a/abstract_client.h b/abstract_client.h index 220afeeeb..db0c1cfd4 100644 --- a/abstract_client.h +++ b/abstract_client.h @@ -1,1385 +1,1385 @@ /******************************************************************** 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 https://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 - **/ + */ Q_PROPERTY(QString colorScheme READ colorScheme NOTIFY colorSchemeChanged) public: ~AbstractClient() override; 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 captionNormal and 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; virtual bool isFullScreenable() const = 0; 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); /** * Set the window as being on the attached list of desktops * On X11 it will be set to the last entry - **/ + */ void setDesktops(QVector desktops); int desktop() const override { return m_desktops.isEmpty() ? (int)NET::OnAllDesktops : m_desktops.last()->x11DesktopNumber(); } QVector desktops() const override { 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* @p property @p fromThisClient or the currentTab() to * all members of the tabGroup() (if there is one) * * eg. if you call: * @code * client->setProperty("kwin_tiling_floats", true); * client->syncTabGroupFor("kwin_tiling_floats", true) * @endcode * 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); /** * Sets the maximization according to @p vertically and @p horizontally. - **/ + */ Q_INVOKABLE 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; /** * Returns whether the window is resizable or has a fixed size. - **/ + */ virtual bool isResizable() const = 0; /** * Returns whether the window is moveable or has a fixed position. - **/ + */ virtual bool isMovable() const = 0; /** * Returns whether the window can be moved to another screen. - **/ + */ 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; /** * Returns whether the window is maximizable or not. - **/ + */ 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); /** * Sets 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. * @param keyboard Defines whether to take keyboard cursor into account. - **/ + */ 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 }; /** * Calculates 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; /** * Adjust the frame size @p frame according to the window's size hints. - **/ + */ 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; /** * @returns the geometry of the virtual keyboard * This geometry is in global coordinates */ QRect virtualKeyboardGeometry() const; /** * Sets the geometry of the virtual keyboard, The window may resize itself in order to make space for the keybaord * This geometry is in global coordinates */ void setVirtualKeyboardGeometry(const QRect &geo); /** * 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; } /** * Default implementation returns @c null. * Mostly intended for X11 clients, from EWMH: * @verbatim * If the WM_TRANSIENT_FOR property is set to None or Root window, the window should be * treated as a transient for all other windows in the same group. It has been noted that this * is a slight ICCCM violation, but as this behavior is pretty standard for many toolkits and * window managers, and is extremely unlikely to break anything, it seems reasonable to document * it as standard. * @endverbatim - **/ + */ virtual bool groupTransient() const; /** * Default implementation returns @c null. * * Mostly for X11 clients, holds the client group - **/ + */ virtual const Group *group() const; /** * Default implementation returns @c null. * * Mostly for X11 clients, holds the client group - **/ + */ virtual Group *group(); /** * Returns whether this is an internal client. * * Internal clients are created by KWin and used for special purpose windows, * like the task switcher, etc. * * Default implementation returns @c false. - **/ + */ virtual bool isInternal() const; /** * Returns whether window rules can be applied to this client. * * Default implementation returns @c true. - **/ + */ virtual bool supportsWindowRules() const; 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 * is emitted. * * Default implementation does nothing. - **/ + */ virtual void doSetActive(); /** * 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 * is emitted. * * Default implementation does nothing. - **/ + */ virtual void doSetKeepBelow(); /** * 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 @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 startMoveResize. * * Implementing classes should return @c false if starting move resize should * get aborted. In that case 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 captionNormal and 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; QRect m_virtualKeyboardGeometry; QRect m_keyboardGeometryRestore; 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/abstract_output.h b/abstract_output.h index 4164371ad..fa0135cad 100644 --- a/abstract_output.h +++ b/abstract_output.h @@ -1,162 +1,162 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_ABSTRACT_OUTPUT_H #define KWIN_ABSTRACT_OUTPUT_H #include #include #include #include #include namespace KWin { class KWIN_EXPORT GammaRamp { public: GammaRamp(uint32_t size); /** * Returns the size of the gamma ramp. - **/ + */ uint32_t size() const; /** * Returns pointer to the first red component in the gamma ramp. * * The returned pointer can be used for altering the red component * in the gamma ramp. - **/ + */ uint16_t *red(); /** * Returns pointer to the first red component in the gamma ramp. - **/ + */ const uint16_t *red() const; /** * Returns pointer to the first green component in the gamma ramp. * * The returned pointer can be used for altering the green component * in the gamma ramp. - **/ + */ uint16_t *green(); /** * Returns pointer to the first green component in the gamma ramp. - **/ + */ const uint16_t *green() const; /** * Returns pointer to the first blue component in the gamma ramp. * * The returned pointer can be used for altering the blue component * in the gamma ramp. - **/ + */ uint16_t *blue(); /** * Returns pointer to the first blue component in the gamma ramp. - **/ + */ const uint16_t *blue() const; private: QVector m_table; uint32_t m_size; }; /** * Generic output representation. - **/ + */ class KWIN_EXPORT AbstractOutput : public QObject { Q_OBJECT public: explicit AbstractOutput(QObject *parent = nullptr); ~AbstractOutput() override; /** * Returns the human readable name of this output. - **/ + */ virtual QString name() const = 0; /** * Returns geometry of this output in device independent pixels. - **/ + */ virtual QRect geometry() const = 0; /** * Returns the approximate vertical refresh rate of this output, in mHz. - **/ + */ virtual int refreshRate() const = 0; /** * Returns whether this output is connected through an internal connector, * e.g. LVDS, or eDP. * * Default implementation returns @c false. - **/ + */ virtual bool isInternal() const; /** * Returns the ratio between physical pixels and logical pixels. * * Default implementation returns 1. - **/ + */ virtual qreal scale() const; /** * Returns the physical size of this output, in millimeters. * * Default implementation returns an invalid QSize. - **/ + */ virtual QSize physicalSize() const; /** * Returns the orientation of this output. * * Default implementation returns Qt::PrimaryOrientation. - **/ + */ virtual Qt::ScreenOrientation orientation() const; /** * Returns the size of the gamma lookup table. * * Default implementation returns 0. - **/ + */ virtual int gammaRampSize() const; /** * Sets the gamma ramp of this output. * * Returns @c true if the gamma ramp was successfully set. - **/ + */ virtual bool setGammaRamp(const GammaRamp &gamma); private: Q_DISABLE_COPY(AbstractOutput) }; } // namespace KWin #endif diff --git a/abstract_wayland_output.h b/abstract_wayland_output.h index 50fd9a5ab..18d2cad8e 100644 --- a/abstract_wayland_output.h +++ b/abstract_wayland_output.h @@ -1,182 +1,182 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_ABSTRACT_WAYLAND_OUTPUT_H #define KWIN_ABSTRACT_WAYLAND_OUTPUT_H #include "abstract_output.h" #include #include #include #include #include #include #include #include #include #include namespace KWayland { namespace Server { class OutputInterface; class OutputDeviceInterface; class OutputChangeSet; class OutputManagementInterface; class XdgOutputInterface; } } namespace KWin { /** * Generic output representation in a Wayland session - **/ + */ class KWIN_EXPORT AbstractWaylandOutput : public AbstractOutput { Q_OBJECT public: explicit AbstractWaylandOutput(QObject *parent = nullptr); ~AbstractWaylandOutput() override; QString name() const override; bool isEnabled() const { return !m_waylandOutput.isNull(); } virtual QSize pixelSize() const = 0; qreal scale() const override { return m_scale; } /** * The geometry of this output in global compositor co-ordinates (i.e scaled) - **/ + */ QRect geometry() const override; QSize physicalSize() const override; Qt::ScreenOrientation orientation() const override { return m_orientation; } /** * Current refresh rate in 1/ms. - **/ + */ int refreshRate() const override; bool isInternal() const override { return m_internal; } void setGlobalPos(const QPoint &pos); void setScale(qreal scale); /** * This sets the changes and tests them against the specific output. - **/ + */ void setChanges(KWayland::Server::OutputChangeSet *changeset); QPointer waylandOutput() const { return m_waylandOutput; } /** * Enable or disable the output. * * This differs from updateDpms as it also removes the wl_output. * The default is on. - **/ + */ void setEnabled(bool enable); Q_SIGNALS: void modeChanged(); protected: void initWaylandOutput(); void initWaylandOutputDevice(const QString &model, const QString &manufacturer, const QByteArray &uuid, const QVector &modes); QPointer xdgOutput() const { return m_xdgOutput; } void createXdgOutput(); QPointer waylandOutputDevice() const { return m_waylandOutputDevice; } QPoint globalPos() const { return m_globalPos; } QSize rawPhysicalSize() const { return m_physicalSize; } void setRawPhysicalSize(const QSize &set) { m_physicalSize = set; } void setOrientation(Qt::ScreenOrientation set) { m_orientation = set; } bool internal() const { return m_internal; } void setInternal(bool set) { m_internal = set; } void setDpmsSupported(bool set) { m_supportsDpms = set; } virtual void updateDpms(KWayland::Server::OutputInterface::DpmsMode mode) { Q_UNUSED(mode); } virtual void updateMode(int modeIndex) { Q_UNUSED(modeIndex); } virtual void transform(KWayland::Server::OutputDeviceInterface::Transform transform) { Q_UNUSED(transform); } void setWaylandMode(const QSize &size, int refreshRate); QSize orientateSize(const QSize &size) const; private: QPointer m_waylandOutput; QPointer m_xdgOutput; QPointer m_waylandOutputDevice; KWayland::Server::OutputInterface::DpmsMode m_dpms = KWayland::Server::OutputInterface::DpmsMode::On; QPoint m_globalPos; qreal m_scale = 1; QSize m_physicalSize; Qt::ScreenOrientation m_orientation = Qt::PrimaryOrientation; bool m_internal = false; bool m_supportsDpms = false; }; } #endif // KWIN_OUTPUT_H diff --git a/activation.cpp b/activation.cpp index 397cc7144..d463eb30a 100644 --- a/activation.cpp +++ b/activation.cpp @@ -1,895 +1,895 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ /* This file contains things relevant to window activation and focus stealing prevention. */ #include "client.h" #include "cursor.h" #include "focuschain.h" #include "netinfo.h" #include "workspace.h" #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include #include #include #include #include "atoms.h" #include "group.h" #include "rules.h" #include "screens.h" #include "useractions.h" #include namespace KWin { /* Prevention of focus stealing: KWin tries to prevent unwanted changes of focus, that would result from mapping a new window. Also, some nasty applications may try to force focus change even in cases when ICCCM 4.2.7 doesn't allow it (e.g. they may try to activate their main window because the user definitely "needs" to see something happened - misusing of QWidget::setActiveWindow() may be such case). There are 4 ways how a window may become active: - the user changes the active window (e.g. focus follows mouse, clicking on some window's titlebar) - the change of focus will be done by KWin, so there's nothing to solve in this case - the change of active window will be requested using the _NET_ACTIVE_WINDOW message (handled in RootInfo::changeActiveWindow()) - such requests will be obeyed, because this request is meant mainly for e.g. taskbar asking the WM to change the active window as a result of some user action. Normal applications should use this request only rarely in special cases. See also below the discussion of _NET_ACTIVE_WINDOW_TRANSFER. - the change of active window will be done by performing XSetInputFocus() on a window that's not currently active. ICCCM 4.2.7 describes when the application may perform change of input focus. In order to handle misbehaving applications, KWin will try to detect focus changes to windows that don't belong to currently active application, and restore focus back to the currently active window, instead of activating the window that got focus (unfortunately there's no way to FocusChangeRedirect similar to e.g. SubstructureRedirect, so there will be short time when the focus will be changed). The check itself that's done is Workspace::allowClientActivation() (see below). - a new window will be mapped - this is the most complicated case. If the new window belongs to the currently active application, it may be safely mapped on top and activated. The same if there's no active window, or the active window is the desktop. These checks are done by Workspace::allowClientActivation(). Following checks need to compare times. One time is the timestamp of last user action in the currently active window, the other time is the timestamp of the action that originally caused mapping of the new window (e.g. when the application was started). If the first time is newer than the second one, the window will not be activated, as that indicates futher user actions took place after the action leading to this new mapped window. This check is done by Workspace::allowClientActivation(). There are several ways how to get the timestamp of action that caused the new mapped window (done in Client::readUserTimeMapTimestamp()) : - the window may have the _NET_WM_USER_TIME property. This way the application may either explicitly request that the window is not activated (by using 0 timestamp), or the property contains the time of last user action in the application. - KWin itself tries to detect time of last user action in every window, by watching KeyPress and ButtonPress events on windows. This way some events may be missed (if they don't propagate to the toplevel window), but it's good as a fallback for applications that don't provide _NET_WM_USER_TIME, and missing some events may at most lead to unwanted focus stealing. - the timestamp may come from application startup notification. Application startup notification, if it exists for the new mapped window, should include time of the user action that caused it. - if there's no timestamp available, it's checked whether the new window belongs to some already running application - if yes, the timestamp will be 0 (i.e. refuse activation) - if the window is from session restored window, the timestamp will be 0 too, unless this application was the active one at the time when the session was saved, in which case the window will be activated if there wasn't any user interaction since the time KWin was started. - as the last resort, the _KDE_NET_USER_CREATION_TIME timestamp is used. For every toplevel window that is created (see CreateNotify handling), this property is set to the at that time current time. Since at this time it's known that the new window doesn't belong to any existing application (better said, the application doesn't have any other window mapped), it is either the very first window of the application, or it is the only window of the application that was hidden before. The latter case is handled by removing the property from windows before withdrawing them, making the timestamp empty for next mapping of the window. In the sooner case, the timestamp will be used. This helps in case when an application is launched without application startup notification, it creates its mainwindow, and starts its initialization (that may possibly take long time). The timestamp used will be older than any user action done after launching this application. - if no timestamp is found at all, the window is activated. The check whether two windows belong to the same application (same process) is done in Client::belongToSameApplication(). Not 100% reliable, but hopefully 99,99% reliable. As a somewhat special case, window activation is always enabled when session saving is in progress. When session saving, the session manager allows only one application to interact with the user. Not allowing window activation in such case would result in e.g. dialogs not becoming active, so focus stealing prevention would cause here more harm than good. Windows that attempted to become active but KWin prevented this will be marked as demanding user attention. They'll get the _NET_WM_STATE_DEMANDS_ATTENTION state, and the taskbar should mark them specially (blink, etc.). The state will be reset when the window eventually really becomes active. There are two more ways how a window can become obtrusive, window stealing focus: By showing above the active window, by either raising itself, or by moving itself on the active desktop. - KWin will refuse raising non-active window above the active one, unless they belong to the same application. Applications shouldn't raise their windows anyway (unless the app wants to raise one of its windows above another of its windows). - KWin activates windows moved to the current desktop (as that seems logical from the user's point of view, after sending the window there directly from KWin, or e.g. using pager). This means applications shouldn't send their windows to another desktop (SELI TODO - but what if they do?) Special cases I can think of: - konqueror reusing, i.e. kfmclient tells running Konqueror instance to open new window - without focus stealing prevention - no problem - with ASN (application startup notification) - ASN is forwarded, and because it's newer than the instance's user timestamp, it takes precedence - without ASN - user timestamp needs to be reset, otherwise it would be used, and it's old; moreover this new window mustn't be detected as window belonging to already running application, or it wouldn't be activated - see Client::sameAppWindowRoleMatch() for the (rather ugly) hack - konqueror preloading, i.e. window is created in advance, and kfmclient tells this Konqueror instance to show it later - without focus stealing prevention - no problem - with ASN - ASN is forwarded, and because it's newer than the instance's user timestamp, it takes precedence - without ASN - user timestamp needs to be reset, otherwise it would be used, and it's old; also, creation timestamp is changed to the time the instance starts (re-)initializing the window, this ensures creation timestamp will still work somewhat even in this case - KUniqueApplication - when the window is already visible, and the new instance wants it to activate - without focus stealing prevention - _NET_ACTIVE_WINDOW - no problem - with ASN - ASN is forwarded, and set on the already visible window, KWin treats the window as new with that ASN - without ASN - _NET_ACTIVE_WINDOW as application request is used, and there's no really usable timestamp, only timestamp from the time the (new) application instance was started, so KWin will activate the window *sigh* - the bad thing here is that there's absolutely no chance to recognize the case of starting this KUniqueApp from Konsole (and thus wanting the already visible window to become active) from the case when something started this KUniqueApp without ASN (in which case the already visible window shouldn't become active) - the only solution is using ASN for starting applications, at least silent (i.e. without feedback) - when one application wants to activate another application's window (e.g. KMail activating already running KAddressBook window ?) - without focus stealing prevention - _NET_ACTIVE_WINDOW - no problem - with ASN - can't be here, it's the KUniqueApp case then - without ASN - _NET_ACTIVE_WINDOW as application request should be used, KWin will activate the new window depending on the timestamp and whether it belongs to the currently active application _NET_ACTIVE_WINDOW usage: data.l[0]= 1 ->app request = 2 ->pager request = 0 - backwards compatibility data.l[1]= timestamp */ //**************************************** // Workspace //**************************************** /** * Informs the workspace about the active client, i.e. the client that * has the focus (or None if no client has the focus). This functions * is called by the client itself that gets focus. It has no other * effect than fixing the focus chain and the return value of * activeClient(). And of course, to propagate the active client to the * world. - **/ + */ void Workspace::setActiveClient(AbstractClient* c) { if (active_client == c) return; if (active_popup && active_popup_client != c && set_active_client_recursion == 0) closeActivePopup(); if (m_userActionsMenu->hasClient() && !m_userActionsMenu->isMenuClient(c) && set_active_client_recursion == 0) { m_userActionsMenu->close(); } StackingUpdatesBlocker blocker(this); ++set_active_client_recursion; updateFocusMousePosition(Cursor::pos()); if (active_client != NULL) { // note that this may call setActiveClient( NULL ), therefore the recursion counter active_client->setActive(false); } active_client = c; Q_ASSERT(c == NULL || c->isActive()); if (active_client) { last_active_client = active_client; FocusChain::self()->update(active_client, FocusChain::MakeFirst); active_client->demandAttention(false); // activating a client can cause a non active fullscreen window to loose the ActiveLayer status on > 1 screens if (screens()->count() > 1) { for (auto it = m_allClients.begin(); it != m_allClients.end(); ++it) { if (*it != active_client && (*it)->layer() == ActiveLayer && (*it)->screen() == active_client->screen()) { updateClientLayer(*it); } } } } updateToolWindows(false); if (c) disableGlobalShortcutsForClient(c->rules()->checkDisableGlobalShortcuts(false)); else disableGlobalShortcutsForClient(false); updateStackingOrder(); // e.g. fullscreens have different layer when active/not-active if (rootInfo()) { rootInfo()->setActiveClient(active_client); } emit clientActivated(active_client); --set_active_client_recursion; } /** * Tries to activate the client \a c. This function performs what you * expect when clicking the respective entry in a taskbar: showing and * raising the client (this may imply switching to the another virtual * desktop) and putting the focus onto it. Once X really gave focus to * the client window as requested, the client itself will call * setActiveClient() and the operation is complete. This may not happen * with certain focus policies, though. * * @see setActiveClient * @see requestFocus - **/ + */ void Workspace::activateClient(AbstractClient* c, bool force) { if (c == NULL) { focusToNull(); setActiveClient(NULL); return; } raiseClient(c); if (!c->isOnCurrentDesktop()) { ++block_focus; VirtualDesktopManager::self()->setCurrent(c->desktop()); --block_focus; } #ifdef KWIN_BUILD_ACTIVITIES if (!c->isOnCurrentActivity()) { ++block_focus; //DBUS! Activities::self()->setCurrent(c->activities().first()); //first isn't necessarily best, but it's easiest --block_focus; } #endif if (c->isMinimized()) c->unminimize(); // ensure the window is really visible - could eg. be a hidden utility window, see bug #348083 c->hideClient(false); // TODO force should perhaps allow this only if the window already contains the mouse if (options->focusPolicyIsReasonable() || force) requestFocus(c, force); // Don't update user time for clients that have focus stealing workaround. // As they usually belong to the current active window but fail to provide // this information, updating their user time would make the user time // of the currently active window old, and reject further activation for it. // E.g. typing URL in minicli which will show kio_uiserver dialog (with workaround), // and then kdesktop shows dialog about SSL certificate. // This needs also avoiding user creation time in Client::readUserTimeMapTimestamp(). if (Client *client = dynamic_cast(c)) { // updateUserTime is X11 specific client->updateUserTime(); } } /** * Tries to activate the client by asking X for the input focus. This * function does not perform any show, raise or desktop switching. See * Workspace::activateClient() instead. * * @see activateClient - **/ + */ void Workspace::requestFocus(AbstractClient* c, bool force) { takeActivity(c, force ? ActivityFocusForce : ActivityFocus); } void Workspace::takeActivity(AbstractClient* c, ActivityFlags flags) { // the 'if ( c == active_client ) return;' optimization mustn't be done here if (!focusChangeEnabled() && (c != active_client)) flags &= ~ActivityFocus; if (!c) { focusToNull(); return; } if (flags & ActivityFocus) { AbstractClient* modal = c->findModal(); if (modal != NULL && modal != c) { if (!modal->isOnDesktop(c->desktop())) modal->setDesktop(c->desktop()); if (!modal->isShown(true) && !modal->isMinimized()) // forced desktop or utility window activateClient(modal); // activating a minimized blocked window will unminimize its modal implicitly // if the click was inside the window (i.e. handled is set), // but it has a modal, there's no need to use handled mode, because // the modal doesn't get the click anyway // raising of the original window needs to be still done if (flags & ActivityRaise) raiseClient(c); c = modal; } cancelDelayFocus(); } if (!flags.testFlag(ActivityFocusForce) && (c->isDock() || c->isSplash())) { // toplevel menus and dock windows don't take focus if not forced // and don't have a flag that they take focus if (!c->dockWantsInput()) { flags &= ~ActivityFocus; } } if (c->isShade()) { if (c->wantsInput() && (flags & ActivityFocus)) { // client cannot accept focus, but at least the window should be active (window menu, et. al. ) c->setActive(true); focusToNull(); } flags &= ~ActivityFocus; } if (c->tabGroup() && c->tabGroup()->current() != c) c->tabGroup()->setCurrent(c); if (!c->isShown(true)) { // shouldn't happen, call activateClient() if needed qCWarning(KWIN_CORE) << "takeActivity: not shown" ; return; } if (flags & ActivityFocus) c->takeFocus(); if (flags & ActivityRaise) workspace()->raiseClient(c); if (!c->isOnActiveScreen()) screens()->setCurrent(c->screen()); } /** * Informs the workspace that the client \a c has been hidden. If it * was the active client (or to-become the active client), * the workspace activates another one. * * @note @p c may already be destroyed. - **/ + */ void Workspace::clientHidden(AbstractClient* c) { assert(!c->isShown(true) || !c->isOnCurrentDesktop() || !c->isOnCurrentActivity()); activateNextClient(c); } AbstractClient *Workspace::clientUnderMouse(int screen) const { ToplevelList::const_iterator it = stackingOrder().constEnd(); while (it != stackingOrder().constBegin()) { AbstractClient *client = qobject_cast(*(--it)); if (!client) { continue; } // rule out clients which are not really visible. // the screen test is rather superfluous for xrandr & twinview since the geometry would differ -> TODO: might be dropped if (!(client->isShown(false) && client->isOnCurrentDesktop() && client->isOnCurrentActivity() && client->isOnScreen(screen))) continue; if (client->geometry().contains(Cursor::pos())) { return client; } } return 0; } // deactivates 'c' and activates next client bool Workspace::activateNextClient(AbstractClient* c) { // if 'c' is not the active or the to-become active one, do nothing if (!(c == active_client || (should_get_focus.count() > 0 && c == should_get_focus.last()))) return false; closeActivePopup(); if (c != NULL) { if (c == active_client) setActiveClient(NULL); should_get_focus.removeAll(c); } // if blocking focus, move focus to the desktop later if needed // in order to avoid flickering if (!focusChangeEnabled()) { focusToNull(); return true; } if (!options->focusPolicyIsReasonable()) return false; AbstractClient* get_focus = NULL; // precedence on keeping the current tabgroup active. to the user that's the same window if (c && c->tabGroup() && c->isShown(false)) { if (c == c->tabGroup()->current()) c->tabGroup()->activateNext(); get_focus = c->tabGroup()->current(); if (get_focus == c) // single tab case - should not happen get_focus = NULL; } const int desktop = VirtualDesktopManager::self()->current(); if (!get_focus && showingDesktop()) get_focus = findDesktop(true, desktop); // to not break the state if (!get_focus && options->isNextFocusPrefersMouse()) { get_focus = clientUnderMouse(c ? c->screen() : screens()->current()); if (get_focus && (get_focus == c || get_focus->isDesktop())) { // should rather not happen, but it cannot get the focus. rest of usability is tested above get_focus = NULL; } } if (!get_focus) { // no suitable window under the mouse -> find sth. else // first try to pass the focus to the (former) active clients leader if (c && c->isTransient()) { auto leaders = c->mainClients(); if (leaders.count() == 1 && FocusChain::self()->isUsableFocusCandidate(leaders.at(0), c)) { get_focus = leaders.at(0); raiseClient(get_focus); // also raise - we don't know where it came from } } if (!get_focus) { // nope, ask the focus chain for the next candidate get_focus = FocusChain::self()->nextForDesktop(c, desktop); } } if (get_focus == NULL) // last chance: focus the desktop get_focus = findDesktop(true, desktop); if (get_focus != NULL) requestFocus(get_focus); else focusToNull(); return true; } void Workspace::setCurrentScreen(int new_screen) { if (new_screen < 0 || new_screen >= screens()->count()) return; if (!options->focusPolicyIsReasonable()) return; closeActivePopup(); const int desktop = VirtualDesktopManager::self()->current(); AbstractClient *get_focus = FocusChain::self()->getForActivation(desktop, new_screen); if (get_focus == NULL) get_focus = findDesktop(true, desktop); if (get_focus != NULL && get_focus != mostRecentlyActivatedClient()) requestFocus(get_focus); screens()->setCurrent(new_screen); } void Workspace::gotFocusIn(const AbstractClient* c) { if (should_get_focus.contains(const_cast< AbstractClient* >(c))) { // remove also all sooner elements that should have got FocusIn, // but didn't for some reason (and also won't anymore, because they were sooner) while (should_get_focus.first() != c) should_get_focus.pop_front(); should_get_focus.pop_front(); // remove 'c' } } void Workspace::setShouldGetFocus(AbstractClient* c) { should_get_focus.append(c); updateStackingOrder(); // e.g. fullscreens have different layer when active/not-active } namespace FSP { enum Level { None = 0, Low, Medium, High, Extreme }; } // focus_in -> the window got FocusIn event // ignore_desktop - call comes from _NET_ACTIVE_WINDOW message, don't refuse just because of window // is on a different desktop bool Workspace::allowClientActivation(const KWin::AbstractClient *c, xcb_timestamp_t time, bool focus_in, bool ignore_desktop) { // options->focusStealingPreventionLevel : // 0 - none - old KWin behaviour, new windows always get focus // 1 - low - focus stealing prevention is applied normally, when unsure, activation is allowed // 2 - normal - focus stealing prevention is applied normally, when unsure, activation is not allowed, // this is the default // 3 - high - new window gets focus only if it belongs to the active application, // or when no window is currently active // 4 - extreme - no window gets focus without user intervention if (time == -1U) time = c->userTime(); int level = c->rules()->checkFSP(options->focusStealingPreventionLevel()); if (session_saving && level <= FSP::Medium) { // <= normal return true; } AbstractClient* ac = mostRecentlyActivatedClient(); if (focus_in) { if (should_get_focus.contains(const_cast< AbstractClient* >(c))) return true; // FocusIn was result of KWin's action // Before getting FocusIn, the active Client already // got FocusOut, and therefore got deactivated. ac = last_active_client; } if (time == 0) { // explicitly asked not to get focus if (!c->rules()->checkAcceptFocus(false)) return false; } const int protection = ac ? ac->rules()->checkFPP(2) : 0; // stealing is unconditionally allowed (NETWM behavior) if (level == FSP::None || protection == FSP::None) return true; // The active client "grabs" the focus or stealing is generally forbidden if (level == FSP::Extreme || protection == FSP::Extreme) return false; // Desktop switching is only allowed in the "no protection" case if (!ignore_desktop && !c->isOnCurrentDesktop()) return false; // allow only with level == 0 // No active client, it's ok to pass focus // NOTICE that extreme protection needs to be handled before to allow protection on unmanged windows if (ac == NULL || ac->isDesktop()) { qCDebug(KWIN_CORE) << "Activation: No client active, allowing"; return true; // no active client -> always allow } // TODO window urgency -> return true? // Unconditionally allow intra-client passing around for lower stealing protections // unless the active client has High interest if (AbstractClient::belongToSameApplication(c, ac, AbstractClient::SameApplicationCheck::RelaxedForActive) && protection < FSP::High) { qCDebug(KWIN_CORE) << "Activation: Belongs to active application"; return true; } if (!c->isOnCurrentDesktop()) // we allowed explicit self-activation across virtual desktops return false; // inside a client or if no client was active, but not otherwise // High FPS, not intr-client change. Only allow if the active client has only minor interest if (level > FSP::Medium && protection > FSP::Low) return false; if (time == -1U) { // no time known qCDebug(KWIN_CORE) << "Activation: No timestamp at all"; // Only allow for Low protection unless active client has High interest in focus if (level < FSP::Medium && protection < FSP::High) return true; // no timestamp at all, don't activate - because there's also creation timestamp // done on CreateNotify, this case should happen only in case application // maps again already used window, i.e. this won't happen after app startup return false; } // Low or medium FSP, usertime comparism is possible Time user_time = ac->userTime(); qCDebug(KWIN_CORE) << "Activation, compared:" << c << ":" << time << ":" << user_time << ":" << (NET::timestampCompare(time, user_time) >= 0); return NET::timestampCompare(time, user_time) >= 0; // time >= user_time } // basically the same like allowClientActivation(), this time allowing // a window to be fully raised upon its own request (XRaiseWindow), // if refused, it will be raised only on top of windows belonging // to the same application bool Workspace::allowFullClientRaising(const KWin::AbstractClient *c, xcb_timestamp_t time) { int level = c->rules()->checkFSP(options->focusStealingPreventionLevel()); if (session_saving && level <= 2) { // <= normal return true; } AbstractClient* ac = mostRecentlyActivatedClient(); if (level == 0) // none return true; if (level == 4) // extreme return false; if (ac == NULL || ac->isDesktop()) { qCDebug(KWIN_CORE) << "Raising: No client active, allowing"; return true; // no active client -> always allow } // TODO window urgency -> return true? if (AbstractClient::belongToSameApplication(c, ac, AbstractClient::SameApplicationCheck::RelaxedForActive)) { qCDebug(KWIN_CORE) << "Raising: Belongs to active application"; return true; } if (level == 3) // high return false; xcb_timestamp_t user_time = ac->userTime(); qCDebug(KWIN_CORE) << "Raising, compared:" << time << ":" << user_time << ":" << (NET::timestampCompare(time, user_time) >= 0); return NET::timestampCompare(time, user_time) >= 0; // time >= user_time } // called from Client after FocusIn that wasn't initiated by KWin and the client // wasn't allowed to activate void Workspace::restoreFocus() { // this updateXTime() is necessary - as FocusIn events don't have // a timestamp *sigh*, kwin's timestamp would be older than the timestamp // that was used by whoever caused the focus change, and therefore // the attempt to restore the focus would fail due to old timestamp updateXTime(); if (should_get_focus.count() > 0) requestFocus(should_get_focus.last()); else if (last_active_client) requestFocus(last_active_client); } void Workspace::clientAttentionChanged(AbstractClient* c, bool set) { if (set) { attention_chain.removeAll(c); attention_chain.prepend(c); } else attention_chain.removeAll(c); emit clientDemandsAttentionChanged(c, set); } //******************************************** // Client //******************************************** /** * Updates the user time (time of last action in the active window). * This is called inside kwin for every action with the window * that qualifies for user interaction (clicking on it, activate it * externally, etc.). - **/ + */ void Client::updateUserTime(xcb_timestamp_t time) { // copied in Group::updateUserTime if (time == XCB_TIME_CURRENT_TIME) { updateXTime(); time = xTime(); } if (time != -1U && (m_userTime == XCB_TIME_CURRENT_TIME || NET::timestampCompare(time, m_userTime) > 0)) { // time > user_time m_userTime = time; shade_below = NULL; // do not hover re-shade a window after it got interaction } group()->updateUserTime(m_userTime); } xcb_timestamp_t Client::readUserCreationTime() const { Xcb::Property prop(false, window(), atoms->kde_net_wm_user_creation_time, XCB_ATOM_CARDINAL, 0, 1); return prop.value(-1); } xcb_timestamp_t Client::readUserTimeMapTimestamp(const KStartupInfoId *asn_id, const KStartupInfoData *asn_data, bool session) const { xcb_timestamp_t time = info->userTime(); //qDebug() << "User timestamp, initial:" << time; //^^ this deadlocks kwin --replace sometimes. // newer ASN timestamp always replaces user timestamp, unless user timestamp is 0 // helps e.g. with konqy reusing if (asn_data != NULL && time != 0) { if (asn_id->timestamp() != 0 && (time == -1U || NET::timestampCompare(asn_id->timestamp(), time) > 0)) { time = asn_id->timestamp(); } } qCDebug(KWIN_CORE) << "User timestamp, ASN:" << time; if (time == -1U) { // The window doesn't have any timestamp. // If it's the first window for its application // (i.e. there's no other window from the same app), // use the _KDE_NET_WM_USER_CREATION_TIME trick. // Otherwise, refuse activation of a window // from already running application if this application // is not the active one (unless focus stealing prevention is turned off). Client* act = dynamic_cast(workspace()->mostRecentlyActivatedClient()); if (act != NULL && !belongToSameApplication(act, this, SameApplicationCheck::RelaxedForActive)) { bool first_window = true; auto sameApplicationActiveHackPredicate = [this](const Client *cl) { // ignore already existing splashes, toolbars, utilities and menus, // as the app may show those before the main window return !cl->isSplash() && !cl->isToolbar() && !cl->isUtility() && !cl->isMenu() && cl != this && Client::belongToSameApplication(cl, this, SameApplicationCheck::RelaxedForActive); }; if (isTransient()) { auto clientMainClients = [this] () -> ClientList { ClientList ret; const auto mcs = mainClients(); for (auto mc: mcs) { if (Client *c = dynamic_cast(mc)) { ret << c; } } return ret; }; if (act->hasTransient(this, true)) ; // is transient for currently active window, even though it's not // the same app (e.g. kcookiejar dialog) -> allow activation else if (groupTransient() && findInList(clientMainClients(), sameApplicationActiveHackPredicate) == NULL) ; // standalone transient else first_window = false; } else { if (workspace()->findClient(sameApplicationActiveHackPredicate)) first_window = false; } // don't refuse if focus stealing prevention is turned off if (!first_window && rules()->checkFSP(options->focusStealingPreventionLevel()) > 0) { qCDebug(KWIN_CORE) << "User timestamp, already exists:" << 0; return 0; // refuse activation } } // Creation time would just mess things up during session startup, // as possibly many apps are started up at the same time. // If there's no active window yet, no timestamp will be needed, // as plain Workspace::allowClientActivation() will return true // in such case. And if there's already active window, // it's better not to activate the new one. // Unless it was the active window at the time // of session saving and there was no user interaction yet, // this check will be done in manage(). if (session) return -1U; time = readUserCreationTime(); } qCDebug(KWIN_CORE) << "User timestamp, final:" << this << ":" << time; return time; } xcb_timestamp_t Client::userTime() const { xcb_timestamp_t time = m_userTime; if (time == 0) // doesn't want focus after showing return 0; assert(group() != NULL); if (time == -1U || (group()->userTime() != -1U && NET::timestampCompare(group()->userTime(), time) > 0)) time = group()->userTime(); return time; } void Client::doSetActive() { updateUrgency(); // demand attention again if it's still urgent info->setState(isActive() ? NET::Focused : NET::States(), NET::Focused); } void Client::startupIdChanged() { KStartupInfoId asn_id; KStartupInfoData asn_data; bool asn_valid = workspace()->checkStartupNotification(window(), asn_id, asn_data); if (!asn_valid) return; // If the ASN contains desktop, move it to the desktop, otherwise move it to the current // desktop (since the new ASN should make the window act like if it's a new application // launched). However don't affect the window's desktop if it's set to be on all desktops. int desktop = VirtualDesktopManager::self()->current(); if (asn_data.desktop() != 0) desktop = asn_data.desktop(); if (!isOnAllDesktops()) workspace()->sendClientToDesktop(this, desktop, true); if (asn_data.xinerama() != -1) workspace()->sendClientToScreen(this, asn_data.xinerama()); Time timestamp = asn_id.timestamp(); if (timestamp != 0) { bool activate = workspace()->allowClientActivation(this, timestamp); if (asn_data.desktop() != 0 && !isOnCurrentDesktop()) activate = false; // it was started on different desktop than current one if (activate) workspace()->activateClient(this); else demandAttention(); } } void Client::updateUrgency() { if (info->urgency()) demandAttention(); } //**************************************** // Group //**************************************** void Group::startupIdChanged() { KStartupInfoId asn_id; KStartupInfoData asn_data; bool asn_valid = workspace()->checkStartupNotification(leader_wid, asn_id, asn_data); if (!asn_valid) return; if (asn_id.timestamp() != 0 && user_time != -1U && NET::timestampCompare(asn_id.timestamp(), user_time) > 0) { user_time = asn_id.timestamp(); } } void Group::updateUserTime(xcb_timestamp_t time) { // copy of Client::updateUserTime if (time == XCB_CURRENT_TIME) { updateXTime(); time = xTime(); } if (time != -1U && (user_time == XCB_CURRENT_TIME || NET::timestampCompare(time, user_time) > 0)) // time > user_time user_time = time; } } // namespace diff --git a/activities.h b/activities.h index 5be842c28..af97787bc 100644 --- a/activities.h +++ b/activities.h @@ -1,129 +1,129 @@ /******************************************************************** 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_ACTIVITIES_H #define KWIN_ACTIVITIES_H #include #include #include #include namespace KActivities { class Controller; } namespace KWin { class Client; class KWIN_EXPORT Activities : public QObject { Q_OBJECT public: ~Activities() override; bool stop(const QString &id); bool start(const QString &id); void setCurrent(const QString &activity); /** * Adds/removes client \a c to/from \a activity. * * Takes care of transients as well. - **/ + */ void toggleClientOnActivity(Client* c, const QString &activity, bool dont_activate); QStringList running() const; QStringList all() const; const QString ¤t() const; const QString &previous() const; static QString nullUuid(); KActivities::Controller::ServiceStatus serviceStatus() const; Q_SIGNALS: /** * This signal is emitted when the global * activity is changed * @param id id of the new current activity - **/ + */ void currentChanged(const QString &id); /** * This signal is emitted when a new activity is added * @param id id of the new activity - **/ + */ void added(const QString &id); /** * This signal is emitted when the activity * is removed * @param id id of the removed activity - **/ + */ void removed(const QString &id); private Q_SLOTS: void slotRemoved(const QString &activity); void slotCurrentChanged(const QString &newActivity); void reallyStop(const QString &id); //dbus deadlocks suck private: QString m_previous; QString m_current; KActivities::Controller *m_controller; KWIN_SINGLETON(Activities) }; inline QStringList Activities::all() const { return m_controller->activities(); } inline const QString &Activities::current() const { return m_current; } inline const QString &Activities::previous() const { return m_previous; } inline QStringList Activities::running() const { return m_controller->activities(KActivities::Info::Running); } inline QString Activities::nullUuid() { // cloned from kactivities/src/lib/core/consumer.cpp return QStringLiteral("00000000-0000-0000-0000-000000000000"); } } #endif // KWIN_ACTIVITIES_H diff --git a/atoms.h b/atoms.h index 74e0fdc61..cb1bd60b4 100644 --- a/atoms.h +++ b/atoms.h @@ -1,111 +1,111 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak 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_ATOMS_H #define KWIN_ATOMS_H #include "xcbutils.h" namespace KWin { class KWIN_EXPORT Atoms { public: Atoms(); Xcb::Atom kwin_running; Xcb::Atom activities; Xcb::Atom wm_protocols; Xcb::Atom wm_delete_window; Xcb::Atom wm_take_focus; Xcb::Atom wm_change_state; Xcb::Atom wm_client_leader; Xcb::Atom wm_window_role; Xcb::Atom wm_state; Xcb::Atom sm_client_id; Xcb::Atom motif_wm_hints; Xcb::Atom net_wm_context_help; Xcb::Atom net_wm_ping; Xcb::Atom net_wm_user_time; Xcb::Atom kde_net_wm_user_creation_time; Xcb::Atom net_wm_take_activity; Xcb::Atom net_wm_window_opacity; Xcb::Atom xdnd_selection; Xcb::Atom xdnd_aware; Xcb::Atom xdnd_enter; Xcb::Atom xdnd_type_list; Xcb::Atom xdnd_position; Xcb::Atom xdnd_status; Xcb::Atom xdnd_action_copy; Xcb::Atom xdnd_action_move; Xcb::Atom xdnd_action_ask; Xcb::Atom xdnd_drop; Xcb::Atom xdnd_leave; Xcb::Atom xdnd_finished; Xcb::Atom net_frame_extents; Xcb::Atom kde_net_wm_frame_strut; Xcb::Atom net_wm_sync_request_counter; Xcb::Atom net_wm_sync_request; Xcb::Atom kde_net_wm_shadow; Xcb::Atom kde_net_wm_tab_group; Xcb::Atom kde_first_in_window_list; Xcb::Atom kde_color_sheme; Xcb::Atom kde_skip_close_animation; Xcb::Atom kde_screen_edge_show; Xcb::Atom gtk_frame_extents; Xcb::Atom kwin_dbus_service; Xcb::Atom utf8_string; Xcb::Atom text; Xcb::Atom uri_list; Xcb::Atom netscape_url; Xcb::Atom moz_url; Xcb::Atom wl_surface_id; Xcb::Atom kde_net_wm_appmenu_service_name; Xcb::Atom kde_net_wm_appmenu_object_path; Xcb::Atom clipboard; Xcb::Atom timestamp; Xcb::Atom targets; Xcb::Atom delete_atom; Xcb::Atom incr; Xcb::Atom wl_selection; /** * @internal - **/ + */ void retrieveHelpers(); private: // helper atoms we need to resolve to "announce" support (see #172028) Xcb::Atom m_dtSmWindowInfo; Xcb::Atom m_motifSupport; bool m_helpersRetrieved; }; extern KWIN_EXPORT Atoms* atoms; } // namespace #endif diff --git a/autotests/integration/kwin_wayland_test.h b/autotests/integration/kwin_wayland_test.h index 5ecdc3be2..310bf5282 100644 --- a/autotests/integration/kwin_wayland_test.h +++ b/autotests/integration/kwin_wayland_test.h @@ -1,256 +1,256 @@ /******************************************************************** 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_WAYLAND_TEST_H #define KWIN_WAYLAND_TEST_H #include "../../main.h" // Qt #include // KWayland #include namespace KWayland { namespace Client { class AppMenuManager; class ConnectionThread; class Compositor; class IdleInhibitManager; class PlasmaShell; class PlasmaWindowManagement; class PointerConstraints; class Seat; class ServerSideDecorationManager; class ShadowManager; class Shell; class ShellSurface; class ShmPool; class SubCompositor; class SubSurface; class Surface; class XdgDecorationManager; } } namespace KWin { namespace Xwl { class Xwayland; } class AbstractClient; class ShellClient; class WaylandTestApplication : public ApplicationWaylandAbstract { Q_OBJECT public: WaylandTestApplication(OperationMode mode, int &argc, char **argv); ~WaylandTestApplication() override; protected: void performStartup() override; private: void createBackend(); void continueStartupWithScreens(); void continueStartupWithScene(); void finalizeStartup(); Xwl::Xwayland *m_xwayland = nullptr; }; namespace Test { enum class AdditionalWaylandInterface { Seat = 1 << 0, Decoration = 1 << 1, PlasmaShell = 1 << 2, WindowManagement = 1 << 3, PointerConstraints = 1 << 4, IdleInhibition = 1 << 5, AppMenu = 1 << 6, ShadowManager = 1 << 7, XdgDecoration = 1 << 8, }; Q_DECLARE_FLAGS(AdditionalWaylandInterfaces, AdditionalWaylandInterface) /** * Creates a Wayland Connection in a dedicated thread and creates various * client side objects which can be used to create windows. * @returns @c true if created successfully, @c false if there was an error * @see destroyWaylandConnection - **/ + */ bool setupWaylandConnection(AdditionalWaylandInterfaces flags = AdditionalWaylandInterfaces()); /** * Destroys the Wayland Connection created with @link{setupWaylandConnection}. * This can be called from cleanup in order to ensure that no Wayland Connection * leaks into the next test method. * @see setupWaylandConnection */ void destroyWaylandConnection(); KWayland::Client::ConnectionThread *waylandConnection(); KWayland::Client::Compositor *waylandCompositor(); KWayland::Client::SubCompositor *waylandSubCompositor(); KWayland::Client::ShadowManager *waylandShadowManager(); KWayland::Client::Shell *waylandShell(); KWayland::Client::ShmPool *waylandShmPool(); KWayland::Client::Seat *waylandSeat(); KWayland::Client::ServerSideDecorationManager *waylandServerSideDecoration(); KWayland::Client::PlasmaShell *waylandPlasmaShell(); KWayland::Client::PlasmaWindowManagement *waylandWindowManagement(); KWayland::Client::PointerConstraints *waylandPointerConstraints(); KWayland::Client::IdleInhibitManager *waylandIdleInhibitManager(); KWayland::Client::AppMenuManager *waylandAppMenuManager(); KWayland::Client::XdgDecorationManager *xdgDecorationManager(); bool waitForWaylandPointer(); bool waitForWaylandTouch(); bool waitForWaylandKeyboard(); void flushWaylandConnection(); KWayland::Client::Surface *createSurface(QObject *parent = nullptr); KWayland::Client::SubSurface *createSubSurface(KWayland::Client::Surface *surface, KWayland::Client::Surface *parentSurface, QObject *parent = nullptr); enum class ShellSurfaceType { WlShell, XdgShellV5, XdgShellV6, XdgShellStable }; enum class CreationSetup { CreateOnly, CreateAndConfigure, /// commit and wait for the configure event, making this surface ready to commit buffers }; /** * Creates either a ShellSurface * or XdgShellSurface * as defined by @arg type * For XDG top levels this method will block for a configure event, make this surface ready to commit buffers */ QObject *createShellSurface(ShellSurfaceType type, KWayland::Client::Surface *surface, QObject *parent = nullptr); KWayland::Client::XdgShellSurface *createXdgShellSurface(ShellSurfaceType type, KWayland::Client::Surface *surface, QObject *parent = nullptr, CreationSetup creationSetup = CreationSetup::CreateAndConfigure); KWayland::Client::ShellSurface *createShellSurface(KWayland::Client::Surface *surface, QObject *parent = nullptr); KWayland::Client::XdgShellSurface *createXdgShellV5Surface(KWayland::Client::Surface *surface, QObject *parent = nullptr, CreationSetup = CreationSetup::CreateAndConfigure); KWayland::Client::XdgShellSurface *createXdgShellV6Surface(KWayland::Client::Surface *surface, QObject *parent = nullptr, CreationSetup = CreationSetup::CreateAndConfigure); KWayland::Client::XdgShellSurface *createXdgShellStableSurface(KWayland::Client::Surface *surface, QObject *parent = nullptr, CreationSetup = CreationSetup::CreateAndConfigure); KWayland::Client::XdgShellPopup *createXdgShellStablePopup(KWayland::Client::Surface *surface, KWayland::Client::XdgShellSurface *parentSurface, const KWayland::Client::XdgPositioner &positioner, QObject *parent = nullptr, CreationSetup = CreationSetup::CreateAndConfigure); /** * Commits the XdgShellSurface to the given surface, and waits for the configure event from the compositor */ void initXdgShellSurface(KWayland::Client::Surface *surface, KWayland::Client::XdgShellSurface *shellSurface); void initXdgShellPopup(KWayland::Client::Surface *surface, KWayland::Client::XdgShellPopup *popup); /** * Creates a shared memory buffer of @p size in @p color and attaches it to the @p surface. * The @p surface gets damaged and committed, thus it's rendered. - **/ + */ void render(KWayland::Client::Surface *surface, const QSize &size, const QColor &color, const QImage::Format &format = QImage::Format_ARGB32_Premultiplied); /** * Creates a shared memory buffer using the supplied image @p img and attaches it to the @p surface */ void render(KWayland::Client::Surface *surface, const QImage &img); /** * Waits till a new ShellClient is shown and returns the created ShellClient. * If no ShellClient gets shown during @p timeout @c null is returned. - **/ + */ ShellClient *waitForWaylandWindowShown(int timeout = 5000); /** * Combination of @link{render} and @link{waitForWaylandWindowShown}. - **/ + */ ShellClient *renderAndWaitForShown(KWayland::Client::Surface *surface, const QSize &size, const QColor &color, const QImage::Format &format = QImage::Format_ARGB32, int timeout = 5000); /** * Waits for the @p client to be destroyed. - **/ + */ bool waitForWindowDestroyed(AbstractClient *client); /** * Locks the screen and waits till the screen is locked. * @returns @c true if the screen could be locked, @c false otherwise - **/ + */ bool lockScreen(); /** * Unlocks the screen and waits till the screen is unlocked. * @returns @c true if the screen could be unlocked, @c false otherwise - **/ + */ bool unlockScreen(); } } Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::Test::AdditionalWaylandInterfaces) Q_DECLARE_METATYPE(KWin::Test::ShellSurfaceType) #define WAYLANDTEST_MAIN_HELPER(TestObject, DPI, OperationMode) \ int main(int argc, char *argv[]) \ { \ setenv("QT_QPA_PLATFORM", "wayland-org.kde.kwin.qpa", true); \ setenv("QT_QPA_PLATFORM_PLUGIN_PATH", QFileInfo(QString::fromLocal8Bit(argv[0])).absolutePath().toLocal8Bit().constData(), true); \ setenv("KWIN_FORCE_OWN_QPA", "1", true); \ qunsetenv("KDE_FULL_SESSION"); \ qunsetenv("KDE_SESSION_VERSION"); \ qunsetenv("XDG_SESSION_DESKTOP"); \ qunsetenv("XDG_CURRENT_DESKTOP"); \ DPI; \ KWin::WaylandTestApplication app(OperationMode, argc, argv); \ app.setAttribute(Qt::AA_Use96Dpi, true); \ TestObject tc; \ return QTest::qExec(&tc, argc, argv); \ } #ifdef NO_XWAYLAND #define WAYLANDTEST_MAIN(TestObject) WAYLANDTEST_MAIN_HELPER(TestObject, QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps), KWin::Application::OperationModeWaylandOnly) #else #define WAYLANDTEST_MAIN(TestObject) WAYLANDTEST_MAIN_HELPER(TestObject, QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps), KWin::Application::OperationModeXwayland) #endif #endif diff --git a/autotests/integration/no_global_shortcuts_test.cpp b/autotests/integration/no_global_shortcuts_test.cpp index bcf588660..8515ce749 100644 --- a/autotests/integration/no_global_shortcuts_test.cpp +++ b/autotests/integration/no_global_shortcuts_test.cpp @@ -1,285 +1,285 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2018 Martin Flöser 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 . *********************************************************************/ #include "kwin_wayland_test.h" #include "cursor.h" #include "input.h" #include "keyboard_input.h" #include "platform.h" #include "screenedge.h" #include "screens.h" #include "wayland_server.h" #include "workspace.h" #include #include #include #include using namespace KWin; using namespace KWayland::Client; static const QString s_socketName = QStringLiteral("wayland_test_kwin_no_global_shortcuts-0"); static const QString s_serviceName = QStringLiteral("org.kde.KWin.Test.ModifierOnlyShortcut"); static const QString s_path = QStringLiteral("/Test"); Q_DECLARE_METATYPE(KWin::ElectricBorder) /** * This test verifies the NoGlobalShortcuts initialization flag - **/ + */ class NoGlobalShortcutsTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testTrigger_data(); void testTrigger(); void testKGlobalAccel(); void testPointerShortcut(); void testAxisShortcut_data(); void testAxisShortcut(); void testScreenEdge(); }; class Target : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KWin.Test.ModifierOnlyShortcut") public: Target(); ~Target() override; public Q_SLOTS: Q_SCRIPTABLE void shortcut(); Q_SIGNALS: void shortcutTriggered(); }; Target::Target() : QObject() { QDBusConnection::sessionBus().registerService(s_serviceName); QDBusConnection::sessionBus().registerObject(s_path, s_serviceName, this, QDBusConnection::ExportScriptableSlots); } Target::~Target() { QDBusConnection::sessionBus().unregisterObject(s_path); QDBusConnection::sessionBus().unregisterService(s_serviceName); } void Target::shortcut() { emit shortcutTriggered(); } void NoGlobalShortcutsTest::initTestCase() { qRegisterMetaType("ElectricBorder"); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit(), KWin::WaylandServer::InitalizationFlag::NoGlobalShortcuts)); kwinApp()->setConfig(KSharedConfig::openConfig(QString(), KConfig::SimpleConfig)); qputenv("KWIN_XKB_DEFAULT_KEYMAP", "1"); qputenv("XKB_DEFAULT_RULES", "evdev"); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); } void NoGlobalShortcutsTest::init() { screens()->setCurrent(0); KWin::Cursor::setPos(QPoint(640, 512)); } void NoGlobalShortcutsTest::cleanup() { } void NoGlobalShortcutsTest::testTrigger_data() { QTest::addColumn("metaConfig"); QTest::addColumn("altConfig"); QTest::addColumn("controlConfig"); QTest::addColumn("shiftConfig"); QTest::addColumn("modifier"); QTest::addColumn>("nonTriggeringMods"); const QStringList trigger = QStringList{s_serviceName, s_path, s_serviceName, QStringLiteral("shortcut")}; const QStringList e = QStringList(); QTest::newRow("leftMeta") << trigger << e << e << e << KEY_LEFTMETA << QList{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("rightMeta") << trigger << e << e << e << KEY_RIGHTMETA << QList{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("leftAlt") << e << trigger << e << e << KEY_LEFTALT << QList{KEY_LEFTMETA, KEY_RIGHTMETA, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("rightAlt") << e << trigger << e << e << KEY_RIGHTALT << QList{KEY_LEFTMETA, KEY_RIGHTMETA, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("leftControl") << e << e << trigger << e << KEY_LEFTCTRL << QList{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTMETA, KEY_RIGHTMETA, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("rightControl") << e << e << trigger << e << KEY_RIGHTCTRL << QList{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTMETA, KEY_RIGHTMETA, KEY_LEFTSHIFT, KEY_RIGHTSHIFT}; QTest::newRow("leftShift") << e << e << e << trigger << KEY_LEFTSHIFT << QList{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTMETA, KEY_RIGHTMETA}; QTest::newRow("rightShift") << e << e << e << trigger <{KEY_LEFTALT, KEY_RIGHTALT, KEY_LEFTCTRL, KEY_RIGHTCTRL, KEY_LEFTMETA, KEY_RIGHTMETA}; } void NoGlobalShortcutsTest::testTrigger() { // test based on ModifierOnlyShortcutTest::testTrigger Target target; QSignalSpy triggeredSpy(&target, &Target::shortcutTriggered); QVERIFY(triggeredSpy.isValid()); KConfigGroup group = kwinApp()->config()->group("ModifierOnlyShortcuts"); QFETCH(QStringList, metaConfig); QFETCH(QStringList, altConfig); QFETCH(QStringList, shiftConfig); QFETCH(QStringList, controlConfig); group.writeEntry("Meta", metaConfig); group.writeEntry("Alt", altConfig); group.writeEntry("Shift", shiftConfig); group.writeEntry("Control", controlConfig); group.sync(); workspace()->slotReconfigure(); // configured shortcut should trigger quint32 timestamp = 1; QFETCH(int, modifier); kwinApp()->platform()->keyboardKeyPressed(modifier, timestamp++); kwinApp()->platform()->keyboardKeyReleased(modifier, timestamp++); QCOMPARE(triggeredSpy.count(), 0); // the other shortcuts should not trigger QFETCH(QList, nonTriggeringMods); for (auto it = nonTriggeringMods.constBegin(), end = nonTriggeringMods.constEnd(); it != end; it++) { kwinApp()->platform()->keyboardKeyPressed(*it, timestamp++); kwinApp()->platform()->keyboardKeyReleased(*it, timestamp++); QCOMPARE(triggeredSpy.count(), 0); } } void NoGlobalShortcutsTest::testKGlobalAccel() { QScopedPointer action(new QAction(nullptr)); action->setProperty("componentName", QStringLiteral(KWIN_NAME)); action->setObjectName(QStringLiteral("globalshortcuts-test-meta-shift-w")); QSignalSpy triggeredSpy(action.data(), &QAction::triggered); QVERIFY(triggeredSpy.isValid()); KGlobalAccel::self()->setShortcut(action.data(), QList{Qt::META + Qt::SHIFT + Qt::Key_W}, KGlobalAccel::NoAutoloading); input()->registerShortcut(Qt::META + Qt::SHIFT + Qt::Key_W, action.data()); // press meta+shift+w quint32 timestamp = 0; kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTMETA, timestamp++); QCOMPARE(input()->keyboardModifiers(), Qt::MetaModifier); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTSHIFT, timestamp++); QCOMPARE(input()->keyboardModifiers(), Qt::ShiftModifier | Qt::MetaModifier); kwinApp()->platform()->keyboardKeyPressed(KEY_W, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_W, timestamp++); // release meta+shift kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTSHIFT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTMETA, timestamp++); QVERIFY(!triggeredSpy.wait()); QCOMPARE(triggeredSpy.count(), 0); } void NoGlobalShortcutsTest::testPointerShortcut() { // based on LockScreenTest::testPointerShortcut QScopedPointer action(new QAction(nullptr)); QSignalSpy actionSpy(action.data(), &QAction::triggered); QVERIFY(actionSpy.isValid()); input()->registerPointerShortcut(Qt::MetaModifier, Qt::LeftButton, action.data()); // try to trigger the shortcut quint32 timestamp = 1; kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTMETA, timestamp++); kwinApp()->platform()->pointerButtonPressed(BTN_LEFT, timestamp++); QCoreApplication::instance()->processEvents(); QCOMPARE(actionSpy.count(), 0); kwinApp()->platform()->pointerButtonReleased(BTN_LEFT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTMETA, timestamp++); QCoreApplication::instance()->processEvents(); QCOMPARE(actionSpy.count(), 0); } void NoGlobalShortcutsTest::testAxisShortcut_data() { QTest::addColumn("direction"); QTest::addColumn("sign"); QTest::newRow("up") << Qt::Vertical << 1; QTest::newRow("down") << Qt::Vertical << -1; QTest::newRow("left") << Qt::Horizontal << 1; QTest::newRow("right") << Qt::Horizontal << -1; } void NoGlobalShortcutsTest::testAxisShortcut() { // based on LockScreenTest::testAxisShortcut QScopedPointer action(new QAction(nullptr)); QSignalSpy actionSpy(action.data(), &QAction::triggered); QVERIFY(actionSpy.isValid()); QFETCH(Qt::Orientation, direction); QFETCH(int, sign); PointerAxisDirection axisDirection = PointerAxisUp; if (direction == Qt::Vertical) { axisDirection = sign > 0 ? PointerAxisUp : PointerAxisDown; } else { axisDirection = sign > 0 ? PointerAxisLeft : PointerAxisRight; } input()->registerAxisShortcut(Qt::MetaModifier, axisDirection, action.data()); // try to trigger the shortcut quint32 timestamp = 1; kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTMETA, timestamp++); if (direction == Qt::Vertical) kwinApp()->platform()->pointerAxisVertical(sign * 5.0, timestamp++); else kwinApp()->platform()->pointerAxisHorizontal(sign * 5.0, timestamp++); QCoreApplication::instance()->processEvents(); QCOMPARE(actionSpy.count(), 0); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTMETA, timestamp++); QCoreApplication::instance()->processEvents(); QCOMPARE(actionSpy.count(), 0); } void NoGlobalShortcutsTest::testScreenEdge() { // based on LockScreenTest::testScreenEdge QSignalSpy screenEdgeSpy(ScreenEdges::self(), &ScreenEdges::approaching); QVERIFY(screenEdgeSpy.isValid()); QCOMPARE(screenEdgeSpy.count(), 0); quint32 timestamp = 1; kwinApp()->platform()->pointerMotion({5, 5}, timestamp++); QCOMPARE(screenEdgeSpy.count(), 0); } WAYLANDTEST_MAIN(NoGlobalShortcutsTest) #include "no_global_shortcuts_test.moc" diff --git a/autotests/tabbox/test_tabbox_clientmodel.h b/autotests/tabbox/test_tabbox_clientmodel.h index 35390a9c9..68ab84be8 100644 --- a/autotests/tabbox/test_tabbox_clientmodel.h +++ b/autotests/tabbox/test_tabbox_clientmodel.h @@ -1,53 +1,53 @@ /******************************************************************** 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 TEST_TABBOX_CLIENT_MODEL_H #define TEST_TABBOX_CLIENT_MODEL_H #include class TestTabBoxClientModel : public QObject { Q_OBJECT private slots: void initTestCase(); /** * Tests that calculating the longest caption does not * crash in case the internal m_clientList contains a weak * pointer to a deleted TabBoxClient. * * See bug #303840 - **/ + */ void testLongestCaptionWithNullClient(); /** * Tests the creation of the Client list for the case that * there is no active Client, but that Clients actually exist. * * See BUG: 305449 - **/ + */ void testCreateClientListNoActiveClient(); /** * Tests the creation of the Client list for the case that * the active Client is not in the Focus chain. * * See BUG: 306260 - **/ + */ void testCreateClientListActiveClientNotInFocusChain(); }; #endif diff --git a/autotests/tabbox/test_tabbox_handler.cpp b/autotests/tabbox/test_tabbox_handler.cpp index e1bdf8840..3013d8786 100644 --- a/autotests/tabbox/test_tabbox_handler.cpp +++ b/autotests/tabbox/test_tabbox_handler.cpp @@ -1,63 +1,63 @@ /******************************************************************** 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 . *********************************************************************/ #include "mock_tabboxhandler.h" #include "clientmodel.h" #include "../testutils.h" #include #include using namespace KWin; class TestTabBoxHandler : public QObject { Q_OBJECT private slots: void initTestCase(); /** * Test to verify that update outline does not crash * if the ModelIndex for which the outline should be * shown is not valid. That is accessing the Pointer * to the Client returns an invalid QVariant. * BUG: 304620 - **/ + */ void testDontCrashUpdateOutlineNullClient(); }; void TestTabBoxHandler::initTestCase() { qApp->setProperty("x11Connection", QVariant::fromValue(QX11Info::connection())); } void TestTabBoxHandler::testDontCrashUpdateOutlineNullClient() { MockTabBoxHandler tabboxhandler; TabBox::TabBoxConfig config; config.setTabBoxMode(TabBox::TabBoxConfig::ClientTabBox); config.setShowTabBox(false); config.setHighlightWindows(false); tabboxhandler.setConfig(config); // now show the tabbox which will attempt to show the outline tabboxhandler.show(); } Q_CONSTRUCTOR_FUNCTION(forceXcb) QTEST_MAIN(TestTabBoxHandler) #include "test_tabbox_handler.moc" diff --git a/autotests/test_xkb.cpp b/autotests/test_xkb.cpp index 7714f0995..9104ffe66 100644 --- a/autotests/test_xkb.cpp +++ b/autotests/test_xkb.cpp @@ -1,513 +1,513 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 Martin Flöser 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 . *********************************************************************/ #include "../xkb.h" #include #include using namespace KWin; class XkbTest : public QObject { Q_OBJECT private Q_SLOTS: void testToQtKey_data(); void testToQtKey(); void testFromQtKey_data(); void testFromQtKey(); }; // from kwindowsystem/src/platforms/xcb/kkeyserver.cpp // adjusted to xkb struct TransKey { Qt::Key keySymQt; xkb_keysym_t keySymX; Qt::KeyboardModifiers modifiers; }; static const TransKey g_rgQtToSymX[] = { { Qt::Key_Escape, XKB_KEY_Escape, Qt::KeyboardModifiers() }, { Qt::Key_Tab, XKB_KEY_Tab, Qt::KeyboardModifiers() }, { Qt::Key_Backtab, XKB_KEY_ISO_Left_Tab, Qt::KeyboardModifiers() }, { Qt::Key_Backspace, XKB_KEY_BackSpace, Qt::KeyboardModifiers() }, { Qt::Key_Return, XKB_KEY_Return, Qt::KeyboardModifiers() }, { Qt::Key_Insert, XKB_KEY_Insert, Qt::KeyboardModifiers() }, { Qt::Key_Delete, XKB_KEY_Delete, Qt::KeyboardModifiers() }, { Qt::Key_Pause, XKB_KEY_Pause, Qt::KeyboardModifiers() }, { Qt::Key_Print, XKB_KEY_Print, Qt::KeyboardModifiers() }, { Qt::Key_SysReq, XKB_KEY_Sys_Req, Qt::KeyboardModifiers() }, { Qt::Key_Home, XKB_KEY_Home, Qt::KeyboardModifiers() }, { Qt::Key_End, XKB_KEY_End, Qt::KeyboardModifiers() }, { Qt::Key_Left, XKB_KEY_Left, Qt::KeyboardModifiers() }, { Qt::Key_Up, XKB_KEY_Up, Qt::KeyboardModifiers() }, { Qt::Key_Right, XKB_KEY_Right, Qt::KeyboardModifiers() }, { Qt::Key_Down, XKB_KEY_Down, Qt::KeyboardModifiers() }, { Qt::Key_PageUp, XKB_KEY_Prior, Qt::KeyboardModifiers() }, { Qt::Key_PageDown, XKB_KEY_Next, Qt::KeyboardModifiers() }, { Qt::Key_CapsLock, XKB_KEY_Caps_Lock, Qt::KeyboardModifiers() }, { Qt::Key_NumLock, XKB_KEY_Num_Lock, Qt::KeyboardModifiers() }, { Qt::Key_ScrollLock, XKB_KEY_Scroll_Lock, Qt::KeyboardModifiers() }, { Qt::Key_F1, XKB_KEY_F1, Qt::KeyboardModifiers() }, { Qt::Key_F2, XKB_KEY_F2, Qt::KeyboardModifiers() }, { Qt::Key_F3, XKB_KEY_F3, Qt::KeyboardModifiers() }, { Qt::Key_F4, XKB_KEY_F4, Qt::KeyboardModifiers() }, { Qt::Key_F5, XKB_KEY_F5, Qt::KeyboardModifiers() }, { Qt::Key_F6, XKB_KEY_F6, Qt::KeyboardModifiers() }, { Qt::Key_F7, XKB_KEY_F7, Qt::KeyboardModifiers() }, { Qt::Key_F8, XKB_KEY_F8, Qt::KeyboardModifiers() }, { Qt::Key_F9, XKB_KEY_F9, Qt::KeyboardModifiers() }, { Qt::Key_F10, XKB_KEY_F10, Qt::KeyboardModifiers() }, { Qt::Key_F11, XKB_KEY_F11, Qt::KeyboardModifiers() }, { Qt::Key_F12, XKB_KEY_F12, Qt::KeyboardModifiers() }, { Qt::Key_F13, XKB_KEY_F13, Qt::KeyboardModifiers() }, { Qt::Key_F14, XKB_KEY_F14, Qt::KeyboardModifiers() }, { Qt::Key_F15, XKB_KEY_F15, Qt::KeyboardModifiers() }, { Qt::Key_F16, XKB_KEY_F16, Qt::KeyboardModifiers() }, { Qt::Key_F17, XKB_KEY_F17, Qt::KeyboardModifiers() }, { Qt::Key_F18, XKB_KEY_F18, Qt::KeyboardModifiers() }, { Qt::Key_F19, XKB_KEY_F19, Qt::KeyboardModifiers() }, { Qt::Key_F20, XKB_KEY_F20, Qt::KeyboardModifiers() }, { Qt::Key_F21, XKB_KEY_F21, Qt::KeyboardModifiers() }, { Qt::Key_F22, XKB_KEY_F22, Qt::KeyboardModifiers() }, { Qt::Key_F23, XKB_KEY_F23, Qt::KeyboardModifiers() }, { Qt::Key_F24, XKB_KEY_F24, Qt::KeyboardModifiers() }, { Qt::Key_F25, XKB_KEY_F25, Qt::KeyboardModifiers() }, { Qt::Key_F26, XKB_KEY_F26, Qt::KeyboardModifiers() }, { Qt::Key_F27, XKB_KEY_F27, Qt::KeyboardModifiers() }, { Qt::Key_F28, XKB_KEY_F28, Qt::KeyboardModifiers() }, { Qt::Key_F29, XKB_KEY_F29, Qt::KeyboardModifiers() }, { Qt::Key_F30, XKB_KEY_F30, Qt::KeyboardModifiers() }, { Qt::Key_F31, XKB_KEY_F31, Qt::KeyboardModifiers() }, { Qt::Key_F32, XKB_KEY_F32, Qt::KeyboardModifiers() }, { Qt::Key_F33, XKB_KEY_F33, Qt::KeyboardModifiers() }, { Qt::Key_F34, XKB_KEY_F34, Qt::KeyboardModifiers() }, { Qt::Key_F35, XKB_KEY_F35, Qt::KeyboardModifiers() }, { Qt::Key_Super_L, XKB_KEY_Super_L, Qt::KeyboardModifiers() }, { Qt::Key_Super_R, XKB_KEY_Super_R, Qt::KeyboardModifiers() }, { Qt::Key_Menu, XKB_KEY_Menu, Qt::KeyboardModifiers() }, { Qt::Key_Hyper_L, XKB_KEY_Hyper_L, Qt::KeyboardModifiers() }, { Qt::Key_Hyper_R, XKB_KEY_Hyper_R, Qt::KeyboardModifiers() }, { Qt::Key_Help, XKB_KEY_Help, Qt::KeyboardModifiers() }, { Qt::Key_Space, XKB_KEY_KP_Space, Qt::KeypadModifier }, { Qt::Key_Tab, XKB_KEY_KP_Tab, Qt::KeypadModifier }, { Qt::Key_Enter, XKB_KEY_KP_Enter, Qt::KeypadModifier }, { Qt::Key_Home, XKB_KEY_KP_Home, Qt::KeypadModifier }, { Qt::Key_Left, XKB_KEY_KP_Left, Qt::KeypadModifier }, { Qt::Key_Up, XKB_KEY_KP_Up, Qt::KeypadModifier }, { Qt::Key_Right, XKB_KEY_KP_Right, Qt::KeypadModifier }, { Qt::Key_Down, XKB_KEY_KP_Down, Qt::KeypadModifier }, { Qt::Key_PageUp, XKB_KEY_KP_Prior, Qt::KeypadModifier }, { Qt::Key_PageDown, XKB_KEY_KP_Next, Qt::KeypadModifier }, { Qt::Key_End, XKB_KEY_KP_End, Qt::KeypadModifier }, { Qt::Key_Clear, XKB_KEY_KP_Begin, Qt::KeypadModifier }, { Qt::Key_Insert, XKB_KEY_KP_Insert, Qt::KeypadModifier }, { Qt::Key_Delete, XKB_KEY_KP_Delete, Qt::KeypadModifier }, { Qt::Key_Equal, XKB_KEY_KP_Equal, Qt::KeypadModifier }, { Qt::Key_Asterisk, XKB_KEY_KP_Multiply, Qt::KeypadModifier }, { Qt::Key_Plus, XKB_KEY_KP_Add, Qt::KeypadModifier }, { Qt::Key_Comma, XKB_KEY_KP_Separator, Qt::KeypadModifier }, { Qt::Key_Minus, XKB_KEY_KP_Subtract, Qt::KeypadModifier }, { Qt::Key_Period, XKB_KEY_KP_Decimal, Qt::KeypadModifier }, { Qt::Key_Slash, XKB_KEY_KP_Divide, Qt::KeypadModifier }, { Qt::Key_Back, XKB_KEY_XF86Back, Qt::KeyboardModifiers() }, { Qt::Key_Forward, XKB_KEY_XF86Forward, Qt::KeyboardModifiers() }, { Qt::Key_Stop, XKB_KEY_XF86Stop, Qt::KeyboardModifiers() }, { Qt::Key_Refresh, XKB_KEY_XF86Refresh, Qt::KeyboardModifiers() }, { Qt::Key_Favorites, XKB_KEY_XF86Favorites, Qt::KeyboardModifiers() }, { Qt::Key_LaunchMedia, XKB_KEY_XF86AudioMedia, Qt::KeyboardModifiers() }, { Qt::Key_OpenUrl, XKB_KEY_XF86OpenURL, Qt::KeyboardModifiers() }, { Qt::Key_HomePage, XKB_KEY_XF86HomePage, Qt::KeyboardModifiers() }, { Qt::Key_Search, XKB_KEY_XF86Search, Qt::KeyboardModifiers() }, { Qt::Key_VolumeDown, XKB_KEY_XF86AudioLowerVolume, Qt::KeyboardModifiers() }, { Qt::Key_VolumeMute, XKB_KEY_XF86AudioMute, Qt::KeyboardModifiers() }, { Qt::Key_VolumeUp, XKB_KEY_XF86AudioRaiseVolume, Qt::KeyboardModifiers() }, { Qt::Key_MediaPlay, XKB_KEY_XF86AudioPlay, Qt::KeyboardModifiers() }, { Qt::Key_MediaStop, XKB_KEY_XF86AudioStop, Qt::KeyboardModifiers() }, { Qt::Key_MediaPrevious, XKB_KEY_XF86AudioPrev, Qt::KeyboardModifiers() }, { Qt::Key_MediaNext, XKB_KEY_XF86AudioNext, Qt::KeyboardModifiers() }, { Qt::Key_MediaRecord, XKB_KEY_XF86AudioRecord, Qt::KeyboardModifiers() }, { Qt::Key_LaunchMail, XKB_KEY_XF86Mail, Qt::KeyboardModifiers() }, { Qt::Key_Launch0, XKB_KEY_XF86MyComputer, Qt::KeyboardModifiers() }, { Qt::Key_Launch1, XKB_KEY_XF86Calculator, Qt::KeyboardModifiers() }, { Qt::Key_Memo, XKB_KEY_XF86Memo, Qt::KeyboardModifiers() }, { Qt::Key_ToDoList, XKB_KEY_XF86ToDoList, Qt::KeyboardModifiers() }, { Qt::Key_Calendar, XKB_KEY_XF86Calendar, Qt::KeyboardModifiers() }, { Qt::Key_PowerDown, XKB_KEY_XF86PowerDown, Qt::KeyboardModifiers() }, { Qt::Key_ContrastAdjust, XKB_KEY_XF86ContrastAdjust, Qt::KeyboardModifiers() }, { Qt::Key_Standby, XKB_KEY_XF86Standby, Qt::KeyboardModifiers() }, { Qt::Key_MonBrightnessUp, XKB_KEY_XF86MonBrightnessUp, Qt::KeyboardModifiers() }, { Qt::Key_MonBrightnessDown, XKB_KEY_XF86MonBrightnessDown, Qt::KeyboardModifiers() }, { Qt::Key_KeyboardLightOnOff, XKB_KEY_XF86KbdLightOnOff, Qt::KeyboardModifiers() }, { Qt::Key_KeyboardBrightnessUp, XKB_KEY_XF86KbdBrightnessUp, Qt::KeyboardModifiers() }, { Qt::Key_KeyboardBrightnessDown, XKB_KEY_XF86KbdBrightnessDown, Qt::KeyboardModifiers() }, { Qt::Key_PowerOff, XKB_KEY_XF86PowerOff, Qt::KeyboardModifiers() }, { Qt::Key_WakeUp, XKB_KEY_XF86WakeUp, Qt::KeyboardModifiers() }, { Qt::Key_Eject, XKB_KEY_XF86Eject, Qt::KeyboardModifiers() }, { Qt::Key_ScreenSaver, XKB_KEY_XF86ScreenSaver, Qt::KeyboardModifiers() }, { Qt::Key_WWW, XKB_KEY_XF86WWW, Qt::KeyboardModifiers() }, { Qt::Key_Sleep, XKB_KEY_XF86Sleep, Qt::KeyboardModifiers() }, { Qt::Key_LightBulb, XKB_KEY_XF86LightBulb, Qt::KeyboardModifiers() }, { Qt::Key_Shop, XKB_KEY_XF86Shop, Qt::KeyboardModifiers() }, { Qt::Key_History, XKB_KEY_XF86History, Qt::KeyboardModifiers() }, { Qt::Key_AddFavorite, XKB_KEY_XF86AddFavorite, Qt::KeyboardModifiers() }, { Qt::Key_HotLinks, XKB_KEY_XF86HotLinks, Qt::KeyboardModifiers() }, { Qt::Key_BrightnessAdjust, XKB_KEY_XF86BrightnessAdjust, Qt::KeyboardModifiers() }, { Qt::Key_Finance, XKB_KEY_XF86Finance, Qt::KeyboardModifiers() }, { Qt::Key_Community, XKB_KEY_XF86Community, Qt::KeyboardModifiers() }, { Qt::Key_AudioRewind, XKB_KEY_XF86AudioRewind, Qt::KeyboardModifiers() }, { Qt::Key_BackForward, XKB_KEY_XF86BackForward, Qt::KeyboardModifiers() }, { Qt::Key_ApplicationLeft, XKB_KEY_XF86ApplicationLeft, Qt::KeyboardModifiers() }, { Qt::Key_ApplicationRight, XKB_KEY_XF86ApplicationRight, Qt::KeyboardModifiers() }, { Qt::Key_Book, XKB_KEY_XF86Book, Qt::KeyboardModifiers() }, { Qt::Key_CD, XKB_KEY_XF86CD, Qt::KeyboardModifiers() }, { Qt::Key_Calculator, XKB_KEY_XF86Calculater, Qt::KeyboardModifiers() }, { Qt::Key_Clear, XKB_KEY_XF86Clear, Qt::KeyboardModifiers() }, { Qt::Key_ClearGrab, XKB_KEY_XF86ClearGrab, Qt::KeyboardModifiers() }, { Qt::Key_Close, XKB_KEY_XF86Close, Qt::KeyboardModifiers() }, { Qt::Key_Copy, XKB_KEY_XF86Copy, Qt::KeyboardModifiers() }, { Qt::Key_Cut, XKB_KEY_XF86Cut, Qt::KeyboardModifiers() }, { Qt::Key_Display, XKB_KEY_XF86Display, Qt::KeyboardModifiers() }, { Qt::Key_DOS, XKB_KEY_XF86DOS, Qt::KeyboardModifiers() }, { Qt::Key_Documents, XKB_KEY_XF86Documents, Qt::KeyboardModifiers() }, { Qt::Key_Excel, XKB_KEY_XF86Excel, Qt::KeyboardModifiers() }, { Qt::Key_Explorer, XKB_KEY_XF86Explorer, Qt::KeyboardModifiers() }, { Qt::Key_Game, XKB_KEY_XF86Game, Qt::KeyboardModifiers() }, { Qt::Key_Go, XKB_KEY_XF86Go, Qt::KeyboardModifiers() }, { Qt::Key_iTouch, XKB_KEY_XF86iTouch, Qt::KeyboardModifiers() }, { Qt::Key_LogOff, XKB_KEY_XF86LogOff, Qt::KeyboardModifiers() }, { Qt::Key_Market, XKB_KEY_XF86Market, Qt::KeyboardModifiers() }, { Qt::Key_Meeting, XKB_KEY_XF86Meeting, Qt::KeyboardModifiers() }, { Qt::Key_MenuKB, XKB_KEY_XF86MenuKB, Qt::KeyboardModifiers() }, { Qt::Key_MenuPB, XKB_KEY_XF86MenuPB, Qt::KeyboardModifiers() }, { Qt::Key_MySites, XKB_KEY_XF86MySites, Qt::KeyboardModifiers() }, { Qt::Key_News, XKB_KEY_XF86News, Qt::KeyboardModifiers() }, { Qt::Key_OfficeHome, XKB_KEY_XF86OfficeHome, Qt::KeyboardModifiers() }, { Qt::Key_Option, XKB_KEY_XF86Option, Qt::KeyboardModifiers() }, { Qt::Key_Paste, XKB_KEY_XF86Paste, Qt::KeyboardModifiers() }, { Qt::Key_Phone, XKB_KEY_XF86Phone, Qt::KeyboardModifiers() }, { Qt::Key_Reply, XKB_KEY_XF86Reply, Qt::KeyboardModifiers() }, { Qt::Key_Reload, XKB_KEY_XF86Reload, Qt::KeyboardModifiers() }, { Qt::Key_RotateWindows, XKB_KEY_XF86RotateWindows, Qt::KeyboardModifiers() }, { Qt::Key_RotationPB, XKB_KEY_XF86RotationPB, Qt::KeyboardModifiers() }, { Qt::Key_RotationKB, XKB_KEY_XF86RotationKB, Qt::KeyboardModifiers() }, { Qt::Key_Save, XKB_KEY_XF86Save, Qt::KeyboardModifiers() }, { Qt::Key_Send, XKB_KEY_XF86Send, Qt::KeyboardModifiers() }, { Qt::Key_Spell, XKB_KEY_XF86Spell, Qt::KeyboardModifiers() }, { Qt::Key_SplitScreen, XKB_KEY_XF86SplitScreen, Qt::KeyboardModifiers() }, { Qt::Key_Support, XKB_KEY_XF86Support, Qt::KeyboardModifiers() }, { Qt::Key_TaskPane, XKB_KEY_XF86TaskPane, Qt::KeyboardModifiers() }, { Qt::Key_Terminal, XKB_KEY_XF86Terminal, Qt::KeyboardModifiers() }, { Qt::Key_Tools, XKB_KEY_XF86Tools, Qt::KeyboardModifiers() }, { Qt::Key_Travel, XKB_KEY_XF86Travel, Qt::KeyboardModifiers() }, { Qt::Key_Video, XKB_KEY_XF86Video, Qt::KeyboardModifiers() }, { Qt::Key_Word, XKB_KEY_XF86Word, Qt::KeyboardModifiers() }, { Qt::Key_Xfer, XKB_KEY_XF86Xfer, Qt::KeyboardModifiers() }, { Qt::Key_ZoomIn, XKB_KEY_XF86ZoomIn, Qt::KeyboardModifiers() }, { Qt::Key_ZoomOut, XKB_KEY_XF86ZoomOut, Qt::KeyboardModifiers() }, { Qt::Key_Away, XKB_KEY_XF86Away, Qt::KeyboardModifiers() }, { Qt::Key_Messenger, XKB_KEY_XF86Messenger, Qt::KeyboardModifiers() }, { Qt::Key_WebCam, XKB_KEY_XF86WebCam, Qt::KeyboardModifiers() }, { Qt::Key_MailForward, XKB_KEY_XF86MailForward, Qt::KeyboardModifiers() }, { Qt::Key_Pictures, XKB_KEY_XF86Pictures, Qt::KeyboardModifiers() }, { Qt::Key_Music, XKB_KEY_XF86Music, Qt::KeyboardModifiers() }, { Qt::Key_Battery, XKB_KEY_XF86Battery, Qt::KeyboardModifiers() }, { Qt::Key_Bluetooth, XKB_KEY_XF86Bluetooth, Qt::KeyboardModifiers() }, { Qt::Key_WLAN, XKB_KEY_XF86WLAN, Qt::KeyboardModifiers() }, { Qt::Key_UWB, XKB_KEY_XF86UWB, Qt::KeyboardModifiers() }, { Qt::Key_AudioForward, XKB_KEY_XF86AudioForward, Qt::KeyboardModifiers() }, { Qt::Key_AudioRepeat, XKB_KEY_XF86AudioRepeat, Qt::KeyboardModifiers() }, { Qt::Key_AudioRandomPlay, XKB_KEY_XF86AudioRandomPlay, Qt::KeyboardModifiers() }, { Qt::Key_Subtitle, XKB_KEY_XF86Subtitle, Qt::KeyboardModifiers() }, { Qt::Key_AudioCycleTrack, XKB_KEY_XF86AudioCycleTrack, Qt::KeyboardModifiers() }, { Qt::Key_Time, XKB_KEY_XF86Time, Qt::KeyboardModifiers() }, { Qt::Key_Select, XKB_KEY_XF86Select, Qt::KeyboardModifiers() }, { Qt::Key_View, XKB_KEY_XF86View, Qt::KeyboardModifiers() }, { Qt::Key_TopMenu, XKB_KEY_XF86TopMenu, Qt::KeyboardModifiers() }, { Qt::Key_Bluetooth, XKB_KEY_XF86Bluetooth, Qt::KeyboardModifiers() }, { Qt::Key_Suspend, XKB_KEY_XF86Suspend, Qt::KeyboardModifiers() }, { Qt::Key_Hibernate, XKB_KEY_XF86Hibernate, Qt::KeyboardModifiers() }, { Qt::Key_TouchpadToggle, XKB_KEY_XF86TouchpadToggle, Qt::KeyboardModifiers() }, { Qt::Key_TouchpadOn, XKB_KEY_XF86TouchpadOn, Qt::KeyboardModifiers() }, { Qt::Key_TouchpadOff, XKB_KEY_XF86TouchpadOff, Qt::KeyboardModifiers() }, { Qt::Key_MicMute, XKB_KEY_XF86AudioMicMute, Qt::KeyboardModifiers() }, { Qt::Key_Launch2, XKB_KEY_XF86Launch0, Qt::KeyboardModifiers() }, { Qt::Key_Launch3, XKB_KEY_XF86Launch1, Qt::KeyboardModifiers() }, { Qt::Key_Launch4, XKB_KEY_XF86Launch2, Qt::KeyboardModifiers() }, { Qt::Key_Launch5, XKB_KEY_XF86Launch3, Qt::KeyboardModifiers() }, { Qt::Key_Launch6, XKB_KEY_XF86Launch4, Qt::KeyboardModifiers() }, { Qt::Key_Launch7, XKB_KEY_XF86Launch5, Qt::KeyboardModifiers() }, { Qt::Key_Launch8, XKB_KEY_XF86Launch6, Qt::KeyboardModifiers() }, { Qt::Key_Launch9, XKB_KEY_XF86Launch7, Qt::KeyboardModifiers() }, { Qt::Key_LaunchA, XKB_KEY_XF86Launch8, Qt::KeyboardModifiers() }, { Qt::Key_LaunchB, XKB_KEY_XF86Launch9, Qt::KeyboardModifiers() }, { Qt::Key_LaunchC, XKB_KEY_XF86LaunchA, Qt::KeyboardModifiers() }, { Qt::Key_LaunchD, XKB_KEY_XF86LaunchB, Qt::KeyboardModifiers() }, { Qt::Key_LaunchE, XKB_KEY_XF86LaunchC, Qt::KeyboardModifiers() }, { Qt::Key_LaunchF, XKB_KEY_XF86LaunchD, Qt::KeyboardModifiers() }, /* * Latin 1 * (ISO/IEC 8859-1 = Unicode U+0020..U+00FF) * Byte 3 = 0 */ { Qt::Key_Exclam, XKB_KEY_exclam , Qt::KeyboardModifiers() }, { Qt::Key_QuoteDbl, XKB_KEY_quotedbl , Qt::KeyboardModifiers() }, { Qt::Key_NumberSign, XKB_KEY_numbersign , Qt::KeyboardModifiers() }, { Qt::Key_Dollar, XKB_KEY_dollar , Qt::KeyboardModifiers() }, { Qt::Key_Percent, XKB_KEY_percent , Qt::KeyboardModifiers() }, { Qt::Key_Ampersand, XKB_KEY_ampersand , Qt::KeyboardModifiers() }, { Qt::Key_Apostrophe, XKB_KEY_apostrophe , Qt::KeyboardModifiers() }, { Qt::Key_ParenLeft, XKB_KEY_parenleft , Qt::KeyboardModifiers() }, { Qt::Key_ParenRight, XKB_KEY_parenright , Qt::KeyboardModifiers() }, { Qt::Key_Asterisk, XKB_KEY_asterisk , Qt::KeyboardModifiers() }, { Qt::Key_Plus, XKB_KEY_plus , Qt::KeyboardModifiers() }, { Qt::Key_Comma, XKB_KEY_comma , Qt::KeyboardModifiers() }, { Qt::Key_Minus, XKB_KEY_minus , Qt::KeyboardModifiers() }, { Qt::Key_Period, XKB_KEY_period , Qt::KeyboardModifiers() }, { Qt::Key_Slash, XKB_KEY_slash , Qt::KeyboardModifiers() }, { Qt::Key_0, XKB_KEY_0 , Qt::KeyboardModifiers() }, { Qt::Key_1, XKB_KEY_1 , Qt::KeyboardModifiers() }, { Qt::Key_2, XKB_KEY_2 , Qt::KeyboardModifiers() }, { Qt::Key_3, XKB_KEY_3 , Qt::KeyboardModifiers() }, { Qt::Key_4, XKB_KEY_4 , Qt::KeyboardModifiers() }, { Qt::Key_5, XKB_KEY_5 , Qt::KeyboardModifiers() }, { Qt::Key_6, XKB_KEY_6 , Qt::KeyboardModifiers() }, { Qt::Key_7, XKB_KEY_7 , Qt::KeyboardModifiers() }, { Qt::Key_8, XKB_KEY_8 , Qt::KeyboardModifiers() }, { Qt::Key_9, XKB_KEY_9 , Qt::KeyboardModifiers() }, { Qt::Key_Colon, XKB_KEY_colon , Qt::KeyboardModifiers() }, { Qt::Key_Semicolon, XKB_KEY_semicolon , Qt::KeyboardModifiers() }, { Qt::Key_Less, XKB_KEY_less , Qt::KeyboardModifiers() }, { Qt::Key_Equal, XKB_KEY_equal , Qt::KeyboardModifiers() }, { Qt::Key_Greater, XKB_KEY_greater , Qt::KeyboardModifiers() }, { Qt::Key_Question, XKB_KEY_question , Qt::KeyboardModifiers() }, { Qt::Key_At, XKB_KEY_at , Qt::KeyboardModifiers() }, { Qt::Key_A, XKB_KEY_A , Qt::ShiftModifier }, { Qt::Key_B, XKB_KEY_B , Qt::ShiftModifier }, { Qt::Key_C, XKB_KEY_C , Qt::ShiftModifier }, { Qt::Key_D, XKB_KEY_D , Qt::ShiftModifier }, { Qt::Key_E, XKB_KEY_E , Qt::ShiftModifier }, { Qt::Key_F, XKB_KEY_F , Qt::ShiftModifier }, { Qt::Key_G, XKB_KEY_G , Qt::ShiftModifier }, { Qt::Key_H, XKB_KEY_H , Qt::ShiftModifier }, { Qt::Key_I, XKB_KEY_I , Qt::ShiftModifier }, { Qt::Key_J, XKB_KEY_J , Qt::ShiftModifier }, { Qt::Key_K, XKB_KEY_K , Qt::ShiftModifier }, { Qt::Key_L, XKB_KEY_L , Qt::ShiftModifier }, { Qt::Key_M, XKB_KEY_M , Qt::ShiftModifier }, { Qt::Key_N, XKB_KEY_N , Qt::ShiftModifier }, { Qt::Key_O, XKB_KEY_O , Qt::ShiftModifier }, { Qt::Key_P, XKB_KEY_P , Qt::ShiftModifier }, { Qt::Key_Q, XKB_KEY_Q , Qt::ShiftModifier }, { Qt::Key_R, XKB_KEY_R , Qt::ShiftModifier }, { Qt::Key_S, XKB_KEY_S , Qt::ShiftModifier }, { Qt::Key_T, XKB_KEY_T , Qt::ShiftModifier }, { Qt::Key_U, XKB_KEY_U , Qt::ShiftModifier }, { Qt::Key_V, XKB_KEY_V , Qt::ShiftModifier }, { Qt::Key_W, XKB_KEY_W , Qt::ShiftModifier }, { Qt::Key_X, XKB_KEY_X , Qt::ShiftModifier }, { Qt::Key_Y, XKB_KEY_Y , Qt::ShiftModifier }, { Qt::Key_Z, XKB_KEY_Z , Qt::ShiftModifier }, { Qt::Key_BracketLeft, XKB_KEY_bracketleft, Qt::KeyboardModifiers() }, { Qt::Key_Backslash, XKB_KEY_backslash , Qt::KeyboardModifiers() }, { Qt::Key_BracketRight, XKB_KEY_bracketright, Qt::KeyboardModifiers()}, { Qt::Key_AsciiCircum, XKB_KEY_asciicircum, Qt::KeyboardModifiers() }, { Qt::Key_Underscore, XKB_KEY_underscore , Qt::KeyboardModifiers() }, { Qt::Key_QuoteLeft, XKB_KEY_quoteleft , Qt::KeyboardModifiers() }, { Qt::Key_A, XKB_KEY_a , Qt::KeyboardModifiers() }, { Qt::Key_B, XKB_KEY_b , Qt::KeyboardModifiers() }, { Qt::Key_C, XKB_KEY_c , Qt::KeyboardModifiers() }, { Qt::Key_D, XKB_KEY_d , Qt::KeyboardModifiers() }, { Qt::Key_E, XKB_KEY_e , Qt::KeyboardModifiers() }, { Qt::Key_F, XKB_KEY_f , Qt::KeyboardModifiers() }, { Qt::Key_G, XKB_KEY_g , Qt::KeyboardModifiers() }, { Qt::Key_H, XKB_KEY_h , Qt::KeyboardModifiers() }, { Qt::Key_I, XKB_KEY_i , Qt::KeyboardModifiers() }, { Qt::Key_J, XKB_KEY_j , Qt::KeyboardModifiers() }, { Qt::Key_K, XKB_KEY_k , Qt::KeyboardModifiers() }, { Qt::Key_L, XKB_KEY_l , Qt::KeyboardModifiers() }, { Qt::Key_M, XKB_KEY_m , Qt::KeyboardModifiers() }, { Qt::Key_N, XKB_KEY_n , Qt::KeyboardModifiers() }, { Qt::Key_O, XKB_KEY_o , Qt::KeyboardModifiers() }, { Qt::Key_P, XKB_KEY_p , Qt::KeyboardModifiers() }, { Qt::Key_Q, XKB_KEY_q , Qt::KeyboardModifiers() }, { Qt::Key_R, XKB_KEY_r , Qt::KeyboardModifiers() }, { Qt::Key_S, XKB_KEY_s , Qt::KeyboardModifiers() }, { Qt::Key_T, XKB_KEY_t , Qt::KeyboardModifiers() }, { Qt::Key_U, XKB_KEY_u , Qt::KeyboardModifiers() }, { Qt::Key_V, XKB_KEY_v , Qt::KeyboardModifiers() }, { Qt::Key_W, XKB_KEY_w , Qt::KeyboardModifiers() }, { Qt::Key_X, XKB_KEY_x , Qt::KeyboardModifiers() }, { Qt::Key_Y, XKB_KEY_y , Qt::KeyboardModifiers() }, { Qt::Key_Z, XKB_KEY_z , Qt::KeyboardModifiers() }, { Qt::Key_BraceLeft, XKB_KEY_braceleft , Qt::KeyboardModifiers() }, { Qt::Key_Bar, XKB_KEY_bar , Qt::KeyboardModifiers() }, { Qt::Key_BraceRight, XKB_KEY_braceright , Qt::KeyboardModifiers() }, { Qt::Key_AsciiTilde, XKB_KEY_asciitilde , Qt::KeyboardModifiers() }, { Qt::Key_nobreakspace, XKB_KEY_nobreakspace , Qt::KeyboardModifiers() }, { Qt::Key_exclamdown, XKB_KEY_exclamdown , Qt::KeyboardModifiers() }, { Qt::Key_cent, XKB_KEY_cent , Qt::KeyboardModifiers() }, { Qt::Key_sterling, XKB_KEY_sterling , Qt::KeyboardModifiers() }, { Qt::Key_currency, XKB_KEY_currency , Qt::KeyboardModifiers() }, { Qt::Key_yen, XKB_KEY_yen , Qt::KeyboardModifiers() }, { Qt::Key_brokenbar, XKB_KEY_brokenbar , Qt::KeyboardModifiers() }, { Qt::Key_section, XKB_KEY_section , Qt::KeyboardModifiers() }, { Qt::Key_diaeresis, XKB_KEY_diaeresis , Qt::KeyboardModifiers() }, { Qt::Key_copyright, XKB_KEY_copyright , Qt::KeyboardModifiers() }, { Qt::Key_ordfeminine, XKB_KEY_ordfeminine , Qt::KeyboardModifiers() }, { Qt::Key_guillemotleft, XKB_KEY_guillemotleft , Qt::KeyboardModifiers() }, { Qt::Key_notsign, XKB_KEY_notsign , Qt::KeyboardModifiers() }, { Qt::Key_hyphen, XKB_KEY_hyphen , Qt::KeyboardModifiers() }, { Qt::Key_registered, XKB_KEY_registered , Qt::KeyboardModifiers() }, { Qt::Key_macron, XKB_KEY_macron , Qt::KeyboardModifiers() }, { Qt::Key_degree, XKB_KEY_degree , Qt::KeyboardModifiers() }, { Qt::Key_plusminus, XKB_KEY_plusminus , Qt::KeyboardModifiers() }, { Qt::Key_twosuperior, XKB_KEY_twosuperior , Qt::KeyboardModifiers() }, { Qt::Key_threesuperior, XKB_KEY_threesuperior , Qt::KeyboardModifiers() }, { Qt::Key_acute, XKB_KEY_acute , Qt::KeyboardModifiers() }, { Qt::Key_mu, XKB_KEY_mu , Qt::KeyboardModifiers() }, { Qt::Key_paragraph, XKB_KEY_paragraph , Qt::KeyboardModifiers() }, { Qt::Key_periodcentered, XKB_KEY_periodcentered, Qt::KeyboardModifiers() }, { Qt::Key_cedilla, XKB_KEY_cedilla , Qt::KeyboardModifiers() }, { Qt::Key_onesuperior, XKB_KEY_onesuperior , Qt::KeyboardModifiers() }, { Qt::Key_masculine, XKB_KEY_masculine , Qt::KeyboardModifiers() }, { Qt::Key_guillemotright, XKB_KEY_guillemotright, Qt::KeyboardModifiers() }, { Qt::Key_onequarter, XKB_KEY_onequarter , Qt::KeyboardModifiers() }, { Qt::Key_onehalf, XKB_KEY_onehalf , Qt::KeyboardModifiers() }, { Qt::Key_threequarters, XKB_KEY_threequarters , Qt::KeyboardModifiers() }, { Qt::Key_questiondown, XKB_KEY_questiondown , Qt::KeyboardModifiers() }, { Qt::Key_Agrave, XKB_KEY_Agrave , Qt::ShiftModifier }, { Qt::Key_Aacute, XKB_KEY_Aacute , Qt::ShiftModifier }, { Qt::Key_Acircumflex, XKB_KEY_Acircumflex , Qt::ShiftModifier }, { Qt::Key_Atilde, XKB_KEY_Atilde , Qt::ShiftModifier }, { Qt::Key_Adiaeresis, XKB_KEY_Adiaeresis , Qt::ShiftModifier }, { Qt::Key_Aring, XKB_KEY_Aring , Qt::ShiftModifier }, { Qt::Key_AE, XKB_KEY_AE , Qt::ShiftModifier }, { Qt::Key_Ccedilla, XKB_KEY_Ccedilla , Qt::ShiftModifier }, { Qt::Key_Egrave, XKB_KEY_Egrave , Qt::ShiftModifier }, { Qt::Key_Eacute, XKB_KEY_Eacute , Qt::ShiftModifier }, { Qt::Key_Ecircumflex, XKB_KEY_Ecircumflex , Qt::ShiftModifier }, { Qt::Key_Ediaeresis, XKB_KEY_Ediaeresis , Qt::ShiftModifier }, { Qt::Key_Igrave, XKB_KEY_Igrave , Qt::ShiftModifier }, { Qt::Key_Iacute, XKB_KEY_Iacute , Qt::ShiftModifier }, { Qt::Key_Icircumflex, XKB_KEY_Icircumflex , Qt::ShiftModifier }, { Qt::Key_Idiaeresis, XKB_KEY_Idiaeresis , Qt::ShiftModifier }, { Qt::Key_ETH, XKB_KEY_ETH , Qt::ShiftModifier }, { Qt::Key_Ntilde, XKB_KEY_Ntilde , Qt::ShiftModifier }, { Qt::Key_Ograve, XKB_KEY_Ograve , Qt::ShiftModifier }, { Qt::Key_Oacute, XKB_KEY_Oacute , Qt::ShiftModifier }, { Qt::Key_Ocircumflex, XKB_KEY_Ocircumflex , Qt::ShiftModifier }, { Qt::Key_Otilde, XKB_KEY_Otilde , Qt::ShiftModifier }, { Qt::Key_Odiaeresis, XKB_KEY_Odiaeresis , Qt::ShiftModifier }, { Qt::Key_multiply, XKB_KEY_multiply , Qt::ShiftModifier }, { Qt::Key_Ooblique, XKB_KEY_Ooblique , Qt::ShiftModifier }, { Qt::Key_Ugrave, XKB_KEY_Ugrave , Qt::ShiftModifier }, { Qt::Key_Uacute, XKB_KEY_Uacute , Qt::ShiftModifier }, { Qt::Key_Ucircumflex, XKB_KEY_Ucircumflex , Qt::ShiftModifier }, { Qt::Key_Udiaeresis, XKB_KEY_Udiaeresis , Qt::ShiftModifier }, { Qt::Key_Yacute, XKB_KEY_Yacute , Qt::ShiftModifier }, { Qt::Key_THORN, XKB_KEY_THORN , Qt::ShiftModifier }, { Qt::Key_ssharp, XKB_KEY_ssharp , Qt::KeyboardModifiers() }, { Qt::Key_Agrave, XKB_KEY_agrave , Qt::KeyboardModifiers() }, { Qt::Key_Aacute, XKB_KEY_aacute , Qt::KeyboardModifiers() }, { Qt::Key_Acircumflex, XKB_KEY_acircumflex , Qt::KeyboardModifiers() }, { Qt::Key_Atilde, XKB_KEY_atilde , Qt::KeyboardModifiers() }, { Qt::Key_Adiaeresis, XKB_KEY_adiaeresis , Qt::KeyboardModifiers() }, { Qt::Key_Aring, XKB_KEY_aring , Qt::KeyboardModifiers() }, { Qt::Key_AE, XKB_KEY_ae , Qt::KeyboardModifiers() }, { Qt::Key_Ccedilla, XKB_KEY_ccedilla , Qt::KeyboardModifiers() }, { Qt::Key_Egrave, XKB_KEY_egrave , Qt::KeyboardModifiers() }, { Qt::Key_Eacute, XKB_KEY_eacute , Qt::KeyboardModifiers() }, { Qt::Key_Ecircumflex, XKB_KEY_ecircumflex , Qt::KeyboardModifiers() }, { Qt::Key_Ediaeresis, XKB_KEY_ediaeresis , Qt::KeyboardModifiers() }, { Qt::Key_Igrave, XKB_KEY_igrave , Qt::KeyboardModifiers() }, { Qt::Key_Iacute, XKB_KEY_iacute , Qt::KeyboardModifiers() }, { Qt::Key_Icircumflex, XKB_KEY_icircumflex , Qt::KeyboardModifiers() }, { Qt::Key_Idiaeresis, XKB_KEY_idiaeresis , Qt::KeyboardModifiers() }, { Qt::Key_ETH, XKB_KEY_eth , Qt::KeyboardModifiers() }, { Qt::Key_Ntilde, XKB_KEY_ntilde , Qt::KeyboardModifiers() }, { Qt::Key_Ograve, XKB_KEY_ograve , Qt::KeyboardModifiers() }, { Qt::Key_Oacute, XKB_KEY_oacute , Qt::KeyboardModifiers() }, { Qt::Key_Ocircumflex, XKB_KEY_ocircumflex , Qt::KeyboardModifiers() }, { Qt::Key_Otilde, XKB_KEY_otilde , Qt::KeyboardModifiers() }, { Qt::Key_Odiaeresis, XKB_KEY_odiaeresis , Qt::KeyboardModifiers() }, { Qt::Key_division, XKB_KEY_division , Qt::KeyboardModifiers() }, { Qt::Key_Ooblique, XKB_KEY_ooblique , Qt::KeyboardModifiers() }, { Qt::Key_Ugrave, XKB_KEY_ugrave , Qt::KeyboardModifiers() }, { Qt::Key_Uacute, XKB_KEY_uacute , Qt::KeyboardModifiers() }, { Qt::Key_Ucircumflex, XKB_KEY_ucircumflex , Qt::KeyboardModifiers() }, { Qt::Key_Udiaeresis, XKB_KEY_udiaeresis , Qt::KeyboardModifiers() }, { Qt::Key_Yacute, XKB_KEY_yacute , Qt::KeyboardModifiers() }, { Qt::Key_THORN, XKB_KEY_thorn , Qt::KeyboardModifiers() }, { Qt::Key_ydiaeresis, XKB_KEY_ydiaeresis, Qt::KeyboardModifiers() }, /* * Numpad - **/ + */ { Qt::Key_0, XKB_KEY_KP_0, Qt::KeypadModifier }, { Qt::Key_1, XKB_KEY_KP_1, Qt::KeypadModifier }, { Qt::Key_2, XKB_KEY_KP_2, Qt::KeypadModifier }, { Qt::Key_3, XKB_KEY_KP_3, Qt::KeypadModifier }, { Qt::Key_4, XKB_KEY_KP_4, Qt::KeypadModifier }, { Qt::Key_5, XKB_KEY_KP_5, Qt::KeypadModifier }, { Qt::Key_6, XKB_KEY_KP_6, Qt::KeypadModifier }, { Qt::Key_7, XKB_KEY_KP_7, Qt::KeypadModifier }, { Qt::Key_8, XKB_KEY_KP_8, Qt::KeypadModifier }, { Qt::Key_9, XKB_KEY_KP_9, Qt::KeypadModifier } }; void XkbTest::testToQtKey_data() { QTest::addColumn("qt"); QTest::addColumn("keySym"); for (std::size_t i = 0; i < sizeof(g_rgQtToSymX) / sizeof(TransKey); i++) { const QByteArray row = QByteArray::number(g_rgQtToSymX[i].keySymX, 16); QTest::newRow(row.constData()) << g_rgQtToSymX[i].keySymQt << g_rgQtToSymX[i].keySymX; } } void XkbTest::testToQtKey() { Xkb xkb; QFETCH(xkb_keysym_t, keySym); QTEST(xkb.toQtKey(keySym), "qt"); } void XkbTest::testFromQtKey_data() { QTest::addColumn("qt"); QTest::addColumn("keySym"); QTest::addColumn("modifiers"); for (std::size_t i = 0; i < sizeof(g_rgQtToSymX) / sizeof(TransKey); i++) { const QByteArray row = QByteArray::number(g_rgQtToSymX[i].keySymX, 16); QTest::newRow(row.constData()) << g_rgQtToSymX[i].keySymQt << g_rgQtToSymX[i].keySymX << g_rgQtToSymX[i].modifiers; } } void XkbTest::testFromQtKey() { Xkb xkb; QFETCH(Qt::Key, qt); QFETCH(Qt::KeyboardModifiers, modifiers); QTEST(xkb.fromQtKey(qt, modifiers), "keySym"); } QTEST_MAIN(XkbTest) #include "test_xkb.moc" diff --git a/autotests/testutils.h b/autotests/testutils.h index 103a81cd1..2fc8c8e2f 100644 --- a/autotests/testutils.h +++ b/autotests/testutils.h @@ -1,63 +1,63 @@ /******************************************************************** 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 TESTUTILS_H #define TESTUTILS_H // KWin #include // XCB #include namespace { static void forceXcb() { qputenv("QT_QPA_PLATFORM", QByteArrayLiteral("xcb")); } } namespace KWin { /** * Wrapper to create an 0,0x10,10 input only window for testing purposes - **/ + */ #ifndef NO_NONE_WINDOW static xcb_window_t createWindow() { xcb_window_t w = xcb_generate_id(connection()); const uint32_t values[] = { true }; xcb_create_window(connection(), 0, w, rootWindow(), 0, 0, 10, 10, 0, XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, XCB_CW_OVERRIDE_REDIRECT, values); return w; } #endif /** * casts XCB_WINDOW_NONE to uint32_t. Needed to make QCOMPARE working. - **/ + */ #ifndef NO_NONE_WINDOW static uint32_t noneWindow() { return XCB_WINDOW_NONE; } #endif } // namespace #endif diff --git a/client.cpp b/client.cpp index ed8a93c9d..451bc1780 100644 --- a/client.cpp +++ b/client.cpp @@ -1,2174 +1,2174 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ // own #include "client.h" // kwin #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include "atoms.h" #include "client_machine.h" #include "composite.h" #include "cursor.h" #include "deleted.h" #include "focuschain.h" #include "group.h" #include "shadow.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "workspace.h" #include "screenedge.h" #include "decorations/decorationbridge.h" #include "decorations/decoratedclient.h" #include #include // KDE #include #include #include // Qt #include #include #include #include #include #include #include // XLib #include #include #include // system #include // c++ #include // Put all externs before the namespace statement to allow the linker // to resolve them properly namespace KWin { const long ClientWinMask = XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_KEYMAP_STATE | XCB_EVENT_MASK_BUTTON_MOTION | XCB_EVENT_MASK_POINTER_MOTION | // need this, too! XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT; // Creating a client: // - only by calling Workspace::createClient() // - it creates a new client and calls manage() for it // // Destroying a client: // - destroyClient() - only when the window itself has been destroyed // - releaseWindow() - the window is kept, only the client itself is destroyed /** * \class Client client.h * \brief The Client class encapsulates a window decoration frame. - **/ + */ /** * This ctor is "dumb" - it only initializes data. All the real initialization * is done in manage(). - **/ + */ Client::Client() : AbstractClient() , m_client() , m_wrapper() , m_frame() , m_activityUpdatesBlocked(false) , m_blockedActivityUpdatesRequireTransients(false) , m_moveResizeGrabWindow() , move_resize_has_keyboard_grab(false) , m_managed(false) , m_transientForId(XCB_WINDOW_NONE) , m_originalTransientForId(XCB_WINDOW_NONE) , shade_below(NULL) , m_motif(atoms->motif_wm_hints) , blocks_compositing(false) , shadeHoverTimer(NULL) , m_colormap(XCB_COLORMAP_NONE) , in_group(NULL) , ping_timer(NULL) , m_killHelperPID(0) , m_pingTimestamp(XCB_TIME_CURRENT_TIME) , m_userTime(XCB_TIME_CURRENT_TIME) // Not known yet , allowed_actions(0) , shade_geometry_change(false) , sm_stacking_order(-1) , activitiesDefined(false) , sessionActivityOverride(false) , needsXWindowMove(false) , m_decoInputExtent() , m_focusOutTimer(nullptr) , m_clientSideDecorated(false) { // TODO: Do all as initialization syncRequest.counter = syncRequest.alarm = XCB_NONE; syncRequest.timeout = syncRequest.failsafeTimeout = NULL; syncRequest.lastTimestamp = xTime(); syncRequest.isPending = false; // Set the initial mapping state mapping_state = Withdrawn; info = NULL; shade_mode = ShadeNone; deleting = false; m_fullscreenMode = FullScreenNone; hidden = false; noborder = false; app_noborder = false; ignore_focus_stealing = false; check_active_modal = false; max_mode = MaximizeRestore; //Client to workspace connections require that each //client constructed be connected to the workspace wrapper geom = QRect(0, 0, 100, 100); // So that decorations don't start with size being (0,0) client_size = QSize(100, 100); ready_for_painting = false; // wait for first damage or sync reply connect(clientMachine(), &ClientMachine::localhostChanged, this, &Client::updateCaption); connect(options, &Options::condensedTitleChanged, this, &Client::updateCaption); connect(this, &Client::moveResizeCursorChanged, this, [this] (CursorShape cursor) { xcb_cursor_t nativeCursor = Cursor::x11Cursor(cursor); m_frame.defineCursor(nativeCursor); if (m_decoInputExtent.isValid()) m_decoInputExtent.defineCursor(nativeCursor); if (isMoveResize()) { // changing window attributes doesn't change cursor if there's pointer grab active xcb_change_active_pointer_grab(connection(), nativeCursor, xTime(), XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW); } }); connect(this, &Client::tabGroupChanged, this, [this] { auto group = tabGroup(); if (group) { unsigned long data[] = {qHash(group)}; //->id(); m_client.changeProperty(atoms->kde_net_wm_tab_group, XCB_ATOM_CARDINAL, 32, 1, data); } else m_client.deleteProperty(atoms->kde_net_wm_tab_group); }); // SELI TODO: Initialize xsizehints?? } /** * "Dumb" destructor. - **/ + */ Client::~Client() { if (m_killHelperPID && !::kill(m_killHelperPID, 0)) { // means the process is alive ::kill(m_killHelperPID, SIGTERM); m_killHelperPID = 0; } //SWrapper::Client::clientRelease(this); if (syncRequest.alarm != XCB_NONE) xcb_sync_destroy_alarm(connection(), syncRequest.alarm); assert(!isMoveResize()); assert(m_client == XCB_WINDOW_NONE); assert(m_wrapper == XCB_WINDOW_NONE); //assert( frameId() == None ); assert(!check_active_modal); for (auto it = m_connections.constBegin(); it != m_connections.constEnd(); ++it) { disconnect(*it); } } // Use destroyClient() or releaseWindow(), Client instances cannot be deleted directly void Client::deleteClient(Client* c) { delete c; } /** * Releases the window. The client has done its job and the window is still existing. - **/ + */ void Client::releaseWindow(bool on_shutdown) { assert(!deleting); deleting = true; #ifdef KWIN_BUILD_TABBOX TabBox::TabBox *tabBox = TabBox::TabBox::self(); if (tabBox->isDisplayed() && tabBox->currentClient() == this) { tabBox->nextPrev(true); } #endif destroyWindowManagementInterface(); Deleted* del = NULL; if (!on_shutdown) { del = Deleted::create(this); } if (isMoveResize()) emit clientFinishUserMovedResized(this); emit windowClosed(this, del); finishCompositing(); RuleBook::self()->discardUsed(this, true); // Remove ForceTemporarily rules StackingUpdatesBlocker blocker(workspace()); if (isMoveResize()) leaveMoveResize(); finishWindowRules(); blockGeometryUpdates(); if (isOnCurrentDesktop() && isShown(true)) addWorkspaceRepaint(visibleRect()); // Grab X during the release to make removing of properties, setting to withdrawn state // and repareting to root an atomic operation (https://lists.kde.org/?l=kde-devel&m=116448102901184&w=2) grabXServer(); exportMappingState(WithdrawnState); setModal(false); // Otherwise its mainwindow wouldn't get focus hidden = true; // So that it's not considered visible anymore (can't use hideClient(), it would set flags) if (!on_shutdown) workspace()->clientHidden(this); m_frame.unmap(); // Destroying decoration would cause ugly visual effect destroyDecoration(); cleanGrouping(); if (!on_shutdown) { workspace()->removeClient(this); // Only when the window is being unmapped, not when closing down KWin (NETWM sections 5.5,5.7) info->setDesktop(0); info->setState(0, info->state()); // Reset all state flags } else untab(); xcb_connection_t *c = connection(); m_client.deleteProperty(atoms->kde_net_wm_user_creation_time); m_client.deleteProperty(atoms->net_frame_extents); m_client.deleteProperty(atoms->kde_net_wm_frame_strut); m_client.reparent(rootWindow(), x(), y()); xcb_change_save_set(c, XCB_SET_MODE_DELETE, m_client); m_client.selectInput(XCB_EVENT_MASK_NO_EVENT); if (on_shutdown) // Map the window, so it can be found after another WM is started m_client.map(); // TODO: Preserve minimized, shaded etc. state? else // Make sure it's not mapped if the app unmapped it (#65279). The app // may do map+unmap before we initially map the window by calling rawShow() from manage(). m_client.unmap(); m_client.reset(); m_wrapper.reset(); m_frame.reset(); //frame = None; unblockGeometryUpdates(); // Don't use GeometryUpdatesBlocker, it would now set the geometry if (!on_shutdown) { disownDataPassedToDeleted(); del->unrefWindow(); } deleteClient(this); ungrabXServer(); } /** * Like releaseWindow(), but this one is called when the window has been already destroyed * (E.g. The application closed it) - **/ + */ void Client::destroyClient() { assert(!deleting); deleting = true; #ifdef KWIN_BUILD_TABBOX TabBox::TabBox *tabBox = TabBox::TabBox::self(); if (tabBox->isDisplayed() && tabBox->currentClient() == this) { tabBox->nextPrev(true); } #endif destroyWindowManagementInterface(); Deleted* del = Deleted::create(this); if (isMoveResize()) emit clientFinishUserMovedResized(this); emit windowClosed(this, del); finishCompositing(ReleaseReason::Destroyed); RuleBook::self()->discardUsed(this, true); // Remove ForceTemporarily rules StackingUpdatesBlocker blocker(workspace()); if (isMoveResize()) leaveMoveResize(); finishWindowRules(); blockGeometryUpdates(); if (isOnCurrentDesktop() && isShown(true)) addWorkspaceRepaint(visibleRect()); setModal(false); hidden = true; // So that it's not considered visible anymore workspace()->clientHidden(this); destroyDecoration(); cleanGrouping(); workspace()->removeClient(this); m_client.reset(); // invalidate m_wrapper.reset(); m_frame.reset(); //frame = None; unblockGeometryUpdates(); // Don't use GeometryUpdatesBlocker, it would now set the geometry disownDataPassedToDeleted(); del->unrefWindow(); deleteClient(this); } void Client::updateInputWindow() { if (!Xcb::Extensions::self()->isShapeInputAvailable()) return; QRegion region; if (!noBorder() && isDecorated()) { const QMargins &r = decoration()->resizeOnlyBorders(); const int left = r.left(); const int top = r.top(); const int right = r.right(); const int bottom = r.bottom(); if (left != 0 || top != 0 || right != 0 || bottom != 0) { region = QRegion(-left, -top, decoration()->size().width() + left + right, decoration()->size().height() + top + bottom); region = region.subtracted(decoration()->rect()); } } if (region.isEmpty()) { m_decoInputExtent.reset(); return; } QRect bounds = region.boundingRect(); input_offset = bounds.topLeft(); // Move the bounding rect to screen coordinates bounds.translate(geometry().topLeft()); // Move the region to input window coordinates region.translate(-input_offset); if (!m_decoInputExtent.isValid()) { const uint32_t mask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK; const uint32_t values[] = {true, XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION }; m_decoInputExtent.create(bounds, XCB_WINDOW_CLASS_INPUT_ONLY, mask, values); if (mapping_state == Mapped) m_decoInputExtent.map(); } else { m_decoInputExtent.setGeometry(bounds); } const QVector rects = Xcb::regionToRects(region); xcb_shape_rectangles(connection(), XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, XCB_CLIP_ORDERING_UNSORTED, m_decoInputExtent, 0, 0, rects.count(), rects.constData()); } void Client::updateDecoration(bool check_workspace_pos, bool force) { if (!force && ((!isDecorated() && noBorder()) || (isDecorated() && !noBorder()))) return; QRect oldgeom = geometry(); QRect oldClientGeom = oldgeom.adjusted(borderLeft(), borderTop(), -borderRight(), -borderBottom()); blockGeometryUpdates(true); if (force) destroyDecoration(); if (!noBorder()) { createDecoration(oldgeom); } else destroyDecoration(); getShadow(); if (check_workspace_pos) checkWorkspacePosition(oldgeom, -2, oldClientGeom); updateInputWindow(); blockGeometryUpdates(false); updateFrameExtents(); } void Client::createDecoration(const QRect& oldgeom) { KDecoration2::Decoration *decoration = Decoration::DecorationBridge::self()->createDecoration(this); if (decoration) { QMetaObject::invokeMethod(decoration, "update", Qt::QueuedConnection); connect(decoration, &KDecoration2::Decoration::shadowChanged, this, &Toplevel::getShadow); connect(decoration, &KDecoration2::Decoration::resizeOnlyBordersChanged, this, &Client::updateInputWindow); connect(decoration, &KDecoration2::Decoration::bordersChanged, this, [this]() { updateFrameExtents(); GeometryUpdatesBlocker blocker(this); // TODO: this is obviously idempotent // calculateGravitation(true) would have to operate on the old border sizes // move(calculateGravitation(true)); // move(calculateGravitation(false)); QRect oldgeom = geometry(); plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); if (!isShade()) checkWorkspacePosition(oldgeom); emit geometryShapeChanged(this, oldgeom); } ); connect(decoratedClient()->decoratedClient(), &KDecoration2::DecoratedClient::widthChanged, this, &Client::updateInputWindow); connect(decoratedClient()->decoratedClient(), &KDecoration2::DecoratedClient::heightChanged, this, &Client::updateInputWindow); } setDecoration(decoration); move(calculateGravitation(false)); plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); if (Compositor::compositing()) { discardWindowPixmap(); } emit geometryShapeChanged(this, oldgeom); } void Client::destroyDecoration() { QRect oldgeom = geometry(); if (isDecorated()) { QPoint grav = calculateGravitation(true); AbstractClient::destroyDecoration(); plainResize(sizeForClientSize(clientSize()), ForceGeometrySet); move(grav); if (compositing()) discardWindowPixmap(); if (!deleting) { emit geometryShapeChanged(this, oldgeom); } } m_decoInputExtent.reset(); } void Client::layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const { if (!isDecorated()) { return; } QRect r = decoration()->rect(); NETStrut strut = info->frameOverlap(); // Ignore the overlap strut when compositing is disabled if (!compositing()) strut.left = strut.top = strut.right = strut.bottom = 0; else if (strut.left == -1 && strut.top == -1 && strut.right == -1 && strut.bottom == -1) { top = QRect(r.x(), r.y(), r.width(), r.height() / 3); left = QRect(r.x(), r.y() + top.height(), width() / 2, r.height() / 3); right = QRect(r.x() + left.width(), r.y() + top.height(), r.width() - left.width(), left.height()); bottom = QRect(r.x(), r.y() + top.height() + left.height(), r.width(), r.height() - left.height() - top.height()); return; } top = QRect(r.x(), r.y(), r.width(), borderTop() + strut.top); bottom = QRect(r.x(), r.y() + r.height() - borderBottom() - strut.bottom, r.width(), borderBottom() + strut.bottom); left = QRect(r.x(), r.y() + top.height(), borderLeft() + strut.left, r.height() - top.height() - bottom.height()); right = QRect(r.x() + r.width() - borderRight() - strut.right, r.y() + top.height(), borderRight() + strut.right, r.height() - top.height() - bottom.height()); } QRect Client::transparentRect() const { if (isShade()) return QRect(); NETStrut strut = info->frameOverlap(); // Ignore the strut when compositing is disabled or the decoration doesn't support it if (!compositing()) strut.left = strut.top = strut.right = strut.bottom = 0; else if (strut.left == -1 && strut.top == -1 && strut.right == -1 && strut.bottom == -1) return QRect(); const QRect r = QRect(clientPos(), clientSize()) .adjusted(strut.left, strut.top, -strut.right, -strut.bottom); if (r.isValid()) return r; return QRect(); } void Client::detectNoBorder() { if (shape()) { noborder = true; app_noborder = true; return; } switch(windowType()) { case NET::Desktop : case NET::Dock : case NET::TopMenu : case NET::Splash : case NET::Notification : case NET::OnScreenDisplay : case NET::CriticalNotification : noborder = true; app_noborder = true; break; case NET::Unknown : case NET::Normal : case NET::Toolbar : case NET::Menu : case NET::Dialog : case NET::Utility : noborder = false; break; default: abort(); } // NET::Override is some strange beast without clear definition, usually // just meaning "noborder", so let's treat it only as such flag, and ignore it as // a window type otherwise (SUPPORTED_WINDOW_TYPES_MASK doesn't include it) if (info->windowType(NET::OverrideMask) == NET::Override) { noborder = true; app_noborder = true; } } void Client::updateFrameExtents() { NETStrut strut; strut.left = borderLeft(); strut.right = borderRight(); strut.top = borderTop(); strut.bottom = borderBottom(); info->setFrameExtents(strut); } Xcb::Property Client::fetchGtkFrameExtents() const { return Xcb::Property(false, m_client, atoms->gtk_frame_extents, XCB_ATOM_CARDINAL, 0, 4); } void Client::readGtkFrameExtents(Xcb::Property &prop) { m_clientSideDecorated = !prop.isNull() && prop->type != 0; emit clientSideDecoratedChanged(); } void Client::detectGtkFrameExtents() { Xcb::Property prop = fetchGtkFrameExtents(); readGtkFrameExtents(prop); } /** * Resizes the decoration, and makes sure the decoration widget gets resize event * even if the size hasn't changed. This is needed to make sure the decoration * re-layouts (e.g. when maximization state changes, * the decoration may alter some borders, but the actual size * of the decoration stays the same). - **/ + */ void Client::resizeDecoration() { triggerDecorationRepaint(); updateInputWindow(); } bool Client::userNoBorder() const { return noborder; } bool Client::isFullScreenable() const { if (!rules()->checkFullScreen(true)) { return false; } if (rules()->checkStrictGeometry(true)) { // check geometry constraints (rule to obey is set) const QRect fsarea = workspace()->clientArea(FullScreenArea, this); if (sizeForClientSize(fsarea.size(), SizemodeAny, true) != fsarea.size()) { return false; // the app wouldn't fit exactly fullscreen geometry due to its strict geometry requirements } } // don't check size constrains - some apps request fullscreen despite requesting fixed size return !isSpecialWindow(); // also better disallow only weird types to go fullscreen } bool Client::noBorder() const { return userNoBorder() || isFullScreen(); } bool Client::userCanSetNoBorder() const { return !isFullScreen() && !isShade() && !tabGroup(); } void Client::setNoBorder(bool set) { if (!userCanSetNoBorder()) return; set = rules()->checkNoBorder(set); if (noborder == set) return; noborder = set; updateDecoration(true, false); updateWindowRules(Rules::NoBorder); } void Client::checkNoBorder() { setNoBorder(app_noborder); } bool Client::wantsShadowToBeRendered() const { return !isFullScreen() && maximizeMode() != MaximizeFull; } void Client::updateShape() { if (shape()) { // Workaround for #19644 - Shaped windows shouldn't have decoration if (!app_noborder) { // Only when shape is detected for the first time, still let the user to override app_noborder = true; noborder = rules()->checkNoBorder(true); updateDecoration(true); } if (noBorder()) { xcb_shape_combine(connection(), XCB_SHAPE_SO_SET, XCB_SHAPE_SK_BOUNDING, XCB_SHAPE_SK_BOUNDING, frameId(), clientPos().x(), clientPos().y(), window()); } } else if (app_noborder) { xcb_shape_mask(connection(), XCB_SHAPE_SO_SET, XCB_SHAPE_SK_BOUNDING, frameId(), 0, 0, XCB_PIXMAP_NONE); detectNoBorder(); app_noborder = noborder; noborder = rules()->checkNoBorder(noborder || m_motif.noBorder()); updateDecoration(true); } // Decoration mask (i.e. 'else' here) setting is done in setMask() // when the decoration calls it or when the decoration is created/destroyed updateInputShape(); if (compositing()) { addRepaintFull(); addWorkspaceRepaint(visibleRect()); // In case shape change removes part of this window } emit geometryShapeChanged(this, geometry()); } static Xcb::Window shape_helper_window(XCB_WINDOW_NONE); void Client::cleanupX11() { shape_helper_window.reset(); } void Client::updateInputShape() { if (hiddenPreview()) // Sets it to none, don't change return; if (Xcb::Extensions::self()->isShapeInputAvailable()) { // There appears to be no way to find out if a window has input // shape set or not, so always propagate the input shape // (it's the same like the bounding shape by default). // Also, build the shape using a helper window, not directly // in the frame window, because the sequence set-shape-to-frame, // remove-shape-of-client, add-input-shape-of-client has the problem // that after the second step there's a hole in the input shape // until the real shape of the client is added and that can make // the window lose focus (which is a problem with mouse focus policies) // TODO: It seems there is, after all - XShapeGetRectangles() - but maybe this is better if (!shape_helper_window.isValid()) shape_helper_window.create(QRect(0, 0, 1, 1)); shape_helper_window.resize(width(), height()); xcb_connection_t *c = connection(); xcb_shape_combine(c, XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, XCB_SHAPE_SK_BOUNDING, shape_helper_window, 0, 0, frameId()); xcb_shape_combine(c, XCB_SHAPE_SO_SUBTRACT, XCB_SHAPE_SK_INPUT, XCB_SHAPE_SK_BOUNDING, shape_helper_window, clientPos().x(), clientPos().y(), window()); xcb_shape_combine(c, XCB_SHAPE_SO_UNION, XCB_SHAPE_SK_INPUT, XCB_SHAPE_SK_INPUT, shape_helper_window, clientPos().x(), clientPos().y(), window()); xcb_shape_combine(c, XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, XCB_SHAPE_SK_INPUT, frameId(), 0, 0, shape_helper_window); } } void Client::hideClient(bool hide) { if (hidden == hide) return; hidden = hide; updateVisibility(); } bool Client::setupCompositing() { if (!Toplevel::setupCompositing()){ return false; } updateVisibility(); // for internalKeep() return true; } void Client::finishCompositing(ReleaseReason releaseReason) { Toplevel::finishCompositing(releaseReason); updateVisibility(); // for safety in case KWin is just resizing the window resetHaveResizeEffect(); } /** * Returns whether the window is minimizable or not - **/ + */ bool Client::isMinimizable() const { if (isSpecialWindow() && !isTransient()) return false; if (!rules()->checkMinimize(true)) return false; if (isTransient()) { // #66868 - Let other xmms windows be minimized when the mainwindow is minimized bool shown_mainwindow = false; auto mainclients = mainClients(); for (auto it = mainclients.constBegin(); it != mainclients.constEnd(); ++it) if ((*it)->isShown(true)) shown_mainwindow = true; if (!shown_mainwindow) return true; } #if 0 // This is here because kicker's taskbar doesn't provide separate entries // for windows with an explicitly given parent // TODO: perhaps this should be redone // Disabled for now, since at least modal dialogs should be minimizable // (resulting in the mainwindow being minimized too). if (transientFor() != NULL) return false; #endif if (!wantsTabFocus()) // SELI, TODO: - NET::Utility? why wantsTabFocus() - skiptaskbar? ? return false; return true; } void Client::doMinimize() { updateVisibility(); updateAllowedActions(); workspace()->updateMinimizedOfTransients(this); // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Minimized); } QRect Client::iconGeometry() const { NETRect r = info->iconGeometry(); QRect geom(r.pos.x, r.pos.y, r.size.width, r.size.height); if (geom.isValid()) return geom; else { // Check all mainwindows of this window (recursively) foreach (AbstractClient * amainwin, mainClients()) { Client *mainwin = dynamic_cast(amainwin); if (!mainwin) { continue; } geom = mainwin->iconGeometry(); if (geom.isValid()) return geom; } // No mainwindow (or their parents) with icon geometry was found return AbstractClient::iconGeometry(); } } bool Client::isShadeable() const { return !isSpecialWindow() && !noBorder() && (rules()->checkShade(ShadeNormal) != rules()->checkShade(ShadeNone)); } void Client::setShade(ShadeMode mode) { if (mode == ShadeHover && isMove()) return; // causes geometry breaks and is probably nasty if (isSpecialWindow() || noBorder()) mode = ShadeNone; mode = rules()->checkShade(mode); if (shade_mode == mode) return; bool was_shade = isShade(); ShadeMode was_shade_mode = shade_mode; shade_mode = mode; // Decorations may turn off some borders when shaded // this has to happen _before_ the tab alignment since it will restrict the minimum geometry #if 0 if (decoration) decoration->borders(border_left, border_right, border_top, border_bottom); #endif // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Shaded); if (was_shade == isShade()) { // Decoration may want to update after e.g. hover-shade changes emit shadeChanged(); return; // No real change in shaded state } assert(isDecorated()); // noborder windows can't be shaded GeometryUpdatesBlocker blocker(this); // TODO: All this unmapping, resizing etc. feels too much duplicated from elsewhere if (isShade()) { // shade_mode == ShadeNormal addWorkspaceRepaint(visibleRect()); // Shade shade_geometry_change = true; QSize s(sizeForClientSize(QSize(clientSize()))); s.setHeight(borderTop() + borderBottom()); m_wrapper.selectInput(ClientWinMask); // Avoid getting UnmapNotify m_wrapper.unmap(); m_client.unmap(); m_wrapper.selectInput(ClientWinMask | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY); exportMappingState(IconicState); plainResize(s); shade_geometry_change = false; if (was_shade_mode == ShadeHover) { if (shade_below && workspace()->stackingOrder().indexOf(shade_below) > -1) workspace()->restack(this, shade_below, true); if (isActive()) workspace()->activateNextClient(this); } else if (isActive()) { workspace()->focusToNull(); } } else { shade_geometry_change = true; if (decoratedClient()) decoratedClient()->signalShadeChange(); QSize s(sizeForClientSize(clientSize())); shade_geometry_change = false; plainResize(s); geom_restore = geometry(); if ((shade_mode == ShadeHover || shade_mode == ShadeActivated) && rules()->checkAcceptFocus(info->input())) setActive(true); if (shade_mode == ShadeHover) { ToplevelList order = workspace()->stackingOrder(); // invalidate, since "this" could be the topmost toplevel and shade_below dangeling shade_below = NULL; // this is likely related to the index parameter?! for (int idx = order.indexOf(this) + 1; idx < order.count(); ++idx) { shade_below = qobject_cast(order.at(idx)); if (shade_below) { break; } } if (shade_below && shade_below->isNormalWindow()) workspace()->raiseClient(this); else shade_below = NULL; } m_wrapper.map(); m_client.map(); exportMappingState(NormalState); if (isActive()) workspace()->requestFocus(this); } info->setState(isShade() ? NET::Shaded : NET::States(0), NET::Shaded); info->setState(isShown(false) ? NET::States(0) : NET::Hidden, NET::Hidden); discardWindowPixmap(); updateVisibility(); updateAllowedActions(); updateWindowRules(Rules::Shade); emit shadeChanged(); } void Client::shadeHover() { setShade(ShadeHover); cancelShadeHoverTimer(); } void Client::shadeUnhover() { if (!tabGroup() || tabGroup()->current() == this || tabGroup()->current()->shadeMode() == ShadeNormal) setShade(ShadeNormal); cancelShadeHoverTimer(); } void Client::cancelShadeHoverTimer() { delete shadeHoverTimer; shadeHoverTimer = 0; } void Client::toggleShade() { // If the mode is ShadeHover or ShadeActive, cancel shade too setShade(shade_mode == ShadeNone ? ShadeNormal : ShadeNone); } void Client::updateVisibility() { if (deleting) return; if (hidden && isCurrentTab()) { info->setState(NET::Hidden, NET::Hidden); setSkipTaskbar(true); // Also hide from taskbar if (compositing() && options->hiddenPreviews() == HiddenPreviewsAlways) internalKeep(); else internalHide(); return; } if (isCurrentTab()) setSkipTaskbar(originalSkipTaskbar()); // Reset from 'hidden' if (isMinimized()) { info->setState(NET::Hidden, NET::Hidden); if (compositing() && options->hiddenPreviews() == HiddenPreviewsAlways) internalKeep(); else internalHide(); return; } info->setState(0, NET::Hidden); if (!isOnCurrentDesktop()) { if (compositing() && options->hiddenPreviews() != HiddenPreviewsNever) internalKeep(); else internalHide(); return; } if (!isOnCurrentActivity()) { if (compositing() && options->hiddenPreviews() != HiddenPreviewsNever) internalKeep(); else internalHide(); return; } internalShow(); } /** * Sets the client window's mapping state. Possible values are * WithdrawnState, IconicState, NormalState. - **/ + */ void Client::exportMappingState(int s) { assert(m_client != XCB_WINDOW_NONE); assert(!deleting || s == WithdrawnState); if (s == WithdrawnState) { m_client.deleteProperty(atoms->wm_state); return; } assert(s == NormalState || s == IconicState); int32_t data[2]; data[0] = s; data[1] = XCB_NONE; m_client.changeProperty(atoms->wm_state, atoms->wm_state, 32, 2, data); } void Client::internalShow() { if (mapping_state == Mapped) return; MappingState old = mapping_state; mapping_state = Mapped; if (old == Unmapped || old == Withdrawn) map(); if (old == Kept) { m_decoInputExtent.map(); updateHiddenPreview(); } emit windowShown(this); } void Client::internalHide() { if (mapping_state == Unmapped) return; MappingState old = mapping_state; mapping_state = Unmapped; if (old == Mapped || old == Kept) unmap(); if (old == Kept) updateHiddenPreview(); addWorkspaceRepaint(visibleRect()); workspace()->clientHidden(this); emit windowHidden(this); } void Client::internalKeep() { assert(compositing()); if (mapping_state == Kept) return; MappingState old = mapping_state; mapping_state = Kept; if (old == Unmapped || old == Withdrawn) map(); m_decoInputExtent.unmap(); if (isActive()) workspace()->focusToNull(); // get rid of input focus, bug #317484 updateHiddenPreview(); addWorkspaceRepaint(visibleRect()); workspace()->clientHidden(this); } /** * Maps (shows) the client. Note that it is mapping state of the frame, * not necessarily the client window itself (i.e. a shaded window is here * considered mapped, even though it is in IconicState). - **/ + */ void Client::map() { // XComposite invalidates backing pixmaps on unmap (minimize, different // virtual desktop, etc.). We kept the last known good pixmap around // for use in effects, but now we want to have access to the new pixmap if (compositing()) discardWindowPixmap(); m_frame.map(); if (!isShade()) { m_wrapper.map(); m_client.map(); m_decoInputExtent.map(); exportMappingState(NormalState); } else exportMappingState(IconicState); addLayerRepaint(visibleRect()); } /** * Unmaps the client. Again, this is about the frame. - **/ + */ void Client::unmap() { // Here it may look like a race condition, as some other client might try to unmap // the window between these two XSelectInput() calls. However, they're supposed to // use XWithdrawWindow(), which also sends a synthetic event to the root window, // which won't be missed, so this shouldn't be a problem. The chance the real UnmapNotify // will be missed is also very minimal, so I don't think it's needed to grab the server // here. m_wrapper.selectInput(ClientWinMask); // Avoid getting UnmapNotify m_frame.unmap(); m_wrapper.unmap(); m_client.unmap(); m_decoInputExtent.unmap(); m_wrapper.selectInput(ClientWinMask | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY); exportMappingState(IconicState); } /** * XComposite doesn't keep window pixmaps of unmapped windows, which means * there wouldn't be any previews of windows that are minimized or on another * virtual desktop. Therefore rawHide() actually keeps such windows mapped. * However special care needs to be taken so that such windows don't interfere. * Therefore they're put very low in the stacking order and they have input shape * set to none, which hopefully is enough. If there's no input shape available, * then it's hoped that there will be some other desktop above it *shrug*. * Using normal shape would be better, but that'd affect other things, e.g. painting * of the actual preview. - **/ + */ void Client::updateHiddenPreview() { if (hiddenPreview()) { workspace()->forceRestacking(); if (Xcb::Extensions::self()->isShapeInputAvailable()) { xcb_shape_rectangles(connection(), XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, XCB_CLIP_ORDERING_UNSORTED, frameId(), 0, 0, 0, NULL); } } else { workspace()->forceRestacking(); updateInputShape(); } } void Client::sendClientMessage(xcb_window_t w, xcb_atom_t a, xcb_atom_t protocol, uint32_t data1, uint32_t data2, uint32_t data3, xcb_timestamp_t timestamp) { xcb_client_message_event_t ev; memset(&ev, 0, sizeof(ev)); ev.response_type = XCB_CLIENT_MESSAGE; ev.window = w; ev.type = a; ev.format = 32; ev.data.data32[0] = protocol; ev.data.data32[1] = timestamp; ev.data.data32[2] = data1; ev.data.data32[3] = data2; ev.data.data32[4] = data3; uint32_t eventMask = 0; if (w == rootWindow()) { eventMask = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT; // Magic! } xcb_send_event(connection(), false, w, eventMask, reinterpret_cast(&ev)); xcb_flush(connection()); } /** * Returns whether the window may be closed (have a close button) - **/ + */ bool Client::isCloseable() const { return rules()->checkCloseable(m_motif.close() && !isSpecialWindow()); } /** * Closes the window by either sending a delete_window message or using XKill. - **/ + */ void Client::closeWindow() { if (!isCloseable()) return; // Update user time, because the window may create a confirming dialog. updateUserTime(); if (info->supportsProtocol(NET::DeleteWindowProtocol)) { sendClientMessage(window(), atoms->wm_protocols, atoms->wm_delete_window); pingWindow(); } else // Client will not react on wm_delete_window. We have not choice // but destroy his connection to the XServer. killWindow(); } /** * Kills the window via XKill - **/ + */ void Client::killWindow() { qCDebug(KWIN_CORE) << "Client::killWindow():" << caption(); killProcess(false); m_client.kill(); // Always kill this client at the server destroyClient(); } /** * Send a ping to the window using _NET_WM_PING if possible if it * doesn't respond within a reasonable time, it will be killed. - **/ + */ void Client::pingWindow() { if (!info->supportsProtocol(NET::PingProtocol)) return; // Can't ping :( if (options->killPingTimeout() == 0) return; // Turned off if (ping_timer != NULL) return; // Pinging already ping_timer = new QTimer(this); connect(ping_timer, &QTimer::timeout, this, [this]() { if (unresponsive()) { qCDebug(KWIN_CORE) << "Final ping timeout, asking to kill:" << caption(); ping_timer->deleteLater(); ping_timer = nullptr; killProcess(true, m_pingTimestamp); return; } qCDebug(KWIN_CORE) << "First ping timeout:" << caption(); setUnresponsive(true); ping_timer->start(); } ); ping_timer->setSingleShot(true); // we'll run the timer twice, at first we'll desaturate the window // and the second time we'll show the "do you want to kill" prompt ping_timer->start(options->killPingTimeout() / 2); m_pingTimestamp = xTime(); workspace()->sendPingToWindow(window(), m_pingTimestamp); } void Client::gotPing(xcb_timestamp_t timestamp) { // Just plain compare is not good enough because of 64bit and truncating and whatnot if (NET::timestampCompare(timestamp, m_pingTimestamp) != 0) return; delete ping_timer; ping_timer = NULL; setUnresponsive(false); if (m_killHelperPID && !::kill(m_killHelperPID, 0)) { // means the process is alive ::kill(m_killHelperPID, SIGTERM); m_killHelperPID = 0; } } void Client::killProcess(bool ask, xcb_timestamp_t timestamp) { if (m_killHelperPID && !::kill(m_killHelperPID, 0)) // means the process is alive return; Q_ASSERT(!ask || timestamp != XCB_TIME_CURRENT_TIME); pid_t pid = info->pid(); if (pid <= 0 || clientMachine()->hostName().isEmpty()) // Needed properties missing return; qCDebug(KWIN_CORE) << "Kill process:" << pid << "(" << clientMachine()->hostName() << ")"; if (!ask) { if (!clientMachine()->isLocal()) { QStringList lst; lst << QString::fromUtf8(clientMachine()->hostName()) << QStringLiteral("kill") << QString::number(pid); QProcess::startDetached(QStringLiteral("xon"), lst); } else ::kill(pid, SIGTERM); } else { QString hostname = clientMachine()->isLocal() ? QStringLiteral("localhost") : QString::fromUtf8(clientMachine()->hostName()); // execute helper from build dir or the system installed one const QFileInfo buildDirBinary{QDir{QCoreApplication::applicationDirPath()}, QStringLiteral("kwin_killer_helper")}; QProcess::startDetached(buildDirBinary.exists() ? buildDirBinary.absoluteFilePath() : QStringLiteral(KWIN_KILLER_BIN), QStringList() << QStringLiteral("--pid") << QString::number(unsigned(pid)) << QStringLiteral("--hostname") << hostname << QStringLiteral("--windowname") << captionNormal() << QStringLiteral("--applicationname") << QString::fromUtf8(resourceClass()) << QStringLiteral("--wid") << QString::number(window()) << QStringLiteral("--timestamp") << QString::number(timestamp), QString(), &m_killHelperPID); } } void Client::doSetSkipTaskbar() { info->setState(skipTaskbar() ? NET::SkipTaskbar : NET::States(0), NET::SkipTaskbar); } void Client::doSetSkipPager() { info->setState(skipPager() ? NET::SkipPager : NET::States(0), NET::SkipPager); } void Client::doSetSkipSwitcher() { info->setState(skipSwitcher() ? NET::SkipSwitcher : NET::States(0), NET::SkipSwitcher); } void Client::doSetDesktop(int desktop, int was_desk) { Q_UNUSED(desktop) Q_UNUSED(was_desk) updateVisibility(); // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Desktop); } /** * Sets whether the client is on @p activity. * If you remove it from its last activity, then it's on all activities. * * Note: If it was on all activities and you try to remove it from one, nothing will happen; * I don't think that's an important enough use case to handle here. - **/ + */ void Client::setOnActivity(const QString &activity, bool enable) { #ifdef KWIN_BUILD_ACTIVITIES if (! Activities::self()) { return; } QStringList newActivitiesList = activities(); if (newActivitiesList.contains(activity) == enable) //nothing to do return; if (enable) { QStringList allActivities = Activities::self()->all(); if (!allActivities.contains(activity)) //bogus ID return; newActivitiesList.append(activity); } else newActivitiesList.removeOne(activity); setOnActivities(newActivitiesList); #else Q_UNUSED(activity) Q_UNUSED(enable) #endif } /** * set exactly which activities this client is on - **/ + */ void Client::setOnActivities(QStringList newActivitiesList) { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return; } QString joinedActivitiesList = newActivitiesList.join(QStringLiteral(",")); joinedActivitiesList = rules()->checkActivity(joinedActivitiesList, false); newActivitiesList = joinedActivitiesList.split(u',', QString::SkipEmptyParts); QStringList allActivities = Activities::self()->all(); auto it = newActivitiesList.begin(); while (it != newActivitiesList.end()) { if (! allActivities.contains(*it)) { it = newActivitiesList.erase(it); } else { it++; } } if (// If we got the request to be on all activities explicitly newActivitiesList.isEmpty() || joinedActivitiesList == Activities::nullUuid() || // If we got a list of activities that covers all activities (newActivitiesList.count() > 1 && newActivitiesList.count() == allActivities.count())) { activityList.clear(); const QByteArray nullUuid = Activities::nullUuid().toUtf8(); m_client.changeProperty(atoms->activities, XCB_ATOM_STRING, 8, nullUuid.length(), nullUuid.constData()); } else { QByteArray joined = joinedActivitiesList.toLatin1(); activityList = newActivitiesList; m_client.changeProperty(atoms->activities, XCB_ATOM_STRING, 8, joined.length(), joined.constData()); } updateActivities(false); #else Q_UNUSED(newActivitiesList) #endif } void Client::blockActivityUpdates(bool b) { if (b) { ++m_activityUpdatesBlocked; } else { Q_ASSERT(m_activityUpdatesBlocked); --m_activityUpdatesBlocked; if (!m_activityUpdatesBlocked) updateActivities(m_blockedActivityUpdatesRequireTransients); } } /** * update after activities changed - **/ + */ void Client::updateActivities(bool includeTransients) { if (m_activityUpdatesBlocked) { m_blockedActivityUpdatesRequireTransients |= includeTransients; return; } emit activitiesChanged(this); m_blockedActivityUpdatesRequireTransients = false; // reset FocusChain::self()->update(this, FocusChain::MakeFirst); updateVisibility(); updateWindowRules(Rules::Activity); // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Activity); } /** * Returns the list of activities the client window is on. * if it's on all activities, the list will be empty. * Don't use this, use isOnActivity() and friends (from class Toplevel) - **/ + */ QStringList Client::activities() const { if (sessionActivityOverride) { return QStringList(); } return activityList; } /** * if @p on is true, sets on all activities. * if it's false, sets it to only be on the current activity - **/ + */ void Client::setOnAllActivities(bool on) { #ifdef KWIN_BUILD_ACTIVITIES if (on == isOnAllActivities()) return; if (on) { setOnActivities(QStringList()); } else { setOnActivity(Activities::self()->current(), true); } #else Q_UNUSED(on) #endif } /** * Performs the actual focusing of the window using XSetInputFocus and WM_TAKE_FOCUS - **/ + */ void Client::takeFocus() { if (rules()->checkAcceptFocus(info->input())) m_client.focus(); else demandAttention(false); // window cannot take input, at least withdraw urgency if (info->supportsProtocol(NET::TakeFocusProtocol)) { sendClientMessage(window(), atoms->wm_protocols, atoms->wm_take_focus, 0, 0, 0, XCB_CURRENT_TIME); } workspace()->setShouldGetFocus(this); bool breakShowingDesktop = !keepAbove(); if (breakShowingDesktop) { foreach (const Client *c, group()->members()) { if (c->isDesktop()) { breakShowingDesktop = false; break; } } } if (breakShowingDesktop) workspace()->setShowingDesktop(false); } /** * 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. * * \sa contextHelp() - **/ + */ bool Client::providesContextHelp() const { return info->supportsProtocol(NET::ContextHelpProtocol); } /** * Invokes context help on the window. Only works if the window * actually provides context help. * * \sa providesContextHelp() - **/ + */ void Client::showContextHelp() { if (info->supportsProtocol(NET::ContextHelpProtocol)) { sendClientMessage(window(), atoms->wm_protocols, atoms->net_wm_context_help); } } /** * Fetches the window's caption (WM_NAME property). It will be * stored in the client's caption(). - **/ + */ void Client::fetchName() { setCaption(readName()); } static inline QString readNameProperty(xcb_window_t w, xcb_atom_t atom) { const auto cookie = xcb_icccm_get_text_property_unchecked(connection(), w, atom); xcb_icccm_get_text_property_reply_t reply; if (xcb_icccm_get_wm_name_reply(connection(), cookie, &reply, nullptr)) { QString retVal; if (reply.encoding == atoms->utf8_string) { retVal = QString::fromUtf8(QByteArray(reply.name, reply.name_len)); } else if (reply.encoding == XCB_ATOM_STRING) { retVal = QString::fromLocal8Bit(QByteArray(reply.name, reply.name_len)); } xcb_icccm_get_text_property_reply_wipe(&reply); return retVal.simplified(); } return QString(); } QString Client::readName() const { if (info->name() && info->name()[0] != '\0') return QString::fromUtf8(info->name()).simplified(); else { return readNameProperty(window(), XCB_ATOM_WM_NAME); } } // The list is taken from https://www.unicode.org/reports/tr9/ (#154840) static const QChar LRM(0x200E); void Client::setCaption(const QString& _s, bool force) { QString s(_s); for (int i = 0; i < s.length(); ) { if (!s[i].isPrint()) { if (QChar(s[i]).isHighSurrogate() && i + 1 < s.length() && QChar(s[i + 1]).isLowSurrogate()) { const uint uc = QChar::surrogateToUcs4(s[i], s[i + 1]); if (!QChar::isPrint(uc)) { s.remove(i, 2); } else { i += 2; } continue; } s.remove(i, 1); continue; } ++i; } const bool changed = (s != cap_normal); if (!force && !changed) { return; } cap_normal = s; if (!force && !changed) { emit captionChanged(); return; } bool reset_name = force; bool was_suffix = (!cap_suffix.isEmpty()); cap_suffix.clear(); QString machine_suffix; if (!options->condensedTitle()) { // machine doesn't qualify for "clean" if (clientMachine()->hostName() != ClientMachine::localhost() && !clientMachine()->isLocal()) machine_suffix = QLatin1String(" <@") + QString::fromUtf8(clientMachine()->hostName()) + QLatin1Char('>') + LRM; } QString shortcut_suffix = shortcutCaptionSuffix(); cap_suffix = machine_suffix + shortcut_suffix; if ((!isSpecialWindow() || isToolbar()) && findClientWithSameCaption()) { int i = 2; do { cap_suffix = machine_suffix + QLatin1String(" <") + QString::number(i) + QLatin1Char('>') + LRM; i++; } while (findClientWithSameCaption()); info->setVisibleName(caption().toUtf8().constData()); reset_name = false; } if ((was_suffix && cap_suffix.isEmpty()) || reset_name) { // If it was new window, it may have old value still set, if the window is reused info->setVisibleName(""); info->setVisibleIconName(""); } else if (!cap_suffix.isEmpty() && !cap_iconic.isEmpty()) // Keep the same suffix in iconic name if it's set info->setVisibleIconName(QString(cap_iconic + cap_suffix).toUtf8().constData()); emit captionChanged(); } void Client::updateCaption() { setCaption(cap_normal, true); } void Client::fetchIconicName() { QString s; if (info->iconName() && info->iconName()[0] != '\0') s = QString::fromUtf8(info->iconName()); else s = readNameProperty(window(), XCB_ATOM_WM_ICON_NAME); if (s != cap_iconic) { bool was_set = !cap_iconic.isEmpty(); cap_iconic = s; if (!cap_suffix.isEmpty()) { if (!cap_iconic.isEmpty()) // Keep the same suffix in iconic name if it's set info->setVisibleIconName(QString(s + cap_suffix).toUtf8().constData()); else if (was_set) info->setVisibleIconName(""); } } } void Client::setClientShown(bool shown) { if (deleting) return; // Don't change shown status if this client is being deleted if (shown != hidden) return; // nothing to change hidden = !shown; if (options->isInactiveTabsSkipTaskbar()) setSkipTaskbar(hidden); // TODO: Causes reshuffle of the taskbar if (shown) { map(); takeFocus(); autoRaise(); FocusChain::self()->update(this, FocusChain::MakeFirst); } else { unmap(); // Don't move tabs to the end of the list when another tab get's activated if (isCurrentTab()) FocusChain::self()->update(this, FocusChain::MakeLast); addWorkspaceRepaint(visibleRect()); } } void Client::getMotifHints() { const bool wasClosable = m_motif.close(); const bool wasNoBorder = m_motif.noBorder(); if (m_managed) // only on property change, initial read is prefetched m_motif.fetch(); m_motif.read(); if (m_motif.hasDecoration() && m_motif.noBorder() != wasNoBorder) { // If we just got a hint telling us to hide decorations, we do so. if (m_motif.noBorder()) noborder = rules()->checkNoBorder(true); // If the Motif hint is now telling us to show decorations, we only do so if the app didn't // instruct us to hide decorations in some other way, though. else if (!app_noborder) noborder = rules()->checkNoBorder(false); } // mminimize; - Ignore, bogus - E.g. shading or sending to another desktop is "minimizing" too // mmaximize; - Ignore, bogus - Maximizing is basically just resizing const bool closabilityChanged = wasClosable != m_motif.close(); if (isManaged()) updateDecoration(true); // Check if noborder state has changed if (closabilityChanged) { emit closeableChanged(isCloseable()); } } void Client::getIcons() { // First read icons from the window itself const QString themedIconName = iconFromDesktopFile(); if (!themedIconName.isEmpty()) { setIcon(QIcon::fromTheme(themedIconName)); return; } QIcon icon; auto readIcon = [this, &icon](int size, bool scale = true) { const QPixmap pix = KWindowSystem::icon(window(), size, size, scale, KWindowSystem::NETWM | KWindowSystem::WMHints, info); if (!pix.isNull()) { icon.addPixmap(pix); } }; readIcon(16); readIcon(32); readIcon(48, false); readIcon(64, false); readIcon(128, false); if (icon.isNull()) { // Then try window group icon = group()->icon(); } if (icon.isNull() && isTransient()) { // Then mainclients auto mainclients = mainClients(); for (auto it = mainclients.constBegin(); it != mainclients.constEnd() && icon.isNull(); ++it) { if (!(*it)->icon().isNull()) { icon = (*it)->icon(); break; } } } if (icon.isNull()) { // And if nothing else, load icon from classhint or xapp icon icon.addPixmap(KWindowSystem::icon(window(), 32, 32, true, KWindowSystem::ClassHint | KWindowSystem::XApp, info)); icon.addPixmap(KWindowSystem::icon(window(), 16, 16, true, KWindowSystem::ClassHint | KWindowSystem::XApp, info)); icon.addPixmap(KWindowSystem::icon(window(), 64, 64, false, KWindowSystem::ClassHint | KWindowSystem::XApp, info)); icon.addPixmap(KWindowSystem::icon(window(), 128, 128, false, KWindowSystem::ClassHint | KWindowSystem::XApp, info)); } setIcon(icon); } void Client::getSyncCounter() { // TODO: make sync working on XWayland static const bool isX11 = kwinApp()->operationMode() == Application::OperationModeX11; if (!Xcb::Extensions::self()->isSyncAvailable() || !isX11) return; Xcb::Property syncProp(false, window(), atoms->net_wm_sync_request_counter, XCB_ATOM_CARDINAL, 0, 1); const xcb_sync_counter_t counter = syncProp.value(XCB_NONE); if (counter != XCB_NONE) { syncRequest.counter = counter; syncRequest.value.hi = 0; syncRequest.value.lo = 0; auto *c = connection(); xcb_sync_set_counter(c, syncRequest.counter, syncRequest.value); if (syncRequest.alarm == XCB_NONE) { const uint32_t mask = XCB_SYNC_CA_COUNTER | XCB_SYNC_CA_VALUE_TYPE | XCB_SYNC_CA_TEST_TYPE | XCB_SYNC_CA_EVENTS; const uint32_t values[] = { syncRequest.counter, XCB_SYNC_VALUETYPE_RELATIVE, XCB_SYNC_TESTTYPE_POSITIVE_TRANSITION, 1 }; syncRequest.alarm = xcb_generate_id(c); auto cookie = xcb_sync_create_alarm_checked(c, syncRequest.alarm, mask, values); ScopedCPointer error(xcb_request_check(c, cookie)); if (!error.isNull()) { syncRequest.alarm = XCB_NONE; } else { xcb_sync_change_alarm_value_list_t value; memset(&value, 0, sizeof(value)); value.value.hi = 0; value.value.lo = 1; value.delta.hi = 0; value.delta.lo = 1; xcb_sync_change_alarm_aux(c, syncRequest.alarm, XCB_SYNC_CA_DELTA | XCB_SYNC_CA_VALUE, &value); } } } } /** * Send the client a _NET_SYNC_REQUEST - **/ + */ void Client::sendSyncRequest() { if (syncRequest.counter == XCB_NONE || syncRequest.isPending) return; // do NOT, NEVER send a sync request when there's one on the stack. the clients will just stop respoding. FOREVER! ... if (!syncRequest.failsafeTimeout) { syncRequest.failsafeTimeout = new QTimer(this); connect(syncRequest.failsafeTimeout, &QTimer::timeout, this, [this]() { // client does not respond to XSYNC requests in reasonable time, remove support if (!ready_for_painting) { // failed on initial pre-show request setReadyForPainting(); setupWindowManagementInterface(); return; } // failed during resize syncRequest.isPending = false; syncRequest.counter = syncRequest.alarm = XCB_NONE; delete syncRequest.timeout; delete syncRequest.failsafeTimeout; syncRequest.timeout = syncRequest.failsafeTimeout = nullptr; syncRequest.lastTimestamp = XCB_CURRENT_TIME; } ); syncRequest.failsafeTimeout->setSingleShot(true); } // if there's no response within 10 seconds, sth. went wrong and we remove XSYNC support from this client. // see events.cpp Client::syncEvent() syncRequest.failsafeTimeout->start(ready_for_painting ? 10000 : 1000); // We increment before the notify so that after the notify // syncCounterSerial will equal the value we are expecting // in the acknowledgement const uint32_t oldLo = syncRequest.value.lo; syncRequest.value.lo++;; if (oldLo > syncRequest.value.lo) { syncRequest.value.hi++; } if (syncRequest.lastTimestamp >= xTime()) { updateXTime(); } // Send the message to client sendClientMessage(window(), atoms->wm_protocols, atoms->net_wm_sync_request, syncRequest.value.lo, syncRequest.value.hi); syncRequest.isPending = true; syncRequest.lastTimestamp = xTime(); } bool Client::wantsInput() const { return rules()->checkAcceptFocus(acceptsFocus() || info->supportsProtocol(NET::TakeFocusProtocol)); } bool Client::acceptsFocus() const { return info->input(); } void Client::setBlockingCompositing(bool block) { const bool usedToBlock = blocks_compositing; blocks_compositing = rules()->checkBlockCompositing(block && options->windowsBlockCompositing()); if (usedToBlock != blocks_compositing) { emit blockingCompositingChanged(blocks_compositing ? this : 0); } } void Client::updateAllowedActions(bool force) { if (!isManaged() && !force) return; NET::Actions old_allowed_actions = NET::Actions(allowed_actions); allowed_actions = 0; if (isMovable()) allowed_actions |= NET::ActionMove; if (isResizable()) allowed_actions |= NET::ActionResize; if (isMinimizable()) allowed_actions |= NET::ActionMinimize; if (isShadeable()) allowed_actions |= NET::ActionShade; // Sticky state not supported if (isMaximizable()) allowed_actions |= NET::ActionMax; if (userCanSetFullScreen()) allowed_actions |= NET::ActionFullScreen; allowed_actions |= NET::ActionChangeDesktop; // Always (Pagers shouldn't show Docks etc.) if (isCloseable()) allowed_actions |= NET::ActionClose; if (old_allowed_actions == allowed_actions) return; // TODO: This could be delayed and compressed - It's only for pagers etc. anyway info->setAllowedActions(allowed_actions); // ONLY if relevant features have changed (and the window didn't just get/loose moveresize for maximization state changes) const NET::Actions relevant = ~(NET::ActionMove|NET::ActionResize); if ((allowed_actions & relevant) != (old_allowed_actions & relevant)) { if ((allowed_actions & NET::ActionMinimize) != (old_allowed_actions & NET::ActionMinimize)) { emit minimizeableChanged(allowed_actions & NET::ActionMinimize); } if ((allowed_actions & NET::ActionShade) != (old_allowed_actions & NET::ActionShade)) { emit shadeableChanged(allowed_actions & NET::ActionShade); } if ((allowed_actions & NET::ActionMax) != (old_allowed_actions & NET::ActionMax)) { emit maximizeableChanged(allowed_actions & NET::ActionMax); } } } void Client::debug(QDebug& stream) const { stream.nospace(); print(stream); } Xcb::StringProperty Client::fetchActivities() const { #ifdef KWIN_BUILD_ACTIVITIES return Xcb::StringProperty(window(), atoms->activities); #else return Xcb::StringProperty(); #endif } void Client::readActivities(Xcb::StringProperty &property) { #ifdef KWIN_BUILD_ACTIVITIES QStringList newActivitiesList; QString prop = QString::fromUtf8(property); activitiesDefined = !prop.isEmpty(); if (prop == Activities::nullUuid()) { //copied from setOnAllActivities to avoid a redundant XChangeProperty. if (!activityList.isEmpty()) { activityList.clear(); updateActivities(true); } return; } if (prop.isEmpty()) { //note: this makes it *act* like it's on all activities but doesn't set the property to 'ALL' if (!activityList.isEmpty()) { activityList.clear(); updateActivities(true); } return; } newActivitiesList = prop.split(u','); if (newActivitiesList == activityList) return; //expected change, it's ok. //otherwise, somebody else changed it. we need to validate before reacting. //if the activities are not synced, and there are existing clients with //activities specified, somebody has restarted kwin. we can not validate //activities in this case. we need to trust the old values. if (Activities::self() && Activities::self()->serviceStatus() != KActivities::Consumer::Unknown) { QStringList allActivities = Activities::self()->all(); if (allActivities.isEmpty()) { qCDebug(KWIN_CORE) << "no activities!?!?"; //don't touch anything, there's probably something bad going on and we don't wanna make it worse return; } for (int i = 0; i < newActivitiesList.size(); ++i) { if (! allActivities.contains(newActivitiesList.at(i))) { qCDebug(KWIN_CORE) << "invalid:" << newActivitiesList.at(i); newActivitiesList.removeAt(i--); } } } setOnActivities(newActivitiesList); #else Q_UNUSED(property) #endif } void Client::checkActivities() { #ifdef KWIN_BUILD_ACTIVITIES Xcb::StringProperty property = fetchActivities(); readActivities(property); #endif } void Client::setSessionActivityOverride(bool needed) { sessionActivityOverride = needed; updateActivities(false); } QRect Client::decorationRect() const { return QRect(0, 0, width(), height()); } Xcb::Property Client::fetchFirstInTabBox() const { return Xcb::Property(false, m_client, atoms->kde_first_in_window_list, atoms->kde_first_in_window_list, 0, 1); } void Client::readFirstInTabBox(Xcb::Property &property) { setFirstInTabBox(property.toBool(32, atoms->kde_first_in_window_list)); } void Client::updateFirstInTabBox() { // TODO: move into KWindowInfo Xcb::Property property = fetchFirstInTabBox(); readFirstInTabBox(property); } Xcb::StringProperty Client::fetchColorScheme() const { return Xcb::StringProperty(m_client, atoms->kde_color_sheme); } void Client::readColorScheme(Xcb::StringProperty &property) { AbstractClient::updateColorScheme(rules()->checkDecoColor(QString::fromUtf8(property))); } void Client::updateColorScheme() { Xcb::StringProperty property = fetchColorScheme(); readColorScheme(property); } bool Client::isClient() const { return true; } NET::WindowType Client::windowType(bool direct, int supportedTypes) const { // TODO: does it make sense to cache the returned window type for SUPPORTED_MANAGED_WINDOW_TYPES_MASK? if (supportedTypes == 0) { supportedTypes = SUPPORTED_MANAGED_WINDOW_TYPES_MASK; } NET::WindowType wt = info->windowType(NET::WindowTypes(supportedTypes)); if (direct) { return wt; } NET::WindowType wt2 = rules()->checkType(wt); if (wt != wt2) { wt = wt2; info->setWindowType(wt); // force hint change } // hacks here if (wt == NET::Unknown) // this is more or less suggested in NETWM spec wt = isTransient() ? NET::Dialog : NET::Normal; return wt; } void Client::cancelFocusOutTimer() { if (m_focusOutTimer) { m_focusOutTimer->stop(); } } xcb_window_t Client::frameId() const { return m_frame; } Xcb::Property Client::fetchShowOnScreenEdge() const { return Xcb::Property(false, window(), atoms->kde_screen_edge_show, XCB_ATOM_CARDINAL, 0, 1); } void Client::readShowOnScreenEdge(Xcb::Property &property) { //value comes in two parts, edge in the lower byte //then the type in the upper byte // 0 = autohide // 1 = raise in front on activate const uint32_t value = property.value(ElectricNone); ElectricBorder border = ElectricNone; switch (value & 0xFF) { case 0: border = ElectricTop; break; case 1: border = ElectricRight; break; case 2: border = ElectricBottom; break; case 3: border = ElectricLeft; break; } if (border != ElectricNone) { disconnect(m_edgeRemoveConnection); disconnect(m_edgeGeometryTrackingConnection); bool successfullyHidden = false; if (((value >> 8) & 0xFF) == 1) { setKeepBelow(true); successfullyHidden = keepBelow(); //request could have failed due to user kwin rules m_edgeRemoveConnection = connect(this, &AbstractClient::keepBelowChanged, this, [this](){ if (!keepBelow()) { ScreenEdges::self()->reserve(this, ElectricNone); } }); } else { hideClient(true); successfullyHidden = isHiddenInternal(); m_edgeGeometryTrackingConnection = connect(this, &Client::geometryChanged, this, [this, border](){ hideClient(true); ScreenEdges::self()->reserve(this, border); }); } if (successfullyHidden) { ScreenEdges::self()->reserve(this, border); } else { ScreenEdges::self()->reserve(this, ElectricNone); } } else if (!property.isNull() && property->type != XCB_ATOM_NONE) { // property value is incorrect, delete the property // so that the client knows that it is not hidden xcb_delete_property(connection(), window(), atoms->kde_screen_edge_show); } else { // restore // TODO: add proper unreserve //this will call showOnScreenEdge to reset the state disconnect(m_edgeGeometryTrackingConnection); ScreenEdges::self()->reserve(this, ElectricNone); } } void Client::updateShowOnScreenEdge() { Xcb::Property property = fetchShowOnScreenEdge(); readShowOnScreenEdge(property); } void Client::showOnScreenEdge() { disconnect(m_edgeRemoveConnection); hideClient(false); setKeepBelow(false); xcb_delete_property(connection(), window(), atoms->kde_screen_edge_show); } void Client::addDamage(const QRegion &damage) { if (!ready_for_painting) { // avoid "setReadyForPainting()" function calling overhead if (syncRequest.counter == XCB_NONE) { // cannot detect complete redraw, consider done now setReadyForPainting(); setupWindowManagementInterface(); } } repaints_region += damage; Toplevel::addDamage(damage); } bool Client::belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const { const Client *c2 = dynamic_cast(other); if (!c2) { return false; } return Client::belongToSameApplication(this, c2, checks); } void Client::updateTabGroupStates(TabGroup::States states) { if (auto t = tabGroup()) { t->updateStates(this, states); } } QSize Client::resizeIncrements() const { return m_geometryHints.resizeIncrements(); } Xcb::StringProperty Client::fetchApplicationMenuServiceName() const { return Xcb::StringProperty(m_client, atoms->kde_net_wm_appmenu_service_name); } void Client::readApplicationMenuServiceName(Xcb::StringProperty &property) { updateApplicationMenuServiceName(QString::fromUtf8(property)); } void Client::checkApplicationMenuServiceName() { Xcb::StringProperty property = fetchApplicationMenuServiceName(); readApplicationMenuServiceName(property); } Xcb::StringProperty Client::fetchApplicationMenuObjectPath() const { return Xcb::StringProperty(m_client, atoms->kde_net_wm_appmenu_object_path); } void Client::readApplicationMenuObjectPath(Xcb::StringProperty &property) { updateApplicationMenuObjectPath(QString::fromUtf8(property)); } void Client::checkApplicationMenuObjectPath() { Xcb::StringProperty property = fetchApplicationMenuObjectPath(); readApplicationMenuObjectPath(property); } void Client::handleSync() { setReadyForPainting(); setupWindowManagementInterface(); syncRequest.isPending = false; if (syncRequest.failsafeTimeout) syncRequest.failsafeTimeout->stop(); if (isResize()) { if (syncRequest.timeout) syncRequest.timeout->stop(); performMoveResize(); } else // setReadyForPainting does as well, but there's a small chance for resize syncs after the resize ended addRepaintFull(); } } // namespace diff --git a/client.h b/client.h index 7813ace08..58f050ce7 100644 --- a/client.h +++ b/client.h @@ -1,699 +1,699 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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_CLIENT_H #define KWIN_CLIENT_H // kwin #include "options.h" #include "rules.h" #include "tabgroup.h" #include "abstract_client.h" #include "xcbutils.h" // Qt #include #include #include #include #include // X #include // TODO: Cleanup the order of things in this .h file class QTimer; class KStartupInfoData; class KStartupInfoId; namespace KWin { /** * @brief Defines Predicates on how to search for a Client. * * Used by Workspace::findClient. - **/ + */ enum class Predicate { WindowMatch, WrapperIdMatch, FrameIdMatch, InputIdMatch }; class KWIN_EXPORT Client : public AbstractClient { Q_OBJECT /** * 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. * The value is evaluated each time the getter is called. * Because of that no changed signal is provided. - **/ + */ Q_PROPERTY(QSize basicUnit READ basicUnit) /** * A client can block compositing. That is while the Client is alive and the state is set, * Compositing is suspended and is resumed when there are no Clients blocking compositing any * more. * * This is actually set by a window property, unfortunately not used by the target application * group. For convenience it's exported as a property to the scripts. * * Use with care! - **/ + */ Q_PROPERTY(bool blocksCompositing READ isBlockingCompositing WRITE setBlockingCompositing NOTIFY blockingCompositingChanged) /** * Whether the Client uses client side window decorations. * Only GTK+ are detected. - **/ + */ Q_PROPERTY(bool clientSideDecorated READ isClientSideDecorated NOTIFY clientSideDecoratedChanged) public: explicit Client(); xcb_window_t wrapperId() const; xcb_window_t inputId() const { return m_decoInputExtent; } xcb_window_t frameId() const override; bool isTransient() const override; bool groupTransient() const override; bool wasOriginallyGroupTransient() const; QList mainClients() const override; // Call once before loop , is not indirect bool hasTransient(const AbstractClient* c, bool indirect) const override; void checkTransient(xcb_window_t w); AbstractClient* findModal(bool allow_itself = false) override; const Group* group() const override; Group* group() override; void checkGroup(Group* gr = NULL, bool force = false); void changeClientLeaderGroup(Group* gr); void updateWindowRules(Rules::Types selection) override; void updateFullscreenMonitors(NETFullscreenMonitors topology); bool hasNETSupport() const; QSize minSize() const override; QSize maxSize() const override; QSize basicUnit() const; QSize clientSize() const override; QPoint inputPos() const { return input_offset; } // Inside of geometry() bool windowEvent(xcb_generic_event_t *e); NET::WindowType windowType(bool direct = false, int supported_types = 0) const override; bool manage(xcb_window_t w, bool isMapped); void releaseWindow(bool on_shutdown = false); void destroyClient(); QStringList activities() const override; void setOnActivity(const QString &activity, bool enable); void setOnAllActivities(bool set) override; void setOnActivities(QStringList newActivitiesList) override; void updateActivities(bool includeTransients); void blockActivityUpdates(bool b = true) override; /// Is not minimized and not hidden. I.e. normally visible on some virtual desktop. bool isShown(bool shaded_is_shown) const override; bool isHiddenInternal() const override; // For compositing ShadeMode shadeMode() const override; // Prefer isShade() void setShade(ShadeMode mode) override; bool isShadeable() const override; bool isMaximizable() const override; QRect geometryRestore() const override; MaximizeMode maximizeMode() const override; bool isMinimizable() const override; QRect iconGeometry() const override; bool isFullScreenable() const override; void setFullScreen(bool set, bool user = true) override; bool isFullScreen() const override; bool userCanSetFullScreen() const override; QRect geometryFSRestore() const { return geom_fs_restore; // only for session saving } int fullScreenMode() const { return m_fullscreenMode; // only for session saving } bool userNoBorder() const; bool noBorder() const override; void setNoBorder(bool set) override; bool userCanSetNoBorder() const override; void checkNoBorder() override; int sessionStackingOrder() const; // Auxiliary functions, depend on the windowType bool wantsInput() const override; bool isResizable() const override; bool isMovable() const override; bool isMovableAcrossScreens() const override; bool isCloseable() const override; ///< May be closed by the user (May have a close button) void takeFocus() override; void updateDecoration(bool check_workspace_pos, bool force = false) override; void updateShape(); using AbstractClient::setGeometry; void setGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) override; /// plainResize() simply resizes void plainResize(int w, int h, ForceGeometry_t force = NormalGeometrySet); void plainResize(const QSize& s, ForceGeometry_t force = NormalGeometrySet); /// resizeWithChecks() resizes according to gravity, and checks workarea position using AbstractClient::resizeWithChecks; void resizeWithChecks(int w, int h, ForceGeometry_t force = NormalGeometrySet) override; void resizeWithChecks(int w, int h, xcb_gravity_t gravity, ForceGeometry_t force = NormalGeometrySet); void resizeWithChecks(const QSize& s, xcb_gravity_t gravity, ForceGeometry_t force = NormalGeometrySet); QSize sizeForClientSize(const QSize&, Sizemode mode = SizemodeAny, bool noframe = false) const override; bool providesContextHelp() const override; Options::WindowOperation mouseButtonToWindowOperation(Qt::MouseButtons button); bool performMouseCommand(Options::MouseCommand, const QPoint& globalPos) override; QRect adjustedClientArea(const QRect& desktop, const QRect& area) const; xcb_colormap_t colormap() const; /// Updates visibility depending on being shaded, virtual desktop, etc. void updateVisibility(); /// Hides a client - Basically like minimize, but without effects, it's simply hidden void hideClient(bool hide) override; bool hiddenPreview() const; ///< Window is mapped in order to get a window pixmap bool setupCompositing() override; void finishCompositing(ReleaseReason releaseReason = ReleaseReason::Release) override; void setBlockingCompositing(bool block); inline bool isBlockingCompositing() { return blocks_compositing; } QString captionNormal() const override { return cap_normal; } QString captionSuffix() const override { return cap_suffix; } using AbstractClient::keyPressEvent; void keyPressEvent(uint key_code, xcb_timestamp_t time); // FRAME ?? void updateMouseGrab() override; xcb_window_t moveResizeGrabWindow() const; const QPoint calculateGravitation(bool invert, int gravity = 0) const; // FRAME public? void NETMoveResize(int x_root, int y_root, NET::Direction direction); void NETMoveResizeWindow(int flags, int x, int y, int width, int height); void restackWindow(xcb_window_t above, int detail, NET::RequestSource source, xcb_timestamp_t timestamp, bool send_event = false); void gotPing(xcb_timestamp_t timestamp); void updateUserTime(xcb_timestamp_t time = XCB_TIME_CURRENT_TIME); xcb_timestamp_t userTime() const override; bool hasUserTimeSupport() const; /// Does 'delete c;' static void deleteClient(Client* c); static bool belongToSameApplication(const Client* c1, const Client* c2, SameApplicationChecks checks = SameApplicationChecks()); static bool sameAppWindowRoleMatch(const Client* c1, const Client* c2, bool active_hack); void killWindow() override; void toggleShade(); void showContextHelp() override; void cancelShadeHoverTimer(); void checkActiveModal(); StrutRect strutRect(StrutArea area) const; StrutRects strutRects() const; bool hasStrut() const override; /** * If shown is true the client is mapped and raised, if false * the client is unmapped and hidden, this function is called * when the tabbing group of the client switches its visible * client. - **/ + */ void setClientShown(bool shown) override; /** * Whether or not the window has a strut that expands through the invisible area of * an xinerama setup where the monitors are not the same resolution. - **/ + */ bool hasOffscreenXineramaStrut() const; // Decorations <-> Effects QRect decorationRect() const override; QRect transparentRect() const override; bool isClientSideDecorated() const; bool wantsShadowToBeRendered() const override; void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const override; Xcb::Property fetchFirstInTabBox() const; void readFirstInTabBox(Xcb::Property &property); void updateFirstInTabBox(); Xcb::StringProperty fetchColorScheme() const; void readColorScheme(Xcb::StringProperty &property); void updateColorScheme() override; //sets whether the client should be faked as being on all activities (and be shown during session save) void setSessionActivityOverride(bool needed); bool isClient() const override; template void print(T &stream) const; void cancelFocusOutTimer(); /** * Restores the Client after it had been hidden due to show on screen edge functionality. * In addition the property gets deleted so that the Client knows that it is visible again. - **/ + */ void showOnScreenEdge() override; Xcb::StringProperty fetchApplicationMenuServiceName() const; void readApplicationMenuServiceName(Xcb::StringProperty &property); void checkApplicationMenuServiceName(); Xcb::StringProperty fetchApplicationMenuObjectPath() const; void readApplicationMenuObjectPath(Xcb::StringProperty &property); void checkApplicationMenuObjectPath(); struct SyncRequest { xcb_sync_counter_t counter; xcb_sync_int64_t value; xcb_sync_alarm_t alarm; xcb_timestamp_t lastTimestamp; QTimer *timeout, *failsafeTimeout; bool isPending; }; const SyncRequest &getSyncRequest() const { return syncRequest; } void handleSync(); static void cleanupX11(); public Q_SLOTS: void closeWindow() override; void updateCaption() override; private Q_SLOTS: void shadeHover(); void shadeUnhover(); private: // Use Workspace::createClient() ~Client() override; ///< Use destroyClient() or releaseWindow() // Handlers for X11 events bool mapRequestEvent(xcb_map_request_event_t *e); void unmapNotifyEvent(xcb_unmap_notify_event_t *e); void destroyNotifyEvent(xcb_destroy_notify_event_t *e); void configureRequestEvent(xcb_configure_request_event_t *e); void propertyNotifyEvent(xcb_property_notify_event_t *e) override; void clientMessageEvent(xcb_client_message_event_t *e) override; void enterNotifyEvent(xcb_enter_notify_event_t *e); void leaveNotifyEvent(xcb_leave_notify_event_t *e); void focusInEvent(xcb_focus_in_event_t *e); void focusOutEvent(xcb_focus_out_event_t *e); void damageNotifyEvent() override; bool buttonPressEvent(xcb_window_t w, int button, int state, int x, int y, int x_root, int y_root, xcb_timestamp_t time = XCB_CURRENT_TIME); bool buttonReleaseEvent(xcb_window_t w, int button, int state, int x, int y, int x_root, int y_root); bool motionNotifyEvent(xcb_window_t w, int state, int x, int y, int x_root, int y_root); Client* findAutogroupCandidate() const; protected: void debug(QDebug& stream) const override; void addDamage(const QRegion &damage) override; bool belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const override; void doSetActive() override; void doSetKeepAbove() override; void doSetKeepBelow() override; void doSetDesktop(int desktop, int was_desk) override; void doMinimize() override; void doSetSkipPager() override; void doSetSkipTaskbar() override; void doSetSkipSwitcher() override; bool belongsToDesktop() const override; void setGeometryRestore(const QRect &geo) override; void updateTabGroupStates(TabGroup::States states) override; void doMove(int x, int y) override; bool doStartMoveResize() override; void doPerformMoveResize() override; bool isWaitingForMoveResizeSync() const override; void doResizeSync() override; QSize resizeIncrements() const override; bool acceptsFocus() const override; //Signals for the scripting interface //Signals make an excellent way for communication //in between objects as compared to simple function //calls Q_SIGNALS: void clientManaging(KWin::Client*); void clientFullScreenSet(KWin::Client*, bool, bool); /** * Emitted whenever the Client want to show it menu - **/ + */ void showRequest(); /** * Emitted whenever the Client's menu is closed - **/ + */ void menuHidden(); /** * Emitted whenever the Client's menu is available - **/ + */ void appMenuAvailable(); /** * Emitted whenever the Client's menu is unavailable - **/ + */ void appMenuUnavailable(); /** * Emitted whenever the Client's block compositing state changes. - **/ + */ void blockingCompositingChanged(KWin::Client *client); void clientSideDecoratedChanged(); private: void exportMappingState(int s); // ICCCM 4.1.3.1, 4.1.4, NETWM 2.5.1 bool isManaged() const; ///< Returns false if this client is not yet managed void updateAllowedActions(bool force = false); QRect fullscreenMonitorsArea(NETFullscreenMonitors topology) const; void changeMaximize(bool horizontal, bool vertical, bool adjust) override; void getWmNormalHints(); void getMotifHints(); void getIcons(); void fetchName(); void fetchIconicName(); QString readName() const; void setCaption(const QString& s, bool force = false); bool hasTransientInternal(const Client* c, bool indirect, ConstClientList& set) const; void setShortcutInternal() override; void configureRequest(int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool); NETExtendedStrut strut() const; int checkShadeGeometry(int w, int h); void getSyncCounter(); void sendSyncRequest(); void leaveMoveResize() override; void positionGeometryTip() override; void grabButton(int mod); void ungrabButton(int mod); void resizeDecoration(); void createDecoration(const QRect &oldgeom); void pingWindow(); void killProcess(bool ask, xcb_timestamp_t timestamp = XCB_TIME_CURRENT_TIME); void updateUrgency(); static void sendClientMessage(xcb_window_t w, xcb_atom_t a, xcb_atom_t protocol, uint32_t data1 = 0, uint32_t data2 = 0, uint32_t data3 = 0, xcb_timestamp_t timestamp = xTime()); void embedClient(xcb_window_t w, xcb_visualid_t visualid, xcb_colormap_t colormap, uint8_t depth); void detectNoBorder(); Xcb::Property fetchGtkFrameExtents() const; void readGtkFrameExtents(Xcb::Property &prop); void detectGtkFrameExtents(); void destroyDecoration() override; void updateFrameExtents(); void internalShow(); void internalHide(); void internalKeep(); void map(); void unmap(); void updateHiddenPreview(); void updateInputShape(); xcb_timestamp_t readUserTimeMapTimestamp(const KStartupInfoId* asn_id, const KStartupInfoData* asn_data, bool session) const; xcb_timestamp_t readUserCreationTime() const; void startupIdChanged(); void updateInputWindow(); Xcb::Property fetchShowOnScreenEdge() const; void readShowOnScreenEdge(Xcb::Property &property); /** * Reads the property and creates/destroys the screen edge if required * and shows/hides the client. - **/ + */ void updateShowOnScreenEdge(); Xcb::Window m_client; Xcb::Window m_wrapper; Xcb::Window m_frame; QStringList activityList; int m_activityUpdatesBlocked; bool m_blockedActivityUpdatesRequireTransients; Xcb::Window m_moveResizeGrabWindow; bool move_resize_has_keyboard_grab; bool m_managed; Xcb::GeometryHints m_geometryHints; void sendSyntheticConfigureNotify(); enum MappingState { Withdrawn, ///< Not handled, as per ICCCM WithdrawnState Mapped, ///< The frame is mapped Unmapped, ///< The frame is not mapped Kept ///< The frame should be unmapped, but is kept (For compositing) }; MappingState mapping_state; Xcb::TransientFor fetchTransient() const; void readTransientProperty(Xcb::TransientFor &transientFor); void readTransient(); xcb_window_t verifyTransientFor(xcb_window_t transient_for, bool set); void addTransient(AbstractClient* cl) override; void removeTransient(AbstractClient* cl) override; void removeFromMainClients(); void cleanGrouping(); void checkGroupTransients(); void setTransient(xcb_window_t new_transient_for_id); xcb_window_t m_transientForId; xcb_window_t m_originalTransientForId; ShadeMode shade_mode; Client *shade_below; uint deleting : 1; ///< True when doing cleanup and destroying the client Xcb::MotifHints m_motif; uint hidden : 1; ///< Forcibly hidden by calling hide() uint noborder : 1; uint app_noborder : 1; ///< App requested no border via window type, shape extension, etc. uint ignore_focus_stealing : 1; ///< Don't apply focus stealing prevention to this client bool blocks_compositing; enum FullScreenMode { FullScreenNone, FullScreenNormal } m_fullscreenMode; MaximizeMode max_mode; QRect geom_restore; QRect geom_fs_restore; QTimer* shadeHoverTimer; xcb_colormap_t m_colormap; QString cap_normal, cap_iconic, cap_suffix; Group* in_group; QTimer* ping_timer; qint64 m_killHelperPID; xcb_timestamp_t m_pingTimestamp; xcb_timestamp_t m_userTime; NET::Actions allowed_actions; QSize client_size; bool shade_geometry_change; SyncRequest syncRequest; static bool check_active_modal; ///< \see Client::checkActiveModal() int sm_stacking_order; friend struct ResetupRulesProcedure; friend bool performTransiencyCheck(); Xcb::StringProperty fetchActivities() const; void readActivities(Xcb::StringProperty &property); void checkActivities(); bool activitiesDefined; //whether the x property was actually set bool sessionActivityOverride; bool needsXWindowMove; Xcb::Window m_decoInputExtent; QPoint input_offset; QTimer *m_focusOutTimer; QList m_connections; bool m_clientSideDecorated; QMetaObject::Connection m_edgeRemoveConnection; QMetaObject::Connection m_edgeGeometryTrackingConnection; }; inline xcb_window_t Client::wrapperId() const { return m_wrapper; } inline bool Client::isClientSideDecorated() const { return m_clientSideDecorated; } inline bool Client::groupTransient() const { return m_transientForId == rootWindow(); } // Needed because verifyTransientFor() may set transient_for_id to root window, // if the original value has a problem (window doesn't exist, etc.) inline bool Client::wasOriginallyGroupTransient() const { return m_originalTransientForId == rootWindow(); } inline bool Client::isTransient() const { return m_transientForId != XCB_WINDOW_NONE; } inline const Group* Client::group() const { return in_group; } inline Group* Client::group() { return in_group; } inline bool Client::isShown(bool shaded_is_shown) const { return !isMinimized() && (!isShade() || shaded_is_shown) && !hidden && (!tabGroup() || tabGroup()->current() == this); } inline bool Client::isHiddenInternal() const { return hidden; } inline ShadeMode Client::shadeMode() const { return shade_mode; } inline QRect Client::geometryRestore() const { return geom_restore; } inline void Client::setGeometryRestore(const QRect &geo) { geom_restore = geo; } inline MaximizeMode Client::maximizeMode() const { return max_mode; } inline bool Client::isFullScreen() const { return m_fullscreenMode != FullScreenNone; } inline bool Client::hasNETSupport() const { return info->hasNETSupport(); } inline xcb_colormap_t Client::colormap() const { return m_colormap; } inline int Client::sessionStackingOrder() const { return sm_stacking_order; } inline bool Client::isManaged() const { return m_managed; } inline QSize Client::clientSize() const { return client_size; } inline void Client::plainResize(const QSize& s, ForceGeometry_t force) { plainResize(s.width(), s.height(), force); } inline void Client::resizeWithChecks(int w, int h, AbstractClient::ForceGeometry_t force) { resizeWithChecks(w, h, XCB_GRAVITY_BIT_FORGET, force); } inline void Client::resizeWithChecks(const QSize& s, xcb_gravity_t gravity, ForceGeometry_t force) { resizeWithChecks(s.width(), s.height(), gravity, force); } inline bool Client::hasUserTimeSupport() const { return info->userTime() != -1U; } inline xcb_window_t Client::moveResizeGrabWindow() const { return m_moveResizeGrabWindow; } inline bool Client::hiddenPreview() const { return mapping_state == Kept; } template inline void Client::print(T &stream) const { stream << "\'Client:" << window() << ";WMCLASS:" << resourceClass() << ":" << resourceName() << ";Caption:" << caption() << "\'"; } } // namespace Q_DECLARE_METATYPE(KWin::Client*) Q_DECLARE_METATYPE(QList) #endif diff --git a/colorcorrection/colorcorrectdbusinterface.h b/colorcorrection/colorcorrectdbusinterface.h index 30fabdb74..22570e86f 100644 --- a/colorcorrection/colorcorrectdbusinterface.h +++ b/colorcorrection/colorcorrectdbusinterface.h @@ -1,126 +1,126 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2017 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_NIGHTCOLOR_DBUS_INTERFACE_H #define KWIN_NIGHTCOLOR_DBUS_INTERFACE_H #include #include namespace KWin { namespace ColorCorrect { class Manager; class ColorCorrectDBusInterface : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.ColorCorrect") public: explicit ColorCorrectDBusInterface(Manager *parent); ~ColorCorrectDBusInterface() override = default; public Q_SLOTS: /** * @brief Gives information about the current state of Night Color. * * The returned variant hash has always the fields: * - ActiveEnabled * - Active * - Mode * - NightTemperatureEnabled * - NightTemperature * - Running * - CurrentColorTemperature * - LatitudeAuto * - LongitudeAuto * - LocationEnabled * - LatitudeFixed * - LongitudeFixed * - TimingsEnabled * - MorningBeginFixed * - EveningBeginFixed * - TransitionTime * * @return QHash * @see nightColorConfigChange * @see signalNightColorConfigChange * @since 5.12 - **/ + */ QHash nightColorInfo(); /** * @brief Allows changing the Night Color configuration. * * The provided variant hash can have the following fields: * - Active * - Mode * - NightTemperature * - LatitudeAuto * - LongitudeAuto * - LatitudeFixed * - LongitudeFixed * - MorningBeginFixed * - EveningBeginFixed * - TransitionTime * * It returns true if the configuration change was successful, otherwise false. * A change request for the location or timings needs to provide all relevant fields at the same time * to be successful. Otherwise the whole change request will get ignored. A change request will be ignored * as a whole as well, if one of the provided information has been sent in a wrong format. * * @return bool * @see nightColorInfo * @see signalNightColorConfigChange * @since 5.12 - **/ + */ bool setNightColorConfig(QHash data); /** * @brief For receiving auto location updates, primarily through the KDE Daemon * @return void * @since 5.12 - **/ + */ void nightColorAutoLocationUpdate(double latitude, double longitude); Q_SIGNALS: /** * @brief Emits that the Night Color configuration has been changed. * * The provided variant hash provides the same fields as nightColorInfo * * @return void * @see nightColorInfo * @see nightColorConfigChange * @since 5.12 - **/ + */ void nightColorConfigChanged(QHash data); private: Manager *m_manager; }; } } #endif // KWIN_NIGHTCOLOR_DBUS_INTERFACE_H diff --git a/colorcorrection/constants.h b/colorcorrection/constants.h index 47de8503f..7a46c4285 100644 --- a/colorcorrection/constants.h +++ b/colorcorrection/constants.h @@ -1,289 +1,289 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2017 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_NIGHTCOLOR_CONSTANTS_H #define KWIN_NIGHTCOLOR_CONSTANTS_H namespace KWin { namespace ColorCorrect { static const int MSC_DAY = 86400000; static const int MIN_TEMPERATURE = 1000; static const int NEUTRAL_TEMPERATURE = 6500; static const int DEFAULT_NIGHT_TEMPERATURE = 4500; static const int FALLBACK_SLOW_UPDATE_TIME = 1800000; /* 30 minutes */ /** * Whitepoint values for temperatures at 100K intervals. * These will be interpolated for the actual temperature. * This table was provided by Ingo Thies, 2013. * See the following file for more information: * https://github.com/jonls/redshift/blob/master/README-colorramp - **/ + */ static const float blackbodyColor[] = { 1.00000000, 0.18172716, 0.00000000, /* 1000K */ 1.00000000, 0.25503671, 0.00000000, /* 1100K */ 1.00000000, 0.30942099, 0.00000000, /* 1200K */ 1.00000000, 0.35357379, 0.00000000, /* ... */ 1.00000000, 0.39091524, 0.00000000, 1.00000000, 0.42322816, 0.00000000, 1.00000000, 0.45159884, 0.00000000, 1.00000000, 0.47675916, 0.00000000, 1.00000000, 0.49923747, 0.00000000, 1.00000000, 0.51943421, 0.00000000, 1.00000000, 0.54360078, 0.08679949, /* 2000K */ 1.00000000, 0.56618736, 0.14065513, 1.00000000, 0.58734976, 0.18362641, 1.00000000, 0.60724493, 0.22137978, 1.00000000, 0.62600248, 0.25591950, 1.00000000, 0.64373109, 0.28819679, 1.00000000, 0.66052319, 0.31873863, 1.00000000, 0.67645822, 0.34786758, 1.00000000, 0.69160518, 0.37579588, 1.00000000, 0.70602449, 0.40267128, 1.00000000, 0.71976951, 0.42860152, /* 3000K */ 1.00000000, 0.73288760, 0.45366838, 1.00000000, 0.74542112, 0.47793608, 1.00000000, 0.75740814, 0.50145662, 1.00000000, 0.76888303, 0.52427322, 1.00000000, 0.77987699, 0.54642268, 1.00000000, 0.79041843, 0.56793692, 1.00000000, 0.80053332, 0.58884417, 1.00000000, 0.81024551, 0.60916971, 1.00000000, 0.81957693, 0.62893653, 1.00000000, 0.82854786, 0.64816570, /* 4000K */ 1.00000000, 0.83717703, 0.66687674, 1.00000000, 0.84548188, 0.68508786, 1.00000000, 0.85347859, 0.70281616, 1.00000000, 0.86118227, 0.72007777, 1.00000000, 0.86860704, 0.73688797, /* 4500K */ 1.00000000, 0.87576611, 0.75326132, 1.00000000, 0.88267187, 0.76921169, 1.00000000, 0.88933596, 0.78475236, 1.00000000, 0.89576933, 0.79989606, 1.00000000, 0.90198230, 0.81465502, /* 5000K */ 1.00000000, 0.90963069, 0.82838210, 1.00000000, 0.91710889, 0.84190889, 1.00000000, 0.92441842, 0.85523742, 1.00000000, 0.93156127, 0.86836903, 1.00000000, 0.93853986, 0.88130458, 1.00000000, 0.94535695, 0.89404470, 1.00000000, 0.95201559, 0.90658983, 1.00000000, 0.95851906, 0.91894041, 1.00000000, 0.96487079, 0.93109690, 1.00000000, 0.97107439, 0.94305985, /* 6000K */ 1.00000000, 0.97713351, 0.95482993, 1.00000000, 0.98305189, 0.96640795, 1.00000000, 0.98883326, 0.97779486, 1.00000000, 0.99448139, 0.98899179, 1.00000000, 1.00000000, 1.00000000, /* 6500K */ 0.98947904, 0.99348723, 1.00000000, 0.97940448, 0.98722715, 1.00000000, 0.96975025, 0.98120637, 1.00000000, 0.96049223, 0.97541240, 1.00000000, 0.95160805, 0.96983355, 1.00000000, /* 7000K */ 0.94303638, 0.96443333, 1.00000000, 0.93480451, 0.95923080, 1.00000000, 0.92689056, 0.95421394, 1.00000000, 0.91927697, 0.94937330, 1.00000000, 0.91194747, 0.94470005, 1.00000000, 0.90488690, 0.94018594, 1.00000000, 0.89808115, 0.93582323, 1.00000000, 0.89151710, 0.93160469, 1.00000000, 0.88518247, 0.92752354, 1.00000000, 0.87906581, 0.92357340, 1.00000000, /* 8000K */ 0.87315640, 0.91974827, 1.00000000, 0.86744421, 0.91604254, 1.00000000, 0.86191983, 0.91245088, 1.00000000, 0.85657444, 0.90896831, 1.00000000, 0.85139976, 0.90559011, 1.00000000, 0.84638799, 0.90231183, 1.00000000, 0.84153180, 0.89912926, 1.00000000, 0.83682430, 0.89603843, 1.00000000, 0.83225897, 0.89303558, 1.00000000, 0.82782969, 0.89011714, 1.00000000, /* 9000K */ 0.82353066, 0.88727974, 1.00000000, 0.81935641, 0.88452017, 1.00000000, 0.81530175, 0.88183541, 1.00000000, 0.81136180, 0.87922257, 1.00000000, 0.80753191, 0.87667891, 1.00000000, 0.80380769, 0.87420182, 1.00000000, 0.80018497, 0.87178882, 1.00000000, 0.79665980, 0.86943756, 1.00000000, 0.79322843, 0.86714579, 1.00000000, 0.78988728, 0.86491137, 1.00000000, /* 10000K */ 0.78663296, 0.86273225, 1.00000000, 0.78346225, 0.86060650, 1.00000000, 0.78037207, 0.85853224, 1.00000000, 0.77735950, 0.85650771, 1.00000000, 0.77442176, 0.85453121, 1.00000000, 0.77155617, 0.85260112, 1.00000000, 0.76876022, 0.85071588, 1.00000000, 0.76603147, 0.84887402, 1.00000000, 0.76336762, 0.84707411, 1.00000000, 0.76076645, 0.84531479, 1.00000000, /* 11000K */ 0.75822586, 0.84359476, 1.00000000, 0.75574383, 0.84191277, 1.00000000, 0.75331843, 0.84026762, 1.00000000, 0.75094780, 0.83865816, 1.00000000, 0.74863017, 0.83708329, 1.00000000, 0.74636386, 0.83554194, 1.00000000, 0.74414722, 0.83403311, 1.00000000, 0.74197871, 0.83255582, 1.00000000, 0.73985682, 0.83110912, 1.00000000, 0.73778012, 0.82969211, 1.00000000, /* 12000K */ 0.73574723, 0.82830393, 1.00000000, 0.73375683, 0.82694373, 1.00000000, 0.73180765, 0.82561071, 1.00000000, 0.72989845, 0.82430410, 1.00000000, 0.72802807, 0.82302316, 1.00000000, 0.72619537, 0.82176715, 1.00000000, 0.72439927, 0.82053539, 1.00000000, 0.72263872, 0.81932722, 1.00000000, 0.72091270, 0.81814197, 1.00000000, 0.71922025, 0.81697905, 1.00000000, /* 13000K */ 0.71756043, 0.81583783, 1.00000000, 0.71593234, 0.81471775, 1.00000000, 0.71433510, 0.81361825, 1.00000000, 0.71276788, 0.81253878, 1.00000000, 0.71122987, 0.81147883, 1.00000000, 0.70972029, 0.81043789, 1.00000000, 0.70823838, 0.80941546, 1.00000000, 0.70678342, 0.80841109, 1.00000000, 0.70535469, 0.80742432, 1.00000000, 0.70395153, 0.80645469, 1.00000000, /* 14000K */ 0.70257327, 0.80550180, 1.00000000, 0.70121928, 0.80456522, 1.00000000, 0.69988894, 0.80364455, 1.00000000, 0.69858167, 0.80273941, 1.00000000, 0.69729688, 0.80184943, 1.00000000, 0.69603402, 0.80097423, 1.00000000, 0.69479255, 0.80011347, 1.00000000, 0.69357196, 0.79926681, 1.00000000, 0.69237173, 0.79843391, 1.00000000, 0.69119138, 0.79761446, 1.00000000, /* 15000K */ 0.69003044, 0.79680814, 1.00000000, 0.68888844, 0.79601466, 1.00000000, 0.68776494, 0.79523371, 1.00000000, 0.68665951, 0.79446502, 1.00000000, 0.68557173, 0.79370830, 1.00000000, 0.68450119, 0.79296330, 1.00000000, 0.68344751, 0.79222975, 1.00000000, 0.68241029, 0.79150740, 1.00000000, 0.68138918, 0.79079600, 1.00000000, 0.68038380, 0.79009531, 1.00000000, /* 16000K */ 0.67939381, 0.78940511, 1.00000000, 0.67841888, 0.78872517, 1.00000000, 0.67745866, 0.78805526, 1.00000000, 0.67651284, 0.78739518, 1.00000000, 0.67558112, 0.78674472, 1.00000000, 0.67466317, 0.78610368, 1.00000000, 0.67375872, 0.78547186, 1.00000000, 0.67286748, 0.78484907, 1.00000000, 0.67198916, 0.78423512, 1.00000000, 0.67112350, 0.78362984, 1.00000000, /* 17000K */ 0.67027024, 0.78303305, 1.00000000, 0.66942911, 0.78244457, 1.00000000, 0.66859988, 0.78186425, 1.00000000, 0.66778228, 0.78129191, 1.00000000, 0.66697610, 0.78072740, 1.00000000, 0.66618110, 0.78017057, 1.00000000, 0.66539706, 0.77962127, 1.00000000, 0.66462376, 0.77907934, 1.00000000, 0.66386098, 0.77854465, 1.00000000, 0.66310852, 0.77801705, 1.00000000, /* 18000K */ 0.66236618, 0.77749642, 1.00000000, 0.66163375, 0.77698261, 1.00000000, 0.66091106, 0.77647551, 1.00000000, 0.66019791, 0.77597498, 1.00000000, 0.65949412, 0.77548090, 1.00000000, 0.65879952, 0.77499315, 1.00000000, 0.65811392, 0.77451161, 1.00000000, 0.65743716, 0.77403618, 1.00000000, 0.65676908, 0.77356673, 1.00000000, 0.65610952, 0.77310316, 1.00000000, /* 19000K */ 0.65545831, 0.77264537, 1.00000000, 0.65481530, 0.77219324, 1.00000000, 0.65418036, 0.77174669, 1.00000000, 0.65355332, 0.77130560, 1.00000000, 0.65293404, 0.77086988, 1.00000000, 0.65232240, 0.77043944, 1.00000000, 0.65171824, 0.77001419, 1.00000000, 0.65112144, 0.76959404, 1.00000000, 0.65053187, 0.76917889, 1.00000000, 0.64994941, 0.76876866, 1.00000000, /* 20000K */ 0.64937392, 0.76836326, 1.00000000, 0.64880528, 0.76796263, 1.00000000, 0.64824339, 0.76756666, 1.00000000, 0.64768812, 0.76717529, 1.00000000, 0.64713935, 0.76678844, 1.00000000, 0.64659699, 0.76640603, 1.00000000, 0.64606092, 0.76602798, 1.00000000, 0.64553103, 0.76565424, 1.00000000, 0.64500722, 0.76528472, 1.00000000, 0.64448939, 0.76491935, 1.00000000, /* 21000K */ 0.64397745, 0.76455808, 1.00000000, 0.64347129, 0.76420082, 1.00000000, 0.64297081, 0.76384753, 1.00000000, 0.64247594, 0.76349813, 1.00000000, 0.64198657, 0.76315256, 1.00000000, 0.64150261, 0.76281076, 1.00000000, 0.64102399, 0.76247267, 1.00000000, 0.64055061, 0.76213824, 1.00000000, 0.64008239, 0.76180740, 1.00000000, 0.63961926, 0.76148010, 1.00000000, /* 22000K */ 0.63916112, 0.76115628, 1.00000000, 0.63870790, 0.76083590, 1.00000000, 0.63825953, 0.76051890, 1.00000000, 0.63781592, 0.76020522, 1.00000000, 0.63737701, 0.75989482, 1.00000000, 0.63694273, 0.75958764, 1.00000000, 0.63651299, 0.75928365, 1.00000000, 0.63608774, 0.75898278, 1.00000000, 0.63566691, 0.75868499, 1.00000000, 0.63525042, 0.75839025, 1.00000000, /* 23000K */ 0.63483822, 0.75809849, 1.00000000, 0.63443023, 0.75780969, 1.00000000, 0.63402641, 0.75752379, 1.00000000, 0.63362667, 0.75724075, 1.00000000, 0.63323097, 0.75696053, 1.00000000, 0.63283925, 0.75668310, 1.00000000, 0.63245144, 0.75640840, 1.00000000, 0.63206749, 0.75613641, 1.00000000, 0.63168735, 0.75586707, 1.00000000, 0.63131096, 0.75560036, 1.00000000, /* 24000K */ 0.63093826, 0.75533624, 1.00000000, 0.63056920, 0.75507467, 1.00000000, 0.63020374, 0.75481562, 1.00000000, 0.62984181, 0.75455904, 1.00000000, 0.62948337, 0.75430491, 1.00000000, 0.62912838, 0.75405319, 1.00000000, 0.62877678, 0.75380385, 1.00000000, 0.62842852, 0.75355685, 1.00000000, 0.62808356, 0.75331217, 1.00000000, 0.62774186, 0.75306977, 1.00000000, /* 25000K */ 0.62740336, 0.75282962, 1.00000000 }; } } #endif // KWIN_NIGHTCOLOR_CONSTANTS_H diff --git a/colorcorrection/manager.h b/colorcorrection/manager.h index 1d9ccd545..853d3dbc1 100644 --- a/colorcorrection/manager.h +++ b/colorcorrection/manager.h @@ -1,203 +1,203 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2017 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_COLORCORRECT_MANAGER_H #define KWIN_COLORCORRECT_MANAGER_H #include "constants.h" #include #include #include #include class QTimer; namespace KWin { class Workspace; namespace ColorCorrect { typedef QPair DateTimes; typedef QPair Times; class ColorCorrectDBusInterface; /** * This enum type is used to specify operation mode of the night color manager. - **/ + */ enum NightColorMode { /** * Color temperature is computed based on the current position of the Sun. * * Location of the user is provided by Plasma. - **/ + */ Automatic, /** * Color temperature is computed based on the current position of the Sun. * * Location of the user is provided by themselves. - **/ + */ Location, /** * Color temperature is computed based on the current time. * * Sunrise and sunset times have to be specified by the user. - **/ + */ Timings, /** * Color temperature is constant thoughout the day. - **/ + */ Constant, }; /** * The night color manager is a blue light filter similar to Redshift. * * There are four modes this manager can operate in: Automatic, Location, Timings, * and Constant. Both Automatic and Location modes derive screen color temperature * from the current position of the Sun, the only difference between two is how * coordinates of the user are specified. If the user is located near the North or * South pole, we can't compute correct position of the Sun, that's why we need * Timings and Constant mode. * * With the Timings mode, screen color temperature is computed based on the clock * time. The user needs to specify timings of the sunset and sunrise as well the * transition time. * * With the Constant mode, screen color temperature is always constant. - **/ + */ class KWIN_EXPORT Manager : public QObject { Q_OBJECT public: Manager(QObject *parent); void init(); /** * Get current configuration * @see changeConfiguration * @since 5.12 - **/ + */ QHash info() const; /** * Change configuration * @see info * @since 5.12 - **/ + */ bool changeConfiguration(QHash data); void autoLocationUpdate(double latitude, double longitude); /** * Toggles the active state of the filter. * * A quick transition will be started if the difference between current screen * color temperature and target screen color temperature is too large. Target * temperature is defined in context of the new active state. * * If the filter becomes inactive after calling this method, the target color * temperature is 6500 K. * * If the filter becomes active after calling this method, the target screen * color temperature is defined by the current operation mode. * * Note that this method is a no-op if the underlying platform doesn't support * adjusting gamma ramps. - **/ + */ void toggle(); // for auto tests void reparseConfigAndReset(); public Q_SLOTS: void resetSlowUpdateStartTimer(); void quickAdjust(); Q_SIGNALS: void configChange(QHash data); private: void initShortcuts(); void readConfig(); void hardReset(); void slowUpdate(int targetTemp); void resetAllTimers(); int currentTargetTemp() const; void cancelAllTimers(); /** * Quick shift on manual change to current target Temperature - **/ + */ void resetQuickAdjustTimer(); /** * Slow shift to daytime target Temperature - **/ + */ void resetSlowUpdateTimer(); void updateSunTimings(bool force); DateTimes getSunTimings(QDate date, double latitude, double longitude, bool morning) const; bool checkAutomaticSunTimings() const; bool daylight() const; void commitGammaRamps(int temperature); ColorCorrectDBusInterface *m_iface; bool m_active; bool m_running = false; NightColorMode m_mode = NightColorMode::Automatic; // the previous and next sunrise/sunset intervals - in UTC time DateTimes m_prev = DateTimes(); DateTimes m_next = DateTimes(); // manual times from config QTime m_morning = QTime(6,0); QTime m_evening = QTime(18,0); int m_trTime = 30; // saved in minutes > 1 // auto location provided by work space double m_latAuto; double m_lngAuto; // manual location from config double m_latFixed; double m_lngFixed; QTimer *m_slowUpdateStartTimer = nullptr; QTimer *m_slowUpdateTimer = nullptr; QTimer *m_quickAdjustTimer = nullptr; int m_currentTemp = NEUTRAL_TEMPERATURE; int m_dayTargetTemp = NEUTRAL_TEMPERATURE; int m_nightTargetTemp = DEFAULT_NIGHT_TEMPERATURE; int m_failedCommitAttempts = 0; // The Workspace class needs to call initShortcuts during initialization. friend class KWin::Workspace; }; } } #endif // KWIN_COLORCORRECT_MANAGER_H diff --git a/colorcorrection/suncalc.h b/colorcorrection/suncalc.h index 4cfcea055..79943fe82 100644 --- a/colorcorrection/suncalc.h +++ b/colorcorrection/suncalc.h @@ -1,47 +1,47 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2017 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_SUNCALCULATOR_H #define KWIN_SUNCALCULATOR_H #include #include #include namespace KWin { namespace ColorCorrect { /** * Calculates for a given location and date two of the * following sun timings in their temporal order: * - Nautical dawn and sunrise for the morning * - Sunset and nautical dusk for the evening * @since 5.12 - **/ + */ QPair calculateSunTimings(QDate prompt, double latitude, double longitude, bool morning); } } #endif // KWIN_SUNCALCULATOR_H diff --git a/composite.h b/composite.h index 69804ce8f..d2e8a4f3f 100644 --- a/composite.h +++ b/composite.h @@ -1,228 +1,228 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Arthur Arlt 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 . *********************************************************************/ #pragma once #include #include #include #include #include #include namespace KWin { class Client; class CompositorSelectionOwner; class Scene; class KWIN_EXPORT Compositor : public QObject { Q_OBJECT public: enum SuspendReason { NoReasonSuspend = 0, UserSuspend = 1 << 0, BlockRuleSuspend = 1 << 1, ScriptSuspend = 1 << 2, AllReasonSuspend = 0xff }; Q_DECLARE_FLAGS(SuspendReasons, SuspendReason) enum class State { On = 0, Off, Starting, Stopping }; ~Compositor() override; // when adding repaints caused by a window, you probably want to use // either Toplevel::addRepaint() or Toplevel::addWorkspaceRepaint() void addRepaint(const QRect& r); void addRepaint(const QRegion& r); void addRepaint(int x, int y, int w, int h); void addRepaintFull(); /** * Schedules a new repaint if no repaint is currently scheduled. - **/ + */ void scheduleRepaint(); /** * Notifies the compositor that SwapBuffers() is about to be called. * Rendering of the next frame will be deferred until bufferSwapComplete() * is called. - **/ + */ void aboutToSwapBuffers(); /** * Notifies the compositor that a pending buffer swap has completed. - **/ + */ void bufferSwapComplete(); /** * @brief Suspends the Compositor if it is currently active. * * Note: it is possible that the Compositor is not able to suspend. Use isActive to check * whether the Compositor has been suspended. * * @return void * @see resume * @see isActive - **/ + */ Q_INVOKABLE void suspend(Compositor::SuspendReason reason); /** * @brief Resumes the Compositor if it is currently suspended. * * Note: it is possible that the Compositor cannot be resumed, that is there might be Clients * blocking the usage of Compositing or the Scene might be broken. Use isActive to check * whether the Compositor has been resumed. Also check isCompositingPossible and * isOpenGLBroken. * * Note: The starting of the Compositor can require some time and is partially done threaded. * After this method returns the setup may not have been completed. * * @return void * @see suspend * @see isActive * @see isCompositingPossible * @see isOpenGLBroken - **/ + */ Q_INVOKABLE void resume(Compositor::SuspendReason reason); /** * Toggles compositing, that is if the Compositor is suspended it will be resumed * and if the Compositor is active it will be suspended. * Invoked by keybinding (shortcut default: Shift + Alt + F12). - **/ + */ void toggleCompositing(); /** * Re-initializes the Compositor completely. * Connected to the D-Bus signal org.kde.KWin /KWin reinitCompositing - **/ + */ void reinitialize(); /** * Whether the Compositor is active. That is a Scene is present and the Compositor is * not shutting down itself. - **/ + */ bool isActive(); int xrrRefreshRate() const { return m_xrrRefreshRate; } bool hasScene() const { return m_scene != NULL; } /** * Checks whether @p w is the Scene's overlay window. - **/ + */ bool checkForOverlayWindow(WId w) const; /** * @returns Whether the Scene's Overlay X Window is visible. - **/ + */ bool isOverlayWindowVisible() const; Scene *scene() { return m_scene; } /** * @brief Static check to test whether the Compositor is available and active. * * @return bool @c true if there is a Compositor and it is active, @c false otherwise - **/ + */ static bool compositing() { return s_compositor != NULL && s_compositor->isActive(); } void updateCompositeBlocking(); void updateClientCompositeBlocking(KWin::Client* c); // for delayed supportproperty management of effects void keepSupportProperty(xcb_atom_t atom); void removeSupportProperty(xcb_atom_t atom); Q_SIGNALS: void compositingToggled(bool active); void aboutToDestroy(); void aboutToToggleCompositing(); void sceneCreated(); void bufferSwapCompleted(); protected: void timerEvent(QTimerEvent *te) override; private: Q_INVOKABLE void start(); void stop(); void claimCompositorSelection(); /** * Continues the startup after Scene And Workspace are created - **/ + */ void startupWithWorkspace(); void setupX11Support(); void setCompositeTimer(); void performCompositing(); bool windowRepaintsPending() const; void releaseCompositorSelection(); void deleteUnusedSupportProperties(); void slotConfigChanged(); State m_state; /** * Whether the Compositor is currently suspended, 8 bits encoding the reason - **/ + */ SuspendReasons m_suspended; QBasicTimer compositeTimer; CompositorSelectionOwner *m_selectionOwner; QTimer m_releaseSelectionTimer; QList m_unusedSupportProperties; QTimer m_unusedSupportPropertyTimer; qint64 vBlankInterval, fpsInterval; int m_xrrRefreshRate; QRegion repaints_region; qint64 m_timeSinceLastVBlank; Scene *m_scene; bool m_bufferSwapPending; bool m_composeAtSwapCompletion; int m_framesToTestForSafety = 3; QElapsedTimer m_monotonicClock; KWIN_SINGLETON_VARIABLE(Compositor, s_compositor) }; } diff --git a/cursor.h b/cursor.h index 5874c0236..3a561a302 100644 --- a/cursor.h +++ b/cursor.h @@ -1,304 +1,304 @@ /******************************************************************** 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 { /** * Extension of Qt::CursorShape with values not currently present there - **/ + */ 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 }; } /** * @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: ~Cursor() override; void startMousePolling(); void stopMousePolling(); /** * @brief Enables tracking changes of cursor images. * * After enabling cursor change tracking the signal cursorChanged will be emitted * whenever a change to the cursor image is recognized. * * Use 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 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 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 specification - **/ + */ 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 startCursorTracking. * * @see startCursorTracking * @see stopCursorTracking - **/ + */ void cursorChanged(); void themeChanged(); protected: /** * Called from 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 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 @ref pos() to allow syncing the internal position with the underlying * system's cursor position. - **/ + */ virtual void doGetPos(); /** * Called from 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 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 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 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 @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 * 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); ~InputRedirectionCursor() override; protected: void doSetPos() override; void doStartCursorTracking() override; void doStopCursorTracking() override; 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/dbusinterface.h b/dbusinterface.h index 88d935355..d11ff515b 100644 --- a/dbusinterface.h +++ b/dbusinterface.h @@ -1,254 +1,254 @@ /******************************************************************** 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_DBUS_INTERFACE_H #define KWIN_DBUS_INTERFACE_H #include #include #include "virtualdesktopsdbustypes.h" namespace KWin { class Compositor; class VirtualDesktopManager; /** * @brief This class is a wrapper for the org.kde.KWin D-Bus interface. * * The main purpose of this class is to be exported on the D-Bus as object /KWin. * It is a pure wrapper to provide the deprecated D-Bus methods which have been * removed from Workspace which used to implement the complete D-Bus interface. * * Nowadays the D-Bus interfaces are distributed, parts of it are exported on * /Compositor, parts on /Effects and parts on /KWin. The implementation in this * class just delegates the method calls to the actual implementation in one of the * three singletons. * * @author Martin Gräßlin - **/ + */ class DBusInterface: public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KWin") public: explicit DBusInterface(QObject *parent); ~DBusInterface() override; public: // PROPERTIES public Q_SLOTS: // METHODS Q_NOREPLY void cascadeDesktop(); int currentDesktop(); Q_NOREPLY void killWindow(); void nextDesktop(); void previousDesktop(); Q_NOREPLY void reconfigure(); bool setCurrentDesktop(int desktop); bool startActivity(const QString &in0); bool stopActivity(const QString &in0); QString supportInformation(); Q_NOREPLY void unclutterDesktop(); Q_NOREPLY void showDebugConsole(); QVariantMap queryWindowInfo(); QVariantMap getWindowInfo(const QString &uuid); private Q_SLOTS: void becomeKWinService(const QString &service); private: void announceService(); QString m_serviceName; QDBusMessage m_replyQueryWindowInfo; }; class CompositorDBusInterface : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Compositing") /** * @brief Whether the Compositor is active. That is a Scene is present and the Compositor is * not shutting down itself. - **/ + */ Q_PROPERTY(bool active READ isActive) /** * @brief Whether compositing is possible. Mostly means whether the required X extensions * are available. - **/ + */ Q_PROPERTY(bool compositingPossible READ isCompositingPossible) /** * @brief The reason why compositing is not possible. Empty String if compositing is possible. - **/ + */ Q_PROPERTY(QString compositingNotPossibleReason READ compositingNotPossibleReason) /** * @brief Whether OpenGL has failed badly in the past (crash) and is considered as broken. - **/ + */ Q_PROPERTY(bool openGLIsBroken READ isOpenGLBroken) /** * The type of the currently used Scene: * @li @c none No Compositing * @li @c xrender XRender * @li @c gl1 OpenGL 1 * @li @c gl2 OpenGL 2 * @li @c gles OpenGL ES 2 - **/ + */ Q_PROPERTY(QString compositingType READ compositingType) /** * @brief All currently supported OpenGLPlatformInterfaces. * * Possible values: * @li glx * @li egl * * Values depend on operation mode and compile time options. - **/ + */ Q_PROPERTY(QStringList supportedOpenGLPlatformInterfaces READ supportedOpenGLPlatformInterfaces) Q_PROPERTY(bool platformRequiresCompositing READ platformRequiresCompositing) public: explicit CompositorDBusInterface(Compositor *parent); ~CompositorDBusInterface() override = default; bool isActive() const; bool isCompositingPossible() const; QString compositingNotPossibleReason() const; bool isOpenGLBroken() const; QString compositingType() const; QStringList supportedOpenGLPlatformInterfaces() const; bool platformRequiresCompositing() const; public Q_SLOTS: /** * @brief Suspends the Compositor if it is currently active. * * Note: it is possible that the Compositor is not able to suspend. Use isActive to check * whether the Compositor has been suspended. * * @return void * @see resume * @see isActive - **/ + */ void suspend(); /** * @brief Resumes the Compositor if it is currently suspended. * * Note: it is possible that the Compositor cannot be resumed, that is there might be Clients * blocking the usage of Compositing or the Scene might be broken. Use isActive to check * whether the Compositor has been resumed. Also check isCompositingPossible and * isOpenGLBroken. * * Note: The starting of the Compositor can require some time and is partially done threaded. * After this method returns the setup may not have been completed. * * @return void * @see suspend * @see isActive * @see isCompositingPossible * @see isOpenGLBroken - **/ + */ void resume(); /** * @brief Used by Compositing KCM after settings change. * * On signal Compositor reloads settings and restarts. */ void reinitialize(); Q_SIGNALS: void compositingToggled(bool active); private: Compositor *m_compositor; }; //TODO: disable all of this in case of kiosk? class VirtualDesktopManagerDBusInterface : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KWin.VirtualDesktopManager") /** * 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 NOTIFY countChanged) /** * The number of rows the virtual desktops will be laid out in - **/ + */ Q_PROPERTY(uint rows READ rows WRITE setRows NOTIFY rowsChanged) /** * The id of the virtual desktop which is currently in use. - **/ + */ Q_PROPERTY(QString 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) /** * list of key/value pairs which every one of them is representing a desktop - **/ + */ Q_PROPERTY(KWin::DBusDesktopDataVector desktops READ desktops NOTIFY desktopsChanged); public: VirtualDesktopManagerDBusInterface(VirtualDesktopManager *parent); ~VirtualDesktopManagerDBusInterface() override = default; uint count() const; void setRows(uint rows); uint rows() const; void setCurrent(const QString &id); QString current() const; void setNavigationWrappingAround(bool wraps); bool isNavigationWrappingAround() const; KWin::DBusDesktopDataVector desktops() const; Q_SIGNALS: void countChanged(uint count); void rowsChanged(uint rows); void currentChanged(const QString &id); void navigationWrappingAroundChanged(bool wraps); void desktopsChanged(KWin::DBusDesktopDataVector); void desktopDataChanged(const QString &id, KWin::DBusDesktopDataStruct); void desktopCreated(const QString &id, KWin::DBusDesktopDataStruct); void desktopRemoved(const QString &id); public Q_SLOTS: /** * Create a desktop with a new name at a given position * note: the position starts from 1 - **/ + */ void createDesktop(uint position, const QString &name); void setDesktopName(const QString &id, const QString &name); void removeDesktop(const QString &id); private: VirtualDesktopManager *m_manager; }; } // namespace #endif // KWIN_DBUS_INTERFACE_H diff --git a/decorations/decorationrenderer.h b/decorations/decorationrenderer.h index ca63fc391..ac3aa7e83 100644 --- a/decorations/decorationrenderer.h +++ b/decorations/decorationrenderer.h @@ -1,86 +1,86 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_DECORATION_RENDERER_H #define KWIN_DECORATION_RENDERER_H #include #include #include namespace KWin { class Deleted; namespace Decoration { class DecoratedClientImpl; class KWIN_EXPORT Renderer : public QObject { Q_OBJECT public: ~Renderer() override; void schedule(const QRect &rect); /** * Reparents this Renderer to the @p deleted. * After this call the Renderer is no longer able to render * anything, client() returns a nullptr. - **/ + */ virtual void reparent(Deleted *deleted); Q_SIGNALS: void renderScheduled(const QRect &geo); protected: explicit Renderer(DecoratedClientImpl *client); /** * @returns the scheduled paint region and resets - **/ + */ QRegion getScheduled(); virtual void render() = 0; DecoratedClientImpl *client() { return m_client; } bool areImageSizesDirty() const { return m_imageSizesDirty; } void resetImageSizesDirty() { m_imageSizesDirty = false; } QImage renderToImage(const QRect &geo); private: DecoratedClientImpl *m_client; QRegion m_scheduled; bool m_imageSizesDirty; }; } } #endif diff --git a/deleted.h b/deleted.h index d16d22257..df10a5c3f 100644 --- a/deleted.h +++ b/deleted.h @@ -1,251 +1,251 @@ /******************************************************************** 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_DELETED_H #define KWIN_DELETED_H #include "toplevel.h" namespace KWin { class AbstractClient; namespace Decoration { class Renderer; } class KWIN_EXPORT Deleted : public Toplevel { Q_OBJECT public: static Deleted* create(Toplevel* c); // used by effects to keep the window around for e.g. fadeout effects when it's destroyed void refWindow(); void unrefWindow(); void discard(); int desktop() const override; QStringList activities() const override; QVector desktops() const override; QPoint clientPos() const override; QSize clientSize() const override; QPoint clientContentPos() const override { return m_contentPos; } QRect transparentRect() const override; bool isDeleted() const override; xcb_window_t frameId() const override; bool noBorder() const { return no_border; } void layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const; QRect decorationRect() const override; Layer layer() const override { return m_layer; } bool isMinimized() const { return m_minimized; } bool isModal() const { return m_modal; } QList mainClients() const { return m_mainClients; } NET::WindowType windowType(bool direct = false, int supported_types = 0) const override; bool wasClient() const { return m_wasClient; } double opacity() const override; QByteArray windowRole() const override; const Decoration::Renderer *decorationRenderer() const { return m_decorationRenderer; } bool isFullScreen() const { return m_fullscreen; } bool isCurrentTab() const { return m_wasCurrentTab; } bool keepAbove() const { return m_keepAbove; } bool keepBelow() const { return m_keepBelow; } QString caption() const { return m_caption; } /** * Returns whether the client was active. * * @returns @c true if the client was active at the time when it was closed, * @c false otherwise - **/ + */ bool wasActive() const { return m_wasActive; } /** * Returns whether this was an X11 client. * * @returns @c true if it was an X11 client, @c false otherwise. - **/ + */ bool wasX11Client() const { return m_wasX11Client; } /** * Returns whether this was a Wayland client. * * @returns @c true if it was a Wayland client, @c false otherwise. - **/ + */ bool wasWaylandClient() const { return m_wasWaylandClient; } /** * Returns whether the client was a transient. * * @returns @c true if it was a transient, @c false otherwise. - **/ + */ bool wasTransient() const { return !m_transientFor.isEmpty(); } /** * Returns whether the client was a group transient. * * @returns @c true if it was a group transient, @c false otherwise. * @note This is relevant only for X11 clients. - **/ + */ bool wasGroupTransient() const { return m_wasGroupTransient; } /** * Checks whether this client was a transient for given toplevel. * * @param toplevel Toplevel against which we are testing. * @returns @c true if it was a transient for given toplevel, @c false otherwise. - **/ + */ bool wasTransientFor(const Toplevel *toplevel) const { return m_transientFor.contains(const_cast(toplevel)); } /** * Returns the list of transients. * * Because the window is Deleted, it can have only Deleted child transients. - **/ + */ DeletedList transients() const { return m_transients; } /** * Returns whether the client was a popup. * * @returns @c true if the client was a popup, @c false otherwise. - **/ + */ bool isPopupWindow() const override { return m_wasPopupWindow; } QVector x11DesktopIds() const; /** * Whether this Deleted represents the outline. - **/ + */ bool isOutline() const override { return m_wasOutline; } protected: void debug(QDebug& stream) const override; private Q_SLOTS: void mainClientClosed(KWin::Toplevel *client); void transientForClosed(Toplevel *toplevel, Deleted *deleted); private: Deleted(); // use create() void copyToDeleted(Toplevel* c); ~Deleted() override; // deleted only using unrefWindow() void addTransient(Deleted *transient); void removeTransient(Deleted *transient); void addTransientFor(AbstractClient *parent); void removeTransientFor(Deleted *parent); int delete_refcount; int desk; QStringList activityList; QRect contentsRect; // for clientPos()/clientSize() QPoint m_contentPos; QRect transparent_rect; xcb_window_t m_frame; QVector m_desktops; bool no_border; QRect decoration_left; QRect decoration_right; QRect decoration_top; QRect decoration_bottom; Layer m_layer; bool m_minimized; bool m_modal; QList m_mainClients; bool m_wasClient; bool m_wasCurrentTab; Decoration::Renderer *m_decorationRenderer; double m_opacity; NET::WindowType m_type = NET::Unknown; QByteArray m_windowRole; bool m_fullscreen; bool m_keepAbove; bool m_keepBelow; QString m_caption; bool m_wasActive; bool m_wasX11Client; bool m_wasWaylandClient; bool m_wasGroupTransient; ToplevelList m_transientFor; DeletedList m_transients; bool m_wasPopupWindow; bool m_wasOutline; }; inline void Deleted::refWindow() { ++delete_refcount; } } // namespace Q_DECLARE_METATYPE(KWin::Deleted*) #endif diff --git a/effectloader.h b/effectloader.h index bbab66b25..c7ad1f6a9 100644 --- a/effectloader.h +++ b/effectloader.h @@ -1,377 +1,377 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_EFFECT_LOADER_H #define KWIN_EFFECT_LOADER_H #include // KDE #include #include // Qt #include #include #include #include #include namespace KWin { class Effect; class EffectPluginFactory; enum class BuiltInEffect; /** * @brief Flags defining how a Loader should load an Effect. * * These Flags are only used internally when querying the configuration on whether * an Effect should be loaded. * * @see AbstractEffectLoader::readConfig() - **/ + */ enum class LoadEffectFlag { Load = 1 << 0, ///< Effect should be loaded CheckDefaultFunction = 1 << 2 ///< The Check Default Function needs to be invoked if the Effect provides it }; Q_DECLARE_FLAGS(LoadEffectFlags, LoadEffectFlag) /** * @brief Interface to describe how an effect loader has to function. * * The AbstractEffectLoader specifies the methods a concrete loader has to implement and how * those methods are expected to perform. Also it provides an interface to the outside world * (that is EffectsHandlerImpl). * * The abstraction is used because there are multiple types of Effects which need to be loaded: * @li Built-In Effects * @li Scripted Effects * @li Binary Plugin Effects * * Serving all of them with one Effect Loader is rather complex given that different stores need * to be queried at the same time. Thus the idea is to have one implementation per type and one * implementation which makes use of all of them and combines the loading. - **/ + */ class KWIN_EXPORT AbstractEffectLoader : public QObject { Q_OBJECT public: ~AbstractEffectLoader() override; /** * @brief The KSharedConfig this EffectLoader should operate on. * * Important: a valid KSharedConfig must be provided before trying to load any effects! * * @param config * @internal - **/ + */ virtual void setConfig(KSharedConfig::Ptr config); /** * @brief Whether this Effect Loader can load the Effect with the given @p name. * * The Effect Loader determines whether it knows or can find an Effect called @p name, * and thus whether it can attempt to load the Effect. * * @param name The name of the Effect to look for. * @return bool @c true if the Effect Loader knows this effect, false otherwise - **/ + */ virtual bool hasEffect(const QString &name) const = 0; /** * @brief All the Effects this loader knows of. * * The implementation should re-query its store whenever this method is invoked. * It's possible that the store of effects changed (e.g. a new one got installed) * * @return QStringList The internal names of the known Effects - **/ + */ virtual QStringList listOfKnownEffects() const = 0; /** * @brief Synchronous loading of the Effect with the given @p name. * * Loads the Effect without checking any configuration value or any enabled by default * function provided by the Effect. * * The loader is expected to apply the following checks: * If the Effect is already loaded, the Effect should not get loaded again. Thus the loader * is expected to track which Effects it has loaded, and which of those have been destroyed. * The loader should check whether the Effect is supported. If the Effect indicates it is * not supported, it should not get loaded. * * If the Effect loaded successfully the signal effectLoaded(KWin::Effect*,const QString&) * must be emitted. Otherwise the user of the loader is not able to get the loaded Effect. * It's not returning the Effect as queryAndLoadAll() is working async and thus the users * of the loader are expected to be prepared for async loading. * * @param name The internal name of the Effect which should be loaded * @return bool @c true if the effect could be loaded, @c false in error case * @see queryAndLoadAll() * @see effectLoaded(KWin::Effect*,const QString&) - **/ + */ virtual bool loadEffect(const QString &name) = 0; /** * @brief The Effect Loader should query its store for all available effects and try to load them. * * The Effect Loader is supposed to perform this operation in a highly async way. If there is * IO which needs to be performed this should be done in a background thread and a queue should * be used to load the effects. The loader should make sure to not load more than one Effect * in one event cycle. Loading the Effect has to be performed in the Compositor thread and * thus blocks the Compositor. Therefore after loading one Effect all events should get * processed first, so that the Compositor can perform a painting pass if needed. To simplify * this operation one can use the EffectLoadQueue. This requires to add another loadEffect * method with the custom loader specific type to refer to an Effect and LoadEffectFlags. * * The LoadEffectFlags have to be determined by querying the configuration with readConfig(). * If the Load flag is set the loading can proceed and all the checks from * loadEffect(const QString &) have to be applied. * In addition if the CheckDefaultFunction flag is set and the Effect provides such a method, * it should be queried to determine whether the Effect is enabled by default. If such a method * returns @c false the Effect should not get loaded. If the Effect does not provide a way to * query whether it's enabled by default at runtime the flag can get ignored. * * If the Effect loaded successfully the signal effectLoaded(KWin::Effect*,const QString&) * must be emitted. * * @see loadEffect(const QString &) * @see effectLoaded(KWin::Effect*,const QString&) - **/ + */ virtual void queryAndLoadAll() = 0; /** * @brief Whether the Effect with the given @p name is supported by the compositing backend. * * @param name The name of the Effect to check. * @return bool @c true if it is supported, @c false otherwise - **/ + */ virtual bool isEffectSupported(const QString &name) const = 0; /** * @brief Clears the load queue, that is all scheduled Effects are discarded from loading. - **/ + */ virtual void clear() = 0; Q_SIGNALS: /** * @brief The loader emits this signal when it successfully loaded an effect. * * @param effect The created Effect * @param name The internal name of the loaded Effect * @return void - **/ + */ void effectLoaded(KWin::Effect *effect, const QString &name); protected: explicit AbstractEffectLoader(QObject *parent = nullptr); /** * @brief Checks the configuration for the Effect identified by @p effectName. * * For each Effect there could be a key called "Enabled". If there is such a key * the returned flags will contain Load in case it's @c true. If the key does not exist the * @p defaultValue determines whether the Effect should be loaded. A value of @c true means * that Load | CheckDefaultFunction is returned, in case of @c false no Load flags are returned. * * @param effectName The name of the Effect to look for in the configuration * @param defaultValue Whether the Effect is enabled by default or not. * @returns Flags indicating whether the Effect should be loaded and how it should be loaded - **/ + */ LoadEffectFlags readConfig(const QString &effectName, bool defaultValue) const; private: KSharedConfig::Ptr m_config; }; /** * @brief Helper class to queue the loading of Effects. * * Loading an Effect has to be done in the compositor thread and thus the Compositor is blocked * while the Effect loads. To not block the compositor for several frames the loading of all * Effects need to be queued. By invoking the slot dequeue() through a QueuedConnection the queue * can ensure that events are processed between the loading of two Effects and thus the compositor * doesn't block. * * As it needs to be a slot, the queue must subclass QObject, but it also needs to be templated as * the information to load an Effect is specific to the Effect Loader. Thus there is the * AbstractEffectLoadQueue providing the slots as pure virtual functions and the templated * EffectLoadQueue inheriting from AbstractEffectLoadQueue. * * The queue operates like a normal queue providing enqueue and a scheduleDequeue instead of dequeue. * - **/ + */ class AbstractEffectLoadQueue : public QObject { Q_OBJECT public: explicit AbstractEffectLoadQueue(QObject *parent = nullptr) : QObject(parent) { } protected Q_SLOTS: virtual void dequeue() = 0; }; template class EffectLoadQueue : public AbstractEffectLoadQueue { public: explicit EffectLoadQueue(Loader *parent) : AbstractEffectLoadQueue(parent) , m_effectLoader(parent) , m_dequeueScheduled(false) { } void enqueue(const QPair value) { m_queue.enqueue(value); scheduleDequeue(); } void clear() { m_queue.clear(); m_dequeueScheduled = false; } protected: void dequeue() override { if (m_queue.isEmpty()) { return; } m_dequeueScheduled = false; const auto pair = m_queue.dequeue(); m_effectLoader->loadEffect(pair.first, pair.second); scheduleDequeue(); } private: void scheduleDequeue() { if (m_queue.isEmpty() || m_dequeueScheduled) { return; } m_dequeueScheduled = true; QMetaObject::invokeMethod(this, "dequeue", Qt::QueuedConnection); } Loader *m_effectLoader; bool m_dequeueScheduled; QQueue> m_queue; }; /** * @brief Can load the Built-In-Effects - **/ + */ class BuiltInEffectLoader : public AbstractEffectLoader { Q_OBJECT public: explicit BuiltInEffectLoader(QObject *parent = nullptr); ~BuiltInEffectLoader() override; bool hasEffect(const QString &name) const override; bool isEffectSupported(const QString &name) const override; QStringList listOfKnownEffects() const override; void clear() override; void queryAndLoadAll() override; bool loadEffect(const QString& name) override; bool loadEffect(BuiltInEffect effect, LoadEffectFlags flags); private: bool loadEffect(const QString &name, BuiltInEffect effect, LoadEffectFlags flags); QString internalName(const QString &name) const; EffectLoadQueue *m_queue; QMap m_loadedEffects; }; /** * @brief Can load scripted Effects - **/ + */ class KWIN_EXPORT ScriptedEffectLoader : public AbstractEffectLoader { Q_OBJECT public: explicit ScriptedEffectLoader(QObject* parent = nullptr); ~ScriptedEffectLoader() override; bool hasEffect(const QString &name) const override; bool isEffectSupported(const QString &name) const override; QStringList listOfKnownEffects() const override; void clear() override; void queryAndLoadAll() override; bool loadEffect(const QString &name) override; bool loadEffect(const KPluginMetaData &effect, LoadEffectFlags flags); private: QList findAllEffects() const; KPluginMetaData findEffect(const QString &name) const; QStringList m_loadedEffects; EffectLoadQueue< ScriptedEffectLoader, KPluginMetaData > *m_queue; QMetaObject::Connection m_queryConnection; }; class PluginEffectLoader : public AbstractEffectLoader { Q_OBJECT public: explicit PluginEffectLoader(QObject *parent = nullptr); ~PluginEffectLoader() override; bool hasEffect(const QString &name) const override; bool isEffectSupported(const QString &name) const override; QStringList listOfKnownEffects() const override; void clear() override; void queryAndLoadAll() override; bool loadEffect(const QString &name) override; bool loadEffect(const KPluginMetaData &info, LoadEffectFlags flags); void setPluginSubDirectory(const QString &directory); private: QVector findAllEffects() const; KPluginMetaData findEffect(const QString &name) const; EffectPluginFactory *factory(const KPluginMetaData &info) const; QStringList m_loadedEffects; EffectLoadQueue< PluginEffectLoader, KPluginMetaData> *m_queue; QString m_pluginSubDirectory; QMetaObject::Connection m_queryConnection; }; class EffectLoader : public AbstractEffectLoader { Q_OBJECT public: explicit EffectLoader(QObject *parent = nullptr); ~EffectLoader() override; bool hasEffect(const QString &name) const override; bool isEffectSupported(const QString &name) const override; QStringList listOfKnownEffects() const override; bool loadEffect(const QString &name) override; void queryAndLoadAll() override; void setConfig(KSharedConfig::Ptr config) override; void clear() override; private: QList m_loaders; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::LoadEffectFlags) #endif diff --git a/effects.h b/effects.h index a7736e570..67ff7b746 100644 --- a/effects.h +++ b/effects.h @@ -1,669 +1,669 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak 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_EFFECTSIMPL_H #define KWIN_EFFECTSIMPL_H #include "kwineffects.h" #include "scene.h" #include #include #include namespace Plasma { class Theme; } namespace KWayland { namespace Server { class Display; } } class QDBusPendingCallWatcher; class QDBusServiceWatcher; namespace KWin { class AbstractThumbnailItem; class DesktopThumbnailItem; class WindowThumbnailItem; class AbstractClient; class Client; class Compositor; class Deleted; class EffectLoader; class Toplevel; class Unmanaged; class WindowPropertyNotifyX11Filter; class KWIN_EXPORT EffectsHandlerImpl : public EffectsHandler { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Effects") Q_PROPERTY(QStringList activeEffects READ activeEffects) Q_PROPERTY(QStringList loadedEffects READ loadedEffects) Q_PROPERTY(QStringList listOfEffects READ listOfEffects) public: EffectsHandlerImpl(Compositor *compositor, Scene *scene); ~EffectsHandlerImpl() override; void prePaintScreen(ScreenPrePaintData& data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData& data) override; /** * Special hook to perform a paintScreen but just with the windows on @p desktop. - **/ + */ void paintDesktop(int desktop, int mask, QRegion region, ScreenPaintData& data); void postPaintScreen() override; void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) override; void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void postPaintWindow(EffectWindow* w) override; void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) override; Effect *provides(Effect::Feature ef); void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void buildQuads(EffectWindow* w, WindowQuadList& quadList) override; void activateWindow(EffectWindow* c) override; EffectWindow* activeWindow() const override; void moveWindow(EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0) override; void windowToDesktop(EffectWindow* w, int desktop) override; void windowToScreen(EffectWindow* w, int screen) override; void setShowingDesktop(bool showing) override; QString currentActivity() const override; int currentDesktop() const override; int numberOfDesktops() const override; void setCurrentDesktop(int desktop) override; void setNumberOfDesktops(int desktops) override; QSize desktopGridSize() const override; int desktopGridWidth() const override; int desktopGridHeight() const override; int workspaceWidth() const override; int workspaceHeight() const override; int desktopAtCoords(QPoint coords) const override; QPoint desktopGridCoords(int id) const override; QPoint desktopCoords(int id) const override; int desktopAbove(int desktop = 0, bool wrap = true) const override; int desktopToRight(int desktop = 0, bool wrap = true) const override; int desktopBelow(int desktop = 0, bool wrap = true) const override; int desktopToLeft(int desktop = 0, bool wrap = true) const override; QString desktopName(int desktop) const override; bool optionRollOverDesktops() const override; QPoint cursorPos() const override; bool grabKeyboard(Effect* effect) override; void ungrabKeyboard() override; // not performing XGrabPointer void startMouseInterception(Effect *effect, Qt::CursorShape shape) override; void stopMouseInterception(Effect *effect) override; bool isMouseInterception() const; void registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) override; void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) override; void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) override; void registerTouchpadSwipeShortcut(SwipeDirection direction, QAction *action) override; void* getProxy(QString name) override; void startMousePolling() override; void stopMousePolling() override; EffectWindow* findWindow(WId id) const override; EffectWindow* findWindow(KWayland::Server::SurfaceInterface *surf) const override; EffectWindow *findWindow(QWindow *w) const override; EffectWindow *findWindow(const QUuid &id) const override; EffectWindowList stackingOrder() const override; void setElevatedWindow(KWin::EffectWindow* w, bool set) override; void setTabBoxWindow(EffectWindow*) override; void setTabBoxDesktop(int) override; EffectWindowList currentTabBoxWindowList() const override; void refTabBox() override; void unrefTabBox() override; void closeTabBox() override; QList< int > currentTabBoxDesktopList() const override; int currentTabBoxDesktop() const override; EffectWindow* currentTabBoxWindow() const override; void setActiveFullScreenEffect(Effect* e) override; Effect* activeFullScreenEffect() const override; bool hasActiveFullScreenEffect() const override; void addRepaintFull() override; void addRepaint(const QRect& r) override; void addRepaint(const QRegion& r) override; void addRepaint(int x, int y, int w, int h) override; int activeScreen() const override; int numScreens() const override; int screenNumber(const QPoint& pos) const override; QRect clientArea(clientAreaOption, int screen, int desktop) const override; QRect clientArea(clientAreaOption, const EffectWindow* c) const override; QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const override; QSize virtualScreenSize() const override; QRect virtualScreenGeometry() const override; double animationTimeFactor() const override; WindowQuadType newWindowQuadType() override; void defineCursor(Qt::CursorShape shape) override; bool checkInputWindowEvent(QMouseEvent *e); bool checkInputWindowEvent(QWheelEvent *e); void checkInputWindowStacking(); void reserveElectricBorder(ElectricBorder border, Effect *effect) override; void unreserveElectricBorder(ElectricBorder border, Effect *effect) override; void registerTouchBorder(ElectricBorder border, QAction *action) override; void unregisterTouchBorder(ElectricBorder border, QAction *action) override; unsigned long xrenderBufferPicture() override; QPainter* scenePainter() override; void reconfigure() override; QByteArray readRootProperty(long atom, long type, int format) const override; xcb_atom_t announceSupportProperty(const QByteArray& propertyName, Effect* effect) override; void removeSupportProperty(const QByteArray& propertyName, Effect* effect) override; bool hasDecorationShadows() const override; bool decorationsHaveAlpha() const override; bool decorationSupportsBlurBehind() const override; EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment) const override; QVariant kwinOption(KWinOption kwopt) override; bool isScreenLocked() const override; bool makeOpenGLContextCurrent() override; void doneOpenGLContextCurrent() override; xcb_connection_t *xcbConnection() const override; xcb_window_t x11RootWindow() const override; // internal (used by kwin core or compositing code) void startPaint(); void grabbedKeyboardEvent(QKeyEvent* e); bool hasKeyboardGrab() const; void desktopResized(const QSize &size); void reloadEffect(Effect *effect) override; QStringList loadedEffects() const; QStringList listOfEffects() const; void unloadAllEffects(); QList elevatedWindows() const; QStringList activeEffects() const; /** * @returns Whether we are currently in a desktop rendering process triggered by paintDesktop hook - **/ + */ bool isDesktopRendering() const { return m_desktopRendering; } /** * @returns the desktop currently being rendered in the paintDesktop hook. - **/ + */ int currentRenderedDesktop() const { return m_currentRenderedDesktop; } KWayland::Server::Display *waylandDisplay() const override; bool animationsSupported() const override; PlatformCursorImage cursorImage() const override; void hideCursor() override; void showCursor() override; void startInteractiveWindowSelection(std::function callback) override; void startInteractivePositionSelection(std::function callback) override; void showOnScreenMessage(const QString &message, const QString &iconName = QString()) override; void hideOnScreenMessage(OnScreenMessageHideFlags flags = OnScreenMessageHideFlags()) override; KSharedConfigPtr config() const override; KSharedConfigPtr inputConfig() const override; Scene *scene() const { return m_scene; } bool touchDown(quint32 id, const QPointF &pos, quint32 time); bool touchMotion(quint32 id, const QPointF &pos, quint32 time); bool touchUp(quint32 id, quint32 time); void highlightWindows(const QVector &windows); bool isPropertyTypeRegistered(xcb_atom_t atom) const { return registered_atoms.contains(atom); } void windowToDesktops(EffectWindow *w, const QVector &desktops) override; /** * Finds an effect with the given name. * * @param name The name of the effect. * @returns The effect with the given name @p name, or nullptr if there * is no such effect loaded. - **/ + */ Effect *findEffect(const QString &name) const; public Q_SLOTS: void slotCurrentTabAboutToChange(EffectWindow* from, EffectWindow* to); void slotTabAdded(EffectWindow* from, EffectWindow* to); void slotTabRemoved(EffectWindow* c, EffectWindow* newActiveWindow); // slots for D-Bus interface Q_SCRIPTABLE void reconfigureEffect(const QString& name); Q_SCRIPTABLE bool loadEffect(const QString& name); Q_SCRIPTABLE void toggleEffect(const QString& name); Q_SCRIPTABLE void unloadEffect(const QString& name); Q_SCRIPTABLE bool isEffectLoaded(const QString& name) const; Q_SCRIPTABLE bool isEffectSupported(const QString& name); Q_SCRIPTABLE QList areEffectsSupported(const QStringList &names); Q_SCRIPTABLE QString supportInformation(const QString& name) const; Q_SCRIPTABLE QString debug(const QString& name, const QString& parameter = QString()) const; protected Q_SLOTS: void slotClientShown(KWin::Toplevel*); void slotShellClientShown(KWin::Toplevel*); void slotUnmanagedShown(KWin::Toplevel*); void slotWindowClosed(KWin::Toplevel *c, KWin::Deleted *d); void slotClientMaximized(KWin::AbstractClient *c, MaximizeMode maxMode); void slotOpacityChanged(KWin::Toplevel *t, qreal oldOpacity); void slotClientModalityChanged(); void slotGeometryShapeChanged(KWin::Toplevel *t, const QRect &old); void slotPaddingChanged(KWin::Toplevel *t, const QRect &old); void slotWindowDamaged(KWin::Toplevel *t, const QRect& r); protected: void connectNotify(const QMetaMethod &signal) override; void disconnectNotify(const QMetaMethod &signal) override; void effectsChanged(); void setupAbstractClientConnections(KWin::AbstractClient *c); void setupClientConnections(KWin::Client *c); void setupUnmanagedConnections(KWin::Unmanaged *u); /** * Default implementation does nothing and returns @c true. - **/ + */ virtual bool doGrabKeyboard(); /** * Default implementation does nothing. - **/ + */ virtual void doUngrabKeyboard(); /** * Default implementation sets Effects override cursor on the PointerInputRedirection. - **/ + */ virtual void doStartMouseInterception(Qt::CursorShape shape); /** * Default implementation removes the Effects override cursor on the PointerInputRedirection. - **/ + */ virtual void doStopMouseInterception(); /** * Default implementation does nothing - **/ + */ virtual void doCheckInputWindowStacking(); Effect* keyboard_grab_effect; Effect* fullscreen_effect; QList elevated_windows; QMultiMap< int, EffectPair > effect_order; QHash< long, int > registered_atoms; int next_window_quad_type; private: void registerPropertyType(long atom, bool reg); void destroyEffect(Effect *effect); typedef QVector< Effect*> EffectsList; typedef EffectsList::const_iterator EffectsIterator; EffectsList m_activeEffects; EffectsIterator m_currentDrawWindowIterator; EffectsIterator m_currentPaintWindowIterator; EffectsIterator m_currentPaintEffectFrameIterator; EffectsIterator m_currentPaintScreenIterator; EffectsIterator m_currentBuildQuadsIterator; typedef QHash< QByteArray, QList< Effect*> > PropertyEffectMap; PropertyEffectMap m_propertiesForEffects; QHash m_managedProperties; Compositor *m_compositor; Scene *m_scene; bool m_desktopRendering; int m_currentRenderedDesktop; QList m_grabbedMouseEffects; EffectLoader *m_effectLoader; int m_trackingCursorChanges; std::unique_ptr m_x11WindowPropertyNotify; }; class EffectWindowImpl : public EffectWindow { Q_OBJECT public: explicit EffectWindowImpl(Toplevel *toplevel); ~EffectWindowImpl() override; void enablePainting(int reason) override; void disablePainting(int reason) override; bool isPaintingEnabled() override; void addRepaint(const QRect &r) override; void addRepaint(int x, int y, int w, int h) override; void addRepaintFull() override; void addLayerRepaint(const QRect &r) override; void addLayerRepaint(int x, int y, int w, int h) override; void refWindow() override; void unrefWindow() override; const EffectWindowGroup* group() const override; bool isDeleted() const override; bool isMinimized() const override; double opacity() const override; bool hasAlpha() const override; QStringList activities() const override; int desktop() const override; QVector desktops() const override; int x() const override; int y() const override; int width() const override; int height() const override; QSize basicUnit() const override; QRect geometry() const override; QString caption() const override; QRect expandedGeometry() const override; QRegion shape() const override; int screen() const override; bool hasOwnShape() const override; // only for shadow effect, for now QPoint pos() const override; QSize size() const override; QRect rect() const override; bool isMovable() const override; bool isMovableAcrossScreens() const override; bool isUserMove() const override; bool isUserResize() const override; QRect iconGeometry() const override; bool isDesktop() const override; bool isDock() const override; bool isToolbar() const override; bool isMenu() const override; bool isNormalWindow() const override; bool isSpecialWindow() const override; bool isDialog() const override; bool isSplash() const override; bool isUtility() const override; bool isDropdownMenu() const override; bool isPopupMenu() const override; bool isTooltip() const override; bool isNotification() const override; bool isCriticalNotification() const override; bool isOnScreenDisplay() const override; bool isComboBox() const override; bool isDNDIcon() const override; bool skipsCloseAnimation() const override; bool acceptsFocus() const override; bool keepAbove() const override; bool keepBelow() const override; bool isModal() const override; bool isPopupWindow() const override; bool isOutline() const override; KWayland::Server::SurfaceInterface *surface() const override; bool isFullScreen() const override; bool isUnresponsive() const override; QRect contentsRect() const override; bool decorationHasAlpha() const override; QIcon icon() const override; QString windowClass() const override; NET::WindowType windowType() const override; bool isSkipSwitcher() const override; bool isCurrentTab() const override; QString windowRole() const override; bool isManaged() const override; bool isWaylandClient() const override; bool isX11Client() const override; QRect decorationInnerRect() const override; QByteArray readProperty(long atom, long type, int format) const override; void deleteProperty(long atom) const override; EffectWindow* findModal() override; EffectWindowList mainWindows() const override; WindowQuadList buildQuads(bool force = false) const override; void minimize() override; void unminimize() override; void closeWindow() override; void referencePreviousWindowPixmap() override; void unreferencePreviousWindowPixmap() override; QWindow *internalWindow() const override; const Toplevel* window() const; Toplevel* window(); void setWindow(Toplevel* w); // internal void setSceneWindow(Scene::Window* w); // internal const Scene::Window* sceneWindow() const; // internal Scene::Window* sceneWindow(); // internal void elevate(bool elevate); void setData(int role, const QVariant &data) override; QVariant data(int role) const override; void registerThumbnail(AbstractThumbnailItem *item); QHash > const &thumbnails() const { return m_thumbnails; } QList const &desktopThumbnails() const { return m_desktopThumbnails; } private Q_SLOTS: void thumbnailDestroyed(QObject *object); void thumbnailTargetChanged(); void desktopThumbnailDestroyed(QObject *object); private: void insertThumbnail(WindowThumbnailItem *item); Toplevel* toplevel; Scene::Window* sw; // This one is used only during paint pass. QHash dataMap; QHash > m_thumbnails; QList m_desktopThumbnails; bool managed = false; bool waylandClient; bool x11Client; }; class EffectWindowGroupImpl : public EffectWindowGroup { public: explicit EffectWindowGroupImpl(Group* g); EffectWindowList members() const override; private: Group* group; }; class KWIN_EXPORT EffectFrameImpl : public QObject, public EffectFrame { Q_OBJECT public: explicit EffectFrameImpl(EffectFrameStyle style, bool staticSize = true, QPoint position = QPoint(-1, -1), Qt::Alignment alignment = Qt::AlignCenter); ~EffectFrameImpl() override; void free() override; void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0) override; Qt::Alignment alignment() const override; void setAlignment(Qt::Alignment alignment) override; const QFont& font() const override; void setFont(const QFont& font) override; const QRect& geometry() const override; void setGeometry(const QRect& geometry, bool force = false) override; const QIcon& icon() const override; void setIcon(const QIcon& icon) override; const QSize& iconSize() const override; void setIconSize(const QSize& size) override; void setPosition(const QPoint& point) override; const QString& text() const override; void setText(const QString& text) override; EffectFrameStyle style() const override { return m_style; }; Plasma::FrameSvg& frame() { return m_frame; } bool isStatic() const { return m_static; }; void finalRender(QRegion region, double opacity, double frameOpacity) const; void setShader(GLShader* shader) override { m_shader = shader; } GLShader* shader() const override { return m_shader; } void setSelection(const QRect& selection) override; const QRect& selection() const { return m_selectionGeometry; } Plasma::FrameSvg& selectionFrame() { return m_selection; } /** * The foreground text color as specified by the default Plasma theme. - **/ + */ QColor styledTextColor(); private Q_SLOTS: void plasmaThemeChanged(); private: Q_DISABLE_COPY(EffectFrameImpl) // As we need to use Qt slots we cannot copy this class void align(QRect &geometry); // positions geometry around m_point respecting m_alignment void autoResize(); // Auto-resize if not a static size EffectFrameStyle m_style; Plasma::FrameSvg m_frame; // TODO: share between all EffectFrames Plasma::FrameSvg m_selection; // Position bool m_static; QPoint m_point; Qt::Alignment m_alignment; QRect m_geometry; // Contents QString m_text; QFont m_font; QIcon m_icon; QSize m_iconSize; QRect m_selectionGeometry; Scene::EffectFrame* m_sceneFrame; GLShader* m_shader; Plasma::Theme *m_theme; }; inline QList EffectsHandlerImpl::elevatedWindows() const { if (isScreenLocked()) return QList(); return elevated_windows; } inline xcb_window_t EffectsHandlerImpl::x11RootWindow() const { return rootWindow(); } inline xcb_connection_t *EffectsHandlerImpl::xcbConnection() const { return connection(); } inline EffectWindowGroupImpl::EffectWindowGroupImpl(Group* g) : group(g) { } EffectWindow* effectWindow(Toplevel* w); EffectWindow* effectWindow(Scene::Window* w); inline const Scene::Window* EffectWindowImpl::sceneWindow() const { return sw; } inline Scene::Window* EffectWindowImpl::sceneWindow() { return sw; } inline const Toplevel* EffectWindowImpl::window() const { return toplevel; } inline Toplevel* EffectWindowImpl::window() { return toplevel; } } // namespace #endif diff --git a/effects/coverswitch/coverswitch.h b/effects/coverswitch/coverswitch.h index 994df1c1f..7b071b987 100644 --- a/effects/coverswitch/coverswitch.h +++ b/effects/coverswitch/coverswitch.h @@ -1,166 +1,166 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 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_COVERSWITCH_H #define KWIN_COVERSWITCH_H #include #include #include #include #include #include #include #include namespace KWin { class CoverSwitchEffect : public Effect { Q_OBJECT Q_PROPERTY(int animationDuration READ configuredAnimationDuration) Q_PROPERTY(bool animateSwitch READ isAnimateSwitch) Q_PROPERTY(bool animateStart READ isAnimateStart) Q_PROPERTY(bool animateStop READ isAnimateStop) Q_PROPERTY(bool reflection READ isReflection) Q_PROPERTY(bool windowTitle READ isWindowTitle) Q_PROPERTY(qreal zPosition READ windowZPosition) Q_PROPERTY(bool primaryTabBox READ isPrimaryTabBox) Q_PROPERTY(bool secondaryTabBox READ isSecondaryTabBox) // TODO: mirror colors public: CoverSwitchEffect(); ~CoverSwitchEffect() override; void reconfigure(ReconfigureFlags) override; void prePaintScreen(ScreenPrePaintData &data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData &data) override; void postPaintScreen() override; void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) override; void windowInputMouseEvent(QEvent *e) override; bool isActive() const override; static bool supported(); // for properties int configuredAnimationDuration() const { return animationDuration.count(); } bool isAnimateSwitch() const { return animateSwitch; } bool isAnimateStart() const { return animateStart; } bool isAnimateStop() const { return animateStop; } bool isReflection() const { return reflection; } bool isWindowTitle() const { return windowTitle; } qreal windowZPosition() const { return zPosition; } bool isPrimaryTabBox() const { return primaryTabBox; } bool isSecondaryTabBox() const { return secondaryTabBox; } int requestedEffectChainPosition() const override { return 50; } public Q_SLOTS: void slotWindowClosed(KWin::EffectWindow *c); void slotTabBoxAdded(int mode); void slotTabBoxClosed(); void slotTabBoxUpdated(); void slotTabBoxKeyEvent(QKeyEvent* event); private: void paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, bool reflectedWindows = false); void paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data); void paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow); void paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow = NULL); void selectNextOrPreviousWindow(bool forward); inline void selectNextWindow() { selectNextOrPreviousWindow(true); } inline void selectPreviousWindow() { selectNextOrPreviousWindow(false); } void abort(); /** * Updates the caption of the caption frame. * Taking care of rewording the desktop client. * As well sets the icon for the caption frame. - **/ + */ void updateCaption(); bool mActivated; float angle; bool animateSwitch; bool animateStart; bool animateStop; bool animation; bool start; bool stop; bool reflection; float mirrorColor[2][4]; bool windowTitle; std::chrono::milliseconds animationDuration; bool stopRequested; bool startRequested; TimeLine timeLine; QRect area; float zPosition; float scaleFactor; enum Direction { Left, Right }; Direction direction; QQueue scheduled_directions; EffectWindow* selected_window; int activeScreen; QList< EffectWindow* > leftWindows; QList< EffectWindow* > rightWindows; EffectWindowList currentWindowList; EffectWindowList referrencedWindows; EffectFrame* captionFrame; QFont captionFont; bool primaryTabBox; bool secondaryTabBox; GLShader *m_reflectionShader; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_modelviewMatrix; }; } // namespace #endif diff --git a/effects/diminactive/diminactive.cpp b/effects/diminactive/diminactive.cpp index 11619b12c..77083dbe7 100644 --- a/effects/diminactive/diminactive.cpp +++ b/effects/diminactive/diminactive.cpp @@ -1,420 +1,420 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Lubos Lunak Copyright (C) 2007 Christian Nitschkowski 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 . *********************************************************************/ // own #include "diminactive.h" // KConfigSkeleton #include "diminactiveconfig.h" namespace KWin { /** * Checks if two windows belong to the same window group * * One possible example of a window group is an app window and app * preferences window(e.g. Dolphin window and Dolphin Preferences window). * * @param w1 The first window * @param w2 The second window * @returns @c true if both windows belong to the same window group, @c false otherwise - **/ + */ static inline bool belongToSameGroup(const EffectWindow *w1, const EffectWindow *w2) { return w1 && w2 && w1->group() && w1->group() == w2->group(); } DimInactiveEffect::DimInactiveEffect() { initConfig(); reconfigure(ReconfigureAll); connect(effects, &EffectsHandler::windowActivated, this, &DimInactiveEffect::windowActivated); connect(effects, &EffectsHandler::windowClosed, this, &DimInactiveEffect::windowClosed); connect(effects, &EffectsHandler::windowDeleted, this, &DimInactiveEffect::windowDeleted); connect(effects, &EffectsHandler::activeFullScreenEffectChanged, this, &DimInactiveEffect::activeFullScreenEffectChanged); connect(effects, &EffectsHandler::windowKeepAboveChanged, this, &DimInactiveEffect::updateActiveWindow); connect(effects, &EffectsHandler::windowFullScreenChanged, this, &DimInactiveEffect::updateActiveWindow); } DimInactiveEffect::~DimInactiveEffect() { } void DimInactiveEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) DimInactiveConfig::self()->read(); // TODO: Use normalized strength param. m_dimStrength = DimInactiveConfig::strength() / 100.0; m_dimPanels = DimInactiveConfig::dimPanels(); m_dimDesktop = DimInactiveConfig::dimDesktop(); m_dimKeepAbove = DimInactiveConfig::dimKeepAbove(); m_dimByGroup = DimInactiveConfig::dimByGroup(); m_dimFullScreen = DimInactiveConfig::dimFullScreen(); updateActiveWindow(effects->activeWindow()); m_activeWindowGroup = (m_dimByGroup && m_activeWindow) ? m_activeWindow->group() : nullptr; m_fullScreenTransition.timeLine.setDuration( std::chrono::milliseconds(static_cast(animationTime(250)))); effects->addRepaintFull(); } void DimInactiveEffect::prePaintScreen(ScreenPrePaintData &data, int time) { const std::chrono::milliseconds delta(time); if (m_fullScreenTransition.active) { m_fullScreenTransition.timeLine.update(delta); } auto transitionIt = m_transitions.begin(); while (transitionIt != m_transitions.end()) { (*transitionIt).update(delta); ++transitionIt; } effects->prePaintScreen(data, time); } void DimInactiveEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { auto transitionIt = m_transitions.constFind(w); if (transitionIt != m_transitions.constEnd()) { const qreal transitionProgress = (*transitionIt).value(); dimWindow(data, m_dimStrength * transitionProgress); effects->paintWindow(w, mask, region, data); return; } auto forceIt = m_forceDim.constFind(w); if (forceIt != m_forceDim.constEnd()) { const qreal forcedStrength = *forceIt; dimWindow(data, forcedStrength); effects->paintWindow(w, mask, region, data); return; } if (canDimWindow(w)) { dimWindow(data, m_dimStrength); } effects->paintWindow(w, mask, region, data); } void DimInactiveEffect::postPaintScreen() { if (m_fullScreenTransition.active) { if (m_fullScreenTransition.timeLine.done()) { m_fullScreenTransition.active = false; } effects->addRepaintFull(); } auto transitionIt = m_transitions.begin(); while (transitionIt != m_transitions.end()) { EffectWindow *w = transitionIt.key(); if ((*transitionIt).done()) { transitionIt = m_transitions.erase(transitionIt); } else { ++transitionIt; } w->addRepaintFull(); } effects->postPaintScreen(); } void DimInactiveEffect::dimWindow(WindowPaintData &data, qreal strength) { qreal dimFactor; if (m_fullScreenTransition.active) { dimFactor = 1.0 - m_fullScreenTransition.timeLine.value(); } else if (effects->activeFullScreenEffect()) { dimFactor = 0.0; } else { dimFactor = 1.0; } data.multiplyBrightness(1.0 - strength * dimFactor); data.multiplySaturation(1.0 - strength * dimFactor); } bool DimInactiveEffect::canDimWindow(const EffectWindow *w) const { if (m_activeWindow == w) { return false; } if (m_dimByGroup && belongToSameGroup(m_activeWindow, w)) { return false; } if (w->isDock() && !m_dimPanels) { return false; } if (w->isDesktop() && !m_dimDesktop) { return false; } if (w->keepAbove() && !m_dimKeepAbove) { return false; } if (w->isFullScreen() && !m_dimFullScreen) { return false; } if (w->isPopupWindow()) { return false; } if (w->isX11Client() && !w->isManaged()) { return false; } return w->isNormalWindow() || w->isDialog() || w->isUtility() || w->isDock() || w->isDesktop(); } void DimInactiveEffect::scheduleInTransition(EffectWindow *w) { TimeLine &timeLine = m_transitions[w]; timeLine.setDuration( std::chrono::milliseconds(static_cast(animationTime(160)))); if (timeLine.done()) { // If the Out animation is still active, then we're trucating // duration of the timeline(from 250ms to 160ms). If the timeline // is about to be finished with the old duration, then after // changing duration it will be in the "done" state. Thus, we // have to reset the timeline, otherwise it won't update progress. timeLine.reset(); } timeLine.setDirection(TimeLine::Backward); timeLine.setEasingCurve(QEasingCurve::InOutSine); } void DimInactiveEffect::scheduleGroupInTransition(EffectWindow *w) { if (!m_dimByGroup) { scheduleInTransition(w); return; } if (!w->group()) { scheduleInTransition(w); return; } const auto members = w->group()->members(); for (EffectWindow *member : members) { scheduleInTransition(member); } } void DimInactiveEffect::scheduleOutTransition(EffectWindow *w) { TimeLine &timeLine = m_transitions[w]; timeLine.setDuration( std::chrono::milliseconds(static_cast(animationTime(250)))); if (timeLine.done()) { timeLine.reset(); } timeLine.setDirection(TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::InOutSine); } void DimInactiveEffect::scheduleGroupOutTransition(EffectWindow *w) { if (!m_dimByGroup) { scheduleOutTransition(w); return; } if (!w->group()) { scheduleOutTransition(w); return; } const auto members = w->group()->members(); for (EffectWindow *member : members) { scheduleOutTransition(member); } } void DimInactiveEffect::scheduleRepaint(EffectWindow *w) { if (!m_dimByGroup) { w->addRepaintFull(); return; } if (!w->group()) { w->addRepaintFull(); return; } const auto members = w->group()->members(); for (EffectWindow *member : members) { member->addRepaintFull(); } } void DimInactiveEffect::windowActivated(EffectWindow *w) { if (!w) { return; } if (m_activeWindow == w) { return; } if (m_dimByGroup && belongToSameGroup(m_activeWindow, w)) { m_activeWindow = w; return; } // WORKAROUND: Deleted windows do not belong to any of window groups. // So, if one of windows in a window group is closed, the In transition // will be false-triggered for the rest of the window group. In addition // to the active window, keep track of active window group so we can // tell whether "focus" moved from a closed window to some other window // in a window group. if (m_dimByGroup && w->group() && w->group() == m_activeWindowGroup) { m_activeWindow = w; return; } EffectWindow *previousActiveWindow = m_activeWindow; m_activeWindow = canDimWindow(w) ? w : nullptr; m_activeWindowGroup = (m_dimByGroup && m_activeWindow) ? m_activeWindow->group() : nullptr; if (previousActiveWindow) { scheduleGroupOutTransition(previousActiveWindow); scheduleRepaint(previousActiveWindow); } if (m_activeWindow) { scheduleGroupInTransition(m_activeWindow); scheduleRepaint(m_activeWindow); } } void DimInactiveEffect::windowClosed(EffectWindow *w) { // When a window is closed, we should force current dim strength that // is applied to it to avoid flickering when some effect animates // the disappearing of the window. If there is no such effect then // it won't be dimmed. qreal forcedStrength = 0.0; bool shouldForceDim = false; auto transitionIt = m_transitions.find(w); if (transitionIt != m_transitions.end()) { forcedStrength = m_dimStrength * (*transitionIt).value(); shouldForceDim = true; m_transitions.erase(transitionIt); } else if (m_activeWindow == w) { forcedStrength = 0.0; shouldForceDim = true; } else if (m_dimByGroup && belongToSameGroup(m_activeWindow, w)) { forcedStrength = 0.0; shouldForceDim = true; } else if (canDimWindow(w)) { forcedStrength = m_dimStrength; shouldForceDim = true; } if (shouldForceDim) { m_forceDim.insert(w, forcedStrength); } if (m_activeWindow == w) { m_activeWindow = nullptr; } } void DimInactiveEffect::windowDeleted(EffectWindow *w) { m_forceDim.remove(w); // FIXME: Sometimes we can miss the window close signal because KWin // can activate a window that is not ready for painting and the window // gets destroyed immediately. So, we have to remove active transitions // for that window here, otherwise we'll crash in postPaintScreen. m_transitions.remove(w); } void DimInactiveEffect::activeFullScreenEffectChanged() { if (m_fullScreenTransition.timeLine.done()) { m_fullScreenTransition.timeLine.reset(); } m_fullScreenTransition.timeLine.setDirection( effects->activeFullScreenEffect() ? TimeLine::Forward : TimeLine::Backward ); m_fullScreenTransition.active = true; effects->addRepaintFull(); } void DimInactiveEffect::updateActiveWindow(EffectWindow *w) { if (effects->activeWindow() == nullptr) { return; } if (effects->activeWindow() != w) { return; } // Need to reset m_activeWindow because canDimWindow depends on it. m_activeWindow = nullptr; m_activeWindow = canDimWindow(w) ? w : nullptr; } } // namespace KWin diff --git a/effects/effect_builtins.h b/effects/effect_builtins.h index 1500de3e3..435042f77 100644 --- a/effects/effect_builtins.h +++ b/effects/effect_builtins.h @@ -1,107 +1,107 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_EFFECT_BUILTINS_H #define KWIN_EFFECT_BUILTINS_H #include #include #include #include namespace KWin { class Effect; /** * Defines all the built in effects. - **/ + */ enum class BuiltInEffect { Invalid, ///< not a valid Effect Blur, ColorPicker, Contrast, CoverSwitch, Cube, CubeSlide, DesktopGrid, DimInactive, FallApart, FlipSwitch, Glide, HighlightWindow, Invert, Kscreen, LookingGlass, MagicLamp, Magnifier, MouseClick, MouseMark, PresentWindows, Resize, ScreenEdge, ScreenShot, Sheet, ShowFps, ShowPaint, Slide, SlideBack, SlidingPopups, SnapHelper, StartupFeedback, ThumbnailAside, TouchPoints, TrackMouse, WindowGeometry, WobblyWindows, Zoom }; namespace BuiltInEffects { struct EffectData { QString name; QString displayName; QString comment; QString category; QString exclusiveCategory; QUrl video; bool enabled; bool internal; std::function createFunction; std::function supportedFunction; std::function enabledFunction; }; KWINEFFECTS_EXPORT Effect *create(BuiltInEffect effect); KWINEFFECTS_EXPORT bool available(const QString &name); KWINEFFECTS_EXPORT bool supported(BuiltInEffect effect); KWINEFFECTS_EXPORT bool checkEnabledByDefault(BuiltInEffect effect); KWINEFFECTS_EXPORT bool enabledByDefault(BuiltInEffect effect); KWINEFFECTS_EXPORT QString nameForEffect(BuiltInEffect effect); KWINEFFECTS_EXPORT BuiltInEffect builtInForName(const QString &name); KWINEFFECTS_EXPORT QStringList availableEffectNames(); KWINEFFECTS_EXPORT QList availableEffects(); KWINEFFECTS_EXPORT const EffectData &effectData(BuiltInEffect effect); } } #endif diff --git a/effects/flipswitch/flipswitch.h b/effects/flipswitch/flipswitch.h index 6f86e6d93..922236be0 100644 --- a/effects/flipswitch/flipswitch.h +++ b/effects/flipswitch/flipswitch.h @@ -1,165 +1,165 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008, 2009 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_FLIPSWITCH_H #define KWIN_FLIPSWITCH_H #include #include #include #include #include namespace KWin { class FlipSwitchEffect : public Effect { Q_OBJECT Q_PROPERTY(bool tabBox READ isTabBox) Q_PROPERTY(bool tabBoxAlternative READ isTabBoxAlternative) Q_PROPERTY(int duration READ duration) Q_PROPERTY(int angle READ angle) Q_PROPERTY(qreal xPosition READ xPosition) Q_PROPERTY(qreal yPosition READ yPosition) Q_PROPERTY(bool windowTitle READ isWindowTitle) public: FlipSwitchEffect(); ~FlipSwitchEffect() override; void reconfigure(ReconfigureFlags) override; void prePaintScreen(ScreenPrePaintData& data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData& data) override; void postPaintScreen() override; void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) override; void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void grabbedKeyboardEvent(QKeyEvent* e) override; void windowInputMouseEvent(QEvent* e) override; bool isActive() const override; int requestedEffectChainPosition() const override { return 50; } static bool supported(); // for properties bool isTabBox() const { return m_tabbox; } bool isTabBoxAlternative() const { return m_tabboxAlternative; } int duration() const { return m_timeLine.duration(); } int angle() const { return m_angle; } qreal xPosition() const { return m_xPosition; } qreal yPosition() const { return m_yPosition; } bool isWindowTitle() const { return m_windowTitle; } private Q_SLOTS: void toggleActiveCurrent(); void toggleActiveAllDesktops(); void globalShortcutChanged(QAction *action, QKeySequence shortcut); void slotWindowAdded(KWin::EffectWindow* w); void slotWindowClosed(KWin::EffectWindow *w); void slotTabBoxAdded(int mode); void slotTabBoxClosed(); void slotTabBoxUpdated(); void slotTabBoxKeyEvent(QKeyEvent* event); private: class ItemInfo; enum SwitchingDirection { DirectionForward, DirectionBackward }; enum FlipSwitchMode { TabboxMode, CurrentDesktopMode, AllDesktopsMode }; void setActive(bool activate, FlipSwitchMode mode); bool isSelectableWindow(EffectWindow *w) const; void scheduleAnimation(const SwitchingDirection& direction, int distance = 1); void adjustWindowMultiScreen(const EffectWindow *w, WindowPaintData& data); void selectNextOrPreviousWindow(bool forward); inline void selectNextWindow() { selectNextOrPreviousWindow(true); } inline void selectPreviousWindow() { selectNextOrPreviousWindow(false); } /** * Updates the caption of the caption frame. * Taking care of rewording the desktop client. * As well sets the icon for the caption frame. - **/ + */ void updateCaption(); QQueue< SwitchingDirection> m_scheduledDirections; EffectWindow* m_selectedWindow; QTimeLine m_timeLine; QTimeLine m_startStopTimeLine; QTimeLine::CurveShape m_currentAnimationShape; QRect m_screenArea; int m_activeScreen; bool m_active; bool m_start; bool m_stop; bool m_animation; bool m_hasKeyboardGrab; FlipSwitchMode m_mode; EffectFrame* m_captionFrame; QFont m_captionFont; EffectWindowList m_flipOrderedWindows; QHash< const EffectWindow*, ItemInfo* > m_windows; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_modelviewMatrix; // options bool m_tabbox; bool m_tabboxAlternative; float m_angle; float m_xPosition; float m_yPosition; bool m_windowTitle; // Shortcuts QList m_shortcutCurrent; QList m_shortcutAll; }; class FlipSwitchEffect::ItemInfo { public: ItemInfo(); ~ItemInfo(); bool deleted; double opacity; double brightness; double saturation; }; } // namespace #endif diff --git a/effects/invert/invert.h b/effects/invert/invert.h index 598faddc0..25a3d796e 100644 --- a/effects/invert/invert.h +++ b/effects/invert/invert.h @@ -1,75 +1,75 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Rivo Laks Copyright (C) 2008 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_INVERT_H #define KWIN_INVERT_H #include namespace KWin { class GLShader; /** * Inverts desktop's colors - **/ + */ class InvertEffect : public Effect { Q_OBJECT public: InvertEffect(); ~InvertEffect() override; void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void paintEffectFrame(KWin::EffectFrame* frame, QRegion region, double opacity, double frameOpacity) override; bool isActive() const override; bool provides(Feature) override; int requestedEffectChainPosition() const override; static bool supported(); public Q_SLOTS: void toggleScreenInversion(); void toggleWindow(); void slotWindowClosed(KWin::EffectWindow *w); protected: bool loadData(); private: bool m_inited; bool m_valid; GLShader* m_shader; bool m_allWindows; QList m_windows; }; inline int InvertEffect::requestedEffectChainPosition() const { return 99; } } // namespace #endif diff --git a/effects/kscreen/kscreen.cpp b/effects/kscreen/kscreen.cpp index 6c3ce844a..28dfb7514 100644 --- a/effects/kscreen/kscreen.cpp +++ b/effects/kscreen/kscreen.cpp @@ -1,192 +1,192 @@ /******************************************************************** 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 . *********************************************************************/ // own #include "kscreen.h" // KConfigSkeleton #include "kscreenconfig.h" /** * How this effect works: * * Effect announces that it is around through property _KDE_KWIN_KSCREEN_SUPPORT on the root window. * * KScreen watches for this property and when it wants to adjust screens, KScreen goes * through the following protocol: * 1. KScreen sets the property value to 1 * 2. Effect starts to fade out all windows * 3. When faded out the effect sets property value to 2 * 4. KScreen adjusts the screens * 5. KScreen sets property value to 3 * 6. Effect starts to fade in all windows again * 7. Effect sets back property value to 0 * * The property has type 32 bits cardinal. To test it use: * xprop -root -f _KDE_KWIN_KSCREEN_SUPPORT 32c -set _KDE_KWIN_KSCREEN_SUPPORT 1 * * The states are: * 0: normal * 1: fading out * 2: faded out * 3: fading in - **/ + */ namespace KWin { KscreenEffect::KscreenEffect() : Effect() , m_state(StateNormal) , m_atom(effects->announceSupportProperty("_KDE_KWIN_KSCREEN_SUPPORT", this)) { initConfig(); connect(effects, &EffectsHandler::propertyNotify, this, &KscreenEffect::propertyNotify); connect(effects, &EffectsHandler::xcbConnectionChanged, this, [this] { m_atom = effects->announceSupportProperty(QByteArrayLiteral("_KDE_KWIN_KSCREEN_SUPPORT"), this); } ); reconfigure(ReconfigureAll); } KscreenEffect::~KscreenEffect() { } void KscreenEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) KscreenConfig::self()->read(); m_timeLine.setDuration( std::chrono::milliseconds(animationTime(250))); } void KscreenEffect::prePaintScreen(ScreenPrePaintData &data, int time) { if (m_state == StateFadingIn || m_state == StateFadingOut) { m_timeLine.update(std::chrono::milliseconds(time)); if (m_timeLine.done()) { switchState(); } } effects->prePaintScreen(data, time); } void KscreenEffect::postPaintScreen() { if (m_state == StateFadingIn || m_state == StateFadingOut) { effects->addRepaintFull(); } } void KscreenEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { if (m_state != StateNormal) { data.setTranslucent(); } effects->prePaintWindow(w, data, time); } void KscreenEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { //fade to black and fully opaque switch (m_state) { case StateFadingOut: data.setOpacity(data.opacity() + (1.0 - data.opacity()) * m_timeLine.value()); data.multiplyBrightness(1.0 - m_timeLine.value()); break; case StateFadedOut: data.multiplyOpacity(0.0); data.multiplyBrightness(0.0); break; case StateFadingIn: data.setOpacity(data.opacity() + (1.0 - data.opacity()) * (1.0 - m_timeLine.value())); data.multiplyBrightness(m_timeLine.value()); break; default: // no adjustment break; } effects->paintWindow(w, mask, region, data); } void KscreenEffect::propertyNotify(EffectWindow *window, long int atom) { if (window || atom != m_atom || m_atom == XCB_ATOM_NONE) { return; } QByteArray byteData = effects->readRootProperty(m_atom, XCB_ATOM_CARDINAL, 32); const uint32_t *data = byteData.isEmpty() ? nullptr : reinterpret_cast(byteData.data()); if (!data // Property was deleted || data[0] == 0) { // normal state - KWin should have switched to it if (m_state != StateNormal) { m_state = StateNormal; effects->addRepaintFull(); } return; } if (data[0] == 2) { // faded out state - KWin should have switched to it if (m_state != StateFadedOut) { m_state = StateFadedOut; effects->addRepaintFull(); } return; } if (data[0] == 1) { // kscreen wants KWin to fade out all windows m_state = StateFadingOut; m_timeLine.reset(); effects->addRepaintFull(); return; } if (data[0] == 3) { // kscreen wants KWin to fade in again m_state = StateFadingIn; m_timeLine.reset(); effects->addRepaintFull(); return; } qCDebug(KWINEFFECTS) << "Incorrect Property state, immediate stop: " << data[0]; m_state = StateNormal; effects->addRepaintFull(); } void KscreenEffect::switchState() { long value = -1l; if (m_state == StateFadingOut) { m_state = StateFadedOut; value = 2l; } else if (m_state == StateFadingIn) { m_state = StateNormal; value = 0l; } if (value != -1l && m_atom != XCB_ATOM_NONE) { xcb_change_property(xcbConnection(), XCB_PROP_MODE_REPLACE, x11RootWindow(), m_atom, XCB_ATOM_CARDINAL, 32, 1, &value); } } bool KscreenEffect::isActive() const { return m_state != StateNormal; } } // namespace KWin diff --git a/effects/lookingglass/lookingglass.h b/effects/lookingglass/lookingglass.h index 84a0e63bc..bed2a2fce 100644 --- a/effects/lookingglass/lookingglass.h +++ b/effects/lookingglass/lookingglass.h @@ -1,83 +1,83 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Rivo Laks Copyright (C) 2007 Christian Nitschkowski 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_LOOKINGGLASS_H #define KWIN_LOOKINGGLASS_H #include namespace KWin { class GLRenderTarget; class GLShader; class GLTexture; class GLVertexBuffer; /** * Enhanced magnifier - **/ + */ class LookingGlassEffect : public Effect { Q_OBJECT Q_PROPERTY(int initialRadius READ initialRadius) public: LookingGlassEffect(); ~LookingGlassEffect() override; void reconfigure(ReconfigureFlags) override; void prePaintScreen(ScreenPrePaintData& data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData &data) override; bool isActive() const override; static bool supported(); // for properties int initialRadius() const { return initialradius; } public Q_SLOTS: void toggle(); void zoomIn(); void zoomOut(); void slotMouseChanged(const QPoint& pos, const QPoint& old, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); private: bool loadData(); double zoom; double target_zoom; bool polling; // Mouse polling int radius; int initialradius; GLTexture *m_texture; GLRenderTarget *m_fbo; GLVertexBuffer *m_vbo; GLShader *m_shader; bool m_enabled; bool m_valid; }; } // namespace #endif diff --git a/effects/presentwindows/presentwindows.h b/effects/presentwindows/presentwindows.h index 21881d261..d4bfa7e99 100644 --- a/effects/presentwindows/presentwindows.h +++ b/effects/presentwindows/presentwindows.h @@ -1,352 +1,352 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Rivo Laks Copyright (C) 2008 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_PRESENTWINDOWS_H #define KWIN_PRESENTWINDOWS_H #include "presentwindows_proxy.h" #include class QMouseEvent; class QElapsedTimer; class QQuickView; namespace KWin { class CloseWindowView : public QObject { Q_OBJECT public: explicit CloseWindowView(QObject *parent = 0); void windowInputMouseEvent(QMouseEvent* e); void disarm(); void show(); void hide(); bool isVisible() const; // delegate to QWindow int width() const; int height() const; QSize size() const; QRect geometry() const; WId winId() const; void setGeometry(const QRect &geometry); QPoint mapFromGlobal(const QPoint &pos) const; Q_SIGNALS: void requestClose(); private: QScopedPointer m_armTimer; QScopedPointer m_window; bool m_visible; QPoint m_pos; bool m_posIsValid; }; /** * Expose-like effect which shows all windows on current desktop side-by-side, * letting the user select active window. - **/ + */ class PresentWindowsEffect : public Effect { Q_OBJECT Q_PROPERTY(int layoutMode READ layoutMode) Q_PROPERTY(bool showCaptions READ isShowCaptions) Q_PROPERTY(bool showIcons READ isShowIcons) Q_PROPERTY(bool doNotCloseWindows READ isDoNotCloseWindows) Q_PROPERTY(bool ignoreMinimized READ isIgnoreMinimized) Q_PROPERTY(int accuracy READ accuracy) Q_PROPERTY(bool fillGaps READ isFillGaps) Q_PROPERTY(int fadeDuration READ fadeDuration) Q_PROPERTY(bool showPanel READ isShowPanel) Q_PROPERTY(int leftButtonWindow READ leftButtonWindow) Q_PROPERTY(int rightButtonWindow READ rightButtonWindow) Q_PROPERTY(int middleButtonWindow READ middleButtonWindow) Q_PROPERTY(int leftButtonDesktop READ leftButtonDesktop) Q_PROPERTY(int middleButtonDesktop READ middleButtonDesktop) Q_PROPERTY(int rightButtonDesktop READ rightButtonDesktop) // TODO: electric borders private: // Structures struct WindowData { bool visible; bool deleted; bool referenced; double opacity; double highlight; EffectFrame* textFrame; EffectFrame* iconFrame; }; typedef QHash DataHash; struct GridSize { int columns; int rows; }; public: PresentWindowsEffect(); ~PresentWindowsEffect() override; void reconfigure(ReconfigureFlags) override; void* proxy() override; // Screen painting void prePaintScreen(ScreenPrePaintData &data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData &data) override; void postPaintScreen() override; // Window painting void prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) override; void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) override; // User interaction bool borderActivated(ElectricBorder border) override; void windowInputMouseEvent(QEvent *e) override; void grabbedKeyboardEvent(QKeyEvent *e) override; bool isActive() const override; bool touchDown(quint32 id, const QPointF &pos, quint32 time) override; bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override; bool touchUp(quint32 id, quint32 time) override; int requestedEffectChainPosition() const override { return 70; } enum { LayoutNatural, LayoutRegularGrid, LayoutFlexibleGrid }; // Layout modes enum PresentWindowsMode { ModeAllDesktops, // Shows windows of all desktops ModeCurrentDesktop, // Shows windows on current desktop ModeSelectedDesktop, // Shows windows of selected desktop via property (m_desktop) ModeWindowGroup, // Shows windows selected via property ModeWindowClass // Shows all windows of same class as selected class }; enum WindowMouseAction { WindowNoAction = 0, // Nothing WindowActivateAction = 1, // Activates the window and deactivates the effect WindowExitAction = 2, // Deactivates the effect without activating new window WindowToCurrentDesktopAction = 3, // Brings window to current desktop WindowToAllDesktopsAction = 4, // Brings window to all desktops WindowMinimizeAction = 5, // Minimizes the window WindowCloseAction = 6 // Closes the window }; enum DesktopMouseAction { DesktopNoAction = 0, // nothing DesktopActivateAction = 1, // Activates the window and deactivates the effect DesktopExitAction = 2, // Deactivates the effect without activating new window DesktopShowDesktopAction = 3 // Minimizes all windows }; // for properties int layoutMode() const { return m_layoutMode; } bool isShowCaptions() const { return m_showCaptions; } bool isShowIcons() const { return m_showIcons; } bool isDoNotCloseWindows() const { return m_doNotCloseWindows; } bool isIgnoreMinimized() const { return m_ignoreMinimized; } int accuracy() const { return m_accuracy; } bool isFillGaps() const { return m_fillGaps; } int fadeDuration() const { return m_fadeDuration; } bool isShowPanel() const { return m_showPanel; } int leftButtonWindow() const { return m_leftButtonWindow; } int rightButtonWindow() const { return m_rightButtonWindow; } int middleButtonWindow() const { return m_middleButtonWindow; } int leftButtonDesktop() const { return m_leftButtonDesktop; } int middleButtonDesktop() const { return m_middleButtonDesktop; } int rightButtonDesktop() const { return m_rightButtonDesktop; } public Q_SLOTS: void setActive(bool active); void toggleActive() { m_mode = ModeCurrentDesktop; setActive(!m_activated); } void toggleActiveAllDesktops() { m_mode = ModeAllDesktops; setActive(!m_activated); } void toggleActiveClass(); // slots for global shortcut changed // needed to toggle the effect void globalShortcutChanged(QAction *action, const QKeySequence &seq); // EffectsHandler void slotWindowAdded(KWin::EffectWindow *w); void slotWindowClosed(KWin::EffectWindow *w); void slotWindowDeleted(KWin::EffectWindow *w); void slotWindowGeometryShapeChanged(KWin::EffectWindow *w, const QRect &old); // atoms void slotPropertyNotify(KWin::EffectWindow* w, long atom); private Q_SLOTS: void closeWindow(); void elevateCloseWindow(); protected: // Window rearranging void rearrangeWindows(); void reCreateGrids(); void calculateWindowTransformations(EffectWindowList windowlist, int screen, WindowMotionManager& motionManager, bool external = false); void calculateWindowTransformationsClosest(EffectWindowList windowlist, int screen, WindowMotionManager& motionManager); void calculateWindowTransformationsKompose(EffectWindowList windowlist, int screen, WindowMotionManager& motionManager); void calculateWindowTransformationsNatural(EffectWindowList windowlist, int screen, WindowMotionManager& motionManager); // Helper functions for window rearranging inline double aspectRatio(EffectWindow *w) { return w->width() / double(w->height()); } inline int widthForHeight(EffectWindow *w, int height) { return int((height / double(w->height())) * w->width()); } inline int heightForWidth(EffectWindow *w, int width) { return int((width / double(w->width())) * w->height()); } bool isOverlappingAny(EffectWindow *w, const QHash &targets, const QRegion &border); // Filter box void updateFilterFrame(); // Helper functions bool isSelectableWindow(EffectWindow *w); bool isVisibleWindow(EffectWindow *w); void setHighlightedWindow(EffectWindow *w); EffectWindow* relativeWindow(EffectWindow *w, int xdiff, int ydiff, bool wrap) const; EffectWindow* findFirstWindow() const; void updateCloseWindow(); // Helper functions for mouse actions void mouseActionWindow(WindowMouseAction& action); void mouseActionDesktop(DesktopMouseAction& action); void inputEventUpdate(const QPoint &pos, QEvent::Type type = QEvent::None, Qt::MouseButton button = Qt::NoButton); private: PresentWindowsEffectProxy m_proxy; friend class PresentWindowsEffectProxy; // User configuration settings QList m_borderActivate; QList m_borderActivateAll; QList m_borderActivateClass; int m_layoutMode; bool m_showCaptions; bool m_showIcons; bool m_doNotCloseWindows; int m_accuracy; bool m_fillGaps; double m_fadeDuration; bool m_showPanel; // Activation bool m_activated; bool m_ignoreMinimized; double m_decalOpacity; bool m_hasKeyboardGrab; PresentWindowsMode m_mode; int m_desktop; EffectWindowList m_selectedWindows; EffectWindow *m_managerWindow; QString m_class; bool m_needInitialSelection; // Window data WindowMotionManager m_motionManager; DataHash m_windowData; EffectWindow *m_highlightedWindow; // Grid layout info QList m_gridSizes; // Filter box EffectFrame* m_filterFrame; QString m_windowFilter; // Shortcut - needed to toggle the effect QList shortcut; QList shortcutAll; QList shortcutClass; // Atoms // Present windows for all windows of given desktop // -1 for all desktops long m_atomDesktop; // Present windows for group of window ids long m_atomWindows; // Mouse Actions WindowMouseAction m_leftButtonWindow; WindowMouseAction m_middleButtonWindow; WindowMouseAction m_rightButtonWindow; DesktopMouseAction m_leftButtonDesktop; DesktopMouseAction m_middleButtonDesktop; DesktopMouseAction m_rightButtonDesktop; CloseWindowView* m_closeView; EffectWindow* m_closeWindow; Qt::Corner m_closeButtonCorner; struct { quint32 id = 0; bool active = false; } m_touch; QAction *m_exposeAction; QAction *m_exposeAllAction; QAction *m_exposeClassAction; }; } // namespace #endif diff --git a/effects/screenshot/screenshot.h b/effects/screenshot/screenshot.h index b2b0fc24a..bbbc789b0 100644 --- a/effects/screenshot/screenshot.h +++ b/effects/screenshot/screenshot.h @@ -1,174 +1,174 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 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_SCREENSHOT_H #define KWIN_SCREENSHOT_H #include #include #include #include #include #include #include namespace KWin { class ScreenShotEffect : public Effect, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Screenshot") public: enum ScreenShotType { INCLUDE_DECORATION = 1 << 0, INCLUDE_CURSOR = 1 << 1 }; ScreenShotEffect(); ~ScreenShotEffect() override; void paintScreen(int mask, QRegion region, ScreenPaintData &data) override; void postPaintScreen() override; bool isActive() const override; int requestedEffectChainPosition() const override { return 50; } static bool supported(); static void convertFromGLImage(QImage &img, int w, int h); public Q_SLOTS: Q_SCRIPTABLE void screenshotForWindow(qulonglong winid, int mask = 0); /** * Starts an interactive window screenshot session. The user can select a window to * screenshot. * * Once the window is selected the screenshot is saved into a file and the path gets * returned to the DBus peer. * * @param mask The mask for what to include in the screenshot - **/ + */ Q_SCRIPTABLE QString interactive(int mask = 0); /** * Starts an interactive window screenshot session. The user can select a window to * screenshot. * * Once the window is selected the screenshot is saved into the @p fd passed to the * method. It is intended to be used with a pipe, so that the invoking side can just * read from the pipe. The image gets written into the fd using a QDataStream. * * @param fd File descriptor into which the screenshot should be saved * @param mask The mask for what to include in the screenshot - **/ + */ Q_SCRIPTABLE void interactive(QDBusUnixFileDescriptor fd, int mask = 0); Q_SCRIPTABLE void screenshotWindowUnderCursor(int mask = 0); /** * Saves a screenshot of all screen into a file and returns the path to the file. * Functionality requires hardware support, if not available a null string is returned. * @param captureCursor Whether to include the cursor in the image * @returns Path to stored screenshot, or null string in failure case. - **/ + */ Q_SCRIPTABLE QString screenshotFullscreen(bool captureCursor = false); /** * Starts an interactive screenshot session. * * The user is asked to confirm that a screenshot is taken by having to actively * click and giving the possibility to cancel. * * Once the screenshot is taken it gets saved into the @p fd passed to the * method. It is intended to be used with a pipe, so that the invoking side can just * read from the pipe. The image gets written into the fd using a QDataStream. * * @param fd File descriptor into which the screenshot should be saved * @param captureCursor Whether to include the mouse cursor - **/ + */ Q_SCRIPTABLE void screenshotFullscreen(QDBusUnixFileDescriptor fd, bool captureCursor = false); /** * Saves a screenshot of the screen identified by @p screen into a file and returns the path to the file. * Functionality requires hardware support, if not available a null string is returned. * @param screen Number of screen as numbered by QDesktopWidget * @param captureCursor Whether to include the cursor in the image * @returns Path to stored screenshot, or null string in failure case. - **/ + */ Q_SCRIPTABLE QString screenshotScreen(int screen, bool captureCursor = false); /** * Starts an interactive screenshot of a screen session. * * The user is asked to select the screen to screenshot. * * Once the screenshot is taken it gets saved into the @p fd passed to the * method. It is intended to be used with a pipe, so that the invoking side can just * read from the pipe. The image gets written into the fd using a QDataStream. * * @param fd File descriptor into which the screenshot should be saved * @param captureCursor Whether to include the mouse cursor - **/ + */ Q_SCRIPTABLE void screenshotScreen(QDBusUnixFileDescriptor fd, bool captureCursor = false); /** * Saves a screenshot of the selected geometry into a file and returns the path to the file. * Functionality requires hardware support, if not available a null string is returned. * @param x Left upper x coord of region * @param y Left upper y coord of region * @param width Width of the region to screenshot * @param height Height of the region to screenshot * @param captureCursor Whether to include the cursor in the image * @returns Path to stored screenshot, or null string in failure case. - **/ + */ Q_SCRIPTABLE QString screenshotArea(int x, int y, int width, int height, bool captureCursor = false); Q_SIGNALS: Q_SCRIPTABLE void screenshotCreated(qulonglong handle); private Q_SLOTS: void windowClosed( KWin::EffectWindow* w ); private: void grabPointerImage(QImage& snapshot, int offsetx, int offsety); QImage blitScreenshot(const QRect &geometry); QString saveTempImage(const QImage &img); void sendReplyImage(const QImage &img); enum class InfoMessageMode { Window, Screen }; void showInfoMessage(InfoMessageMode mode); void hideInfoMessage(); bool isTakingScreenshot() const; EffectWindow *m_scheduledScreenshot; ScreenShotType m_type; QRect m_scheduledGeometry; QDBusMessage m_replyMessage; QRect m_cachedOutputGeometry; QImage m_multipleOutputsImage; QRegion m_multipleOutputsRendered; bool m_captureCursor = false; enum class WindowMode { NoCapture, Xpixmap, File, FileDescriptor }; WindowMode m_windowMode = WindowMode::NoCapture; int m_fd = -1; }; } // namespace #endif // KWIN_SCREENSHOT_H diff --git a/effects/slide/slide.cpp b/effects/slide/slide.cpp index 8267516b0..2d0d10907 100644 --- a/effects/slide/slide.cpp +++ b/effects/slide/slide.cpp @@ -1,458 +1,458 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Lubos Lunak Copyright (C) 2008 Lucas Murray 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 . *********************************************************************/ // own #include "slide.h" // KConfigSkeleton #include "slideconfig.h" namespace KWin { SlideEffect::SlideEffect() { initConfig(); reconfigure(ReconfigureAll); m_timeLine.setEasingCurve(QEasingCurve::OutCubic); connect(effects, QOverload::of(&EffectsHandler::desktopChanged), this, &SlideEffect::desktopChanged); connect(effects, &EffectsHandler::windowAdded, this, &SlideEffect::windowAdded); connect(effects, &EffectsHandler::windowDeleted, this, &SlideEffect::windowDeleted); connect(effects, &EffectsHandler::numberDesktopsChanged, this, &SlideEffect::numberDesktopsChanged); connect(effects, &EffectsHandler::numberScreensChanged, this, &SlideEffect::numberScreensChanged); } SlideEffect::~SlideEffect() { if (m_active) { stop(); } } bool SlideEffect::supported() { return effects->animationsSupported(); } void SlideEffect::reconfigure(ReconfigureFlags) { SlideConfig::self()->read(); m_timeLine.setDuration( std::chrono::milliseconds(animationTime(500))); m_hGap = SlideConfig::horizontalGap(); m_vGap = SlideConfig::verticalGap(); m_slideDocks = SlideConfig::slideDocks(); m_slideBackground = SlideConfig::slideBackground(); } void SlideEffect::prePaintScreen(ScreenPrePaintData &data, int time) { m_timeLine.update(std::chrono::milliseconds(time)); data.mask |= PAINT_SCREEN_TRANSFORMED | PAINT_SCREEN_BACKGROUND_FIRST; effects->prePaintScreen(data, time); } /** * Wrap vector @p diff around grid @p w x @p h. * * Wrapping is done in such a way that magnitude of x and y component of vector * @p diff is less than half of @p w and half of @p h, respectively. This will * result in having the "shortest" path between two points. * * @param diff Vector between two points * @param w Width of the desktop grid * @param h Height of the desktop grid - **/ + */ inline void wrapDiff(QPoint &diff, int w, int h) { if (diff.x() > w/2) { diff.setX(diff.x() - w); } else if (diff.x() < -w/2) { diff.setX(diff.x() + w); } if (diff.y() > h/2) { diff.setY(diff.y() - h); } else if (diff.y() < -h/2) { diff.setY(diff.y() + h); } } inline QRegion buildClipRegion(const QPoint &pos, int w, int h) { const QSize screenSize = effects->virtualScreenSize(); QRegion r = QRect(pos, screenSize); if (effects->optionRollOverDesktops()) { r |= (r & QRect(-w, 0, w, h)).translated(w, 0); // W r |= (r & QRect(w, 0, w, h)).translated(-w, 0); // E r |= (r & QRect(0, -h, w, h)).translated(0, h); // N r |= (r & QRect(0, h, w, h)).translated(0, -h); // S r |= (r & QRect(-w, -h, w, h)).translated(w, h); // NW r |= (r & QRect(w, -h, w, h)).translated(-w, h); // NE r |= (r & QRect(w, h, w, h)).translated(-w, -h); // SE r |= (r & QRect(-w, h, w, h)).translated(w, -h); // SW } return r; } void SlideEffect::paintScreen(int mask, QRegion region, ScreenPaintData &data) { const bool wrap = effects->optionRollOverDesktops(); const int w = workspaceWidth(); const int h = workspaceHeight(); QPoint currentPos = m_startPos + m_diff * m_timeLine.value(); // When "Desktop navigation wraps around" checkbox is checked, currentPos // can be outside the rectangle Rect{x:-w, y:-h, width:2*w, height: 2*h}, // so we map currentPos back to the rect. if (wrap) { currentPos.setX(currentPos.x() % w); currentPos.setY(currentPos.y() % h); } QVector visibleDesktops; visibleDesktops.reserve(4); // 4 - maximum number of visible desktops const QRegion clipRegion = buildClipRegion(currentPos, w, h); for (int i = 1; i <= effects->numberOfDesktops(); i++) { const QRect desktopGeo = desktopGeometry(i); if (!clipRegion.contains(desktopGeo)) { continue; } visibleDesktops << i; } // When we enter a virtual desktop that has a window in fullscreen mode, // stacking order is fine. When we leave a virtual desktop that has // a window in fullscreen mode, stacking order is no longer valid // because panels are raised above the fullscreen window. Construct // a list of fullscreen windows, so we can decide later whether // docks should be visible on different virtual desktops. if (m_slideDocks) { const auto windows = effects->stackingOrder(); m_paintCtx.fullscreenWindows.clear(); for (EffectWindow *w : windows) { if (!w->isFullScreen()) { continue; } m_paintCtx.fullscreenWindows << w; } } // If screen is painted with either PAINT_SCREEN_TRANSFORMED or // PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS there is no clipping!! // Push the screen geometry to the paint clipper so everything outside // of the screen geometry is clipped. PaintClipper pc(QRegion(effects->virtualScreenGeometry())); // Screen is painted in several passes. Each painting pass paints // a single virtual desktop. There could be either 2 or 4 painting // passes, depending how an user moves between virtual desktops. // Windows, such as docks or keep-above windows, are painted in // the last pass so they are above other windows. m_paintCtx.firstPass = true; const int lastDesktop = visibleDesktops.last(); for (int desktop : qAsConst(visibleDesktops)) { m_paintCtx.desktop = desktop; m_paintCtx.lastPass = (lastDesktop == desktop); m_paintCtx.translation = desktopCoords(desktop) - currentPos; if (wrap) { wrapDiff(m_paintCtx.translation, w, h); } effects->paintScreen(mask, region, data); m_paintCtx.firstPass = false; } } /** * Decide whether given window @p w should be transformed/translated. * @returns @c true if given window @p w should be transformed, otherwise @c false - **/ + */ bool SlideEffect::isTranslated(const EffectWindow *w) const { if (w->isOnAllDesktops()) { if (w->isDock()) { return m_slideDocks; } if (w->isDesktop()) { return m_slideBackground; } return false; } else if (w == m_movingWindow) { return false; } else if (w->isOnDesktop(m_paintCtx.desktop)) { return true; } return false; } /** * Decide whether given window @p w should be painted. * @returns @c true if given window @p w should be painted, otherwise @c false - **/ + */ bool SlideEffect::isPainted(const EffectWindow *w) const { if (w->isOnAllDesktops()) { if (w->isDock()) { if (!m_slideDocks) { return m_paintCtx.lastPass; } for (const EffectWindow *fw : qAsConst(m_paintCtx.fullscreenWindows)) { if (fw->isOnDesktop(m_paintCtx.desktop) && fw->screen() == w->screen()) { return false; } } return true; } if (w->isDesktop()) { // If desktop background is not being slided, draw it only // in the first pass. Otherwise, desktop backgrounds from // follow-up virtual desktops will be drawn above windows // from previous virtual desktops. return m_slideBackground || m_paintCtx.firstPass; } // In order to make sure that 'keep above' windows are above // other windows during transition to another virtual desktop, // they should be painted in the last pass. if (w->keepAbove()) { return m_paintCtx.lastPass; } return true; } else if (w == m_movingWindow) { return m_paintCtx.lastPass; } else if (w->isOnDesktop(m_paintCtx.desktop)) { return true; } return false; } void SlideEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { const bool painted = isPainted(w); if (painted) { w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else { w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } if (painted && isTranslated(w)) { data.setTransformed(); } effects->prePaintWindow(w, data, time); } void SlideEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { if (isTranslated(w)) { data += m_paintCtx.translation; } effects->paintWindow(w, mask, region, data); } void SlideEffect::postPaintScreen() { if (m_timeLine.done()) { stop(); } effects->addRepaintFull(); effects->postPaintScreen(); } /** * Get position of the top-left corner of desktop @p id within desktop grid with gaps. * @param id ID of a virtual desktop - **/ + */ QPoint SlideEffect::desktopCoords(int id) const { QPoint c = effects->desktopCoords(id); const QPoint gridPos = effects->desktopGridCoords(id); c.setX(c.x() + m_hGap * gridPos.x()); c.setY(c.y() + m_vGap * gridPos.y()); return c; } /** * Get geometry of desktop @p id within desktop grid with gaps. * @param id ID of a virtual desktop - **/ + */ QRect SlideEffect::desktopGeometry(int id) const { QRect g = effects->virtualScreenGeometry(); g.translate(desktopCoords(id)); return g; } /** * Get width of a virtual desktop grid. - **/ + */ int SlideEffect::workspaceWidth() const { int w = effects->workspaceWidth(); w += m_hGap * effects->desktopGridWidth(); return w; } /** * Get height of a virtual desktop grid. - **/ + */ int SlideEffect::workspaceHeight() const { int h = effects->workspaceHeight(); h += m_vGap * effects->desktopGridHeight(); return h; } bool SlideEffect::shouldElevate(const EffectWindow *w) const { // Static docks(i.e. this effect doesn't slide docks) should be elevated // so they can properly animate themselves when an user enters or leaves // a virtual desktop with a window in fullscreen mode. return w->isDock() && !m_slideDocks; } void SlideEffect::start(int old, int current, EffectWindow *movingWindow) { m_movingWindow = movingWindow; const bool wrap = effects->optionRollOverDesktops(); const int w = workspaceWidth(); const int h = workspaceHeight(); if (m_active) { QPoint passed = m_diff * m_timeLine.value(); QPoint currentPos = m_startPos + passed; QPoint delta = desktopCoords(current) - desktopCoords(old); if (wrap) { wrapDiff(delta, w, h); } m_diff += delta - passed; m_startPos = currentPos; // TODO: Figure out how to smooth movement. m_timeLine.reset(); return; } const auto windows = effects->stackingOrder(); for (EffectWindow *w : windows) { if (shouldElevate(w)) { effects->setElevatedWindow(w, true); m_elevatedWindows << w; } w->setData(WindowForceBackgroundContrastRole, QVariant(true)); w->setData(WindowForceBlurRole, QVariant(true)); } m_diff = desktopCoords(current) - desktopCoords(old); if (wrap) { wrapDiff(m_diff, w, h); } m_startPos = desktopCoords(old); m_timeLine.reset(); m_active = true; effects->setActiveFullScreenEffect(this); effects->addRepaintFull(); } void SlideEffect::stop() { const EffectWindowList windows = effects->stackingOrder(); for (EffectWindow *w : windows) { w->setData(WindowForceBackgroundContrastRole, QVariant()); w->setData(WindowForceBlurRole, QVariant()); } for (EffectWindow *w : m_elevatedWindows) { effects->setElevatedWindow(w, false); } m_elevatedWindows.clear(); m_paintCtx.fullscreenWindows.clear(); m_movingWindow = nullptr; m_active = false; effects->setActiveFullScreenEffect(nullptr); } void SlideEffect::desktopChanged(int old, int current, EffectWindow *with) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) { return; } start(old, current, with); } void SlideEffect::windowAdded(EffectWindow *w) { if (!m_active) { return; } if (shouldElevate(w)) { effects->setElevatedWindow(w, true); m_elevatedWindows << w; } w->setData(WindowForceBackgroundContrastRole, QVariant(true)); w->setData(WindowForceBlurRole, QVariant(true)); } void SlideEffect::windowDeleted(EffectWindow *w) { if (!m_active) { return; } if (w == m_movingWindow) { m_movingWindow = nullptr; } m_elevatedWindows.removeAll(w); m_paintCtx.fullscreenWindows.removeAll(w); } void SlideEffect::numberDesktopsChanged(uint) { if (!m_active) { return; } stop(); } void SlideEffect::numberScreensChanged() { if (!m_active) { return; } stop(); } } // namespace KWin diff --git a/effects/wobblywindows/wobblywindows.h b/effects/wobblywindows/wobblywindows.h index 8169cd739..b9c58a31b 100644 --- a/effects/wobblywindows/wobblywindows.h +++ b/effects/wobblywindows/wobblywindows.h @@ -1,219 +1,219 @@ /***************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Cédric Borgese You can Freely distribute this program under the GNU General Public License. See the file "COPYING" for the exact licensing terms. ******************************************************************/ #ifndef KWIN_WOBBLYWINDOWS_H #define KWIN_WOBBLYWINDOWS_H // Include with base class for effects. #include namespace KWin { struct ParameterSet; /** * Effect which wobble windows - **/ + */ class WobblyWindowsEffect : public Effect { Q_OBJECT Q_PROPERTY(qreal stiffness READ stiffness) Q_PROPERTY(qreal drag READ drag) Q_PROPERTY(qreal moveFactor READ moveFactor) Q_PROPERTY(qreal xTesselation READ xTesselation) Q_PROPERTY(qreal yTesselation READ yTesselation) Q_PROPERTY(qreal minVelocity READ minVelocity) Q_PROPERTY(qreal maxVelocity READ maxVelocity) Q_PROPERTY(qreal stopVelocity READ stopVelocity) Q_PROPERTY(qreal minAcceleration READ minAcceleration) Q_PROPERTY(qreal maxAcceleration READ maxAcceleration) Q_PROPERTY(qreal stopAcceleration READ stopAcceleration) Q_PROPERTY(bool moveEffectEnabled READ isMoveEffectEnabled) Q_PROPERTY(bool openEffectEnabled READ isOpenEffectEnabled) Q_PROPERTY(bool closeEffectEnabled READ isCloseEffectEnabled) Q_PROPERTY(bool moveWobble READ isMoveWobble) Q_PROPERTY(bool resizeWobble READ isResizeWobble) public: WobblyWindowsEffect(); ~WobblyWindowsEffect() override; void reconfigure(ReconfigureFlags) override; void prePaintScreen(ScreenPrePaintData& data, int time) override; void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) override; void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void postPaintScreen() override; bool isActive() const override; int requestedEffectChainPosition() const override { // Please notice that the Wobbly Windows effect has to be placed // after the Maximize effect in the effect chain, otherwise there // can be visual artifacts when dragging maximized windows. return 70; } // Wobbly model parameters void setStiffness(qreal stiffness); void setDrag(qreal drag); void setVelocityThreshold(qreal velocityThreshold); void setMoveFactor(qreal factor); struct Pair { qreal x; qreal y; }; enum WindowStatus { Free, Moving, Openning, Closing }; static bool supported(); // for properties qreal stiffness() const { return m_stiffness; } qreal drag() const { return m_drag; } qreal moveFactor() const { return m_move_factor; } qreal xTesselation() const { return m_xTesselation; } qreal yTesselation() const { return m_yTesselation; } qreal minVelocity() const { return m_minVelocity; } qreal maxVelocity() const { return m_maxVelocity; } qreal stopVelocity() const { return m_stopVelocity; } qreal minAcceleration() const { return m_minAcceleration; } qreal maxAcceleration() const { return m_maxAcceleration; } qreal stopAcceleration() const { return m_stopAcceleration; } bool isMoveEffectEnabled() const { return m_moveEffectEnabled; } bool isOpenEffectEnabled() const { return m_openEffectEnabled; } bool isCloseEffectEnabled() const { return m_closeEffectEnabled; } bool isMoveWobble() const { return m_moveWobble; } bool isResizeWobble() const { return m_resizeWobble; } public Q_SLOTS: void slotWindowAdded(KWin::EffectWindow *w); void slotWindowClosed(KWin::EffectWindow *w); void slotWindowStartUserMovedResized(KWin::EffectWindow *w); void slotWindowStepUserMovedResized(KWin::EffectWindow *w, const QRect &geometry); void slotWindowFinishUserMovedResized(KWin::EffectWindow *w); void slotWindowMaximizeStateChanged(KWin::EffectWindow *w, bool horizontal, bool vertical); private: void cancelWindowGrab(KWin::EffectWindow *w, int grabRole); void startMovedResized(EffectWindow* w); void stepMovedResized(EffectWindow* w); bool updateWindowWobblyDatas(EffectWindow* w, qreal time); struct WindowWobblyInfos { Pair* origin; Pair* position; Pair* velocity; Pair* acceleration; Pair* buffer; // if true, the physics system moves this point based only on it "normal" destination // given by the window position, ignoring neighbour points. bool* constraint; unsigned int width; unsigned int height; unsigned int count; Pair* bezierSurface; unsigned int bezierWidth; unsigned int bezierHeight; unsigned int bezierCount; WindowStatus status; // for closing QRectF closeRect; // for resizing. Only sides that have moved will wobble bool can_wobble_top, can_wobble_left, can_wobble_right, can_wobble_bottom; QRect resize_original_rect; }; QHash< const EffectWindow*, WindowWobblyInfos > windows; QRegion m_updateRegion; qreal m_stiffness; qreal m_drag; qreal m_move_factor; // the default tesselation for windows // use qreal instead of int as I really often need // these values as real to do divisions. qreal m_xTesselation; qreal m_yTesselation; qreal m_minVelocity; qreal m_maxVelocity; qreal m_stopVelocity; qreal m_minAcceleration; qreal m_maxAcceleration; qreal m_stopAcceleration; bool m_moveEffectEnabled; bool m_openEffectEnabled; bool m_closeEffectEnabled; bool m_moveWobble; // Expands m_moveEffectEnabled bool m_resizeWobble; void initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) const; void freeWobblyInfo(WindowWobblyInfos& wwi) const; void wobblyOpenInit(WindowWobblyInfos& wwi) const; void wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* w) const; WobblyWindowsEffect::Pair computeBezierPoint(const WindowWobblyInfos& wwi, Pair point) const; static void heightRingLinearMean(Pair** data_pointer, WindowWobblyInfos& wwi); void setParameterSet(const ParameterSet& pset); }; } // namespace KWin #endif // WOBBLYWINDOWS_H diff --git a/events.cpp b/events.cpp index 48b7999b7..b0fe982c8 100644 --- a/events.cpp +++ b/events.cpp @@ -1,1345 +1,1345 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ /* This file contains things relevant to handling incoming events. */ #include "client.h" #include "cursor.h" #include "focuschain.h" #include "netinfo.h" #include "workspace.h" #include "atoms.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "group.h" #include "rules.h" #include "unmanaged.h" #include "useractions.h" #include "effects.h" #include "screens.h" #include "xcbutils.h" #include #include #include #include #include #include #include #include #include #include #ifdef XCB_ICCCM_FOUND #include #endif #include "composite.h" #include "x11eventfilter.h" #include "wayland_server.h" #include #ifndef XCB_GE_GENERIC #define XCB_GE_GENERIC 35 typedef struct xcb_ge_generic_event_t { uint8_t response_type; /**< */ uint8_t extension; /**< */ uint16_t sequence; /**< */ uint32_t length; /**< */ uint16_t event_type; /**< */ uint8_t pad0[22]; /**< */ uint32_t full_sequence; /**< */ } xcb_ge_generic_event_t; #endif namespace KWin { // **************************************** // Workspace // **************************************** static xcb_window_t findEventWindow(xcb_generic_event_t *event) { const uint8_t eventType = event->response_type & ~0x80; switch(eventType) { case XCB_KEY_PRESS: case XCB_KEY_RELEASE: return reinterpret_cast(event)->event; case XCB_BUTTON_PRESS: case XCB_BUTTON_RELEASE: return reinterpret_cast(event)->event; case XCB_MOTION_NOTIFY: return reinterpret_cast(event)->event; case XCB_ENTER_NOTIFY: case XCB_LEAVE_NOTIFY: return reinterpret_cast(event)->event; case XCB_FOCUS_IN: case XCB_FOCUS_OUT: return reinterpret_cast(event)->event; case XCB_EXPOSE: return reinterpret_cast(event)->window; case XCB_GRAPHICS_EXPOSURE: return reinterpret_cast(event)->drawable; case XCB_NO_EXPOSURE: return reinterpret_cast(event)->drawable; case XCB_VISIBILITY_NOTIFY: return reinterpret_cast(event)->window; case XCB_CREATE_NOTIFY: return reinterpret_cast(event)->window; case XCB_DESTROY_NOTIFY: return reinterpret_cast(event)->window; case XCB_UNMAP_NOTIFY: return reinterpret_cast(event)->window; case XCB_MAP_NOTIFY: return reinterpret_cast(event)->window; case XCB_MAP_REQUEST: return reinterpret_cast(event)->window; case XCB_REPARENT_NOTIFY: return reinterpret_cast(event)->window; case XCB_CONFIGURE_NOTIFY: return reinterpret_cast(event)->window; case XCB_CONFIGURE_REQUEST: return reinterpret_cast(event)->window; case XCB_GRAVITY_NOTIFY: return reinterpret_cast(event)->window; case XCB_RESIZE_REQUEST: return reinterpret_cast(event)->window; case XCB_CIRCULATE_NOTIFY: case XCB_CIRCULATE_REQUEST: return reinterpret_cast(event)->window; case XCB_PROPERTY_NOTIFY: return reinterpret_cast(event)->window; case XCB_COLORMAP_NOTIFY: return reinterpret_cast(event)->window; case XCB_CLIENT_MESSAGE: return reinterpret_cast(event)->window; default: // extension handling if (eventType == Xcb::Extensions::self()->shapeNotifyEvent()) { return reinterpret_cast(event)->affected_window; } if (eventType == Xcb::Extensions::self()->damageNotifyEvent()) { return reinterpret_cast(event)->drawable; } return XCB_WINDOW_NONE; } } QVector s_xcbEerrors({ QByteArrayLiteral("Success"), QByteArrayLiteral("BadRequest"), QByteArrayLiteral("BadValue"), QByteArrayLiteral("BadWindow"), QByteArrayLiteral("BadPixmap"), QByteArrayLiteral("BadAtom"), QByteArrayLiteral("BadCursor"), QByteArrayLiteral("BadFont"), QByteArrayLiteral("BadMatch"), QByteArrayLiteral("BadDrawable"), QByteArrayLiteral("BadAccess"), QByteArrayLiteral("BadAlloc"), QByteArrayLiteral("BadColor"), QByteArrayLiteral("BadGC"), QByteArrayLiteral("BadIDChoice"), QByteArrayLiteral("BadName"), QByteArrayLiteral("BadLength"), QByteArrayLiteral("BadImplementation"), QByteArrayLiteral("Unknown")}); void Workspace::registerEventFilter(X11EventFilter *filter) { if (filter->isGenericEvent()) m_genericEventFilters.append(filter); else m_eventFilters.append(filter); } void Workspace::unregisterEventFilter(X11EventFilter *filter) { if (filter->isGenericEvent()) m_genericEventFilters.removeOne(filter); else m_eventFilters.removeOne(filter); } /** * Handles workspace specific XCB event - **/ + */ bool Workspace::workspaceEvent(xcb_generic_event_t *e) { const uint8_t eventType = e->response_type & ~0x80; if (!eventType) { // let's check whether it's an error from one of the extensions KWin uses xcb_generic_error_t *error = reinterpret_cast(e); const QVector extensions = Xcb::Extensions::self()->extensions(); for (const auto &extension : extensions) { if (error->major_code == extension.majorOpcode) { QByteArray errorName; if (error->error_code < s_xcbEerrors.size()) { errorName = s_xcbEerrors.at(error->error_code); } else if (error->error_code >= extension.errorBase) { const int index = error->error_code - extension.errorBase; if (index >= 0 && index < extension.errorCodes.size()) { errorName = extension.errorCodes.at(index); } } if (errorName.isEmpty()) { errorName = QByteArrayLiteral("Unknown"); } qCWarning(KWIN_CORE, "XCB error: %d (%s), sequence: %d, resource id: %d, major code: %d (%s), minor code: %d (%s)", int(error->error_code), errorName.constData(), int(error->sequence), int(error->resource_id), int(error->major_code), extension.name.constData(), int(error->minor_code), extension.opCodes.size() > error->minor_code ? extension.opCodes.at(error->minor_code).constData() : "Unknown"); return true; } } return false; } if (eventType == XCB_GE_GENERIC) { xcb_ge_generic_event_t *ge = reinterpret_cast(e); foreach (X11EventFilter *filter, m_genericEventFilters) { if (filter->extension() == ge->extension && filter->genericEventTypes().contains(ge->event_type) && filter->event(e)) { return true; } } } else { foreach (X11EventFilter *filter, m_eventFilters) { if (filter->eventTypes().contains(eventType) && filter->event(e)) { return true; } } } if (effects && static_cast< EffectsHandlerImpl* >(effects)->hasKeyboardGrab() && (eventType == XCB_KEY_PRESS || eventType == XCB_KEY_RELEASE)) return false; // let Qt process it, it'll be intercepted again in eventFilter() // events that should be handled before Clients can get them switch (eventType) { case XCB_CONFIGURE_NOTIFY: if (reinterpret_cast(e)->event == rootWindow()) markXStackingOrderAsDirty(); break; }; const xcb_window_t eventWindow = findEventWindow(e); if (eventWindow != XCB_WINDOW_NONE) { if (Client* c = findClient(Predicate::WindowMatch, eventWindow)) { if (c->windowEvent(e)) return true; } else if (Client* c = findClient(Predicate::WrapperIdMatch, eventWindow)) { if (c->windowEvent(e)) return true; } else if (Client* c = findClient(Predicate::FrameIdMatch, eventWindow)) { if (c->windowEvent(e)) return true; } else if (Client *c = findClient(Predicate::InputIdMatch, eventWindow)) { if (c->windowEvent(e)) return true; } else if (Unmanaged* c = findUnmanaged(eventWindow)) { if (c->windowEvent(e)) return true; } } switch (eventType) { case XCB_CREATE_NOTIFY: { const auto *event = reinterpret_cast(e); if (event->parent == rootWindow() && !QWidget::find(event->window) && !event->override_redirect) { // see comments for allowClientActivation() updateXTime(); const xcb_timestamp_t t = xTime(); xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, event->window, atoms->kde_net_wm_user_creation_time, XCB_ATOM_CARDINAL, 32, 1, &t); } break; } case XCB_UNMAP_NOTIFY: { const auto *event = reinterpret_cast(e); return (event->event != event->window); // hide wm typical event from Qt } case XCB_REPARENT_NOTIFY: { //do not confuse Qt with these events. After all, _we_ are the //window manager who does the reparenting. return true; } case XCB_MAP_REQUEST: { updateXTime(); const auto *event = reinterpret_cast(e); if (Client* c = findClient(Predicate::WindowMatch, event->window)) { // e->xmaprequest.window is different from e->xany.window // TODO this shouldn't be necessary now c->windowEvent(e); FocusChain::self()->update(c, FocusChain::Update); } else if ( true /*|| e->xmaprequest.parent != root */ ) { // NOTICE don't check for the parent being the root window, this breaks when some app unmaps // a window, changes something and immediately maps it back, without giving KWin // a chance to reparent it back to root // since KWin can get MapRequest only for root window children and // children of WindowWrapper (=clients), the check is AFAIK useless anyway // NOTICE: The save-set support in Client::mapRequestEvent() actually requires that // this code doesn't check the parent to be root. if (!createClient(event->window, false)) { xcb_map_window(connection(), event->window); const uint32_t values[] = { XCB_STACK_MODE_ABOVE }; xcb_configure_window(connection(), event->window, XCB_CONFIG_WINDOW_STACK_MODE, values); } } return true; } case XCB_MAP_NOTIFY: { const auto *event = reinterpret_cast(e); if (event->override_redirect) { Unmanaged* c = findUnmanaged(event->window); if (c == NULL) c = createUnmanaged(event->window); if (c) return c->windowEvent(e); } return (event->event != event->window); // hide wm typical event from Qt } case XCB_CONFIGURE_REQUEST: { const auto *event = reinterpret_cast(e); if (event->parent == rootWindow()) { uint32_t values[5] = { 0, 0, 0, 0, 0}; const uint32_t value_mask = event->value_mask & (XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT | XCB_CONFIG_WINDOW_BORDER_WIDTH); int i = 0; if (value_mask & XCB_CONFIG_WINDOW_X) { values[i++] = event->x; } if (value_mask & XCB_CONFIG_WINDOW_Y) { values[i++] = event->y; } if (value_mask & XCB_CONFIG_WINDOW_WIDTH) { values[i++] = event->width; } if (value_mask & XCB_CONFIG_WINDOW_HEIGHT) { values[i++] = event->height; } if (value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) { values[i++] = event->border_width; } xcb_configure_window(connection(), event->window, value_mask, values); return true; } break; } case XCB_FOCUS_IN: { const auto *event = reinterpret_cast(e); if (event->event == rootWindow() && (event->detail == XCB_NOTIFY_DETAIL_NONE || event->detail == XCB_NOTIFY_DETAIL_POINTER_ROOT || event->detail == XCB_NOTIFY_DETAIL_INFERIOR)) { Xcb::CurrentInput currentInput; updateXTime(); // focusToNull() uses xTime(), which is old now (FocusIn has no timestamp) // it seems we can "loose" focus reversions when the closing client hold a grab // => catch the typical pattern (though we don't want the focus on the root anyway) #348935 const bool lostFocusPointerToRoot = currentInput->focus == rootWindow() && event->detail == XCB_NOTIFY_DETAIL_INFERIOR; if (!currentInput.isNull() && (currentInput->focus == XCB_WINDOW_NONE || currentInput->focus == XCB_INPUT_FOCUS_POINTER_ROOT || lostFocusPointerToRoot)) { //kWarning( 1212 ) << "X focus set to None/PointerRoot, reseting focus" ; AbstractClient *c = mostRecentlyActivatedClient(); if (c != NULL) requestFocus(c, true); else if (activateNextClient(NULL)) ; // ok, activated else focusToNull(); } } } // fall through case XCB_FOCUS_OUT: return true; // always eat these, they would tell Qt that KWin is the active app default: break; } return false; } // Used only to filter events that need to be processed by Qt first // (e.g. keyboard input to be composed), otherwise events are // handle by the XEvent filter above bool Workspace::workspaceEvent(QEvent* e) { if ((e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease || e->type() == QEvent::ShortcutOverride) && effects && static_cast< EffectsHandlerImpl* >(effects)->hasKeyboardGrab()) { static_cast< EffectsHandlerImpl* >(effects)->grabbedKeyboardEvent(static_cast< QKeyEvent* >(e)); return true; } return false; } // **************************************** // Client // **************************************** /** * General handler for XEvents concerning the client window - **/ + */ bool Client::windowEvent(xcb_generic_event_t *e) { if (findEventWindow(e) == window()) { // avoid doing stuff on frame or wrapper NET::Properties dirtyProperties; NET::Properties2 dirtyProperties2; double old_opacity = opacity(); info->event(e, &dirtyProperties, &dirtyProperties2); // pass through the NET stuff if ((dirtyProperties & NET::WMName) != 0) fetchName(); if ((dirtyProperties & NET::WMIconName) != 0) fetchIconicName(); if ((dirtyProperties & NET::WMStrut) != 0 || (dirtyProperties2 & NET::WM2ExtendedStrut) != 0) { workspace()->updateClientArea(); } if ((dirtyProperties & NET::WMIcon) != 0) getIcons(); // Note there's a difference between userTime() and info->userTime() // info->userTime() is the value of the property, userTime() also includes // updates of the time done by KWin (ButtonPress on windowrapper etc.). if ((dirtyProperties2 & NET::WM2UserTime) != 0) { workspace()->setWasUserInteraction(); updateUserTime(info->userTime()); } if ((dirtyProperties2 & NET::WM2StartupId) != 0) startupIdChanged(); if (dirtyProperties2 & NET::WM2Opacity) { if (compositing()) { addRepaintFull(); emit opacityChanged(this, old_opacity); } else { // forward to the frame if there's possibly another compositing manager running NETWinInfo i(connection(), frameId(), rootWindow(), 0, 0); i.setOpacity(info->opacity()); } } if (dirtyProperties2 & NET::WM2FrameOverlap) { // ### Inform the decoration } if (dirtyProperties2.testFlag(NET::WM2WindowRole)) { emit windowRoleChanged(); } if (dirtyProperties2.testFlag(NET::WM2WindowClass)) { getResourceClass(); } if (dirtyProperties2.testFlag(NET::WM2BlockCompositing)) { setBlockingCompositing(info->isBlockingCompositing()); } if (dirtyProperties2.testFlag(NET::WM2GroupLeader)) { checkGroup(); updateAllowedActions(); // Group affects isMinimizable() } if (dirtyProperties2.testFlag(NET::WM2Urgency)) { updateUrgency(); } if (dirtyProperties2 & NET::WM2OpaqueRegion) { getWmOpaqueRegion(); } if (dirtyProperties2 & NET::WM2DesktopFileName) { setDesktopFileName(QByteArray(info->desktopFileName())); } } const uint8_t eventType = e->response_type & ~0x80; switch(eventType) { case XCB_UNMAP_NOTIFY: unmapNotifyEvent(reinterpret_cast(e)); break; case XCB_DESTROY_NOTIFY: destroyNotifyEvent(reinterpret_cast(e)); break; case XCB_MAP_REQUEST: // this one may pass the event to workspace return mapRequestEvent(reinterpret_cast(e)); case XCB_CONFIGURE_REQUEST: configureRequestEvent(reinterpret_cast(e)); break; case XCB_PROPERTY_NOTIFY: propertyNotifyEvent(reinterpret_cast(e)); break; case XCB_KEY_PRESS: updateUserTime(reinterpret_cast(e)->time); break; case XCB_BUTTON_PRESS: { const auto *event = reinterpret_cast(e); updateUserTime(event->time); buttonPressEvent(event->event, event->detail, event->state, event->event_x, event->event_y, event->root_x, event->root_y, event->time); break; } case XCB_KEY_RELEASE: // don't update user time on releases // e.g. if the user presses Alt+F2, the Alt release // would appear as user input to the currently active window break; case XCB_BUTTON_RELEASE: { const auto *event = reinterpret_cast(e); // don't update user time on releases // e.g. if the user presses Alt+F2, the Alt release // would appear as user input to the currently active window buttonReleaseEvent(event->event, event->detail, event->state, event->event_x, event->event_y, event->root_x, event->root_y); break; } case XCB_MOTION_NOTIFY: { const auto *event = reinterpret_cast(e); motionNotifyEvent(event->event, event->state, event->event_x, event->event_y, event->root_x, event->root_y); workspace()->updateFocusMousePosition(QPoint(event->root_x, event->root_y)); break; } case XCB_ENTER_NOTIFY: { auto *event = reinterpret_cast(e); enterNotifyEvent(event); // MotionNotify is guaranteed to be generated only if the mouse // move start and ends in the window; for cases when it only // starts or only ends there, Enter/LeaveNotify are generated. // Fake a MotionEvent in such cases to make handle of mouse // events simpler (Qt does that too). motionNotifyEvent(event->event, event->state, event->event_x, event->event_y, event->root_x, event->root_y); workspace()->updateFocusMousePosition(QPoint(event->root_x, event->root_y)); break; } case XCB_LEAVE_NOTIFY: { auto *event = reinterpret_cast(e); motionNotifyEvent(event->event, event->state, event->event_x, event->event_y, event->root_x, event->root_y); leaveNotifyEvent(event); // not here, it'd break following enter notify handling // workspace()->updateFocusMousePosition( QPoint( e->xcrossing.x_root, e->xcrossing.y_root )); break; } case XCB_FOCUS_IN: focusInEvent(reinterpret_cast(e)); break; case XCB_FOCUS_OUT: focusOutEvent(reinterpret_cast(e)); break; case XCB_REPARENT_NOTIFY: break; case XCB_CLIENT_MESSAGE: clientMessageEvent(reinterpret_cast(e)); break; case XCB_EXPOSE: { xcb_expose_event_t *event = reinterpret_cast(e); if (event->window == frameId() && !Compositor::self()->isActive()) { // TODO: only repaint required areas triggerDecorationRepaint(); } break; } default: if (eventType == Xcb::Extensions::self()->shapeNotifyEvent() && reinterpret_cast(e)->affected_window == window()) { detectShape(window()); // workaround for #19644 updateShape(); } if (eventType == Xcb::Extensions::self()->damageNotifyEvent() && reinterpret_cast(e)->drawable == frameId()) damageNotifyEvent(); break; } return true; // eat all events } /** * Handles map requests of the client window - **/ + */ bool Client::mapRequestEvent(xcb_map_request_event_t *e) { if (e->window != window()) { // Special support for the save-set feature, which is a bit broken. // If there's a window from one client embedded in another one, // e.g. using XEMBED, and the embedder suddenly loses its X connection, // save-set will reparent the embedded window to its closest ancestor // that will remains. Unfortunately, with reparenting window managers, // this is not the root window, but the frame (or in KWin's case, // it's the wrapper for the client window). In this case, // the wrapper will get ReparentNotify for a window it won't know, // which will be ignored, and then it gets MapRequest, as save-set // always maps. Returning true here means that Workspace::workspaceEvent() // will handle this MapRequest and manage this window (i.e. act as if // it was reparented to root window). if (e->parent == wrapperId()) return false; return true; // no messing with frame etc. } // also copied in clientMessage() if (isMinimized()) unminimize(); if (isShade()) setShade(ShadeNone); if (!isOnCurrentDesktop()) { if (workspace()->allowClientActivation(this)) workspace()->activateClient(this); else demandAttention(); } return true; } /** * Handles unmap notify events of the client window - **/ + */ void Client::unmapNotifyEvent(xcb_unmap_notify_event_t *e) { if (e->window != window()) return; if (e->event != wrapperId()) { // most probably event from root window when initially reparenting bool ignore = true; if (e->event == rootWindow() && (e->response_type & 0x80)) ignore = false; // XWithdrawWindow() if (ignore) return; } // check whether this is result of an XReparentWindow - client then won't be parented by wrapper // in this case do not release the client (causes reparent to root, removal from saveSet and what not) // but just destroy the client Xcb::Tree tree(m_client); xcb_window_t daddy = tree.parent(); if (daddy == m_wrapper) { releaseWindow(); // unmapped from a regular client state } else { destroyClient(); // the client was moved to some other parent } } void Client::destroyNotifyEvent(xcb_destroy_notify_event_t *e) { if (e->window != window()) return; destroyClient(); } /** * Handles client messages for the client window - **/ + */ void Client::clientMessageEvent(xcb_client_message_event_t *e) { Toplevel::clientMessageEvent(e); if (e->window != window()) return; // ignore frame/wrapper // WM_STATE if (e->type == atoms->wm_change_state) { if (e->data.data32[0] == XCB_ICCCM_WM_STATE_ICONIC) minimize(); return; } } /** * Handles configure requests of the client window - **/ + */ void Client::configureRequestEvent(xcb_configure_request_event_t *e) { if (e->window != window()) return; // ignore frame/wrapper if (isResize() || isMove()) return; // we have better things to do right now if (m_fullscreenMode == FullScreenNormal) { // refuse resizing of fullscreen windows // but allow resizing fullscreen hacks in order to let them cancel fullscreen mode sendSyntheticConfigureNotify(); return; } if (isSplash()) { // no manipulations with splashscreens either sendSyntheticConfigureNotify(); return; } if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) { // first, get rid of a window border m_client.setBorderWidth(0); } if (e->value_mask & (XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_HEIGHT | XCB_CONFIG_WINDOW_WIDTH)) configureRequest(e->value_mask, e->x, e->y, e->width, e->height, 0, false); if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) restackWindow(e->sibling, e->stack_mode, NET::FromApplication, userTime(), false); // Sending a synthetic configure notify always is fine, even in cases where // the ICCCM doesn't require this - it can be though of as 'the WM decided to move // the window later'. The client should not cause that many configure request, // so this should not have any significant impact. With user moving/resizing // the it should be optimized though (see also Client::setGeometry()/plainResize()/move()). sendSyntheticConfigureNotify(); // SELI TODO accept configure requests for isDesktop windows (because kdesktop // may get XRANDR resize event before kwin), but check it's still at the bottom? } /** * Handles property changes of the client window - **/ + */ void Client::propertyNotifyEvent(xcb_property_notify_event_t *e) { Toplevel::propertyNotifyEvent(e); if (e->window != window()) return; // ignore frame/wrapper switch(e->atom) { case XCB_ATOM_WM_NORMAL_HINTS: getWmNormalHints(); break; case XCB_ATOM_WM_NAME: fetchName(); break; case XCB_ATOM_WM_ICON_NAME: fetchIconicName(); break; case XCB_ATOM_WM_TRANSIENT_FOR: readTransient(); break; case XCB_ATOM_WM_HINTS: getIcons(); // because KWin::icon() uses WMHints as fallback break; default: if (e->atom == atoms->motif_wm_hints) { getMotifHints(); } else if (e->atom == atoms->net_wm_sync_request_counter) getSyncCounter(); else if (e->atom == atoms->activities) checkActivities(); else if (e->atom == atoms->kde_first_in_window_list) updateFirstInTabBox(); else if (e->atom == atoms->kde_color_sheme) updateColorScheme(); else if (e->atom == atoms->kde_screen_edge_show) updateShowOnScreenEdge(); else if (e->atom == atoms->gtk_frame_extents) detectGtkFrameExtents(); else if (e->atom == atoms->kde_net_wm_appmenu_service_name) checkApplicationMenuServiceName(); else if (e->atom == atoms->kde_net_wm_appmenu_object_path) checkApplicationMenuObjectPath(); break; } } void Client::enterNotifyEvent(xcb_enter_notify_event_t *e) { if (e->event != frameId()) return; // care only about entering the whole frame #define MOUSE_DRIVEN_FOCUS (!options->focusPolicyIsReasonable() || \ (options->focusPolicy() == Options::FocusFollowsMouse && options->isNextFocusPrefersMouse())) if (e->mode == XCB_NOTIFY_MODE_NORMAL || (e->mode == XCB_NOTIFY_MODE_UNGRAB && MOUSE_DRIVEN_FOCUS)) { if (options->isShadeHover()) { cancelShadeHoverTimer(); if (isShade()) { shadeHoverTimer = new QTimer(this); connect(shadeHoverTimer, SIGNAL(timeout()), this, SLOT(shadeHover())); shadeHoverTimer->setSingleShot(true); shadeHoverTimer->start(options->shadeHoverInterval()); } } #undef MOUSE_DRIVEN_FOCUS enterEvent(QPoint(e->root_x, e->root_y)); return; } } void Client::leaveNotifyEvent(xcb_leave_notify_event_t *e) { if (e->event != frameId()) return; // care only about leaving the whole frame if (e->mode == XCB_NOTIFY_MODE_NORMAL) { if (!isMoveResizePointerButtonDown()) { setMoveResizePointerMode(PositionCenter); updateCursor(); } bool lostMouse = !rect().contains(QPoint(e->event_x, e->event_y)); // 'lostMouse' wouldn't work with e.g. B2 or Keramik, which have non-rectangular decorations // (i.e. the LeaveNotify event comes before leaving the rect and no LeaveNotify event // comes after leaving the rect) - so lets check if the pointer is really outside the window // TODO this still sucks if a window appears above this one - it should lose the mouse // if this window is another client, but not if it's a popup ... maybe after KDE3.1 :( // (repeat after me 'AARGHL!') if (!lostMouse && e->detail != XCB_NOTIFY_DETAIL_INFERIOR) { Xcb::Pointer pointer(frameId()); if (!pointer || !pointer->same_screen || pointer->child == XCB_WINDOW_NONE) { // really lost the mouse lostMouse = true; } } if (lostMouse) { leaveEvent(); cancelShadeHoverTimer(); if (shade_mode == ShadeHover && !isMoveResize() && !isMoveResizePointerButtonDown()) { shadeHoverTimer = new QTimer(this); connect(shadeHoverTimer, SIGNAL(timeout()), this, SLOT(shadeUnhover())); shadeHoverTimer->setSingleShot(true); shadeHoverTimer->start(options->shadeHoverInterval()); } if (isDecorated()) { // sending a move instead of a leave. With leave we need to send proper coords, with move it's handled internally QHoverEvent leaveEvent(QEvent::HoverMove, QPointF(-1, -1), QPointF(-1, -1), Qt::NoModifier); QCoreApplication::sendEvent(decoration(), &leaveEvent); } } if (options->focusPolicy() == Options::FocusStrictlyUnderMouse && isActive() && lostMouse) { workspace()->requestDelayFocus(0); } return; } } #define XCapL KKeyServer::modXLock() #define XNumL KKeyServer::modXNumLock() #define XScrL KKeyServer::modXScrollLock() void Client::grabButton(int modifier) { unsigned int mods[ 8 ] = { 0, XCapL, XNumL, XNumL | XCapL, XScrL, XScrL | XCapL, XScrL | XNumL, XScrL | XNumL | XCapL }; for (int i = 0; i < 8; ++i) m_wrapper.grabButton(XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC, modifier | mods[ i ]); } void Client::ungrabButton(int modifier) { unsigned int mods[ 8 ] = { 0, XCapL, XNumL, XNumL | XCapL, XScrL, XScrL | XCapL, XScrL | XNumL, XScrL | XNumL | XCapL }; for (int i = 0; i < 8; ++i) m_wrapper.ungrabButton(modifier | mods[ i ]); } #undef XCapL #undef XNumL #undef XScrL /** * Releases the passive grab for some modifier combinations when a * window becomes active. This helps broken X programs that * missinterpret LeaveNotify events in grab mode to work properly * (Motif, AWT, Tk, ...) - **/ + */ void Client::updateMouseGrab() { if (workspace()->globalShortcutsDisabled()) { m_wrapper.ungrabButton(); // keep grab for the simple click without modifiers if needed (see below) bool not_obscured = workspace()->topClientOnDesktop(VirtualDesktopManager::self()->current(), -1, true, false) == this; if (!(!options->isClickRaise() || not_obscured)) grabButton(XCB_NONE); return; } if (isActive() && !TabBox::TabBox::self()->forcedGlobalMouseGrab()) { // see TabBox::establishTabBoxGrab() // first grab all modifier combinations m_wrapper.grabButton(XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC); // remove the grab for no modifiers only if the window // is unobscured or if the user doesn't want click raise // (it is unobscured if it the topmost in the unconstrained stacking order, i.e. it is // the most recently raised window) bool not_obscured = workspace()->topClientOnDesktop(VirtualDesktopManager::self()->current(), -1, true, false) == this; if (!options->isClickRaise() || not_obscured) ungrabButton(XCB_NONE); else grabButton(XCB_NONE); ungrabButton(XCB_MOD_MASK_SHIFT); ungrabButton(XCB_MOD_MASK_CONTROL); ungrabButton(XCB_MOD_MASK_CONTROL | XCB_MOD_MASK_SHIFT); } else { m_wrapper.ungrabButton(); // simply grab all modifier combinations m_wrapper.grabButton(XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC); } } static bool modKeyDown(int state) { const uint keyModX = (options->keyCmdAllModKey() == Qt::Key_Meta) ? KKeyServer::modXMeta() : KKeyServer::modXAlt(); return keyModX && (state & KKeyServer::accelModMaskX()) == keyModX; } // return value matters only when filtering events before decoration gets them bool Client::buttonPressEvent(xcb_window_t w, int button, int state, int x, int y, int x_root, int y_root, xcb_timestamp_t time) { if (isMoveResizePointerButtonDown()) { if (w == wrapperId()) xcb_allow_events(connection(), XCB_ALLOW_SYNC_POINTER, XCB_TIME_CURRENT_TIME); //xTime()); return true; } if (w == wrapperId() || w == frameId() || w == inputId()) { // FRAME neco s tohohle by se melo zpracovat, nez to dostane dekorace updateUserTime(time); const bool bModKeyHeld = modKeyDown(state); if (isSplash() && button == XCB_BUTTON_INDEX_1 && !bModKeyHeld) { // hide splashwindow if the user clicks on it hideClient(true); if (w == wrapperId()) xcb_allow_events(connection(), XCB_ALLOW_SYNC_POINTER, XCB_TIME_CURRENT_TIME); //xTime()); return true; } Options::MouseCommand com = Options::MouseNothing; bool was_action = false; if (bModKeyHeld) { was_action = true; switch(button) { case XCB_BUTTON_INDEX_1: com = options->commandAll1(); break; case XCB_BUTTON_INDEX_2: com = options->commandAll2(); break; case XCB_BUTTON_INDEX_3: com = options->commandAll3(); break; case XCB_BUTTON_INDEX_4: case XCB_BUTTON_INDEX_5: com = options->operationWindowMouseWheel(button == XCB_BUTTON_INDEX_4 ? 120 : -120); break; } } else { if (w == wrapperId()) { if (button < 4) { com = getMouseCommand(x11ToQtMouseButton(button), &was_action); } else if (button < 6) { com = getWheelCommand(Qt::Vertical, &was_action); } } } if (was_action) { bool replay = performMouseCommand(com, QPoint(x_root, y_root)); if (isSpecialWindow()) replay = true; if (w == wrapperId()) // these can come only from a grab xcb_allow_events(connection(), replay ? XCB_ALLOW_REPLAY_POINTER : XCB_ALLOW_SYNC_POINTER, XCB_TIME_CURRENT_TIME); //xTime()); return true; } } if (w == wrapperId()) { // these can come only from a grab xcb_allow_events(connection(), XCB_ALLOW_REPLAY_POINTER, XCB_TIME_CURRENT_TIME); //xTime()); return true; } if (w == inputId()) { x = x_root - geometry().x(); y = y_root - geometry().y(); // New API processes core events FIRST and only passes unused ones to the decoration QMouseEvent ev(QMouseEvent::MouseButtonPress, QPoint(x, y), QPoint(x_root, y_root), x11ToQtMouseButton(button), x11ToQtMouseButtons(state), Qt::KeyboardModifiers()); return processDecorationButtonPress(&ev, true); } if (w == frameId() && isDecorated()) { if (button >= 4 && button <= 7) { const Qt::KeyboardModifiers modifiers = x11ToQtKeyboardModifiers(state); // Logic borrowed from qapplication_x11.cpp const int delta = 120 * ((button == 4 || button == 6) ? 1 : -1); const bool hor = (((button == 4 || button == 5) && (modifiers & Qt::AltModifier)) || (button == 6 || button == 7)); const QPoint angle = hor ? QPoint(delta, 0) : QPoint(0, delta); QWheelEvent event(QPointF(x, y), QPointF(x_root, y_root), QPoint(), angle, delta, hor ? Qt::Horizontal : Qt::Vertical, x11ToQtMouseButtons(state), modifiers); event.setAccepted(false); QCoreApplication::sendEvent(decoration(), &event); if (!event.isAccepted() && !hor) { if (titlebarPositionUnderMouse()) { performMouseCommand(options->operationTitlebarMouseWheel(delta), QPoint(x_root, y_root)); } } } else { QMouseEvent event(QEvent::MouseButtonPress, QPointF(x, y), QPointF(x_root, y_root), x11ToQtMouseButton(button), x11ToQtMouseButtons(state), x11ToQtKeyboardModifiers(state)); event.setAccepted(false); QCoreApplication::sendEvent(decoration(), &event); if (!event.isAccepted()) { processDecorationButtonPress(&event); } } return true; } return true; } // return value matters only when filtering events before decoration gets them bool Client::buttonReleaseEvent(xcb_window_t w, int button, int state, int x, int y, int x_root, int y_root) { if (w == frameId() && isDecorated()) { // wheel handled on buttonPress if (button < 4 || button > 7) { QMouseEvent event(QEvent::MouseButtonRelease, QPointF(x, y), QPointF(x_root, y_root), x11ToQtMouseButton(button), x11ToQtMouseButtons(state) & ~x11ToQtMouseButton(button), x11ToQtKeyboardModifiers(state)); event.setAccepted(false); QCoreApplication::sendEvent(decoration(), &event); if (event.isAccepted() || !titlebarPositionUnderMouse()) { invalidateDecorationDoubleClickTimer(); // click was for the deco and shall not init a doubleclick } } } if (w == wrapperId()) { xcb_allow_events(connection(), XCB_ALLOW_SYNC_POINTER, XCB_TIME_CURRENT_TIME); //xTime()); return true; } if (w != frameId() && w != inputId() && w != moveResizeGrabWindow()) return true; if (w == frameId() && workspace()->userActionsMenu() && workspace()->userActionsMenu()->isShown()) { const_cast(workspace()->userActionsMenu())->grabInput(); } x = this->x(); // translate from grab window to local coords y = this->y(); // Check whether other buttons are still left pressed int buttonMask = XCB_BUTTON_MASK_1 | XCB_BUTTON_MASK_2 | XCB_BUTTON_MASK_3; if (button == XCB_BUTTON_INDEX_1) buttonMask &= ~XCB_BUTTON_MASK_1; else if (button == XCB_BUTTON_INDEX_2) buttonMask &= ~XCB_BUTTON_MASK_2; else if (button == XCB_BUTTON_INDEX_3) buttonMask &= ~XCB_BUTTON_MASK_3; if ((state & buttonMask) == 0) { endMoveResize(); } return true; } // return value matters only when filtering events before decoration gets them bool Client::motionNotifyEvent(xcb_window_t w, int state, int x, int y, int x_root, int y_root) { if (w == frameId() && isDecorated() && !isMinimized()) { // TODO Mouse move event dependent on state QHoverEvent event(QEvent::HoverMove, QPointF(x, y), QPointF(x, y)); QCoreApplication::instance()->sendEvent(decoration(), &event); } if (w != frameId() && w != inputId() && w != moveResizeGrabWindow()) return true; // care only about the whole frame if (!isMoveResizePointerButtonDown()) { if (w == inputId()) { int x = x_root - geometry().x();// + padding_left; int y = y_root - geometry().y();// + padding_top; if (isDecorated()) { QHoverEvent event(QEvent::HoverMove, QPointF(x, y), QPointF(x, y)); QCoreApplication::instance()->sendEvent(decoration(), &event); } } Position newmode = modKeyDown(state) ? PositionCenter : mousePosition(); if (newmode != moveResizePointerMode()) { setMoveResizePointerMode(newmode); updateCursor(); } return false; } if (w == moveResizeGrabWindow()) { x = this->x(); // translate from grab window to local coords y = this->y(); } handleMoveResize(QPoint(x, y), QPoint(x_root, y_root)); return true; } void Client::focusInEvent(xcb_focus_in_event_t *e) { if (e->event != window()) return; // only window gets focus if (e->mode == XCB_NOTIFY_MODE_UNGRAB) return; // we don't care if (e->detail == XCB_NOTIFY_DETAIL_POINTER) return; // we don't care if (!isShown(false) || !isOnCurrentDesktop()) // we unmapped it, but it got focus meanwhile -> return; // activateNextClient() already transferred focus elsewhere workspace()->forEachClient([](Client *client) { client->cancelFocusOutTimer(); }); // check if this client is in should_get_focus list or if activation is allowed bool activate = workspace()->allowClientActivation(this, -1U, true); workspace()->gotFocusIn(this); // remove from should_get_focus list if (activate) setActive(true); else { workspace()->restoreFocus(); demandAttention(); } } void Client::focusOutEvent(xcb_focus_out_event_t *e) { if (e->event != window()) return; // only window gets focus if (e->mode == XCB_NOTIFY_MODE_GRAB) return; // we don't care if (isShade()) return; // here neither if (e->detail != XCB_NOTIFY_DETAIL_NONLINEAR && e->detail != XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL) // SELI check all this return; // hack for motif apps like netscape if (QApplication::activePopupWidget()) return; // When a client loses focus, FocusOut events are usually immediatelly // followed by FocusIn events for another client that gains the focus // (unless the focus goes to another screen, or to the nofocus widget). // Without this check, the former focused client would have to be // deactivated, and after that, the new one would be activated, with // a short time when there would be no active client. This can cause // flicker sometimes, e.g. when a fullscreen is shown, and focus is transferred // from it to its transient, the fullscreen would be kept in the Active layer // at the beginning and at the end, but not in the middle, when the active // client would be temporarily none (see Client::belongToLayer() ). // Therefore the setActive(false) call is moved to the end of the current // event queue. If there is a matching FocusIn event in the current queue // this will be processed before the setActive(false) call and the activation // of the Client which gained FocusIn will automatically deactivate the // previously active client. if (!m_focusOutTimer) { m_focusOutTimer = new QTimer(this); m_focusOutTimer->setSingleShot(true); m_focusOutTimer->setInterval(0); connect(m_focusOutTimer, &QTimer::timeout, [this]() { setActive(false); }); } m_focusOutTimer->start(); } // performs _NET_WM_MOVERESIZE void Client::NETMoveResize(int x_root, int y_root, NET::Direction direction) { if (direction == NET::Move) { // move cursor to the provided position to prevent the window jumping there on first movement // the expectation is that the cursor is already at the provided position, // thus it's more a safety measurement Cursor::setPos(QPoint(x_root, y_root)); performMouseCommand(Options::MouseMove, QPoint(x_root, y_root)); } else if (isMoveResize() && direction == NET::MoveResizeCancel) { finishMoveResize(true); setMoveResizePointerButtonDown(false); updateCursor(); } else if (direction >= NET::TopLeft && direction <= NET::Left) { static const Position convert[] = { PositionTopLeft, PositionTop, PositionTopRight, PositionRight, PositionBottomRight, PositionBottom, PositionBottomLeft, PositionLeft }; if (!isResizable() || isShade()) return; if (isMoveResize()) finishMoveResize(false); setMoveResizePointerButtonDown(true); setMoveOffset(QPoint(x_root - x(), y_root - y())); // map from global setInvertedMoveOffset(rect().bottomRight() - moveOffset()); setUnrestrictedMoveResize(false); setMoveResizePointerMode(convert[ direction ]); if (!startMoveResize()) setMoveResizePointerButtonDown(false); updateCursor(); } else if (direction == NET::KeyboardMove) { // ignore mouse coordinates given in the message, mouse position is used by the moving algorithm Cursor::setPos(geometry().center()); performMouseCommand(Options::MouseUnrestrictedMove, geometry().center()); } else if (direction == NET::KeyboardSize) { // ignore mouse coordinates given in the message, mouse position is used by the resizing algorithm Cursor::setPos(geometry().bottomRight()); performMouseCommand(Options::MouseUnrestrictedResize, geometry().bottomRight()); } } void Client::keyPressEvent(uint key_code, xcb_timestamp_t time) { updateUserTime(time); AbstractClient::keyPressEvent(key_code); } // **************************************** // Unmanaged // **************************************** bool Unmanaged::windowEvent(xcb_generic_event_t *e) { double old_opacity = opacity(); NET::Properties dirtyProperties; NET::Properties2 dirtyProperties2; info->event(e, &dirtyProperties, &dirtyProperties2); // pass through the NET stuff if (dirtyProperties2 & NET::WM2Opacity) { if (compositing()) { addRepaintFull(); emit opacityChanged(this, old_opacity); } } if (dirtyProperties2 & NET::WM2OpaqueRegion) { getWmOpaqueRegion(); } if (dirtyProperties2.testFlag(NET::WM2WindowRole)) { emit windowRoleChanged(); } if (dirtyProperties2.testFlag(NET::WM2WindowClass)) { getResourceClass(); } const uint8_t eventType = e->response_type & ~0x80; switch (eventType) { case XCB_DESTROY_NOTIFY: release(ReleaseReason::Destroyed); break; case XCB_UNMAP_NOTIFY:{ workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event // unmap notify might have been emitted due to a destroy notify // but unmap notify gets emitted before the destroy notify, nevertheless at this // point the window is already destroyed. This means any XCB request with the window // will cause an error. // To not run into these errors we try to wait for the destroy notify. For this we // generate a round trip to the X server and wait a very short time span before // handling the release. updateXTime(); // using 1 msec to not just move it at the end of the event loop but add an very short // timespan to cover cases like unmap() followed by destroy(). The only other way to // ensure that the window is not destroyed when we do the release handling is to grab // the XServer which we do not want to do for an Unmanaged. The timespan of 1 msec is // short enough to not cause problems in the close window animations. // It's of course still possible that we miss the destroy in which case non-fatal // X errors are reported to the event loop and logged by Qt. QTimer::singleShot(1, this, SLOT(release())); break; } case XCB_CONFIGURE_NOTIFY: configureNotifyEvent(reinterpret_cast(e)); break; case XCB_PROPERTY_NOTIFY: propertyNotifyEvent(reinterpret_cast(e)); break; case XCB_CLIENT_MESSAGE: clientMessageEvent(reinterpret_cast(e)); break; default: { if (eventType == Xcb::Extensions::self()->shapeNotifyEvent()) { detectShape(window()); addRepaintFull(); addWorkspaceRepaint(geometry()); // in case shape change removes part of this window emit geometryShapeChanged(this, geometry()); } if (eventType == Xcb::Extensions::self()->damageNotifyEvent()) damageNotifyEvent(); break; } } return false; // don't eat events, even our own unmanaged widgets are tracked } void Unmanaged::configureNotifyEvent(xcb_configure_notify_event_t *e) { if (effects) static_cast(effects)->checkInputWindowStacking(); // keep them on top QRect newgeom(e->x, e->y, e->width, e->height); if (newgeom != geom) { addWorkspaceRepaint(visibleRect()); // damage old area QRect old = geom; geom = newgeom; emit geometryChanged(); // update shadow region addRepaintFull(); if (old.size() != geom.size()) discardWindowPixmap(); emit geometryShapeChanged(this, old); } } // **************************************** // Toplevel // **************************************** void Toplevel::propertyNotifyEvent(xcb_property_notify_event_t *e) { if (e->window != window()) return; // ignore frame/wrapper switch(e->atom) { default: if (e->atom == atoms->wm_client_leader) getWmClientLeader(); else if (e->atom == atoms->kde_net_wm_shadow) getShadow(); else if (e->atom == atoms->kde_skip_close_animation) getSkipCloseAnimation(); break; } } void Toplevel::clientMessageEvent(xcb_client_message_event_t *e) { if (e->type == atoms->wl_surface_id) { m_surfaceId = e->data.data32[0]; if (auto w = waylandServer()) { if (auto s = KWayland::Server::SurfaceInterface::get(m_surfaceId, w->xWaylandConnection())) { setSurface(s); } } emit surfaceIdChanged(m_surfaceId); } } } // namespace diff --git a/focuschain.h b/focuschain.h index 91e834fa6..258634192 100644 --- a/focuschain.h +++ b/focuschain.h @@ -1,254 +1,254 @@ /******************************************************************** 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_FOCUS_CHAIN_H #define KWIN_FOCUS_CHAIN_H // KWin #include // Qt #include #include namespace KWin { // forward declarations class AbstractClient; /** * @brief Singleton class to handle the various focus chains. * * A focus chain is a list of Clients containing information on which Client should be activated. * * Internally this FocusChain holds multiple independent chains. There is one chain of most recently * used Clients which is primarily used by TabBox to build up the list of Clients for navigation. * The chains are organized as a normal QList of Clients with the most recently used Client being the * last item of the list, that is a LIFO like structure. * * In addition there is one chain for each virtual desktop which is used to determine which Client * should get activated when the user switches to another virtual desktop. * * Furthermore this class contains various helper methods for the two different kind of chains. - **/ + */ class FocusChain : public QObject { Q_OBJECT public: enum Change { MakeFirst, MakeLast, Update, MakeFirstMinimized = MakeFirst }; ~FocusChain() override; /** * @brief Updates the position of the @p client according to the requested @p change in the * focus chain. * * This method affects both the most recently used focus chain and the per virtual desktop focus * chain. * * In case the client does no longer want to get focus, it is removed from all chains. In case * the client is on all virtual desktops it is ensured that it is present in each of the virtual * desktops focus chain. In case it's on exactly one virtual desktop it is ensured that it is only * in the focus chain for that virtual desktop. * * Depending on @p change the Client is inserted at different positions in the focus chain. In case * of @c MakeFirst it is moved to the first position of the chain, in case of * @c MakeLast it is moved to the last position of the chain. In all other cases it * depends on whether the @p client is the currently active Client. If it is the active Client it * becomes the first Client in the chain, otherwise it is inserted at the second position that is * directly after the currently active Client. * * @param client The Client which should be moved inside the chains. * @param change Where to move the Client * @return void - **/ + */ void update(AbstractClient *client, Change change); /** * @brief Moves @p client behind the @p reference Client in all focus chains. * * @param client The Client to move in the chains * @param reference The Client behind which the @p client should be moved * @return void - **/ + */ void moveAfterClient(AbstractClient *client, AbstractClient *reference); /** * @brief Finds the best Client to become the new active Client in the focus chain for the given * virtual @p desktop. * * In case that separate screen focus is used only Clients on the current screen are considered. * If no Client for activation is found @c null is returned. * * @param desktop The virtual desktop to look for a Client for activation * @return :Client* The Client which could be activated or @c null if there is none. - **/ + */ AbstractClient *getForActivation(uint desktop) const; /** * @brief Finds the best Client to become the new active Client in the focus chain for the given * virtual @p desktop on the given @p screen. * * This method makes only sense to use if separate screen focus is used. If separate screen focus * is disabled the @p screen is ignored. * If no Client for activation is found @c null is returned. * * @param desktop The virtual desktop to look for a Client for activation * @param screen The screen to constrain the search on with separate screen focus * @return :Client* The Client which could be activated or @c null if there is none. - **/ + */ AbstractClient *getForActivation(uint desktop, int screen) const; /** * @brief Checks whether the most recently used focus chain contains the given @p client. * * Does not consider the per-desktop focus chains. * @param client The Client to look for. * @return bool @c true if the most recently used focus chain contains @p client, @c false otherwise. - **/ + */ bool contains(AbstractClient *client) const; /** * @brief Checks whether the focus chain for the given @p desktop contains the given @p client. * * Does not consider the most recently used focus chain. * * @param client The Client to look for. * @param desktop The virtual desktop whose focus chain should be used * @return bool @c true if the focus chain for @p desktop contains @p client, @c false otherwise. - **/ + */ bool contains(AbstractClient *client, uint desktop) const; /** * @brief Queries the most recently used focus chain for the next Client after the given * @p reference Client. * * The navigation wraps around the borders of the chain. That is if the @p reference Client is * the last item of the focus chain, the first Client will be returned. * * If the @p reference Client cannot be found in the focus chain, the first element of the focus * chain is returned. * * @param reference The start point in the focus chain to search * @return :Client* The relatively next Client in the most recently used chain. - **/ + */ AbstractClient *nextMostRecentlyUsed(AbstractClient *reference) const; /** * @brief Queries the focus chain for @p desktop for the next Client in relation to the given * @p reference Client. * * The method finds the first usable Client which is not the @p reference Client. If no Client * can be found @c null is returned * * @param reference The reference Client which should not be returned * @param desktop The virtual desktop whose focus chain should be used * @return :Client* The next usable Client or @c null if none can be found. - **/ + */ AbstractClient *nextForDesktop(AbstractClient *reference, uint desktop) const; /** * @brief Returns the first Client in the most recently used focus chain. First Client in this * case means really the first Client in the chain and not the most recently used Client. * * @return :Client* The first Client in the most recently used chain. - **/ + */ AbstractClient *firstMostRecentlyUsed() const; public Q_SLOTS: /** * @brief Resizes the per virtual desktop focus chains from @p previousSize to @p newSize. * This means that for each virtual desktop between previous and new size a new focus chain is * created and in case the number is reduced the focus chains are destroyed. * * @param previousSize The previous number of virtual desktops * @param newSize The new number of virtual desktops * @return void - **/ + */ void resize(uint previousSize, uint newSize); /** * @brief Removes @p client from all focus chains. * * @param client The Client to remove from all focus chains. * @return void - **/ + */ void remove(KWin::AbstractClient *client); void setSeparateScreenFocus(bool enabled); void setActiveClient(KWin::AbstractClient *client); void setCurrentDesktop(uint previous, uint newDesktop); bool isUsableFocusCandidate(AbstractClient *c, AbstractClient *prev) const; private: using Chain = QList; /** * @brief Makes @p client the first Client in the given focus @p chain. * * This means the existing position of @p client is dropped and @p client is appended to the * @p chain which makes it the first item. * * @param client The Client to become the first in @p chain * @param chain The focus chain to operate on * @return void - **/ + */ void makeFirstInChain(AbstractClient *client, Chain &chain); /** * @brief Makes @p client the last Client in the given focus @p chain. * * This means the existing position of @p client is dropped and @p client is prepended to the * @p chain which makes it the last item. * * @param client The Client to become the last in @p chain * @param chain The focus chain to operate on * @return void - **/ + */ void makeLastInChain(AbstractClient *client, Chain &chain); void moveAfterClientInChain(AbstractClient *client, AbstractClient *reference, Chain &chain); void updateClientInChain(AbstractClient *client, Change change, Chain &chain); void insertClientIntoChain(AbstractClient *client, Chain &chain); Chain m_mostRecentlyUsed; QHash m_desktopFocusChains; bool m_separateScreenFocus; AbstractClient *m_activeClient; uint m_currentDesktop; KWIN_SINGLETON_VARIABLE(FocusChain, s_manager) }; inline bool FocusChain::contains(AbstractClient *client) const { return m_mostRecentlyUsed.contains(client); } inline void FocusChain::setSeparateScreenFocus(bool enabled) { m_separateScreenFocus = enabled; } inline void FocusChain::setActiveClient(AbstractClient *client) { m_activeClient = client; } inline void FocusChain::setCurrentDesktop(uint previous, uint newDesktop) { Q_UNUSED(previous) m_currentDesktop = newDesktop; } } // namespace #endif // KWIN_FOCUS_CHAIN_H diff --git a/geometry.cpp b/geometry.cpp index 27ec3cd2c..9d45c4da4 100644 --- a/geometry.cpp +++ b/geometry.cpp @@ -1,3442 +1,3442 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. 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 . *********************************************************************/ /* This file contains things relevant to geometry, i.e. workspace size, window positions and window sizes. */ #include "client.h" #include "composite.h" #include "cursor.h" #include "netinfo.h" #include "workspace.h" #include "placement.h" #include "geometrytip.h" #include "rules.h" #include "screens.h" #include "effects.h" #include "screenedge.h" #include #include #include #include "outline.h" #include "shell_client.h" #include "wayland_server.h" #include #include namespace KWin { static inline int sign(int v) { return (v > 0) - (v < 0); } //******************************************** // Workspace //******************************************** extern int screen_number; extern bool is_multihead; /** * Resizes the workspace after an XRANDR screen size change - **/ + */ void Workspace::desktopResized() { QRect geom = screens()->geometry(); if (rootInfo()) { NETSize desktop_geometry; desktop_geometry.width = geom.width(); desktop_geometry.height = geom.height(); rootInfo()->setDesktopGeometry(desktop_geometry); } updateClientArea(); saveOldScreenSizes(); // after updateClientArea(), so that one still uses the previous one // TODO: emit a signal instead and remove the deep function calls into edges and effects ScreenEdges::self()->recreateEdges(); if (effects) { static_cast(effects)->desktopResized(geom.size()); } } void Workspace::saveOldScreenSizes() { olddisplaysize = screens()->displaySize(); oldscreensizes.clear(); for( int i = 0; i < screens()->count(); ++i ) oldscreensizes.append( screens()->geometry( i )); } /** * Updates the current client areas according to the current clients. * * If the area changes or force is @c true, the new areas are propagated to the world. * * The client area is the area that is available for clients (that * which is not taken by windows like panels, the top-of-screen menu * etc). * * @see clientArea() - **/ + */ void Workspace::updateClientArea(bool force) { const Screens *s = Screens::self(); int nscreens = s->count(); const int numberOfDesktops = VirtualDesktopManager::self()->count(); QVector< QRect > new_wareas(numberOfDesktops + 1); QVector< StrutRects > new_rmoveareas(numberOfDesktops + 1); QVector< QVector< QRect > > new_sareas(numberOfDesktops + 1); QVector< QRect > screens(nscreens); QRect desktopArea; for (int i = 0; i < nscreens; i++) { desktopArea |= s->geometry(i); } for (int iS = 0; iS < nscreens; iS ++) { screens [iS] = s->geometry(iS); } for (int i = 1; i <= numberOfDesktops; ++i) { new_wareas[ i ] = desktopArea; new_sareas[ i ].resize(nscreens); for (int iS = 0; iS < nscreens; iS ++) new_sareas[ i ][ iS ] = screens[ iS ]; } for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) { if (!(*it)->hasStrut()) continue; QRect r = (*it)->adjustedClientArea(desktopArea, desktopArea); // sanity check that a strut doesn't exclude a complete screen geometry // this is a violation to EWMH, as KWin just ignores the strut for (int i = 0; i < Screens::self()->count(); i++) { if (!r.intersects(Screens::self()->geometry(i))) { qCDebug(KWIN_CORE) << "Adjusted client area would exclude a complete screen, ignore"; r = desktopArea; break; } } StrutRects strutRegion = (*it)->strutRects(); const QRect clientsScreenRect = KWin::screens()->geometry((*it)->screen()); for (auto strut = strutRegion.begin(); strut != strutRegion.end(); strut++) { *strut = StrutRect((*strut).intersected(clientsScreenRect), (*strut).area()); } // Ignore offscreen xinerama struts. These interfere with the larger monitors on the setup // and should be ignored so that applications that use the work area to work out where // windows can go can use the entire visible area of the larger monitors. // This goes against the EWMH description of the work area but it is a toss up between // having unusable sections of the screen (Which can be quite large with newer monitors) // or having some content appear offscreen (Relatively rare compared to other). bool hasOffscreenXineramaStrut = (*it)->hasOffscreenXineramaStrut(); if ((*it)->isOnAllDesktops()) { for (int i = 1; i <= numberOfDesktops; ++i) { if (!hasOffscreenXineramaStrut) new_wareas[ i ] = new_wareas[ i ].intersected(r); new_rmoveareas[ i ] += strutRegion; for (int iS = 0; iS < nscreens; iS ++) { const auto geo = new_sareas[ i ][ iS ].intersected( (*it)->adjustedClientArea(desktopArea, screens[ iS ])); // ignore the geometry if it results in the screen getting removed completely if (!geo.isEmpty()) { new_sareas[ i ][ iS ] = geo; } } } } else { if (!hasOffscreenXineramaStrut) new_wareas[(*it)->desktop()] = new_wareas[(*it)->desktop()].intersected(r); new_rmoveareas[(*it)->desktop()] += strutRegion; for (int iS = 0; iS < nscreens; iS ++) { // qDebug() << "adjusting new_sarea: " << screens[ iS ]; const auto geo = new_sareas[(*it)->desktop()][ iS ].intersected( (*it)->adjustedClientArea(desktopArea, screens[ iS ])); // ignore the geometry if it results in the screen getting removed completely if (!geo.isEmpty()) { new_sareas[(*it)->desktop()][ iS ] = geo; } } } } if (waylandServer()) { auto updateStrutsForWaylandClient = [&] (ShellClient *c) { // assuming that only docks have "struts" and that all docks have a strut if (!c->hasStrut()) { return; } auto margins = [c] (const QRect &geometry) { QMargins margins; if (!geometry.intersects(c->geometry())) { return margins; } // figure out which areas of the overall screen setup it borders const bool left = c->geometry().left() == geometry.left(); const bool right = c->geometry().right() == geometry.right(); const bool top = c->geometry().top() == geometry.top(); const bool bottom = c->geometry().bottom() == geometry.bottom(); const bool horizontal = c->geometry().width() >= c->geometry().height(); if (left && ((!top && !bottom) || !horizontal)) { margins.setLeft(c->geometry().width()); } if (right && ((!top && !bottom) || !horizontal)) { margins.setRight(c->geometry().width()); } if (top && ((!left && !right) || horizontal)) { margins.setTop(c->geometry().height()); } if (bottom && ((!left && !right) || horizontal)) { margins.setBottom(c->geometry().height()); } return margins; }; auto marginsToStrutArea = [] (const QMargins &margins) { if (margins.left() != 0) { return StrutAreaLeft; } if (margins.right() != 0) { return StrutAreaRight; } if (margins.top() != 0) { return StrutAreaTop; } if (margins.bottom() != 0) { return StrutAreaBottom; } return StrutAreaInvalid; }; const auto strut = margins(KWin::screens()->geometry(c->screen())); const StrutRects strutRegion = StrutRects{StrutRect(c->geometry(), marginsToStrutArea(strut))}; QRect r = desktopArea - margins(KWin::screens()->geometry()); if (c->isOnAllDesktops()) { for (int i = 1; i <= numberOfDesktops; ++i) { new_wareas[ i ] = new_wareas[ i ].intersected(r); for (int iS = 0; iS < nscreens; ++iS) { new_sareas[ i ][ iS ] = new_sareas[ i ][ iS ].intersected(screens[iS] - margins(screens[iS])); } new_rmoveareas[ i ] += strutRegion; } } else { new_wareas[c->desktop()] = new_wareas[c->desktop()].intersected(r); for (int iS = 0; iS < nscreens; iS++) { new_sareas[c->desktop()][ iS ] = new_sareas[c->desktop()][ iS ].intersected(screens[iS] - margins(screens[iS])); } new_rmoveareas[ c->desktop() ] += strutRegion; } }; const auto clients = waylandServer()->clients(); for (auto c : clients) { updateStrutsForWaylandClient(c); } const auto internalClients = waylandServer()->internalClients(); for (auto c : internalClients) { updateStrutsForWaylandClient(c); } } #if 0 for (int i = 1; i <= numberOfDesktops(); ++i) { for (int iS = 0; iS < nscreens; iS ++) qCDebug(KWIN_CORE) << "new_sarea: " << new_sareas[ i ][ iS ]; } #endif bool changed = force; if (screenarea.isEmpty()) changed = true; for (int i = 1; !changed && i <= numberOfDesktops; ++i) { if (workarea[ i ] != new_wareas[ i ]) changed = true; if (restrictedmovearea[ i ] != new_rmoveareas[ i ]) changed = true; if (screenarea[ i ].size() != new_sareas[ i ].size()) changed = true; for (int iS = 0; !changed && iS < nscreens; iS ++) if (new_sareas[ i ][ iS ] != screenarea [ i ][ iS ]) changed = true; } if (changed) { workarea = new_wareas; oldrestrictedmovearea = restrictedmovearea; restrictedmovearea = new_rmoveareas; screenarea = new_sareas; if (rootInfo()) { NETRect r; for (int i = 1; i <= numberOfDesktops; i++) { r.pos.x = workarea[ i ].x(); r.pos.y = workarea[ i ].y(); r.size.width = workarea[ i ].width(); r.size.height = workarea[ i ].height(); rootInfo()->setWorkArea(i, r); } } for (auto it = m_allClients.constBegin(); it != m_allClients.constEnd(); ++it) (*it)->checkWorkspacePosition(); oldrestrictedmovearea.clear(); // reset, no longer valid or needed } } void Workspace::updateClientArea() { updateClientArea(false); } /** * Returns the area available for clients. This is the desktop * geometry minus windows on the dock. Placement algorithms should * refer to this rather than Screens::geometry. - **/ + */ QRect Workspace::clientArea(clientAreaOption opt, int screen, int desktop) const { if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = VirtualDesktopManager::self()->current(); if (screen == -1) screen = screens()->current(); const QSize displaySize = screens()->displaySize(); QRect sarea, warea; if (is_multihead) { sarea = (!screenarea.isEmpty() && screen < screenarea[ desktop ].size()) // screens may be missing during KWin initialization or screen config changes ? screenarea[ desktop ][ screen_number ] : screens()->geometry(screen_number); warea = workarea[ desktop ].isNull() ? screens()->geometry(screen_number) : workarea[ desktop ]; } else { sarea = (!screenarea.isEmpty() && screen < screenarea[ desktop ].size()) // screens may be missing during KWin initialization or screen config changes ? screenarea[ desktop ][ screen ] : screens()->geometry(screen); warea = workarea[ desktop ].isNull() ? QRect(0, 0, displaySize.width(), displaySize.height()) : workarea[ desktop ]; } switch(opt) { case MaximizeArea: case PlacementArea: return sarea; case MaximizeFullArea: case FullScreenArea: case MovementArea: case ScreenArea: if (is_multihead) return screens()->geometry(screen_number); else return screens()->geometry(screen); case WorkArea: if (is_multihead) return sarea; else return warea; case FullArea: return QRect(0, 0, displaySize.width(), displaySize.height()); } abort(); } QRect Workspace::clientArea(clientAreaOption opt, const QPoint& p, int desktop) const { return clientArea(opt, screens()->number(p), desktop); } QRect Workspace::clientArea(clientAreaOption opt, const AbstractClient* c) const { return clientArea(opt, c->geometry().center(), c->desktop()); } QRegion Workspace::restrictedMoveArea(int desktop, StrutAreas areas) const { if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = VirtualDesktopManager::self()->current(); QRegion region; foreach (const StrutRect & rect, restrictedmovearea[desktop]) if (areas & rect.area()) region += rect; return region; } bool Workspace::inUpdateClientArea() const { return !oldrestrictedmovearea.isEmpty(); } QRegion Workspace::previousRestrictedMoveArea(int desktop, StrutAreas areas) const { if (desktop == NETWinInfo::OnAllDesktops || desktop == 0) desktop = VirtualDesktopManager::self()->current(); QRegion region; foreach (const StrutRect & rect, oldrestrictedmovearea.at(desktop)) if (areas & rect.area()) region += rect; return region; } QVector< QRect > Workspace::previousScreenSizes() const { return oldscreensizes; } int Workspace::oldDisplayWidth() const { return olddisplaysize.width(); } int Workspace::oldDisplayHeight() const { return olddisplaysize.height(); } /** * Client \a c is moved around to position \a pos. This gives the * workspace the opportunity to interveniate and to implement * snap-to-windows functionality. * * The parameter \a snapAdjust is a multiplier used to calculate the * effective snap zones. When 1.0, it means that the snap zones will be * used without change. - **/ + */ QPoint Workspace::adjustClientPosition(AbstractClient* c, QPoint pos, bool unrestricted, double snapAdjust) { QSize borderSnapZone(options->borderSnapZone(), options->borderSnapZone()); QRect maxRect; int guideMaximized = MaximizeRestore; if (c->maximizeMode() != MaximizeRestore) { maxRect = clientArea(MaximizeArea, pos + c->rect().center(), c->desktop()); QRect geo = c->geometry(); if (c->maximizeMode() & MaximizeHorizontal && (geo.x() == maxRect.left() || geo.right() == maxRect.right())) { guideMaximized |= MaximizeHorizontal; borderSnapZone.setWidth(qMax(borderSnapZone.width() + 2, maxRect.width() / 16)); } if (c->maximizeMode() & MaximizeVertical && (geo.y() == maxRect.top() || geo.bottom() == maxRect.bottom())) { guideMaximized |= MaximizeVertical; borderSnapZone.setHeight(qMax(borderSnapZone.height() + 2, maxRect.height() / 16)); } } if (options->windowSnapZone() || !borderSnapZone.isNull() || options->centerSnapZone()) { const bool sOWO = options->isSnapOnlyWhenOverlapping(); const int screen = screens()->number(pos + c->rect().center()); if (maxRect.isNull()) maxRect = clientArea(MovementArea, screen, c->desktop()); const int xmin = maxRect.left(); const int xmax = maxRect.right() + 1; //desk size const int ymin = maxRect.top(); const int ymax = maxRect.bottom() + 1; const int cx(pos.x()); const int cy(pos.y()); const int cw(c->width()); const int ch(c->height()); const int rx(cx + cw); const int ry(cy + ch); //these don't change int nx(cx), ny(cy); //buffers int deltaX(xmax); int deltaY(ymax); //minimum distance to other clients int lx, ly, lrx, lry; //coords and size for the comparison client, l // border snap const int snapX = borderSnapZone.width() * snapAdjust; //snap trigger const int snapY = borderSnapZone.height() * snapAdjust; if (snapX || snapY) { QRect geo = c->geometry(); const QPoint cp = c->clientPos(); const QSize cs = geo.size() - c->clientSize(); int padding[4] = { cp.x(), cs.width() - cp.x(), cp.y(), cs.height() - cp.y() }; // snap to titlebar / snap to window borders on inner screen edges AbstractClient::Position titlePos = c->titlebarPosition(); if (padding[0] && (titlePos == AbstractClient::PositionLeft || (c->maximizeMode() & MaximizeHorizontal) || screens()->intersecting(geo.translated(maxRect.x() - (padding[0] + geo.x()), 0)) > 1)) padding[0] = 0; if (padding[1] && (titlePos == AbstractClient::PositionRight || (c->maximizeMode() & MaximizeHorizontal) || screens()->intersecting(geo.translated(maxRect.right() + padding[1] - geo.right(), 0)) > 1)) padding[1] = 0; if (padding[2] && (titlePos == AbstractClient::PositionTop || (c->maximizeMode() & MaximizeVertical) || screens()->intersecting(geo.translated(0, maxRect.y() - (padding[2] + geo.y()))) > 1)) padding[2] = 0; if (padding[3] && (titlePos == AbstractClient::PositionBottom || (c->maximizeMode() & MaximizeVertical) || screens()->intersecting(geo.translated(0, maxRect.bottom() + padding[3] - geo.bottom())) > 1)) padding[3] = 0; if ((sOWO ? (cx < xmin) : true) && (qAbs(xmin - cx) < snapX)) { deltaX = xmin - cx; nx = xmin - padding[0]; } if ((sOWO ? (rx > xmax) : true) && (qAbs(rx - xmax) < snapX) && (qAbs(xmax - rx) < deltaX)) { deltaX = rx - xmax; nx = xmax - cw + padding[1]; } if ((sOWO ? (cy < ymin) : true) && (qAbs(ymin - cy) < snapY)) { deltaY = ymin - cy; ny = ymin - padding[2]; } if ((sOWO ? (ry > ymax) : true) && (qAbs(ry - ymax) < snapY) && (qAbs(ymax - ry) < deltaY)) { deltaY = ry - ymax; ny = ymax - ch + padding[3]; } } // windows snap int snap = options->windowSnapZone() * snapAdjust; if (snap) { for (auto l = m_allClients.constBegin(); l != m_allClients.constEnd(); ++l) { if ((*l) == c) continue; if ((*l)->isMinimized()) continue; // is minimized if (!(*l)->isShown(false)) continue; if ((*l)->tabGroup() && (*l) != (*l)->tabGroup()->current()) continue; // is not active tab if (!((*l)->isOnDesktop(c->desktop()) || c->isOnDesktop((*l)->desktop()))) continue; // wrong virtual desktop if (!(*l)->isOnCurrentActivity()) continue; // wrong activity if ((*l)->isDesktop() || (*l)->isSplash()) continue; lx = (*l)->x(); ly = (*l)->y(); lrx = lx + (*l)->width(); lry = ly + (*l)->height(); if (!(guideMaximized & MaximizeHorizontal) && (((cy <= lry) && (cy >= ly)) || ((ry >= ly) && (ry <= lry)) || ((cy <= ly) && (ry >= lry)))) { if ((sOWO ? (cx < lrx) : true) && (qAbs(lrx - cx) < snap) && (qAbs(lrx - cx) < deltaX)) { deltaX = qAbs(lrx - cx); nx = lrx; } if ((sOWO ? (rx > lx) : true) && (qAbs(rx - lx) < snap) && (qAbs(rx - lx) < deltaX)) { deltaX = qAbs(rx - lx); nx = lx - cw; } } if (!(guideMaximized & MaximizeVertical) && (((cx <= lrx) && (cx >= lx)) || ((rx >= lx) && (rx <= lrx)) || ((cx <= lx) && (rx >= lrx)))) { if ((sOWO ? (cy < lry) : true) && (qAbs(lry - cy) < snap) && (qAbs(lry - cy) < deltaY)) { deltaY = qAbs(lry - cy); ny = lry; } //if ( (qAbs( ry-ly ) < snap) && (qAbs( ry - ly ) < deltaY )) if ((sOWO ? (ry > ly) : true) && (qAbs(ry - ly) < snap) && (qAbs(ry - ly) < deltaY)) { deltaY = qAbs(ry - ly); ny = ly - ch; } } // Corner snapping if (!(guideMaximized & MaximizeVertical) && (nx == lrx || nx + cw == lx)) { if ((sOWO ? (ry > lry) : true) && (qAbs(lry - ry) < snap) && (qAbs(lry - ry) < deltaY)) { deltaY = qAbs(lry - ry); ny = lry - ch; } if ((sOWO ? (cy < ly) : true) && (qAbs(cy - ly) < snap) && (qAbs(cy - ly) < deltaY)) { deltaY = qAbs(cy - ly); ny = ly; } } if (!(guideMaximized & MaximizeHorizontal) && (ny == lry || ny + ch == ly)) { if ((sOWO ? (rx > lrx) : true) && (qAbs(lrx - rx) < snap) && (qAbs(lrx - rx) < deltaX)) { deltaX = qAbs(lrx - rx); nx = lrx - cw; } if ((sOWO ? (cx < lx) : true) && (qAbs(cx - lx) < snap) && (qAbs(cx - lx) < deltaX)) { deltaX = qAbs(cx - lx); nx = lx; } } } } // center snap snap = options->centerSnapZone() * snapAdjust; //snap trigger if (snap) { int diffX = qAbs((xmin + xmax) / 2 - (cx + cw / 2)); int diffY = qAbs((ymin + ymax) / 2 - (cy + ch / 2)); if (diffX < snap && diffY < snap && diffX < deltaX && diffY < deltaY) { // Snap to center of screen nx = (xmin + xmax) / 2 - cw / 2; ny = (ymin + ymax) / 2 - ch / 2; } else if (options->borderSnapZone()) { // Enhance border snap if ((nx == xmin || nx == xmax - cw) && diffY < snap && diffY < deltaY) { // Snap to vertical center on screen edge ny = (ymin + ymax) / 2 - ch / 2; } else if (((unrestricted ? ny == ymin : ny <= ymin) || ny == ymax - ch) && diffX < snap && diffX < deltaX) { // Snap to horizontal center on screen edge nx = (xmin + xmax) / 2 - cw / 2; } } } pos = QPoint(nx, ny); } return pos; } QRect Workspace::adjustClientSize(AbstractClient* c, QRect moveResizeGeom, int mode) { //adapted from adjustClientPosition on 29May2004 //this function is called when resizing a window and will modify //the new dimensions to snap to other windows/borders if appropriate if (options->windowSnapZone() || options->borderSnapZone()) { // || options->centerSnapZone ) const bool sOWO = options->isSnapOnlyWhenOverlapping(); const QRect maxRect = clientArea(MovementArea, c->rect().center(), c->desktop()); const int xmin = maxRect.left(); const int xmax = maxRect.right(); //desk size const int ymin = maxRect.top(); const int ymax = maxRect.bottom(); const int cx(moveResizeGeom.left()); const int cy(moveResizeGeom.top()); const int rx(moveResizeGeom.right()); const int ry(moveResizeGeom.bottom()); int newcx(cx), newcy(cy); //buffers int newrx(rx), newry(ry); int deltaX(xmax); int deltaY(ymax); //minimum distance to other clients int lx, ly, lrx, lry; //coords and size for the comparison client, l // border snap int snap = options->borderSnapZone(); //snap trigger if (snap) { deltaX = int(snap); deltaY = int(snap); #define SNAP_BORDER_TOP \ if ((sOWO?(newcyymax):true) && (qAbs(ymax-newry)xmax):true) && (qAbs(xmax-newrx)windowSnapZone(); if (snap) { deltaX = int(snap); deltaY = int(snap); for (auto l = m_allClients.constBegin(); l != m_allClients.constEnd(); ++l) { if ((*l)->isOnDesktop(VirtualDesktopManager::self()->current()) && !(*l)->isMinimized() && (*l) != c) { lx = (*l)->x() - 1; ly = (*l)->y() - 1; lrx = (*l)->x() + (*l)->width(); lry = (*l)->y() + (*l)->height(); #define WITHIN_HEIGHT ((( newcy <= lry ) && ( newcy >= ly )) || \ (( newry >= ly ) && ( newry <= lry )) || \ (( newcy <= ly ) && ( newry >= lry )) ) #define WITHIN_WIDTH ( (( cx <= lrx ) && ( cx >= lx )) || \ (( rx >= lx ) && ( rx <= lrx )) || \ (( cx <= lx ) && ( rx >= lrx )) ) #define SNAP_WINDOW_TOP if ( (sOWO?(newcyly):true) \ && WITHIN_WIDTH \ && (qAbs( ly - newry ) < deltaY) ) { \ deltaY = qAbs( ly - newry ); \ newry=ly; \ } #define SNAP_WINDOW_LEFT if ( (sOWO?(newcxlx):true) \ && WITHIN_HEIGHT \ && (qAbs( lx - newrx ) < deltaX)) \ { \ deltaX = qAbs( lx - newrx ); \ newrx=lx; \ } #define SNAP_WINDOW_C_TOP if ( (sOWO?(newcylry):true) \ && (newcx == lrx || newrx == lx) \ && qAbs(lry-newry) < deltaY ) { \ deltaY = qAbs( lry - newry - 1 ); \ newry = lry - 1; \ } #define SNAP_WINDOW_C_LEFT if ( (sOWO?(newcxlrx):true) \ && (newcy == lry || newry == ly) \ && qAbs(lrx-newrx) < deltaX ) { \ deltaX = qAbs( lrx - newrx - 1 ); \ newrx = lrx - 1; \ } switch(mode) { case AbstractClient::PositionBottomRight: SNAP_WINDOW_BOTTOM SNAP_WINDOW_RIGHT SNAP_WINDOW_C_BOTTOM SNAP_WINDOW_C_RIGHT break; case AbstractClient::PositionRight: SNAP_WINDOW_RIGHT SNAP_WINDOW_C_RIGHT break; case AbstractClient::PositionBottom: SNAP_WINDOW_BOTTOM SNAP_WINDOW_C_BOTTOM break; case AbstractClient::PositionTopLeft: SNAP_WINDOW_TOP SNAP_WINDOW_LEFT SNAP_WINDOW_C_TOP SNAP_WINDOW_C_LEFT break; case AbstractClient::PositionLeft: SNAP_WINDOW_LEFT SNAP_WINDOW_C_LEFT break; case AbstractClient::PositionTop: SNAP_WINDOW_TOP SNAP_WINDOW_C_TOP break; case AbstractClient::PositionTopRight: SNAP_WINDOW_TOP SNAP_WINDOW_RIGHT SNAP_WINDOW_C_TOP SNAP_WINDOW_C_RIGHT break; case AbstractClient::PositionBottomLeft: SNAP_WINDOW_BOTTOM SNAP_WINDOW_LEFT SNAP_WINDOW_C_BOTTOM SNAP_WINDOW_C_LEFT break; default: abort(); break; } } } } // center snap //snap = options->centerSnapZone; //if (snap) // { // // Don't resize snap to center as it interferes too much // // There are two ways of implementing this if wanted: // // 1) Snap only to the same points that the move snap does, and // // 2) Snap to the horizontal and vertical center lines of the screen // } moveResizeGeom = QRect(QPoint(newcx, newcy), QPoint(newrx, newry)); } return moveResizeGeom; } /** * Marks the client as being moved or resized by the user. - **/ + */ void Workspace::setMoveResizeClient(AbstractClient *c) { Q_ASSERT(!c || !movingClient); // Catch attempts to move a second // window while still moving the first one. movingClient = c; if (movingClient) ++block_focus; else --block_focus; } // When kwin crashes, windows will not be gravitated back to their original position // and will remain offset by the size of the decoration. So when restarting, fix this // (the property with the size of the frame remains on the window after the crash). void Workspace::fixPositionAfterCrash(xcb_window_t w, const xcb_get_geometry_reply_t *geometry) { NETWinInfo i(connection(), w, rootWindow(), NET::WMFrameExtents, 0); NETStrut frame = i.frameExtents(); if (frame.left != 0 || frame.top != 0) { // left and top needed due to narrowing conversations restrictions in C++11 const uint32_t left = frame.left; const uint32_t top = frame.top; const uint32_t values[] = { geometry->x - left, geometry->y - top }; xcb_configure_window(connection(), w, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, values); } } //******************************************** // Client //******************************************** /** * Returns \a area with the client's strut taken into account. * * Used from Workspace in updateClientArea. - **/ + */ // TODO move to Workspace? QRect Client::adjustedClientArea(const QRect &desktopArea, const QRect& area) const { QRect r = area; NETExtendedStrut str = strut(); QRect stareaL = QRect( 0, str . left_start, str . left_width, str . left_end - str . left_start + 1); QRect stareaR = QRect( desktopArea . right() - str . right_width + 1, str . right_start, str . right_width, str . right_end - str . right_start + 1); QRect stareaT = QRect( str . top_start, 0, str . top_end - str . top_start + 1, str . top_width); QRect stareaB = QRect( str . bottom_start, desktopArea . bottom() - str . bottom_width + 1, str . bottom_end - str . bottom_start + 1, str . bottom_width); QRect screenarea = workspace()->clientArea(ScreenArea, this); // HACK: workarea handling is not xinerama aware, so if this strut // reserves place at a xinerama edge that's inside the virtual screen, // ignore the strut for workspace setting. if (area == QRect(QPoint(0, 0), screens()->displaySize())) { if (stareaL.left() < screenarea.left()) stareaL = QRect(); if (stareaR.right() > screenarea.right()) stareaR = QRect(); if (stareaT.top() < screenarea.top()) stareaT = QRect(); if (stareaB.bottom() < screenarea.bottom()) stareaB = QRect(); } // Handle struts at xinerama edges that are inside the virtual screen. // They're given in virtual screen coordinates, make them affect only // their xinerama screen. stareaL.setLeft(qMax(stareaL.left(), screenarea.left())); stareaR.setRight(qMin(stareaR.right(), screenarea.right())); stareaT.setTop(qMax(stareaT.top(), screenarea.top())); stareaB.setBottom(qMin(stareaB.bottom(), screenarea.bottom())); if (stareaL . intersects(area)) { // qDebug() << "Moving left of: " << r << " to " << stareaL.right() + 1; r . setLeft(stareaL . right() + 1); } if (stareaR . intersects(area)) { // qDebug() << "Moving right of: " << r << " to " << stareaR.left() - 1; r . setRight(stareaR . left() - 1); } if (stareaT . intersects(area)) { // qDebug() << "Moving top of: " << r << " to " << stareaT.bottom() + 1; r . setTop(stareaT . bottom() + 1); } if (stareaB . intersects(area)) { // qDebug() << "Moving bottom of: " << r << " to " << stareaB.top() - 1; r . setBottom(stareaB . top() - 1); } return r; } NETExtendedStrut Client::strut() const { NETExtendedStrut ext = info->extendedStrut(); NETStrut str = info->strut(); const QSize displaySize = screens()->displaySize(); if (ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0 && (str.left != 0 || str.right != 0 || str.top != 0 || str.bottom != 0)) { // build extended from simple if (str.left != 0) { ext.left_width = str.left; ext.left_start = 0; ext.left_end = displaySize.height(); } if (str.right != 0) { ext.right_width = str.right; ext.right_start = 0; ext.right_end = displaySize.height(); } if (str.top != 0) { ext.top_width = str.top; ext.top_start = 0; ext.top_end = displaySize.width(); } if (str.bottom != 0) { ext.bottom_width = str.bottom; ext.bottom_start = 0; ext.bottom_end = displaySize.width(); } } return ext; } StrutRect Client::strutRect(StrutArea area) const { assert(area != StrutAreaAll); // Not valid const QSize displaySize = screens()->displaySize(); NETExtendedStrut strutArea = strut(); switch(area) { case StrutAreaTop: if (strutArea.top_width != 0) return StrutRect(QRect( strutArea.top_start, 0, strutArea.top_end - strutArea.top_start, strutArea.top_width ), StrutAreaTop); break; case StrutAreaRight: if (strutArea.right_width != 0) return StrutRect(QRect( displaySize.width() - strutArea.right_width, strutArea.right_start, strutArea.right_width, strutArea.right_end - strutArea.right_start ), StrutAreaRight); break; case StrutAreaBottom: if (strutArea.bottom_width != 0) return StrutRect(QRect( strutArea.bottom_start, displaySize.height() - strutArea.bottom_width, strutArea.bottom_end - strutArea.bottom_start, strutArea.bottom_width ), StrutAreaBottom); break; case StrutAreaLeft: if (strutArea.left_width != 0) return StrutRect(QRect( 0, strutArea.left_start, strutArea.left_width, strutArea.left_end - strutArea.left_start ), StrutAreaLeft); break; default: abort(); // Not valid } return StrutRect(); // Null rect } StrutRects Client::strutRects() const { StrutRects region; region += strutRect(StrutAreaTop); region += strutRect(StrutAreaRight); region += strutRect(StrutAreaBottom); region += strutRect(StrutAreaLeft); return region; } bool Client::hasStrut() const { NETExtendedStrut ext = strut(); if (ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0) return false; return true; } bool Client::hasOffscreenXineramaStrut() const { // Get strut as a QRegion QRegion region; region += strutRect(StrutAreaTop); region += strutRect(StrutAreaRight); region += strutRect(StrutAreaBottom); region += strutRect(StrutAreaLeft); // Remove all visible areas so that only the invisible remain for (int i = 0; i < screens()->count(); i ++) region -= screens()->geometry(i); // If there's anything left then we have an offscreen strut return !region.isEmpty(); } void AbstractClient::checkWorkspacePosition(QRect oldGeometry, int oldDesktop, QRect oldClientGeometry) { enum { Left = 0, Top, Right, Bottom }; const int border[4] = { borderLeft(), borderTop(), borderRight(), borderBottom() }; if( !oldGeometry.isValid()) oldGeometry = geometry(); if( oldDesktop == -2 ) oldDesktop = desktop(); if (!oldClientGeometry.isValid()) oldClientGeometry = oldGeometry.adjusted(border[Left], border[Top], -border[Right], -border[Bottom]); if (isDesktop()) return; if (isFullScreen()) { QRect area = workspace()->clientArea(FullScreenArea, this); if (geometry() != area) setGeometry(area); return; } if (isDock()) return; if (maximizeMode() != MaximizeRestore) { // TODO update geom_restore? changeMaximize(false, false, true); // adjust size const QRect screenArea = workspace()->clientArea(ScreenArea, this); QRect geom = geometry(); checkOffscreenPosition(&geom, screenArea); setGeometry(geom); return; } if (quickTileMode() != QuickTileMode(QuickTileFlag::None)) { setGeometry(electricBorderMaximizeGeometry(geometry().center(), desktop())); return; } // this can be true only if this window was mapped before KWin // was started - in such case, don't adjust position to workarea, // because the window already had its position, and if a window // with a strut altering the workarea would be managed in initialization // after this one, this window would be moved if (!workspace() || workspace()->initializing()) return; // If the window was touching an edge before but not now move it so it is again. // Old and new maximums have different starting values so windows on the screen // edge will move when a new strut is placed on the edge. QRect oldScreenArea; if( workspace()->inUpdateClientArea()) { // we need to find the screen area as it was before the change oldScreenArea = QRect( 0, 0, workspace()->oldDisplayWidth(), workspace()->oldDisplayHeight()); int distance = INT_MAX; foreach(const QRect &r, workspace()->previousScreenSizes()) { int d = r.contains( oldGeometry.center()) ? 0 : ( r.center() - oldGeometry.center()).manhattanLength(); if( d < distance ) { distance = d; oldScreenArea = r; } } } else { oldScreenArea = workspace()->clientArea(ScreenArea, oldGeometry.center(), oldDesktop); } const QRect oldGeomTall = QRect(oldGeometry.x(), oldScreenArea.y(), oldGeometry.width(), oldScreenArea.height()); // Full screen height const QRect oldGeomWide = QRect(oldScreenArea.x(), oldGeometry.y(), oldScreenArea.width(), oldGeometry.height()); // Full screen width int oldTopMax = oldScreenArea.y(); int oldRightMax = oldScreenArea.x() + oldScreenArea.width(); int oldBottomMax = oldScreenArea.y() + oldScreenArea.height(); int oldLeftMax = oldScreenArea.x(); const QRect screenArea = workspace()->clientArea(ScreenArea, geometryRestore().center(), desktop()); int topMax = screenArea.y(); int rightMax = screenArea.x() + screenArea.width(); int bottomMax = screenArea.y() + screenArea.height(); int leftMax = screenArea.x(); QRect newGeom = geometryRestore(); // geometry(); QRect newClientGeom = newGeom.adjusted(border[Left], border[Top], -border[Right], -border[Bottom]); const QRect newGeomTall = QRect(newGeom.x(), screenArea.y(), newGeom.width(), screenArea.height()); // Full screen height const QRect newGeomWide = QRect(screenArea.x(), newGeom.y(), screenArea.width(), newGeom.height()); // Full screen width // Get the max strut point for each side where the window is (E.g. Highest point for // the bottom struts bounded by the window's left and right sides). // These 4 compute old bounds ... auto moveAreaFunc = workspace()->inUpdateClientArea() ? &Workspace::previousRestrictedMoveArea : //... the restricted areas changed &Workspace::restrictedMoveArea; //... when e.g. active desktop or screen changes for (const QRect &r : (workspace()->*moveAreaFunc)(oldDesktop, StrutAreaTop)) { QRect rect = r & oldGeomTall; if (!rect.isEmpty()) oldTopMax = qMax(oldTopMax, rect.y() + rect.height()); } for (const QRect &r : (workspace()->*moveAreaFunc)(oldDesktop, StrutAreaRight)) { QRect rect = r & oldGeomWide; if (!rect.isEmpty()) oldRightMax = qMin(oldRightMax, rect.x()); } for (const QRect &r : (workspace()->*moveAreaFunc)(oldDesktop, StrutAreaBottom)) { QRect rect = r & oldGeomTall; if (!rect.isEmpty()) oldBottomMax = qMin(oldBottomMax, rect.y()); } for (const QRect &r : (workspace()->*moveAreaFunc)(oldDesktop, StrutAreaLeft)) { QRect rect = r & oldGeomWide; if (!rect.isEmpty()) oldLeftMax = qMax(oldLeftMax, rect.x() + rect.width()); } // These 4 compute new bounds for (const QRect &r : workspace()->restrictedMoveArea(desktop(), StrutAreaTop)) { QRect rect = r & newGeomTall; if (!rect.isEmpty()) topMax = qMax(topMax, rect.y() + rect.height()); } for (const QRect &r : workspace()->restrictedMoveArea(desktop(), StrutAreaRight)) { QRect rect = r & newGeomWide; if (!rect.isEmpty()) rightMax = qMin(rightMax, rect.x()); } for (const QRect &r : workspace()->restrictedMoveArea(desktop(), StrutAreaBottom)) { QRect rect = r & newGeomTall; if (!rect.isEmpty()) bottomMax = qMin(bottomMax, rect.y()); } for (const QRect &r : workspace()->restrictedMoveArea(desktop(), StrutAreaLeft)) { QRect rect = r & newGeomWide; if (!rect.isEmpty()) leftMax = qMax(leftMax, rect.x() + rect.width()); } // Check if the sides were inside or touching but are no longer bool keep[4] = {false, false, false, false}; bool save[4] = {false, false, false, false}; int padding[4] = {0, 0, 0, 0}; if (oldGeometry.x() >= oldLeftMax) save[Left] = newGeom.x() < leftMax; if (oldGeometry.x() == oldLeftMax) keep[Left] = newGeom.x() != leftMax; else if (oldClientGeometry.x() == oldLeftMax && newClientGeom.x() != leftMax) { padding[0] = border[Left]; keep[Left] = true; } if (oldGeometry.y() >= oldTopMax) save[Top] = newGeom.y() < topMax; if (oldGeometry.y() == oldTopMax) keep[Top] = newGeom.y() != topMax; else if (oldClientGeometry.y() == oldTopMax && newClientGeom.y() != topMax) { padding[1] = border[Left]; keep[Top] = true; } if (oldGeometry.right() <= oldRightMax - 1) save[Right] = newGeom.right() > rightMax - 1; if (oldGeometry.right() == oldRightMax - 1) keep[Right] = newGeom.right() != rightMax - 1; else if (oldClientGeometry.right() == oldRightMax - 1 && newClientGeom.right() != rightMax - 1) { padding[2] = border[Right]; keep[Right] = true; } if (oldGeometry.bottom() <= oldBottomMax - 1) save[Bottom] = newGeom.bottom() > bottomMax - 1; if (oldGeometry.bottom() == oldBottomMax - 1) keep[Bottom] = newGeom.bottom() != bottomMax - 1; else if (oldClientGeometry.bottom() == oldBottomMax - 1 && newClientGeom.bottom() != bottomMax - 1) { padding[3] = border[Bottom]; keep[Bottom] = true; } // if randomly touches opposing edges, do not favor either if (keep[Left] && keep[Right]) { keep[Left] = keep[Right] = false; padding[0] = padding[2] = 0; } if (keep[Top] && keep[Bottom]) { keep[Top] = keep[Bottom] = false; padding[1] = padding[3] = 0; } if (save[Left] || keep[Left]) newGeom.moveLeft(qMax(leftMax, screenArea.x()) - padding[0]); if (padding[0] && screens()->intersecting(newGeom) > 1) newGeom.moveLeft(newGeom.left() + padding[0]); if (save[Top] || keep[Top]) newGeom.moveTop(qMax(topMax, screenArea.y()) - padding[1]); if (padding[1] && screens()->intersecting(newGeom) > 1) newGeom.moveTop(newGeom.top() + padding[1]); if (save[Right] || keep[Right]) newGeom.moveRight(qMin(rightMax - 1, screenArea.right()) + padding[2]); if (padding[2] && screens()->intersecting(newGeom) > 1) newGeom.moveRight(newGeom.right() - padding[2]); if (oldGeometry.x() >= oldLeftMax && newGeom.x() < leftMax) newGeom.setLeft(qMax(leftMax, screenArea.x())); else if (oldClientGeometry.x() >= oldLeftMax && newGeom.x() + border[Left] < leftMax) { newGeom.setLeft(qMax(leftMax, screenArea.x()) - border[Left]); if (screens()->intersecting(newGeom) > 1) newGeom.setLeft(newGeom.left() + border[Left]); } if (save[Bottom] || keep[Bottom]) newGeom.moveBottom(qMin(bottomMax - 1, screenArea.bottom()) + padding[3]); if (padding[3] && screens()->intersecting(newGeom) > 1) newGeom.moveBottom(newGeom.bottom() - padding[3]); if (oldGeometry.y() >= oldTopMax && newGeom.y() < topMax) newGeom.setTop(qMax(topMax, screenArea.y())); else if (oldClientGeometry.y() >= oldTopMax && newGeom.y() + border[Top] < topMax) { newGeom.setTop(qMax(topMax, screenArea.y()) - border[Top]); if (screens()->intersecting(newGeom) > 1) newGeom.setTop(newGeom.top() + border[Top]); } checkOffscreenPosition(&newGeom, screenArea); // Obey size hints. TODO: We really should make sure it stays in the right place if (!isShade()) newGeom.setSize(adjustedSize(newGeom.size())); if (newGeom != geometry()) setGeometry(newGeom); } void AbstractClient::checkOffscreenPosition(QRect* geom, const QRect& screenArea) { if (geom->left() > screenArea.right()) { geom->moveLeft(screenArea.right() - screenArea.width()/4); } else if (geom->right() < screenArea.left()) { geom->moveRight(screenArea.left() + screenArea.width()/4); } if (geom->top() > screenArea.bottom()) { geom->moveTop(screenArea.bottom() - screenArea.height()/4); } else if (geom->bottom() < screenArea.top()) { geom->moveBottom(screenArea.top() + screenArea.width()/4); } } QSize AbstractClient::adjustedSize(const QSize& frame, Sizemode mode) const { // first, get the window size for the given frame size s QSize wsize(frame.width() - (borderLeft() + borderRight()), frame.height() - (borderTop() + borderBottom())); if (wsize.isEmpty()) wsize = QSize(qMax(wsize.width(), 1), qMax(wsize.height(), 1)); return sizeForClientSize(wsize, mode, false); } // this helper returns proper size even if the window is shaded // see also the comment in Client::setGeometry() QSize AbstractClient::adjustedSize() const { return sizeForClientSize(clientSize()); } /** * Calculate the appropriate frame size for the given client size \a * wsize. * * \a wsize is adapted according to the window's size hints (minimum, * maximum and incremental size changes). - **/ + */ QSize Client::sizeForClientSize(const QSize& wsize, Sizemode mode, bool noframe) const { int w = wsize.width(); int h = wsize.height(); if (w < 1 || h < 1) { qCWarning(KWIN_CORE) << "sizeForClientSize() with empty size!" ; } if (w < 1) w = 1; if (h < 1) h = 1; // basesize, minsize, maxsize, paspect and resizeinc have all values defined, // even if they're not set in flags - see getWmNormalHints() QSize min_size = tabGroup() ? tabGroup()->minSize() : minSize(); QSize max_size = tabGroup() ? tabGroup()->maxSize() : maxSize(); if (isDecorated()) { QSize decominsize(0, 0); QSize border_size(borderLeft() + borderRight(), borderTop() + borderBottom()); if (border_size.width() > decominsize.width()) // just in case decominsize.setWidth(border_size.width()); if (border_size.height() > decominsize.height()) decominsize.setHeight(border_size.height()); if (decominsize.width() > min_size.width()) min_size.setWidth(decominsize.width()); if (decominsize.height() > min_size.height()) min_size.setHeight(decominsize.height()); } w = qMin(max_size.width(), w); h = qMin(max_size.height(), h); w = qMax(min_size.width(), w); h = qMax(min_size.height(), h); int w1 = w; int h1 = h; int width_inc = m_geometryHints.resizeIncrements().width(); int height_inc = m_geometryHints.resizeIncrements().height(); int basew_inc = m_geometryHints.baseSize().width(); int baseh_inc = m_geometryHints.baseSize().height(); if (!m_geometryHints.hasBaseSize()) { basew_inc = m_geometryHints.minSize().width(); baseh_inc = m_geometryHints.minSize().height(); } w = int((w - basew_inc) / width_inc) * width_inc + basew_inc; h = int((h - baseh_inc) / height_inc) * height_inc + baseh_inc; // code for aspect ratios based on code from FVWM /* * The math looks like this: * * minAspectX dwidth maxAspectX * ---------- <= ------- <= ---------- * minAspectY dheight maxAspectY * * If that is multiplied out, then the width and height are * invalid in the following situations: * * minAspectX * dheight > minAspectY * dwidth * maxAspectX * dheight < maxAspectY * dwidth * */ if (m_geometryHints.hasAspect()) { double min_aspect_w = m_geometryHints.minAspect().width(); // use doubles, because the values can be MAX_INT double min_aspect_h = m_geometryHints.minAspect().height(); // and multiplying would go wrong otherwise double max_aspect_w = m_geometryHints.maxAspect().width(); double max_aspect_h = m_geometryHints.maxAspect().height(); // According to ICCCM 4.1.2.3 PMinSize should be a fallback for PBaseSize for size increments, // but not for aspect ratio. Since this code comes from FVWM, handles both at the same time, // and I have no idea how it works, let's hope nobody relies on that. const QSize baseSize = m_geometryHints.baseSize(); w -= baseSize.width(); h -= baseSize.height(); int max_width = max_size.width() - baseSize.width(); int min_width = min_size.width() - baseSize.width(); int max_height = max_size.height() - baseSize.height(); int min_height = min_size.height() - baseSize.height(); #define ASPECT_CHECK_GROW_W \ if ( min_aspect_w * h > min_aspect_h * w ) \ { \ int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ if ( w + delta <= max_width ) \ w += delta; \ } #define ASPECT_CHECK_SHRINK_H_GROW_W \ if ( min_aspect_w * h > min_aspect_h * w ) \ { \ int delta = int( h - w * min_aspect_h / min_aspect_w ) / height_inc * height_inc; \ if ( h - delta >= min_height ) \ h -= delta; \ else \ { \ int delta = int( min_aspect_w * h / min_aspect_h - w ) / width_inc * width_inc; \ if ( w + delta <= max_width ) \ w += delta; \ } \ } #define ASPECT_CHECK_GROW_H \ if ( max_aspect_w * h < max_aspect_h * w ) \ { \ int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ if ( h + delta <= max_height ) \ h += delta; \ } #define ASPECT_CHECK_SHRINK_W_GROW_H \ if ( max_aspect_w * h < max_aspect_h * w ) \ { \ int delta = int( w - max_aspect_w * h / max_aspect_h ) / width_inc * width_inc; \ if ( w - delta >= min_width ) \ w -= delta; \ else \ { \ int delta = int( w * max_aspect_h / max_aspect_w - h ) / height_inc * height_inc; \ if ( h + delta <= max_height ) \ h += delta; \ } \ } switch(mode) { case SizemodeAny: #if 0 // make SizemodeAny equal to SizemodeFixedW - prefer keeping fixed width, // so that changing aspect ratio to a different value and back keeps the same size (#87298) { ASPECT_CHECK_SHRINK_H_GROW_W ASPECT_CHECK_SHRINK_W_GROW_H ASPECT_CHECK_GROW_H ASPECT_CHECK_GROW_W break; } #endif case SizemodeFixedW: { // the checks are order so that attempts to modify height are first ASPECT_CHECK_GROW_H ASPECT_CHECK_SHRINK_H_GROW_W ASPECT_CHECK_SHRINK_W_GROW_H ASPECT_CHECK_GROW_W break; } case SizemodeFixedH: { ASPECT_CHECK_GROW_W ASPECT_CHECK_SHRINK_W_GROW_H ASPECT_CHECK_SHRINK_H_GROW_W ASPECT_CHECK_GROW_H break; } case SizemodeMax: { // first checks that try to shrink ASPECT_CHECK_SHRINK_H_GROW_W ASPECT_CHECK_SHRINK_W_GROW_H ASPECT_CHECK_GROW_W ASPECT_CHECK_GROW_H break; } } #undef ASPECT_CHECK_SHRINK_H_GROW_W #undef ASPECT_CHECK_SHRINK_W_GROW_H #undef ASPECT_CHECK_GROW_W #undef ASPECT_CHECK_GROW_H w += baseSize.width(); h += baseSize.height(); } if (!rules()->checkStrictGeometry(!isFullScreen())) { // disobey increments and aspect by explicit rule w = w1; h = h1; } if (!noframe) { w += borderLeft() + borderRight(); h += borderTop() + borderBottom(); } return rules()->checkSize(QSize(w, h)); } /** * Gets the client's normal WM hints and reconfigures itself respectively. - **/ + */ void Client::getWmNormalHints() { const bool hadFixedAspect = m_geometryHints.hasAspect(); // roundtrip to X server m_geometryHints.fetch(); m_geometryHints.read(); if (!hadFixedAspect && m_geometryHints.hasAspect()) { // align to eventual new contraints maximize(max_mode); } // Update min/max size of this group if (tabGroup()) tabGroup()->updateMinMaxSize(); if (isManaged()) { // update to match restrictions QSize new_size = adjustedSize(); if (new_size != size() && !isFullScreen()) { QRect origClientGeometry(pos() + clientPos(), clientSize()); resizeWithChecks(new_size); if ((!isSpecialWindow() || isToolbar()) && !isFullScreen()) { // try to keep the window in its xinerama screen if possible, // if that fails at least keep it visible somewhere QRect area = workspace()->clientArea(MovementArea, this); if (area.contains(origClientGeometry)) keepInArea(area); area = workspace()->clientArea(WorkArea, this); if (area.contains(origClientGeometry)) keepInArea(area); } } } updateAllowedActions(); // affects isResizeable() } QSize Client::minSize() const { return rules()->checkMinSize(m_geometryHints.minSize()); } QSize Client::maxSize() const { return rules()->checkMaxSize(m_geometryHints.maxSize()); } QSize Client::basicUnit() const { return m_geometryHints.resizeIncrements(); } /** * Auxiliary function to inform the client about the current window * configuration. - **/ + */ void Client::sendSyntheticConfigureNotify() { xcb_configure_notify_event_t c; memset(&c, 0, sizeof(c)); c.response_type = XCB_CONFIGURE_NOTIFY; c.event = window(); c.window = window(); c.x = x() + clientPos().x(); c.y = y() + clientPos().y(); c.width = clientSize().width(); c.height = clientSize().height(); c.border_width = 0; c.above_sibling = XCB_WINDOW_NONE; c.override_redirect = 0; xcb_send_event(connection(), true, c.event, XCB_EVENT_MASK_STRUCTURE_NOTIFY, reinterpret_cast(&c)); xcb_flush(connection()); } const QPoint Client::calculateGravitation(bool invert, int gravity) const { int dx, dy; dx = dy = 0; if (gravity == 0) // default (nonsense) value for the argument gravity = m_geometryHints.windowGravity(); // dx, dy specify how the client window moves to make space for the frame switch(gravity) { case NorthWestGravity: // move down right default: dx = borderLeft(); dy = borderTop(); break; case NorthGravity: // move right dx = 0; dy = borderTop(); break; case NorthEastGravity: // move down left dx = -borderRight(); dy = borderTop(); break; case WestGravity: // move right dx = borderLeft(); dy = 0; break; case CenterGravity: break; // will be handled specially case StaticGravity: // don't move dx = 0; dy = 0; break; case EastGravity: // move left dx = -borderRight(); dy = 0; break; case SouthWestGravity: // move up right dx = borderLeft() ; dy = -borderBottom(); break; case SouthGravity: // move up dx = 0; dy = -borderBottom(); break; case SouthEastGravity: // move up left dx = -borderRight(); dy = -borderBottom(); break; } if (gravity != CenterGravity) { // translate from client movement to frame movement dx -= borderLeft(); dy -= borderTop(); } else { // center of the frame will be at the same position client center without frame would be dx = - (borderLeft() + borderRight()) / 2; dy = - (borderTop() + borderBottom()) / 2; } if (!invert) return QPoint(x() + dx, y() + dy); else return QPoint(x() - dx, y() - dy); } void Client::configureRequest(int value_mask, int rx, int ry, int rw, int rh, int gravity, bool from_tool) { // "maximized" is a user setting -> we do not allow the client to resize itself // away from this & against the users explicit wish qCDebug(KWIN_CORE) << this << bool(value_mask & (CWX|CWWidth|CWY|CWHeight)) << bool(maximizeMode() & MaximizeVertical) << bool(maximizeMode() & MaximizeHorizontal); // we want to (partially) ignore the request when the window is somehow maximized or quicktiled bool ignore = !app_noborder && (quickTileMode() != QuickTileMode(QuickTileFlag::None) || maximizeMode() != MaximizeRestore); // however, the user shall be able to force obedience despite and also disobedience in general ignore = rules()->checkIgnoreGeometry(ignore); if (!ignore) { // either we're not max'd / q'tiled or the user allowed the client to break that - so break it. updateQuickTileMode(QuickTileFlag::None); max_mode = MaximizeRestore; emit quickTileModeChanged(); } else if (!app_noborder && quickTileMode() == QuickTileMode(QuickTileFlag::None) && (maximizeMode() == MaximizeVertical || maximizeMode() == MaximizeHorizontal)) { // ignoring can be, because either we do, or the user does explicitly not want it. // for partially maximized windows we want to allow configures in the other dimension. // so we've to ask the user again - to know whether we just ignored for the partial maximization. // the problem here is, that the user can explicitly permit configure requests - even for maximized windows! // we cannot distinguish that from passing "false" for partially maximized windows. ignore = rules()->checkIgnoreGeometry(false); if (!ignore) { // the user is not interested, so we fix up dimensions if (maximizeMode() == MaximizeVertical) value_mask &= ~(CWY|CWHeight); if (maximizeMode() == MaximizeHorizontal) value_mask &= ~(CWX|CWWidth); if (!(value_mask & (CWX|CWWidth|CWY|CWHeight))) { ignore = true; // the modification turned the request void } } } if (ignore) { qCDebug(KWIN_CORE) << "DENIED"; return; // nothing to (left) to do for use - bugs #158974, #252314, #321491 } qCDebug(KWIN_CORE) << "PERMITTED" << this << bool(value_mask & (CWX|CWWidth|CWY|CWHeight)); if (gravity == 0) // default (nonsense) value for the argument gravity = m_geometryHints.windowGravity(); if (value_mask & (CWX | CWY)) { QPoint new_pos = calculateGravitation(true, gravity); // undo gravitation if (value_mask & CWX) new_pos.setX(rx); if (value_mask & CWY) new_pos.setY(ry); // clever(?) workaround for applications like xv that want to set // the location to the current location but miscalculate the // frame size due to kwin being a double-reparenting window // manager if (new_pos.x() == x() + clientPos().x() && new_pos.y() == y() + clientPos().y() && gravity == NorthWestGravity && !from_tool) { new_pos.setX(x()); new_pos.setY(y()); } int nw = clientSize().width(); int nh = clientSize().height(); if (value_mask & CWWidth) nw = rw; if (value_mask & CWHeight) nh = rh; QSize ns = sizeForClientSize(QSize(nw, nh)); // enforces size if needed new_pos = rules()->checkPosition(new_pos); int newScreen = screens()->number(QRect(new_pos, ns).center()); if (newScreen != rules()->checkScreen(newScreen)) return; // not allowed by rule QRect origClientGeometry(pos() + clientPos(), clientSize()); GeometryUpdatesBlocker blocker(this); move(new_pos); plainResize(ns); setGeometry(QRect(calculateGravitation(false, gravity), size())); QRect area = workspace()->clientArea(WorkArea, this); if (!from_tool && (!isSpecialWindow() || isToolbar()) && !isFullScreen() && area.contains(origClientGeometry)) keepInArea(area); // this is part of the kicker-xinerama-hack... it should be // safe to remove when kicker gets proper ExtendedStrut support; // see Workspace::updateClientArea() and // Client::adjustedClientArea() if (hasStrut()) workspace() -> updateClientArea(); } if (value_mask & (CWWidth | CWHeight) && !(value_mask & (CWX | CWY))) { // pure resize int nw = clientSize().width(); int nh = clientSize().height(); if (value_mask & CWWidth) nw = rw; if (value_mask & CWHeight) nh = rh; QSize ns = sizeForClientSize(QSize(nw, nh)); if (ns != size()) { // don't restore if some app sets its own size again QRect origClientGeometry(pos() + clientPos(), clientSize()); GeometryUpdatesBlocker blocker(this); resizeWithChecks(ns, xcb_gravity_t(gravity)); if (!from_tool && (!isSpecialWindow() || isToolbar()) && !isFullScreen()) { // try to keep the window in its xinerama screen if possible, // if that fails at least keep it visible somewhere QRect area = workspace()->clientArea(MovementArea, this); if (area.contains(origClientGeometry)) keepInArea(area); area = workspace()->clientArea(WorkArea, this); if (area.contains(origClientGeometry)) keepInArea(area); } } } geom_restore = geometry(); // No need to send synthetic configure notify event here, either it's sent together // with geometry change, or there's no need to send it. // Handling of the real ConfigureRequest event forces sending it, as there it's necessary. } void Client::resizeWithChecks(int w, int h, xcb_gravity_t gravity, ForceGeometry_t force) { assert(!shade_geometry_change); if (isShade()) { if (h == borderTop() + borderBottom()) { qCWarning(KWIN_CORE) << "Shaded geometry passed for size:" ; } } int newx = x(); int newy = y(); QRect area = workspace()->clientArea(WorkArea, this); // don't allow growing larger than workarea if (w > area.width()) w = area.width(); if (h > area.height()) h = area.height(); QSize tmp = adjustedSize(QSize(w, h)); // checks size constraints, including min/max size w = tmp.width(); h = tmp.height(); if (gravity == 0) { gravity = m_geometryHints.windowGravity(); } switch(gravity) { case NorthWestGravity: // top left corner doesn't move default: break; case NorthGravity: // middle of top border doesn't move newx = (newx + width() / 2) - (w / 2); break; case NorthEastGravity: // top right corner doesn't move newx = newx + width() - w; break; case WestGravity: // middle of left border doesn't move newy = (newy + height() / 2) - (h / 2); break; case CenterGravity: // middle point doesn't move newx = (newx + width() / 2) - (w / 2); newy = (newy + height() / 2) - (h / 2); break; case StaticGravity: // top left corner of _client_ window doesn't move // since decoration doesn't change, equal to NorthWestGravity break; case EastGravity: // // middle of right border doesn't move newx = newx + width() - w; newy = (newy + height() / 2) - (h / 2); break; case SouthWestGravity: // bottom left corner doesn't move newy = newy + height() - h; break; case SouthGravity: // middle of bottom border doesn't move newx = (newx + width() / 2) - (w / 2); newy = newy + height() - h; break; case SouthEastGravity: // bottom right corner doesn't move newx = newx + width() - w; newy = newy + height() - h; break; } setGeometry(newx, newy, w, h, force); } // _NET_MOVERESIZE_WINDOW void Client::NETMoveResizeWindow(int flags, int x, int y, int width, int height) { int gravity = flags & 0xff; int value_mask = 0; if (flags & (1 << 8)) value_mask |= CWX; if (flags & (1 << 9)) value_mask |= CWY; if (flags & (1 << 10)) value_mask |= CWWidth; if (flags & (1 << 11)) value_mask |= CWHeight; configureRequest(value_mask, x, y, width, height, gravity, true); } bool Client::isMovable() const { if (!hasNETSupport() && !m_motif.move()) { return false; } if (isFullScreen()) return false; if (isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) return false; if (rules()->checkPosition(invalidPoint) != invalidPoint) // forced position return false; return true; } bool Client::isMovableAcrossScreens() const { if (!hasNETSupport() && !m_motif.move()) { return false; } if (isSpecialWindow() && !isSplash() && !isToolbar()) // allow moving of splashscreens :) return false; if (rules()->checkPosition(invalidPoint) != invalidPoint) // forced position return false; return true; } bool Client::isResizable() const { if (!hasNETSupport() && !m_motif.resize()) { return false; } if (isFullScreen()) return false; if (isSpecialWindow() || isSplash() || isToolbar()) return false; if (rules()->checkSize(QSize()).isValid()) // forced size return false; const Position mode = moveResizePointerMode(); if ((mode == PositionTop || mode == PositionTopLeft || mode == PositionTopRight || mode == PositionLeft || mode == PositionBottomLeft) && rules()->checkPosition(invalidPoint) != invalidPoint) return false; QSize min = tabGroup() ? tabGroup()->minSize() : minSize(); QSize max = tabGroup() ? tabGroup()->maxSize() : maxSize(); return min.width() < max.width() || min.height() < max.height(); } bool Client::isMaximizable() const { if (!isResizable() || isToolbar()) // SELI isToolbar() ? return false; if (rules()->checkMaximize(MaximizeRestore) == MaximizeRestore && rules()->checkMaximize(MaximizeFull) != MaximizeRestore) return true; return false; } /** * Reimplemented to inform the client about the new window position. - **/ + */ void Client::setGeometry(int x, int y, int w, int h, ForceGeometry_t force) { // this code is also duplicated in Client::plainResize() // Ok, the shading geometry stuff. Generally, code doesn't care about shaded geometry, // simply because there are too many places dealing with geometry. Those places // ignore shaded state and use normal geometry, which they usually should get // from adjustedSize(). Such geometry comes here, and if the window is shaded, // the geometry is used only for client_size, since that one is not used when // shading. Then the frame geometry is adjusted for the shaded geometry. // This gets more complicated in the case the code does only something like // setGeometry( geometry()) - geometry() will return the shaded frame geometry. // Such code is wrong and should be changed to handle the case when the window is shaded, // for example using Client::clientSize() if (shade_geometry_change) ; // nothing else if (isShade()) { if (h == borderTop() + borderBottom()) { qCDebug(KWIN_CORE) << "Shaded geometry passed for size:"; } else { client_size = QSize(w - borderLeft() - borderRight(), h - borderTop() - borderBottom()); h = borderTop() + borderBottom(); } } else { client_size = QSize(w - borderLeft() - borderRight(), h - borderTop() - borderBottom()); } QRect g(x, y, w, h); if (!areGeometryUpdatesBlocked() && g != rules()->checkGeometry(g)) { qCDebug(KWIN_CORE) << "forced geometry fail:" << g << ":" << rules()->checkGeometry(g); } if (force == NormalGeometrySet && geom == g && pendingGeometryUpdate() == PendingGeometryNone) return; geom = g; if (areGeometryUpdatesBlocked()) { if (pendingGeometryUpdate() == PendingGeometryForced) {} // maximum, nothing needed else if (force == ForceGeometrySet) setPendingGeometryUpdate(PendingGeometryForced); else setPendingGeometryUpdate(PendingGeometryNormal); return; } QSize oldClientSize = m_frame.geometry().size(); bool resized = (geometryBeforeUpdateBlocking().size() != geom.size() || pendingGeometryUpdate() == PendingGeometryForced); if (resized) { resizeDecoration(); m_frame.setGeometry(x, y, w, h); if (!isShade()) { QSize cs = clientSize(); m_wrapper.setGeometry(QRect(clientPos(), cs)); if (!isResize() || syncRequest.counter == XCB_NONE) m_client.setGeometry(0, 0, cs.width(), cs.height()); // SELI - won't this be too expensive? // THOMAS - yes, but gtk+ clients will not resize without ... sendSyntheticConfigureNotify(); } updateShape(); } else { if (isMoveResize()) { if (compositing()) // Defer the X update until we leave this mode needsXWindowMove = true; else m_frame.move(x, y); // sendSyntheticConfigureNotify() on finish shall be sufficient } else { m_frame.move(x, y); sendSyntheticConfigureNotify(); } // Unconditionally move the input window: it won't affect rendering m_decoInputExtent.move(QPoint(x, y) + inputPos()); } updateWindowRules(Rules::Position|Rules::Size); // keep track of old maximize mode // to detect changes screens()->setCurrent(this); workspace()->updateStackingOrder(); // need to regenerate decoration pixmaps when either // - size is changed // - maximize mode is changed to MaximizeRestore, when size unchanged // which can happen when untabbing maximized windows if (resized) { if (oldClientSize != QSize(w,h)) discardWindowPixmap(); } emit geometryShapeChanged(this, geometryBeforeUpdateBlocking()); addRepaintDuringGeometryUpdates(); updateGeometryBeforeUpdateBlocking(); // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Geometry); // TODO: this signal is emitted too often emit geometryChanged(); } void Client::plainResize(int w, int h, ForceGeometry_t force) { // this code is also duplicated in Client::setGeometry(), and it's also commented there if (shade_geometry_change) ; // nothing else if (isShade()) { if (h == borderTop() + borderBottom()) { qCDebug(KWIN_CORE) << "Shaded geometry passed for size:"; } else { client_size = QSize(w - borderLeft() - borderRight(), h - borderTop() - borderBottom()); h = borderTop() + borderBottom(); } } else { client_size = QSize(w - borderLeft() - borderRight(), h - borderTop() - borderBottom()); } QSize s(w, h); if (!areGeometryUpdatesBlocked() && s != rules()->checkSize(s)) { qCDebug(KWIN_CORE) << "forced size fail:" << s << ":" << rules()->checkSize(s); } // resuming geometry updates is handled only in setGeometry() assert(pendingGeometryUpdate() == PendingGeometryNone || areGeometryUpdatesBlocked()); if (force == NormalGeometrySet && geom.size() == s) return; geom.setSize(s); if (areGeometryUpdatesBlocked()) { if (pendingGeometryUpdate() == PendingGeometryForced) {} // maximum, nothing needed else if (force == ForceGeometrySet) setPendingGeometryUpdate(PendingGeometryForced); else setPendingGeometryUpdate(PendingGeometryNormal); return; } QSize oldClientSize = m_frame.geometry().size(); resizeDecoration(); m_frame.resize(w, h); // resizeDecoration( s ); if (!isShade()) { QSize cs = clientSize(); m_wrapper.setGeometry(QRect(clientPos(), cs)); m_client.setGeometry(0, 0, cs.width(), cs.height()); } updateShape(); sendSyntheticConfigureNotify(); updateWindowRules(Rules::Position|Rules::Size); screens()->setCurrent(this); workspace()->updateStackingOrder(); if (oldClientSize != QSize(w,h)) discardWindowPixmap(); emit geometryShapeChanged(this, geometryBeforeUpdateBlocking()); addRepaintDuringGeometryUpdates(); updateGeometryBeforeUpdateBlocking(); // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Geometry); // TODO: this signal is emitted too often emit geometryChanged(); } /** * Reimplemented to inform the client about the new window position. - **/ + */ void AbstractClient::move(int x, int y, ForceGeometry_t force) { // resuming geometry updates is handled only in setGeometry() assert(pendingGeometryUpdate() == PendingGeometryNone || areGeometryUpdatesBlocked()); QPoint p(x, y); if (!areGeometryUpdatesBlocked() && p != rules()->checkPosition(p)) { qCDebug(KWIN_CORE) << "forced position fail:" << p << ":" << rules()->checkPosition(p); } if (force == NormalGeometrySet && geom.topLeft() == p) return; geom.moveTopLeft(p); if (areGeometryUpdatesBlocked()) { if (pendingGeometryUpdate() == PendingGeometryForced) {} // maximum, nothing needed else if (force == ForceGeometrySet) setPendingGeometryUpdate(PendingGeometryForced); else setPendingGeometryUpdate(PendingGeometryNormal); return; } doMove(x, y); updateWindowRules(Rules::Position); screens()->setCurrent(this); workspace()->updateStackingOrder(); // client itself is not damaged addRepaintDuringGeometryUpdates(); updateGeometryBeforeUpdateBlocking(); // Update states of all other windows in this group updateTabGroupStates(TabGroup::Geometry); emit geometryChanged(); } void Client::doMove(int x, int y) { m_frame.move(x, y); sendSyntheticConfigureNotify(); } void AbstractClient::blockGeometryUpdates(bool block) { if (block) { if (m_blockGeometryUpdates == 0) m_pendingGeometryUpdate = PendingGeometryNone; ++m_blockGeometryUpdates; } else { if (--m_blockGeometryUpdates == 0) { if (m_pendingGeometryUpdate != PendingGeometryNone) { if (isShade()) setGeometry(QRect(pos(), adjustedSize()), NormalGeometrySet); else setGeometry(geometry(), NormalGeometrySet); m_pendingGeometryUpdate = PendingGeometryNone; } } } } void AbstractClient::maximize(MaximizeMode m) { setMaximize(m & MaximizeVertical, m & MaximizeHorizontal); } void AbstractClient::setMaximize(bool vertically, bool horizontally) { // changeMaximize() flips the state, so change from set->flip const MaximizeMode oldMode = maximizeMode(); changeMaximize( oldMode & MaximizeHorizontal ? !horizontally : horizontally, oldMode & MaximizeVertical ? !vertically : vertically, false); const MaximizeMode newMode = maximizeMode(); if (oldMode != newMode) { emit clientMaximizedStateChanged(this, newMode); emit clientMaximizedStateChanged(this, vertically, horizontally); } } // Update states of all other windows in this group class TabSynchronizer { public: TabSynchronizer(AbstractClient *client, TabGroup::States syncStates) : m_client(client) , m_states(syncStates) { if (client->tabGroup()) client->tabGroup()->blockStateUpdates(true); } ~TabSynchronizer() { syncNow(); } void syncNow() { if (m_client && m_client->tabGroup()) { m_client->tabGroup()->blockStateUpdates(false); m_client->tabGroup()->updateStates(dynamic_cast(m_client), m_states); } m_client = 0; } private: AbstractClient *m_client; TabGroup::States m_states; }; static bool changeMaximizeRecursion = false; void Client::changeMaximize(bool horizontal, bool vertical, bool adjust) { if (changeMaximizeRecursion) return; if (!isResizable() || isToolbar()) // SELI isToolbar() ? return; QRect clientArea; if (isElectricBorderMaximizing()) clientArea = workspace()->clientArea(MaximizeArea, Cursor::pos(), desktop()); else clientArea = workspace()->clientArea(MaximizeArea, this); MaximizeMode old_mode = max_mode; // 'adjust == true' means to update the size only, e.g. after changing workspace size if (!adjust) { if (vertical) max_mode = MaximizeMode(max_mode ^ MaximizeVertical); if (horizontal) max_mode = MaximizeMode(max_mode ^ MaximizeHorizontal); } // if the client insist on a fix aspect ratio, we check whether the maximizing will get us // out of screen bounds and take that as a "full maximization with aspect check" then if (m_geometryHints.hasAspect() && // fixed aspect (max_mode == MaximizeVertical || max_mode == MaximizeHorizontal) && // ondimensional maximization rules()->checkStrictGeometry(true)) { // obey aspect const QSize minAspect = m_geometryHints.minAspect(); const QSize maxAspect = m_geometryHints.maxAspect(); if (max_mode == MaximizeVertical || (old_mode & MaximizeVertical)) { const double fx = minAspect.width(); // use doubles, because the values can be MAX_INT const double fy = maxAspect.height(); // use doubles, because the values can be MAX_INT if (fx*clientArea.height()/fy > clientArea.width()) // too big max_mode = old_mode & MaximizeHorizontal ? MaximizeRestore : MaximizeFull; } else { // max_mode == MaximizeHorizontal const double fx = maxAspect.width(); const double fy = minAspect.height(); if (fy*clientArea.width()/fx > clientArea.height()) // too big max_mode = old_mode & MaximizeVertical ? MaximizeRestore : MaximizeFull; } } max_mode = rules()->checkMaximize(max_mode); if (!adjust && max_mode == old_mode) return; GeometryUpdatesBlocker blocker(this); // QT synchronizing required because we eventually change from QT to Maximized TabSynchronizer syncer(this, TabGroup::Maximized|TabGroup::QuickTile); // maximing one way and unmaximizing the other way shouldn't happen, // so restore first and then maximize the other way if ((old_mode == MaximizeVertical && max_mode == MaximizeHorizontal) || (old_mode == MaximizeHorizontal && max_mode == MaximizeVertical)) { changeMaximize(false, false, false); // restore } // save sizes for restoring, if maximalizing QSize sz; if (isShade()) sz = sizeForClientSize(clientSize()); else sz = size(); if (quickTileMode() == QuickTileMode(QuickTileFlag::None)) { if (!adjust && !(old_mode & MaximizeVertical)) { geom_restore.setTop(y()); geom_restore.setHeight(sz.height()); } if (!adjust && !(old_mode & MaximizeHorizontal)) { geom_restore.setLeft(x()); geom_restore.setWidth(sz.width()); } } // call into decoration update borders if (isDecorated() && decoration()->client() && !(options->borderlessMaximizedWindows() && max_mode == KWin::MaximizeFull)) { changeMaximizeRecursion = true; const auto c = decoration()->client().data(); if ((max_mode & MaximizeVertical) != (old_mode & MaximizeVertical)) { emit c->maximizedVerticallyChanged(max_mode & MaximizeVertical); } if ((max_mode & MaximizeHorizontal) != (old_mode & MaximizeHorizontal)) { emit c->maximizedHorizontallyChanged(max_mode & MaximizeHorizontal); } if ((max_mode == MaximizeFull) != (old_mode == MaximizeFull)) { emit c->maximizedChanged(max_mode & MaximizeFull); } changeMaximizeRecursion = false; } if (options->borderlessMaximizedWindows()) { // triggers a maximize change. // The next setNoBorder interation will exit since there's no change but the first recursion pullutes the restore geometry changeMaximizeRecursion = true; setNoBorder(rules()->checkNoBorder(app_noborder || (m_motif.hasDecoration() && m_motif.noBorder()) || max_mode == MaximizeFull)); changeMaximizeRecursion = false; } const ForceGeometry_t geom_mode = isDecorated() ? ForceGeometrySet : NormalGeometrySet; // Conditional quick tiling exit points if (quickTileMode() != QuickTileMode(QuickTileFlag::None)) { if (old_mode == MaximizeFull && !clientArea.contains(geom_restore.center())) { // Not restoring on the same screen // TODO: The following doesn't work for some reason //quick_tile_mode = QuickTileFlag::None; // And exit quick tile mode manually } else if ((old_mode == MaximizeVertical && max_mode == MaximizeRestore) || (old_mode == MaximizeFull && max_mode == MaximizeHorizontal)) { // Modifying geometry of a tiled window updateQuickTileMode(QuickTileFlag::None); // Exit quick tile mode without restoring geometry } } switch(max_mode) { case MaximizeVertical: { if (old_mode & MaximizeHorizontal) { // actually restoring from MaximizeFull if (geom_restore.width() == 0 || !clientArea.contains(geom_restore.center())) { // needs placement plainResize(adjustedSize(QSize(width() * 2 / 3, clientArea.height()), SizemodeFixedH), geom_mode); Placement::self()->placeSmart(this, clientArea); } else { setGeometry(QRect(QPoint(geom_restore.x(), clientArea.top()), adjustedSize(QSize(geom_restore.width(), clientArea.height()), SizemodeFixedH)), geom_mode); } } else { QRect r(x(), clientArea.top(), width(), clientArea.height()); r.setTopLeft(rules()->checkPosition(r.topLeft())); r.setSize(adjustedSize(r.size(), SizemodeFixedH)); setGeometry(r, geom_mode); } info->setState(NET::MaxVert, NET::Max); break; } case MaximizeHorizontal: { if (old_mode & MaximizeVertical) { // actually restoring from MaximizeFull if (geom_restore.height() == 0 || !clientArea.contains(geom_restore.center())) { // needs placement plainResize(adjustedSize(QSize(clientArea.width(), height() * 2 / 3), SizemodeFixedW), geom_mode); Placement::self()->placeSmart(this, clientArea); } else { setGeometry(QRect(QPoint(clientArea.left(), geom_restore.y()), adjustedSize(QSize(clientArea.width(), geom_restore.height()), SizemodeFixedW)), geom_mode); } } else { QRect r(clientArea.left(), y(), clientArea.width(), height()); r.setTopLeft(rules()->checkPosition(r.topLeft())); r.setSize(adjustedSize(r.size(), SizemodeFixedW)); setGeometry(r, geom_mode); } info->setState(NET::MaxHoriz, NET::Max); break; } case MaximizeRestore: { QRect restore = geometry(); // when only partially maximized, geom_restore may not have the other dimension remembered if (old_mode & MaximizeVertical) { restore.setTop(geom_restore.top()); restore.setBottom(geom_restore.bottom()); } if (old_mode & MaximizeHorizontal) { restore.setLeft(geom_restore.left()); restore.setRight(geom_restore.right()); } if (!restore.isValid()) { QSize s = QSize(clientArea.width() * 2 / 3, clientArea.height() * 2 / 3); if (geom_restore.width() > 0) s.setWidth(geom_restore.width()); if (geom_restore.height() > 0) s.setHeight(geom_restore.height()); plainResize(adjustedSize(s)); Placement::self()->placeSmart(this, clientArea); restore = geometry(); if (geom_restore.width() > 0) restore.moveLeft(geom_restore.x()); if (geom_restore.height() > 0) restore.moveTop(geom_restore.y()); geom_restore = restore; // relevant for mouse pos calculation, bug #298646 } if (m_geometryHints.hasAspect()) { restore.setSize(adjustedSize(restore.size(), SizemodeAny)); } setGeometry(restore, geom_mode); if (!clientArea.contains(geom_restore.center())) // Not restoring to the same screen Placement::self()->place(this, clientArea); info->setState(0, NET::Max); updateQuickTileMode(QuickTileFlag::None); break; } case MaximizeFull: { QRect r(clientArea); r.setTopLeft(rules()->checkPosition(r.topLeft())); r.setSize(adjustedSize(r.size(), SizemodeMax)); if (r.size() != clientArea.size()) { // to avoid off-by-one errors... if (isElectricBorderMaximizing() && r.width() < clientArea.width()) { r.moveLeft(qMax(clientArea.left(), Cursor::pos().x() - r.width()/2)); r.moveRight(qMin(clientArea.right(), r.right())); } else { r.moveCenter(clientArea.center()); const bool closeHeight = r.height() > 97*clientArea.height()/100; const bool closeWidth = r.width() > 97*clientArea.width() /100; const bool overHeight = r.height() > clientArea.height(); const bool overWidth = r.width() > clientArea.width(); if (closeWidth || closeHeight) { Position titlePos = titlebarPosition(); const QRect screenArea = workspace()->clientArea(ScreenArea, clientArea.center(), desktop()); if (closeHeight) { bool tryBottom = titlePos == PositionBottom; if ((overHeight && titlePos == PositionTop) || screenArea.top() == clientArea.top()) r.setTop(clientArea.top()); else tryBottom = true; if (tryBottom && (overHeight || screenArea.bottom() == clientArea.bottom())) r.setBottom(clientArea.bottom()); } if (closeWidth) { bool tryLeft = titlePos == PositionLeft; if ((overWidth && titlePos == PositionRight) || screenArea.right() == clientArea.right()) r.setRight(clientArea.right()); else tryLeft = true; if (tryLeft && (overWidth || screenArea.left() == clientArea.left())) r.setLeft(clientArea.left()); } } } r.moveTopLeft(rules()->checkPosition(r.topLeft())); } setGeometry(r, geom_mode); if (options->electricBorderMaximize() && r.top() == clientArea.top()) updateQuickTileMode(QuickTileFlag::Maximize); else updateQuickTileMode(QuickTileFlag::None); info->setState(NET::Max, NET::Max); break; } default: break; } syncer.syncNow(); // important because of window rule updates! updateAllowedActions(); updateWindowRules(Rules::MaximizeVert|Rules::MaximizeHoriz|Rules::Position|Rules::Size); emit quickTileModeChanged(); } bool Client::userCanSetFullScreen() const { if (!isFullScreenable()) { return false; } return isNormalWindow() || isDialog(); } void Client::setFullScreen(bool set, bool user) { set = rules()->checkFullScreen(set); const bool wasFullscreen = isFullScreen(); if (wasFullscreen == set) { return; } if (user && !userCanSetFullScreen()) { return; } setShade(ShadeNone); if (wasFullscreen) { workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event } else { geom_fs_restore = geometry(); } if (set) { m_fullscreenMode = FullScreenNormal; untab(); workspace()->raiseClient(this); } else { m_fullscreenMode = FullScreenNone; } StackingUpdatesBlocker blocker1(workspace()); GeometryUpdatesBlocker blocker2(this); // active fullscreens get different layer workspace()->updateClientLayer(this); info->setState(isFullScreen() ? NET::FullScreen : NET::States(0), NET::FullScreen); updateDecoration(false, false); if (set) { if (info->fullscreenMonitors().isSet()) { setGeometry(fullscreenMonitorsArea(info->fullscreenMonitors())); } else { setGeometry(workspace()->clientArea(FullScreenArea, this)); } } else { Q_ASSERT(!geom_fs_restore.isNull()); const int currentScreen = screen(); setGeometry(QRect(geom_fs_restore.topLeft(), adjustedSize(geom_fs_restore.size()))); if(currentScreen != screen()) { workspace()->sendClientToScreen(this, currentScreen); } } updateWindowRules(Rules::Fullscreen | Rules::Position | Rules::Size); emit clientFullScreenSet(this, set, user); emit fullScreenChanged(); } void Client::updateFullscreenMonitors(NETFullscreenMonitors topology) { int nscreens = screens()->count(); // qDebug() << "incoming request with top: " << topology.top << " bottom: " << topology.bottom // << " left: " << topology.left << " right: " << topology.right // << ", we have: " << nscreens << " screens."; if (topology.top >= nscreens || topology.bottom >= nscreens || topology.left >= nscreens || topology.right >= nscreens) { qCWarning(KWIN_CORE) << "fullscreenMonitors update failed. request higher than number of screens."; return; } info->setFullscreenMonitors(topology); if (isFullScreen()) setGeometry(fullscreenMonitorsArea(topology)); } /** * Calculates the bounding rectangle defined by the 4 monitor indices indicating the * top, bottom, left, and right edges of the window when the fullscreen state is enabled. - **/ + */ QRect Client::fullscreenMonitorsArea(NETFullscreenMonitors requestedTopology) const { QRect top, bottom, left, right, total; top = screens()->geometry(requestedTopology.top); bottom = screens()->geometry(requestedTopology.bottom); left = screens()->geometry(requestedTopology.left); right = screens()->geometry(requestedTopology.right); total = top.united(bottom.united(left.united(right))); // qDebug() << "top: " << top << " bottom: " << bottom // << " left: " << left << " right: " << right; // qDebug() << "returning rect: " << total; return total; } static GeometryTip* geometryTip = 0; void Client::positionGeometryTip() { assert(isMove() || isResize()); // Position and Size display if (effects && static_cast(effects)->provides(Effect::GeometryTip)) return; // some effect paints this for us if (options->showGeometryTip()) { if (!geometryTip) { geometryTip = new GeometryTip(&m_geometryHints); } QRect wgeom(moveResizeGeometry()); // position of the frame, size of the window itself wgeom.setWidth(wgeom.width() - (width() - clientSize().width())); wgeom.setHeight(wgeom.height() - (height() - clientSize().height())); if (isShade()) wgeom.setHeight(0); geometryTip->setGeometry(wgeom); if (!geometryTip->isVisible()) geometryTip->show(); geometryTip->raise(); } } bool AbstractClient::startMoveResize() { assert(!isMoveResize()); assert(QWidget::keyboardGrabber() == NULL); assert(QWidget::mouseGrabber() == NULL); stopDelayedMoveResize(); if (QApplication::activePopupWidget() != NULL) return false; // popups have grab if (isFullScreen() && (screens()->count() < 2 || !isMovableAcrossScreens())) return false; if (!doStartMoveResize()) { return false; } invalidateDecorationDoubleClickTimer(); setMoveResize(true); workspace()->setMoveResizeClient(this); const Position mode = moveResizePointerMode(); if (mode != PositionCenter) { // means "isResize()" but moveResizeMode = true is set below if (maximizeMode() == MaximizeFull) { // partial is cond. reset in finishMoveResize setGeometryRestore(geometry()); // "restore" to current geometry setMaximize(false, false); } } if (quickTileMode() != QuickTileMode(QuickTileFlag::None) && mode != PositionCenter) { // Cannot use isResize() yet // Exit quick tile mode when the user attempts to resize a tiled window updateQuickTileMode(QuickTileFlag::None); // Do so without restoring original geometry setGeometryRestore(geometry()); emit quickTileModeChanged(); } updateHaveResizeEffect(); updateInitialMoveResizeGeometry(); checkUnrestrictedMoveResize(); emit clientStartUserMovedResized(this); if (ScreenEdges::self()->isDesktopSwitchingMovingClients()) ScreenEdges::self()->reserveDesktopSwitching(true, Qt::Vertical|Qt::Horizontal); return true; } bool Client::doStartMoveResize() { bool has_grab = false; // This reportedly improves smoothness of the moveresize operation, // something with Enter/LeaveNotify events, looks like XFree performance problem or something *shrug* // (https://lists.kde.org/?t=107302193400001&r=1&w=2) QRect r = workspace()->clientArea(FullArea, this); m_moveResizeGrabWindow.create(r, XCB_WINDOW_CLASS_INPUT_ONLY, 0, NULL, rootWindow()); m_moveResizeGrabWindow.map(); m_moveResizeGrabWindow.raise(); updateXTime(); const xcb_grab_pointer_cookie_t cookie = xcb_grab_pointer_unchecked(connection(), false, m_moveResizeGrabWindow, XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION | XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_LEAVE_WINDOW, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, m_moveResizeGrabWindow, Cursor::x11Cursor(cursor()), xTime()); ScopedCPointer pointerGrab(xcb_grab_pointer_reply(connection(), cookie, NULL)); if (!pointerGrab.isNull() && pointerGrab->status == XCB_GRAB_STATUS_SUCCESS) { has_grab = true; } if (!has_grab && grabXKeyboard(frameId())) has_grab = move_resize_has_keyboard_grab = true; if (!has_grab) { // at least one grab is necessary in order to be able to finish move/resize m_moveResizeGrabWindow.reset(); return false; } return true; } void AbstractClient::finishMoveResize(bool cancel) { GeometryUpdatesBlocker blocker(this); const bool wasResize = isResize(); // store across leaveMoveResize leaveMoveResize(); if (cancel) setGeometry(initialMoveResizeGeometry()); else { const QRect &moveResizeGeom = moveResizeGeometry(); if (wasResize) { const bool restoreH = maximizeMode() == MaximizeHorizontal && moveResizeGeom.width() != initialMoveResizeGeometry().width(); const bool restoreV = maximizeMode() == MaximizeVertical && moveResizeGeom.height() != initialMoveResizeGeometry().height(); if (restoreH || restoreV) { changeMaximize(restoreV, restoreH, false); } } setGeometry(moveResizeGeom); } checkScreen(); // needs to be done because clientFinishUserMovedResized has not yet re-activated online alignment if (screen() != moveResizeStartScreen()) { workspace()->sendClientToScreen(this, screen()); // checks rule validity if (maximizeMode() != MaximizeRestore) checkWorkspacePosition(); } if (isElectricBorderMaximizing()) { setQuickTileMode(electricBorderMode()); setElectricBorderMaximizing(false); } else if (!cancel) { QRect geom_restore = geometryRestore(); if (!(maximizeMode() & MaximizeHorizontal)) { geom_restore.setX(geometry().x()); geom_restore.setWidth(geometry().width()); } if (!(maximizeMode() & MaximizeVertical)) { geom_restore.setY(geometry().y()); geom_restore.setHeight(geometry().height()); } setGeometryRestore(geom_restore); } // FRAME update(); emit clientFinishUserMovedResized(this); } void Client::leaveMoveResize() { if (needsXWindowMove) { // Do the deferred move m_frame.move(geom.topLeft()); needsXWindowMove = false; } if (!isResize()) sendSyntheticConfigureNotify(); // tell the client about it's new final position if (geometryTip) { geometryTip->hide(); delete geometryTip; geometryTip = NULL; } if (move_resize_has_keyboard_grab) ungrabXKeyboard(); move_resize_has_keyboard_grab = false; xcb_ungrab_pointer(connection(), xTime()); m_moveResizeGrabWindow.reset(); if (syncRequest.counter == XCB_NONE) // don't forget to sanitize since the timeout will no more fire syncRequest.isPending = false; delete syncRequest.timeout; syncRequest.timeout = NULL; AbstractClient::leaveMoveResize(); } // This function checks if it actually makes sense to perform a restricted move/resize. // If e.g. the titlebar is already outside of the workarea, there's no point in performing // a restricted move resize, because then e.g. resize would also move the window (#74555). // NOTE: Most of it is duplicated from handleMoveResize(). void AbstractClient::checkUnrestrictedMoveResize() { if (isUnrestrictedMoveResize()) return; const QRect &moveResizeGeom = moveResizeGeometry(); QRect desktopArea = workspace()->clientArea(WorkArea, moveResizeGeom.center(), desktop()); int left_marge, right_marge, top_marge, bottom_marge, titlebar_marge; // restricted move/resize - keep at least part of the titlebar always visible // how much must remain visible when moved away in that direction left_marge = qMin(100 + borderRight(), moveResizeGeom.width()); right_marge = qMin(100 + borderLeft(), moveResizeGeom.width()); // width/height change with opaque resizing, use the initial ones titlebar_marge = initialMoveResizeGeometry().height(); top_marge = borderBottom(); bottom_marge = borderTop(); if (isResize()) { if (moveResizeGeom.bottom() < desktopArea.top() + top_marge) setUnrestrictedMoveResize(true); if (moveResizeGeom.top() > desktopArea.bottom() - bottom_marge) setUnrestrictedMoveResize(true); if (moveResizeGeom.right() < desktopArea.left() + left_marge) setUnrestrictedMoveResize(true); if (moveResizeGeom.left() > desktopArea.right() - right_marge) setUnrestrictedMoveResize(true); if (!isUnrestrictedMoveResize() && moveResizeGeom.top() < desktopArea.top()) // titlebar mustn't go out setUnrestrictedMoveResize(true); } if (isMove()) { if (moveResizeGeom.bottom() < desktopArea.top() + titlebar_marge - 1) setUnrestrictedMoveResize(true); // no need to check top_marge, titlebar_marge already handles it if (moveResizeGeom.top() > desktopArea.bottom() - bottom_marge + 1) // titlebar mustn't go out setUnrestrictedMoveResize(true); if (moveResizeGeom.right() < desktopArea.left() + left_marge) setUnrestrictedMoveResize(true); if (moveResizeGeom.left() > desktopArea.right() - right_marge) setUnrestrictedMoveResize(true); } } // When the user pressed mouse on the titlebar, don't activate move immediatelly, // since it may be just a click. Activate instead after a delay. Move used to be // activated only after moving by several pixels, but that looks bad. void AbstractClient::startDelayedMoveResize() { Q_ASSERT(!m_moveResize.delayedTimer); m_moveResize.delayedTimer = new QTimer(this); m_moveResize.delayedTimer->setSingleShot(true); connect(m_moveResize.delayedTimer, &QTimer::timeout, this, [this]() { assert(isMoveResizePointerButtonDown()); if (!startMoveResize()) { setMoveResizePointerButtonDown(false); } updateCursor(); stopDelayedMoveResize(); } ); m_moveResize.delayedTimer->start(QApplication::startDragTime()); } void AbstractClient::stopDelayedMoveResize() { delete m_moveResize.delayedTimer; m_moveResize.delayedTimer = nullptr; } void AbstractClient::handleMoveResize(const QPoint &local, const QPoint &global) { const QRect oldGeo = geometry(); handleMoveResize(local.x(), local.y(), global.x(), global.y()); if (!isFullScreen() && isMove()) { if (quickTileMode() != QuickTileMode(QuickTileFlag::None) && oldGeo != geometry()) { GeometryUpdatesBlocker blocker(this); setQuickTileMode(QuickTileFlag::None); const QRect &geom_restore = geometryRestore(); setMoveOffset(QPoint(double(moveOffset().x()) / double(oldGeo.width()) * double(geom_restore.width()), double(moveOffset().y()) / double(oldGeo.height()) * double(geom_restore.height()))); if (rules()->checkMaximize(MaximizeRestore) == MaximizeRestore) setMoveResizeGeometry(geom_restore); handleMoveResize(local.x(), local.y(), global.x(), global.y()); // fix position } else if (quickTileMode() == QuickTileMode(QuickTileFlag::None) && isResizable()) { checkQuickTilingMaximizationZones(global.x(), global.y()); } } } bool Client::isWaitingForMoveResizeSync() const { return syncRequest.isPending && isResize(); } void AbstractClient::handleMoveResize(int x, int y, int x_root, int y_root) { if (isWaitingForMoveResizeSync()) return; // we're still waiting for the client or the timeout const Position mode = moveResizePointerMode(); if ((mode == PositionCenter && !isMovableAcrossScreens()) || (mode != PositionCenter && (isShade() || !isResizable()))) return; if (!isMoveResize()) { QPoint p(QPoint(x/* - padding_left*/, y/* - padding_top*/) - moveOffset()); if (p.manhattanLength() >= QApplication::startDragDistance()) { if (!startMoveResize()) { setMoveResizePointerButtonDown(false); updateCursor(); return; } updateCursor(); } else return; } // ShadeHover or ShadeActive, ShadeNormal was already avoided above if (mode != PositionCenter && shadeMode() != ShadeNone) setShade(ShadeNone); QPoint globalPos(x_root, y_root); // these two points limit the geometry rectangle, i.e. if bottomleft resizing is done, // the bottomleft corner should be at is at (topleft.x(), bottomright().y()) QPoint topleft = globalPos - moveOffset(); QPoint bottomright = globalPos + invertedMoveOffset(); QRect previousMoveResizeGeom = moveResizeGeometry(); // TODO move whole group when moving its leader or when the leader is not mapped? auto titleBarRect = [this](bool &transposed, int &requiredPixels) -> QRect { const QRect &moveResizeGeom = moveResizeGeometry(); QRect r(moveResizeGeom); r.moveTopLeft(QPoint(0,0)); switch (titlebarPosition()) { default: case PositionTop: r.setHeight(borderTop()); break; case PositionLeft: r.setWidth(borderLeft()); transposed = true; break; case PositionBottom: r.setTop(r.bottom() - borderBottom()); break; case PositionRight: r.setLeft(r.right() - borderRight()); transposed = true; break; } // When doing a restricted move we must always keep 100px of the titlebar // visible to allow the user to be able to move it again. requiredPixels = qMin(100 * (transposed ? r.width() : r.height()), moveResizeGeom.width() * moveResizeGeom.height()); return r; }; bool update = false; if (isResize()) { QRect orig = initialMoveResizeGeometry(); Sizemode sizemode = SizemodeAny; auto calculateMoveResizeGeom = [this, &topleft, &bottomright, &orig, &sizemode, &mode]() { switch(mode) { case PositionTopLeft: setMoveResizeGeometry(QRect(topleft, orig.bottomRight())); break; case PositionBottomRight: setMoveResizeGeometry(QRect(orig.topLeft(), bottomright)); break; case PositionBottomLeft: setMoveResizeGeometry(QRect(QPoint(topleft.x(), orig.y()), QPoint(orig.right(), bottomright.y()))); break; case PositionTopRight: setMoveResizeGeometry(QRect(QPoint(orig.x(), topleft.y()), QPoint(bottomright.x(), orig.bottom()))); break; case PositionTop: setMoveResizeGeometry(QRect(QPoint(orig.left(), topleft.y()), orig.bottomRight())); sizemode = SizemodeFixedH; // try not to affect height break; case PositionBottom: setMoveResizeGeometry(QRect(orig.topLeft(), QPoint(orig.right(), bottomright.y()))); sizemode = SizemodeFixedH; break; case PositionLeft: setMoveResizeGeometry(QRect(QPoint(topleft.x(), orig.top()), orig.bottomRight())); sizemode = SizemodeFixedW; break; case PositionRight: setMoveResizeGeometry(QRect(orig.topLeft(), QPoint(bottomright.x(), orig.bottom()))); sizemode = SizemodeFixedW; break; case PositionCenter: default: abort(); break; } }; // first resize (without checking constrains), then snap, then check bounds, then check constrains calculateMoveResizeGeom(); // adjust new size to snap to other windows/borders setMoveResizeGeometry(workspace()->adjustClientSize(this, moveResizeGeometry(), mode)); if (!isUnrestrictedMoveResize()) { // Make sure the titlebar isn't behind a restricted area. We don't need to restrict // the other directions. If not visible enough, move the window to the closest valid // point. We bruteforce this by slowly moving the window back to its previous position QRegion availableArea(workspace()->clientArea(FullArea, -1, 0)); // On the screen availableArea -= workspace()->restrictedMoveArea(desktop()); // Strut areas bool transposed = false; int requiredPixels; QRect bTitleRect = titleBarRect(transposed, requiredPixels); int lastVisiblePixels = -1; QRect lastTry = moveResizeGeometry(); bool titleFailed = false; for (;;) { const QRect titleRect(bTitleRect.translated(moveResizeGeometry().topLeft())); int visiblePixels = 0; int realVisiblePixels = 0; for (const QRect &rect : availableArea) { const QRect r = rect & titleRect; realVisiblePixels += r.width() * r.height(); if ((transposed && r.width() == titleRect.width()) || // Only the full size regions... (!transposed && r.height() == titleRect.height())) // ...prevents long slim areas visiblePixels += r.width() * r.height(); } if (visiblePixels >= requiredPixels) break; // We have reached a valid position if (realVisiblePixels <= lastVisiblePixels) { if (titleFailed && realVisiblePixels < lastVisiblePixels) break; // we won't become better else { if (!titleFailed) setMoveResizeGeometry(lastTry); titleFailed = true; } } lastVisiblePixels = realVisiblePixels; QRect moveResizeGeom = moveResizeGeometry(); lastTry = moveResizeGeom; // Not visible enough, move the window to the closest valid point. We bruteforce // this by slowly moving the window back to its previous position. // The geometry changes at up to two edges, the one with the title (if) shall take // precedence. The opposing edge has no impact on visiblePixels and only one of // the adjacent can alter at a time, ie. it's enough to ignore adjacent edges // if the title edge altered bool leftChanged = previousMoveResizeGeom.left() != moveResizeGeom.left(); bool rightChanged = previousMoveResizeGeom.right() != moveResizeGeom.right(); bool topChanged = previousMoveResizeGeom.top() != moveResizeGeom.top(); bool btmChanged = previousMoveResizeGeom.bottom() != moveResizeGeom.bottom(); auto fixChangedState = [titleFailed](bool &major, bool &counter, bool &ad1, bool &ad2) { counter = false; if (titleFailed) major = false; if (major) ad1 = ad2 = false; }; switch (titlebarPosition()) { default: case PositionTop: fixChangedState(topChanged, btmChanged, leftChanged, rightChanged); break; case PositionLeft: fixChangedState(leftChanged, rightChanged, topChanged, btmChanged); break; case PositionBottom: fixChangedState(btmChanged, topChanged, leftChanged, rightChanged); break; case PositionRight: fixChangedState(rightChanged, leftChanged, topChanged, btmChanged); break; } if (topChanged) moveResizeGeom.setTop(moveResizeGeom.y() + sign(previousMoveResizeGeom.y() - moveResizeGeom.y())); else if (leftChanged) moveResizeGeom.setLeft(moveResizeGeom.x() + sign(previousMoveResizeGeom.x() - moveResizeGeom.x())); else if (btmChanged) moveResizeGeom.setBottom(moveResizeGeom.bottom() + sign(previousMoveResizeGeom.bottom() - moveResizeGeom.bottom())); else if (rightChanged) moveResizeGeom.setRight(moveResizeGeom.right() + sign(previousMoveResizeGeom.right() - moveResizeGeom.right())); else break; // no position changed - that's certainly not good setMoveResizeGeometry(moveResizeGeom); } } // Always obey size hints, even when in "unrestricted" mode QSize size = adjustedSize(moveResizeGeometry().size(), sizemode); // the new topleft and bottomright corners (after checking size constrains), if they'll be needed topleft = QPoint(moveResizeGeometry().right() - size.width() + 1, moveResizeGeometry().bottom() - size.height() + 1); bottomright = QPoint(moveResizeGeometry().left() + size.width() - 1, moveResizeGeometry().top() + size.height() - 1); orig = moveResizeGeometry(); // if aspect ratios are specified, both dimensions may change. // Therefore grow to the right/bottom if needed. // TODO it should probably obey gravity rather than always using right/bottom ? if (sizemode == SizemodeFixedH) orig.setRight(bottomright.x()); else if (sizemode == SizemodeFixedW) orig.setBottom(bottomright.y()); calculateMoveResizeGeom(); if (moveResizeGeometry().size() != previousMoveResizeGeom.size()) update = true; } else if (isMove()) { assert(mode == PositionCenter); if (!isMovable()) { // isMovableAcrossScreens() must have been true to get here // Special moving of maximized windows on Xinerama screens int screen = screens()->number(globalPos); if (isFullScreen()) setMoveResizeGeometry(workspace()->clientArea(FullScreenArea, screen, 0)); else { QRect moveResizeGeom = workspace()->clientArea(MaximizeArea, screen, 0); QSize adjSize = adjustedSize(moveResizeGeom.size(), SizemodeMax); if (adjSize != moveResizeGeom.size()) { QRect r(moveResizeGeom); moveResizeGeom.setSize(adjSize); moveResizeGeom.moveCenter(r.center()); } setMoveResizeGeometry(moveResizeGeom); } } else { // first move, then snap, then check bounds QRect moveResizeGeom = moveResizeGeometry(); moveResizeGeom.moveTopLeft(topleft); moveResizeGeom.moveTopLeft(workspace()->adjustClientPosition(this, moveResizeGeom.topLeft(), isUnrestrictedMoveResize())); setMoveResizeGeometry(moveResizeGeom); if (!isUnrestrictedMoveResize()) { const QRegion strut = workspace()->restrictedMoveArea(desktop()); // Strut areas QRegion availableArea(workspace()->clientArea(FullArea, -1, 0)); // On the screen availableArea -= strut; // Strut areas bool transposed = false; int requiredPixels; QRect bTitleRect = titleBarRect(transposed, requiredPixels); for (;;) { QRect moveResizeGeom = moveResizeGeometry(); const QRect titleRect(bTitleRect.translated(moveResizeGeom.topLeft())); int visiblePixels = 0; for (const QRect &rect : availableArea) { const QRect r = rect & titleRect; if ((transposed && r.width() == titleRect.width()) || // Only the full size regions... (!transposed && r.height() == titleRect.height())) // ...prevents long slim areas visiblePixels += r.width() * r.height(); } if (visiblePixels >= requiredPixels) break; // We have reached a valid position // (esp.) if there're more screens with different struts (panels) it the titlebar // will be movable outside the movearea (covering one of the panels) until it // crosses the panel "too much" (not enough visiblePixels) and then stucks because // it's usually only pushed by 1px to either direction // so we first check whether we intersect suc strut and move the window below it // immediately (it's still possible to hit the visiblePixels >= titlebarArea break // by moving the window slightly downwards, but it won't stuck) // see bug #274466 // and bug #301805 for why we can't just match the titlearea against the screen if (screens()->count() > 1) { // optimization // TODO: could be useful on partial screen struts (half-width panels etc.) int newTitleTop = -1; for (const QRect &r : strut) { if (r.top() == 0 && r.width() > r.height() && // "top panel" r.intersects(moveResizeGeom) && moveResizeGeom.top() < r.bottom()) { newTitleTop = r.bottom() + 1; break; } } if (newTitleTop > -1) { moveResizeGeom.moveTop(newTitleTop); // invalid position, possibly on screen change setMoveResizeGeometry(moveResizeGeom); break; } } int dx = sign(previousMoveResizeGeom.x() - moveResizeGeom.x()), dy = sign(previousMoveResizeGeom.y() - moveResizeGeom.y()); if (visiblePixels && dx) // means there's no full width cap -> favor horizontally dy = 0; else if (dy) dx = 0; // Move it back moveResizeGeom.translate(dx, dy); setMoveResizeGeometry(moveResizeGeom); if (moveResizeGeom == previousMoveResizeGeom) { break; // Prevent lockup } } } } if (moveResizeGeometry().topLeft() != previousMoveResizeGeom.topLeft()) update = true; } else abort(); if (!update) return; if (isResize() && !haveResizeEffect()) { doResizeSync(); } else performMoveResize(); if (isMove()) { ScreenEdges::self()->check(globalPos, QDateTime::fromMSecsSinceEpoch(xTime())); } } void Client::doResizeSync() { if (!syncRequest.timeout) { syncRequest.timeout = new QTimer(this); connect(syncRequest.timeout, &QTimer::timeout, this, &Client::performMoveResize); syncRequest.timeout->setSingleShot(true); } if (syncRequest.counter != XCB_NONE) { syncRequest.timeout->start(250); sendSyncRequest(); } else { // for clients not supporting the XSYNC protocol, we syncRequest.isPending = true; // limit the resizes to 30Hz to take pointless load from X11 syncRequest.timeout->start(33); // and the client, the mouse is still moved at full speed } // and no human can control faster resizes anyway const QRect &moveResizeGeom = moveResizeGeometry(); m_client.setGeometry(0, 0, moveResizeGeom.width() - (borderLeft() + borderRight()), moveResizeGeom.height() - (borderTop() + borderBottom())); } void AbstractClient::performMoveResize() { const QRect &moveResizeGeom = moveResizeGeometry(); if (isMove() || (isResize() && !haveResizeEffect())) { setGeometry(moveResizeGeom); } doPerformMoveResize(); if (isResize()) addRepaintFull(); positionGeometryTip(); emit clientStepUserMovedResized(this, moveResizeGeom); } void Client::doPerformMoveResize() { if (syncRequest.counter == XCB_NONE) // client w/o XSYNC support. allow the next resize event syncRequest.isPending = false; // NEVER do this for clients with a valid counter // (leads to sync request races in some clients) } void AbstractClient::setElectricBorderMode(QuickTileMode mode) { if (mode != QuickTileMode(QuickTileFlag::Maximize)) { // sanitize the mode, ie. simplify "invalid" combinations if ((mode & QuickTileFlag::Horizontal) == QuickTileMode(QuickTileFlag::Horizontal)) mode &= ~QuickTileMode(QuickTileFlag::Horizontal); if ((mode & QuickTileFlag::Vertical) == QuickTileMode(QuickTileFlag::Vertical)) mode &= ~QuickTileMode(QuickTileFlag::Vertical); } m_electricMode = mode; } void AbstractClient::setElectricBorderMaximizing(bool maximizing) { m_electricMaximizing = maximizing; if (maximizing) outline()->show(electricBorderMaximizeGeometry(Cursor::pos(), desktop()), moveResizeGeometry()); else outline()->hide(); elevate(maximizing); } QRect AbstractClient::electricBorderMaximizeGeometry(QPoint pos, int desktop) { if (electricBorderMode() == QuickTileMode(QuickTileFlag::Maximize)) { if (maximizeMode() == MaximizeFull) return geometryRestore(); else return workspace()->clientArea(MaximizeArea, pos, desktop); } QRect ret = workspace()->clientArea(MaximizeArea, pos, desktop); if (electricBorderMode() & QuickTileFlag::Left) ret.setRight(ret.left()+ret.width()/2 - 1); else if (electricBorderMode() & QuickTileFlag::Right) ret.setLeft(ret.right()-(ret.width()-ret.width()/2) + 1); if (electricBorderMode() & QuickTileFlag::Top) ret.setBottom(ret.top()+ret.height()/2 - 1); else if (electricBorderMode() & QuickTileFlag::Bottom) ret.setTop(ret.bottom()-(ret.height()-ret.height()/2) + 1); return ret; } void AbstractClient::setQuickTileMode(QuickTileMode mode, bool keyboard) { // Only allow quick tile on a regular or maximized window if (!isResizable() && maximizeMode() != MaximizeFull) return; workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event GeometryUpdatesBlocker blocker(this); if (mode == QuickTileMode(QuickTileFlag::Maximize)) { TabSynchronizer syncer(this, TabGroup::QuickTile|TabGroup::Geometry|TabGroup::Maximized); m_quickTileMode = int(QuickTileFlag::None); if (maximizeMode() == MaximizeFull) { setMaximize(false, false); } else { QRect prev_geom_restore = geometryRestore(); // setMaximize() would set moveResizeGeom as geom_restore m_quickTileMode = int(QuickTileFlag::Maximize); setMaximize(true, true); QRect clientArea = workspace()->clientArea(MaximizeArea, this); if (geometry().top() != clientArea.top()) { QRect r(geometry()); r.moveTop(clientArea.top()); setGeometry(r); } setGeometryRestore(prev_geom_restore); } emit quickTileModeChanged(); return; } // sanitize the mode, ie. simplify "invalid" combinations if ((mode & QuickTileFlag::Horizontal) == QuickTileMode(QuickTileFlag::Horizontal)) mode &= ~QuickTileMode(QuickTileFlag::Horizontal); if ((mode & QuickTileFlag::Vertical) == QuickTileMode(QuickTileFlag::Vertical)) mode &= ~QuickTileMode(QuickTileFlag::Vertical); setElectricBorderMode(mode); // used by ::electricBorderMaximizeGeometry(.) // restore from maximized so that it is possible to tile maximized windows with one hit or by dragging if (maximizeMode() != MaximizeRestore) { TabSynchronizer syncer(this, TabGroup::QuickTile|TabGroup::Geometry|TabGroup::Maximized); if (mode != QuickTileMode(QuickTileFlag::None)) { // decorations may turn off some borders when tiled const ForceGeometry_t geom_mode = isDecorated() ? ForceGeometrySet : NormalGeometrySet; m_quickTileMode = int(QuickTileFlag::None); // Temporary, so the maximize code doesn't get all confused setMaximize(false, false); setGeometry(electricBorderMaximizeGeometry(keyboard ? geometry().center() : Cursor::pos(), desktop()), geom_mode); // Store the mode change m_quickTileMode = mode; } else { m_quickTileMode = mode; setMaximize(false, false); } emit quickTileModeChanged(); return; } if (mode != QuickTileMode(QuickTileFlag::None)) { TabSynchronizer syncer(this, TabGroup::QuickTile|TabGroup::Geometry); QPoint whichScreen = keyboard ? geometry().center() : Cursor::pos(); // If trying to tile to the side that the window is already tiled to move the window to the next // screen if it exists, otherwise toggle the mode (set QuickTileFlag::None) if (quickTileMode() == mode) { const int numScreens = screens()->count(); const int curScreen = screen(); int nextScreen = curScreen; QVarLengthArray screens(numScreens); for (int i = 0; i < numScreens; ++i) // Cache screens[i] = Screens::self()->geometry(i); for (int i = 0; i < numScreens; ++i) { if (i == curScreen) continue; if (screens[i].bottom() <= screens[curScreen].top() || screens[i].top() >= screens[curScreen].bottom()) continue; // not in horizontal line const int x = screens[i].center().x(); if ((mode & QuickTileFlag::Horizontal) == QuickTileMode(QuickTileFlag::Left)) { if (x >= screens[curScreen].center().x() || (curScreen != nextScreen && x <= screens[nextScreen].center().x())) continue; // not left of current or more left then found next } else if ((mode & QuickTileFlag::Horizontal) == QuickTileMode(QuickTileFlag::Right)) { if (x <= screens[curScreen].center().x() || (curScreen != nextScreen && x >= screens[nextScreen].center().x())) continue; // not right of current or more right then found next } nextScreen = i; } if (nextScreen == curScreen) { mode = QuickTileFlag::None; // No other screens, toggle tiling } else { // Move to other screen setGeometry(geometryRestore().translated(screens[nextScreen].topLeft() - screens[curScreen].topLeft())); whichScreen = screens[nextScreen].center(); // Swap sides if (mode & QuickTileFlag::Horizontal) { mode = (~mode & QuickTileFlag::Horizontal) | (mode & QuickTileFlag::Vertical); } } setElectricBorderMode(mode); // used by ::electricBorderMaximizeGeometry(.) } else if (quickTileMode() == QuickTileMode(QuickTileFlag::None)) { // Not coming out of an existing tile, not shifting monitors, we're setting a brand new tile. // Store geometry first, so we can go out of this tile later. setGeometryRestore(geometry()); } if (mode != QuickTileMode(QuickTileFlag::None)) { m_quickTileMode = mode; // decorations may turn off some borders when tiled const ForceGeometry_t geom_mode = isDecorated() ? ForceGeometrySet : NormalGeometrySet; // Temporary, so the maximize code doesn't get all confused m_quickTileMode = int(QuickTileFlag::None); setGeometry(electricBorderMaximizeGeometry(whichScreen, desktop()), geom_mode); } // Store the mode change m_quickTileMode = mode; } if (mode == QuickTileMode(QuickTileFlag::None)) { TabSynchronizer syncer(this, TabGroup::QuickTile|TabGroup::Geometry); m_quickTileMode = int(QuickTileFlag::None); // Untiling, so just restore geometry, and we're done. if (!geometryRestore().isValid()) // invalid if we started maximized and wait for placement setGeometryRestore(geometry()); // decorations may turn off some borders when tiled const ForceGeometry_t geom_mode = isDecorated() ? ForceGeometrySet : NormalGeometrySet; setGeometry(geometryRestore(), geom_mode); checkWorkspacePosition(); // Just in case it's a different screen } emit quickTileModeChanged(); } void AbstractClient::sendToScreen(int newScreen) { newScreen = rules()->checkScreen(newScreen); if (isActive()) { screens()->setCurrent(newScreen); // might impact the layer of a fullscreen window foreach (AbstractClient *cc, workspace()->allClientList()) { if (cc->isFullScreen() && cc->screen() == newScreen) { cc->updateLayer(); } } } if (screen() == newScreen) // Don't use isOnScreen(), that's true even when only partially return; GeometryUpdatesBlocker blocker(this); // operating on the maximized / quicktiled window would leave the old geom_restore behind, // so we clear the state first MaximizeMode maxMode = maximizeMode(); QuickTileMode qtMode = quickTileMode(); if (maxMode != MaximizeRestore) maximize(MaximizeRestore); if (qtMode != QuickTileMode(QuickTileFlag::None)) setQuickTileMode(QuickTileFlag::None, true); QRect oldScreenArea = workspace()->clientArea(MaximizeArea, this); QRect screenArea = workspace()->clientArea(MaximizeArea, newScreen, desktop()); // the window can have its center so that the position correction moves the new center onto // the old screen, what will tile it where it is. Ie. the screen is not changed // this happens esp. with electric border quicktiling if (qtMode != QuickTileMode(QuickTileFlag::None)) keepInArea(oldScreenArea); QRect oldGeom = geometry(); QRect newGeom = oldGeom; // move the window to have the same relative position to the center of the screen // (i.e. one near the middle of the right edge will also end up near the middle of the right edge) QPoint center = newGeom.center() - oldScreenArea.center(); center.setX(center.x() * screenArea.width() / oldScreenArea.width()); center.setY(center.y() * screenArea.height() / oldScreenArea.height()); center += screenArea.center(); newGeom.moveCenter(center); setGeometry(newGeom); // If the window was inside the old screen area, explicitly make sure its inside also the new screen area. // Calling checkWorkspacePosition() should ensure that, but when moving to a small screen the window could // be big enough to overlap outside of the new screen area, making struts from other screens come into effect, // which could alter the resulting geometry. if (oldScreenArea.contains(oldGeom)) { keepInArea(screenArea); } // align geom_restore - checkWorkspacePosition operates on it setGeometryRestore(geometry()); checkWorkspacePosition(oldGeom); // re-align geom_restore to constrained geometry setGeometryRestore(geometry()); // finally reset special states // NOTICE that MaximizeRestore/QuickTileFlag::None checks are required. // eg. setting QuickTileFlag::None would break maximization if (maxMode != MaximizeRestore) maximize(maxMode); if (qtMode != QuickTileMode(QuickTileFlag::None) && qtMode != quickTileMode()) setQuickTileMode(qtMode, true); auto tso = workspace()->ensureStackingOrder(transients()); for (auto it = tso.constBegin(), end = tso.constEnd(); it != end; ++it) (*it)->sendToScreen(newScreen); } } // namespace diff --git a/gestures.h b/gestures.h index f0889620e..53b06e381 100644 --- a/gestures.h +++ b/gestures.h @@ -1,221 +1,221 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 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_GESTURES_H #define KWIN_GESTURES_H #include #include #include #include #include #include namespace KWin { class Gesture : public QObject { Q_OBJECT public: ~Gesture() override; protected: explicit Gesture(QObject *parent); Q_SIGNALS: /** * Matching of a gesture started and this Gesture might match. * On further evaluation either the signal @ref triggered or * @ref cancelled will get emitted. - **/ + */ void started(); /** * Gesture matching ended and this Gesture matched. - **/ + */ void triggered(); /** * This Gesture no longer matches. - **/ + */ void cancelled(); }; class SwipeGesture : public Gesture { Q_OBJECT public: enum class Direction { Down, Left, Up, Right }; explicit SwipeGesture(QObject *parent = nullptr); ~SwipeGesture() override; bool minimumFingerCountIsRelevant() const { return m_minimumFingerCountRelevant; } void setMinimumFingerCount(uint count) { m_minimumFingerCount = count; m_minimumFingerCountRelevant = true; } uint minimumFingerCount() const { return m_minimumFingerCount; } bool maximumFingerCountIsRelevant() const { return m_maximumFingerCountRelevant; } void setMaximumFingerCount(uint count) { m_maximumFingerCount = count; m_maximumFingerCountRelevant = true; } uint maximumFingerCount() const { return m_maximumFingerCount; } Direction direction() const { return m_direction; } void setDirection(Direction direction) { m_direction = direction; } void setMinimumX(int x) { m_minimumX = x; m_minimumXRelevant = true; } int minimumX() const { return m_minimumX; } bool minimumXIsRelevant() const { return m_minimumXRelevant; } void setMinimumY(int y) { m_minimumY = y; m_minimumYRelevant = true; } int minimumY() const { return m_minimumY; } bool minimumYIsRelevant() const { return m_minimumYRelevant; } void setMaximumX(int x) { m_maximumX = x; m_maximumXRelevant = true; } int maximumX() const { return m_maximumX; } bool maximumXIsRelevant() const { return m_maximumXRelevant; } void setMaximumY(int y) { m_maximumY = y; m_maximumYRelevant = true; } int maximumY() const { return m_maximumY; } bool maximumYIsRelevant() const { return m_maximumYRelevant; } void setStartGeometry(const QRect &geometry); QSizeF minimumDelta() const { return m_minimumDelta; } void setMinimumDelta(const QSizeF &delta) { m_minimumDelta = delta; m_minimumDeltaRelevant = true; } bool isMinimumDeltaRelevant() const { return m_minimumDeltaRelevant; } qreal minimumDeltaReachedProgress(const QSizeF &delta) const; bool minimumDeltaReached(const QSizeF &delta) const; Q_SIGNALS: /** * The progress of the gesture if a minimumDelta is set. * The progress is reported in [0.0,1.0] - **/ + */ void progress(qreal); private: bool m_minimumFingerCountRelevant = false; uint m_minimumFingerCount = 0; bool m_maximumFingerCountRelevant = false; uint m_maximumFingerCount = 0; Direction m_direction = Direction::Down; bool m_minimumXRelevant = false; int m_minimumX = 0; bool m_minimumYRelevant = false; int m_minimumY = 0; bool m_maximumXRelevant = false; int m_maximumX = 0; bool m_maximumYRelevant = false; int m_maximumY = 0; bool m_minimumDeltaRelevant = false; QSizeF m_minimumDelta; }; class KWIN_EXPORT GestureRecognizer : public QObject { Q_OBJECT public: GestureRecognizer(QObject *parent = nullptr); ~GestureRecognizer() override; void registerGesture(Gesture *gesture); void unregisterGesture(Gesture *gesture); int startSwipeGesture(uint fingerCount) { return startSwipeGesture(fingerCount, QPointF(), StartPositionBehavior::Irrelevant); } int startSwipeGesture(const QPointF &startPos) { return startSwipeGesture(1, startPos, StartPositionBehavior::Relevant); } void updateSwipeGesture(const QSizeF &delta); void cancelSwipeGesture(); void endSwipeGesture(); private: void cancelActiveSwipeGestures(); enum class StartPositionBehavior { Relevant, Irrelevant }; int startSwipeGesture(uint fingerCount, const QPointF &startPos, StartPositionBehavior startPosBehavior); QVector m_gestures; QVector m_activeSwipeGestures; QMap m_destroyConnections; QVector m_swipeUpdates; }; } Q_DECLARE_METATYPE(KWin::SwipeGesture::Direction) #endif diff --git a/globalshortcuts.h b/globalshortcuts.h index 5272f16e4..791f3862d 100644 --- a/globalshortcuts.h +++ b/globalshortcuts.h @@ -1,192 +1,192 @@ /******************************************************************** 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_GLOBALSHORTCUTS_H #define KWIN_GLOBALSHORTCUTS_H // KWin #include // Qt #include class QAction; class KGlobalAccelD; class KGlobalAccelInterface; namespace KWin { class GlobalShortcut; class SwipeGesture; class GestureRecognizer; /** * @brief Manager for the global shortcut system inside KWin. * * This class is responsible for holding all the global shortcuts and to process a key press event. * That is trigger a shortcut if there is a match. * * For internal shortcut handling (those which are delivered inside KWin) QActions are used and * triggered if the shortcut matches. For external shortcut handling a DBus interface is used. - **/ + */ class GlobalShortcutsManager : public QObject { Q_OBJECT public: explicit GlobalShortcutsManager(QObject *parent = nullptr); ~GlobalShortcutsManager() override; void init(); /** * @brief Registers an internal global pointer shortcut * * @param action The action to trigger if the shortcut is pressed * @param modifiers The modifiers which need to be hold to trigger the action * @param pointerButtons The pointer button which needs to be pressed - **/ + */ void registerPointerShortcut(QAction *action, Qt::KeyboardModifiers modifiers, Qt::MouseButtons pointerButtons); /** * @brief Registers an internal global axis shortcut * * @param action The action to trigger if the shortcut is triggered * @param modifiers The modifiers which need to be hold to trigger the action * @param axis The pointer axis - **/ + */ void registerAxisShortcut(QAction *action, Qt::KeyboardModifiers modifiers, PointerAxisDirection axis); void registerTouchpadSwipe(QAction *action, SwipeDirection direction); /** * @brief Processes a key event to decide whether a shortcut needs to be triggered. * * If a shortcut triggered this method returns @c true to indicate to the caller that the event * should not be further processed. If there is no shortcut which triggered for the key, then * @c false is returned. * * @param modifiers The current hold modifiers * @param keyQt The Qt::Key which got pressed * @return @c true if a shortcut triggered, @c false otherwise - **/ + */ bool processKey(Qt::KeyboardModifiers modifiers, int keyQt); bool processPointerPressed(Qt::KeyboardModifiers modifiers, Qt::MouseButtons pointerButtons); /** * @brief Processes a pointer axis event to decide whether a shortcut needs to be triggered. * * If a shortcut triggered this method returns @c true to indicate to the caller that the event * should not be further processed. If there is no shortcut which triggered for the key, then * @c false is returned. * * @param modifiers The current hold modifiers * @param axis The axis direction which has triggered this event * @return @c true if a shortcut triggered, @c false otherwise - **/ + */ bool processAxis(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis); void processSwipeStart(uint fingerCount); void processSwipeUpdate(const QSizeF &delta); void processSwipeCancel(); void processSwipeEnd(); void setKGlobalAccelInterface(KGlobalAccelInterface *interface) { m_kglobalAccelInterface = interface; } private: void objectDeleted(QObject *object); QHash > m_pointerShortcuts; QHash > m_axisShortcuts; QHash > m_swipeShortcuts; KGlobalAccelD *m_kglobalAccel = nullptr; KGlobalAccelInterface *m_kglobalAccelInterface = nullptr; GestureRecognizer *m_gestureRecognizer; }; class GlobalShortcut { public: virtual ~GlobalShortcut(); const QKeySequence &shortcut() const; Qt::KeyboardModifiers pointerButtonModifiers() const; Qt::MouseButtons pointerButtons() const; SwipeDirection swipeDirection() const { return m_swipeDirection; } virtual void invoke() = 0; protected: GlobalShortcut(const QKeySequence &shortcut); GlobalShortcut(Qt::KeyboardModifiers pointerButtonModifiers, Qt::MouseButtons pointerButtons); GlobalShortcut(Qt::KeyboardModifiers axisModifiers); GlobalShortcut(SwipeDirection direction); private: QKeySequence m_shortcut; Qt::KeyboardModifiers m_pointerModifiers; Qt::MouseButtons m_pointerButtons; SwipeDirection m_swipeDirection = SwipeDirection::Invalid;; }; class InternalGlobalShortcut : public GlobalShortcut { public: InternalGlobalShortcut(Qt::KeyboardModifiers modifiers, const QKeySequence &shortcut, QAction *action); InternalGlobalShortcut(Qt::KeyboardModifiers pointerButtonModifiers, Qt::MouseButtons pointerButtons, QAction *action); InternalGlobalShortcut(Qt::KeyboardModifiers axisModifiers, PointerAxisDirection axis, QAction *action); InternalGlobalShortcut(Qt::KeyboardModifiers swipeModifier, SwipeDirection direction, QAction *action); ~InternalGlobalShortcut() override; void invoke() override; QAction *action() const; SwipeGesture *swipeGesture() const { return m_swipe.data(); } private: QAction *m_action; QScopedPointer m_swipe; }; inline QAction *InternalGlobalShortcut::action() const { return m_action; } inline const QKeySequence &GlobalShortcut::shortcut() const { return m_shortcut; } inline Qt::KeyboardModifiers GlobalShortcut::pointerButtonModifiers() const { return m_pointerModifiers; } inline Qt::MouseButtons GlobalShortcut::pointerButtons() const { return m_pointerButtons; } } // namespace #endif diff --git a/group.cpp b/group.cpp index 2183ef855..6972159b7 100644 --- a/group.cpp +++ b/group.cpp @@ -1,920 +1,920 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ /* This file contains things relevant to window grouping. */ //#define QT_CLEAN_NAMESPACE #include "group.h" #include #include "workspace.h" #include "client.h" #include "effects.h" #include #include #include #include /* TODO Rename as many uses of 'transient' as possible (hasTransient->hasSubwindow,etc.), or I'll get it backwards in half of the cases again. */ namespace KWin { //******************************************** // Group //******************************************** Group::Group(Window leader_P) : leader_client(NULL), leader_wid(leader_P), leader_info(NULL), user_time(-1U), refcount(0) { if (leader_P != None) { leader_client = workspace()->findClient(Predicate::WindowMatch, leader_P); leader_info = new NETWinInfo(connection(), leader_P, rootWindow(), 0, NET::WM2StartupId); } effect_group = new EffectWindowGroupImpl(this); workspace()->addGroup(this); } Group::~Group() { delete leader_info; delete effect_group; } QIcon Group::icon() const { if (leader_client != NULL) return leader_client->icon(); else if (leader_wid != None) { QIcon ic; NETWinInfo info(connection(), leader_wid, rootWindow(), NET::WMIcon, NET::WM2IconPixmap); auto readIcon = [&ic, &info, this](int size, bool scale = true) { const QPixmap pix = KWindowSystem::icon(leader_wid, size, size, scale, KWindowSystem::NETWM | KWindowSystem::WMHints, &info); if (!pix.isNull()) { ic.addPixmap(pix); } }; readIcon(16); readIcon(32); readIcon(48, false); readIcon(64, false); readIcon(128, false); return ic; } return QIcon(); } void Group::addMember(Client* member_P) { _members.append(member_P); // qDebug() << "GROUPADD:" << this << ":" << member_P; // qDebug() << kBacktrace(); } void Group::removeMember(Client* member_P) { // qDebug() << "GROUPREMOVE:" << this << ":" << member_P; // qDebug() << kBacktrace(); Q_ASSERT(_members.contains(member_P)); _members.removeAll(member_P); // there are cases when automatic deleting of groups must be delayed, // e.g. when removing a member and doing some operation on the possibly // other members of the group (which would be however deleted already // if there were no other members) if (refcount == 0 && _members.isEmpty()) { workspace()->removeGroup(this); delete this; } } void Group::ref() { ++refcount; } void Group::deref() { if (--refcount == 0 && _members.isEmpty()) { workspace()->removeGroup(this); delete this; } } void Group::gotLeader(Client* leader_P) { assert(leader_P->window() == leader_wid); leader_client = leader_P; } void Group::lostLeader() { assert(!_members.contains(leader_client)); leader_client = NULL; if (_members.isEmpty()) { workspace()->removeGroup(this); delete this; } } //*************************************** // Workspace //*************************************** Group* Workspace::findGroup(xcb_window_t leader) const { assert(leader != None); for (GroupList::ConstIterator it = groups.constBegin(); it != groups.constEnd(); ++it) if ((*it)->leader() == leader) return *it; return NULL; } // Client is group transient, but has no group set. Try to find // group with windows with the same client leader. Group* Workspace::findClientLeaderGroup(const Client* c) const { Group* ret = NULL; for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) { if (*it == c) continue; if ((*it)->wmClientLeader() == c->wmClientLeader()) { if (ret == NULL || ret == (*it)->group()) ret = (*it)->group(); else { // There are already two groups with the same client leader. // This most probably means the app uses group transients without // setting group for its windows. Merging the two groups is a bad // hack, but there's no really good solution for this case. ClientList old_group = (*it)->group()->members(); // old_group autodeletes when being empty for (int pos = 0; pos < old_group.count(); ++pos) { Client* tmp = old_group[ pos ]; if (tmp != c) tmp->changeClientLeaderGroup(ret); } } } } return ret; } void Workspace::updateMinimizedOfTransients(AbstractClient* c) { // if mainwindow is minimized or shaded, minimize transients too if (c->isMinimized()) { for (auto it = c->transients().constBegin(); it != c->transients().constEnd(); ++it) { if ((*it)->isModal()) continue; // there's no reason to hide modal dialogs with the main client // but to keep them to eg. watch progress or whatever if (!(*it)->isMinimized()) { (*it)->minimize(); updateMinimizedOfTransients((*it)); } } if (c->isModal()) { // if a modal dialog is minimized, minimize its mainwindow too foreach (AbstractClient * c2, c->mainClients()) c2->minimize(); } } else { // else unmiminize the transients for (auto it = c->transients().constBegin(); it != c->transients().constEnd(); ++it) { if ((*it)->isMinimized()) { (*it)->unminimize(); updateMinimizedOfTransients((*it)); } } if (c->isModal()) { foreach (AbstractClient * c2, c->mainClients()) c2->unminimize(); } } } /** * Sets the client \a c's transient windows' on_all_desktops property to \a on_all_desktops. - **/ + */ void Workspace::updateOnAllDesktopsOfTransients(AbstractClient* c) { for (auto it = c->transients().constBegin(); it != c->transients().constEnd(); ++it) { if ((*it)->isOnAllDesktops() != c->isOnAllDesktops()) (*it)->setOnAllDesktops(c->isOnAllDesktops()); } } // A new window has been mapped. Check if it's not a mainwindow for some already existing transient window. void Workspace::checkTransients(xcb_window_t w) { for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) (*it)->checkTransient(w); } //**************************************** // Toplevel //**************************************** // hacks for broken apps here // all resource classes are forced to be lowercase bool Toplevel::resourceMatch(const Toplevel* c1, const Toplevel* c2) { return c1->resourceClass() == c2->resourceClass(); } //**************************************** // Client //**************************************** bool Client::belongToSameApplication(const Client* c1, const Client* c2, SameApplicationChecks checks) { bool same_app = false; // tests that definitely mean they belong together if (c1 == c2) same_app = true; else if (c1->isTransient() && c2->hasTransient(c1, true)) same_app = true; // c1 has c2 as mainwindow else if (c2->isTransient() && c1->hasTransient(c2, true)) same_app = true; // c2 has c1 as mainwindow else if (c1->group() == c2->group()) same_app = true; // same group else if (c1->wmClientLeader() == c2->wmClientLeader() && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), && c2->wmClientLeader() != c2->window()) // don't use in this test then same_app = true; // same client leader // tests that mean they most probably don't belong together else if ((c1->pid() != c2->pid() && !checks.testFlag(SameApplicationCheck::AllowCrossProcesses)) || c1->wmClientMachine(false) != c2->wmClientMachine(false)) ; // different processes else if (c1->wmClientLeader() != c2->wmClientLeader() && c1->wmClientLeader() != c1->window() // if WM_CLIENT_LEADER is not set, it returns window(), && c2->wmClientLeader() != c2->window() // don't use in this test then && !checks.testFlag(SameApplicationCheck::AllowCrossProcesses)) ; // different client leader else if (!resourceMatch(c1, c2)) ; // different apps else if (!sameAppWindowRoleMatch(c1, c2, checks.testFlag(SameApplicationCheck::RelaxedForActive)) && !checks.testFlag(SameApplicationCheck::AllowCrossProcesses)) ; // "different" apps else if (c1->pid() == 0 || c2->pid() == 0) ; // old apps that don't have _NET_WM_PID, consider them different // if they weren't found to match above else same_app = true; // looks like it's the same app return same_app; } // Non-transient windows with window role containing '#' are always // considered belonging to different applications (unless // the window role is exactly the same). KMainWindow sets // window role this way by default, and different KMainWindow // usually "are" different application from user's point of view. // This help with no-focus-stealing for e.g. konqy reusing. // On the other hand, if one of the windows is active, they are // considered belonging to the same application. This is for // the cases when opening new mainwindow directly from the application, // e.g. 'Open New Window' in konqy ( active_hack == true ). bool Client::sameAppWindowRoleMatch(const Client* c1, const Client* c2, bool active_hack) { if (c1->isTransient()) { while (const Client *t = dynamic_cast(c1->transientFor())) c1 = t; if (c1->groupTransient()) return c1->group() == c2->group(); #if 0 // if a group transient is in its own group, it didn't possibly have a group, // and therefore should be considered belonging to the same app like // all other windows from the same app || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; #endif } if (c2->isTransient()) { while (const Client *t = dynamic_cast(c2->transientFor())) c2 = t; if (c2->groupTransient()) return c1->group() == c2->group(); #if 0 || c1->group()->leaderClient() == c1 || c2->group()->leaderClient() == c2; #endif } int pos1 = c1->windowRole().indexOf('#'); int pos2 = c2->windowRole().indexOf('#'); if ((pos1 >= 0 && pos2 >= 0)) { if (!active_hack) // without the active hack for focus stealing prevention, return c1 == c2; // different mainwindows are always different apps if (!c1->isActive() && !c2->isActive()) return c1 == c2; else return true; } return true; } /* Transiency stuff: ICCCM 4.1.2.6, NETWM 7.3 WM_TRANSIENT_FOR is basically means "this is my mainwindow". For NET::Unknown windows, transient windows are considered to be NET::Dialog windows, for compatibility with non-NETWM clients. KWin may adjust the value of this property in some cases (window pointing to itself or creating a loop, keeping NET::Splash windows above other windows from the same app, etc.). Client::transient_for_id is the value of the WM_TRANSIENT_FOR property, after possibly being adjusted by KWin. Client::transient_for points to the Client this Client is transient for, or is NULL. If Client::transient_for_id is poiting to the root window, the window is considered to be transient for the whole window group, as suggested in NETWM 7.3. In the case of group transient window, Client::transient_for is NULL, and Client::groupTransient() returns true. Such window is treated as if it were transient for every window in its window group that has been mapped _before_ it (or, to be exact, was added to the same group before it). Otherwise two group transients can create loops, which can lead very very nasty things (bug #67914 and all its dupes). Client::original_transient_for_id is the value of the property, which may be different if Client::transient_for_id if e.g. forcing NET::Splash to be kept on top of its window group, or when the mainwindow is not mapped yet, in which case the window is temporarily made group transient, and when the mainwindow is mapped, transiency is re-evaluated. This can get a bit complicated with with e.g. two Konqueror windows created by the same process. They should ideally appear like two independent applications to the user. This should be accomplished by all windows in the same process having the same window group (needs to be changed in Qt at the moment), and using non-group transients poiting to their relevant mainwindow for toolwindows etc. KWin should handle both group and non-group transient dialogs well. In other words: - non-transient windows : isTransient() == false - normal transients : transientFor() != NULL - group transients : groupTransient() == true - list of mainwindows : mainClients() (call once and loop over the result) - list of transients : transients() - every window in the group : group()->members() */ Xcb::TransientFor Client::fetchTransient() const { return Xcb::TransientFor(window()); } void Client::readTransientProperty(Xcb::TransientFor &transientFor) { xcb_window_t new_transient_for_id = XCB_WINDOW_NONE; if (transientFor.getTransientFor(&new_transient_for_id)) { m_originalTransientForId = new_transient_for_id; new_transient_for_id = verifyTransientFor(new_transient_for_id, true); } else { m_originalTransientForId = XCB_WINDOW_NONE; new_transient_for_id = verifyTransientFor(XCB_WINDOW_NONE, false); } setTransient(new_transient_for_id); } void Client::readTransient() { Xcb::TransientFor transientFor = fetchTransient(); readTransientProperty(transientFor); } void Client::setTransient(xcb_window_t new_transient_for_id) { if (new_transient_for_id != m_transientForId) { removeFromMainClients(); Client *transient_for = nullptr; m_transientForId = new_transient_for_id; if (m_transientForId != XCB_WINDOW_NONE && !groupTransient()) { transient_for = workspace()->findClient(Predicate::WindowMatch, m_transientForId); assert(transient_for != NULL); // verifyTransient() had to check this transient_for->addTransient(this); } // checkGroup() will check 'check_active_modal' setTransientFor(transient_for); checkGroup(NULL, true); // force, because transiency has changed workspace()->updateClientLayer(this); workspace()->resetUpdateToolWindowsTimer(); emit transientChanged(); } } void Client::removeFromMainClients() { if (transientFor()) transientFor()->removeTransient(this); if (groupTransient()) { for (ClientList::ConstIterator it = group()->members().constBegin(); it != group()->members().constEnd(); ++it) (*it)->removeTransient(this); } } // *sigh* this transiency handling is madness :( // This one is called when destroying/releasing a window. // It makes sure this client is removed from all grouping // related lists. void Client::cleanGrouping() { // qDebug() << "CLEANGROUPING:" << this; // for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // qDebug() << "CL:" << *it; // ClientList mains; // mains = mainClients(); // for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // qDebug() << "MN:" << *it; removeFromMainClients(); // qDebug() << "CLEANGROUPING2:" << this; // for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // qDebug() << "CL2:" << *it; // mains = mainClients(); // for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // qDebug() << "MN2:" << *it; for (auto it = transients().constBegin(); it != transients().constEnd(); ) { if ((*it)->transientFor() == this) { removeTransient(*it); it = transients().constBegin(); // restart, just in case something more has changed with the list } else ++it; } // qDebug() << "CLEANGROUPING3:" << this; // for ( ClientList::ConstIterator it = group()->members().begin(); // it != group()->members().end(); // ++it ) // qDebug() << "CL3:" << *it; // mains = mainClients(); // for ( ClientList::ConstIterator it = mains.begin(); // it != mains.end(); // ++it ) // qDebug() << "MN3:" << *it; // HACK // removeFromMainClients() did remove 'this' from transient // lists of all group members, but then made windows that // were transient for 'this' group transient, which again // added 'this' to those transient lists :( ClientList group_members = group()->members(); group()->removeMember(this); in_group = NULL; for (ClientList::ConstIterator it = group_members.constBegin(); it != group_members.constEnd(); ++it) (*it)->removeTransient(this); // qDebug() << "CLEANGROUPING4:" << this; // for ( ClientList::ConstIterator it = group_members.begin(); // it != group_members.end(); // ++it ) // qDebug() << "CL4:" << *it; m_transientForId = XCB_WINDOW_NONE; } // Make sure that no group transient is considered transient // for a window that is (directly or indirectly) transient for it // (including another group transients). // Non-group transients not causing loops are checked in verifyTransientFor(). void Client::checkGroupTransients() { for (ClientList::ConstIterator it1 = group()->members().constBegin(); it1 != group()->members().constEnd(); ++it1) { if (!(*it1)->groupTransient()) // check all group transients in the group continue; // TODO optimize to check only the changed ones? for (ClientList::ConstIterator it2 = group()->members().constBegin(); it2 != group()->members().constEnd(); ++it2) { // group transients can be transient only for others in the group, // so don't make them transient for the ones that are transient for it if (*it1 == *it2) continue; for (AbstractClient* cl = (*it2)->transientFor(); cl != NULL; cl = cl->transientFor()) { if (cl == *it1) { // don't use removeTransient(), that would modify *it2 too (*it2)->removeTransientFromList(*it1); continue; } } // if *it1 and *it2 are both group transients, and are transient for each other, // make only *it2 transient for *it1 (i.e. subwindow), as *it2 came later, // and should be therefore on top of *it1 // TODO This could possibly be optimized, it also requires hasTransient() to check for loops. if ((*it2)->groupTransient() && (*it1)->hasTransient(*it2, true) && (*it2)->hasTransient(*it1, true)) (*it2)->removeTransientFromList(*it1); // if there are already windows W1 and W2, W2 being transient for W1, and group transient W3 // is added, make it transient only for W2, not for W1, because it's already indirectly // transient for it - the indirect transiency actually shouldn't break anything, // but it can lead to exponentially expensive operations (#95231) // TODO this is pretty slow as well for (ClientList::ConstIterator it3 = group()->members().constBegin(); it3 != group()->members().constEnd(); ++it3) { if (*it1 == *it2 || *it2 == *it3 || *it1 == *it3) continue; if ((*it2)->hasTransient(*it1, false) && (*it3)->hasTransient(*it1, false)) { if ((*it2)->hasTransient(*it3, true)) (*it2)->removeTransientFromList(*it1); if ((*it3)->hasTransient(*it2, true)) (*it3)->removeTransientFromList(*it1); } } } } } /** * Check that the window is not transient for itself, and similar nonsense. - **/ + */ xcb_window_t Client::verifyTransientFor(xcb_window_t new_transient_for, bool set) { xcb_window_t new_property_value = new_transient_for; // make sure splashscreens are shown above all their app's windows, even though // they're in Normal layer if (isSplash() && new_transient_for == XCB_WINDOW_NONE) new_transient_for = rootWindow(); if (new_transient_for == XCB_WINDOW_NONE) { if (set) // sometimes WM_TRANSIENT_FOR is set to None, instead of root window new_property_value = new_transient_for = rootWindow(); else return XCB_WINDOW_NONE; } if (new_transient_for == window()) { // pointing to self // also fix the property itself qCWarning(KWIN_CORE) << "Client " << this << " has WM_TRANSIENT_FOR poiting to itself." ; new_property_value = new_transient_for = rootWindow(); } // The transient_for window may be embedded in another application, // so kwin cannot see it. Try to find the managed client for the // window and fix the transient_for property if possible. xcb_window_t before_search = new_transient_for; while (new_transient_for != XCB_WINDOW_NONE && new_transient_for != rootWindow() && !workspace()->findClient(Predicate::WindowMatch, new_transient_for)) { Xcb::Tree tree(new_transient_for); if (tree.isNull()) { break; } new_transient_for = tree->parent; } if (Client* new_transient_for_client = workspace()->findClient(Predicate::WindowMatch, new_transient_for)) { if (new_transient_for != before_search) { qCDebug(KWIN_CORE) << "Client " << this << " has WM_TRANSIENT_FOR poiting to non-toplevel window " << before_search << ", child of " << new_transient_for_client << ", adjusting."; new_property_value = new_transient_for; // also fix the property } } else new_transient_for = before_search; // nice try // loop detection // group transients cannot cause loops, because they're considered transient only for non-transient // windows in the group int count = 20; xcb_window_t loop_pos = new_transient_for; while (loop_pos != XCB_WINDOW_NONE && loop_pos != rootWindow()) { Client* pos = workspace()->findClient(Predicate::WindowMatch, loop_pos); if (pos == NULL) break; loop_pos = pos->m_transientForId; if (--count == 0 || pos == this) { qCWarning(KWIN_CORE) << "Client " << this << " caused WM_TRANSIENT_FOR loop." ; new_transient_for = rootWindow(); } } if (new_transient_for != rootWindow() && workspace()->findClient(Predicate::WindowMatch, new_transient_for) == NULL) { // it's transient for a specific window, but that window is not mapped new_transient_for = rootWindow(); } if (new_property_value != m_originalTransientForId) Xcb::setTransientFor(window(), new_property_value); return new_transient_for; } void Client::addTransient(AbstractClient* cl) { AbstractClient::addTransient(cl); if (workspace()->mostRecentlyActivatedClient() == this && cl->isModal()) check_active_modal = true; // qDebug() << "ADDTRANS:" << this << ":" << cl; // qDebug() << kBacktrace(); // for ( ClientList::ConstIterator it = transients_list.begin(); // it != transients_list.end(); // ++it ) // qDebug() << "AT:" << (*it); } void Client::removeTransient(AbstractClient* cl) { // qDebug() << "REMOVETRANS:" << this << ":" << cl; // qDebug() << kBacktrace(); // cl is transient for this, but this is going away // make cl group transient AbstractClient::removeTransient(cl); if (cl->transientFor() == this) { if (Client *c = dynamic_cast(cl)) { c->m_transientForId = XCB_WINDOW_NONE; c->setTransientFor(nullptr); // SELI // SELI cl->setTransient( rootWindow()); c->setTransient(XCB_WINDOW_NONE); } } } // A new window has been mapped. Check if it's not a mainwindow for this already existing window. void Client::checkTransient(xcb_window_t w) { if (m_originalTransientForId != w) return; w = verifyTransientFor(w, true); setTransient(w); } // returns true if cl is the transient_for window for this client, // or recursively the transient_for window bool Client::hasTransient(const AbstractClient* cl, bool indirect) const { if (const Client *c = dynamic_cast(cl)) { // checkGroupTransients() uses this to break loops, so hasTransient() must detect them ConstClientList set; return hasTransientInternal(c, indirect, set); } return false; } bool Client::hasTransientInternal(const Client* cl, bool indirect, ConstClientList& set) const { if (const Client *t = dynamic_cast(cl->transientFor())) { if (t == this) return true; if (!indirect) return false; if (set.contains(cl)) return false; set.append(cl); return hasTransientInternal(t, indirect, set); } if (!cl->isTransient()) return false; if (group() != cl->group()) return false; // cl is group transient, search from top if (transients().contains(const_cast< Client* >(cl))) return true; if (!indirect) return false; if (set.contains(this)) return false; set.append(this); for (auto it = transients().constBegin(); it != transients().constEnd(); ++it) { const Client *c = qobject_cast(*it); if (!c) { continue; } if (c->hasTransientInternal(cl, indirect, set)) return true; } return false; } QList Client::mainClients() const { if (!isTransient()) return QList(); if (const AbstractClient *t = transientFor()) return QList{const_cast< AbstractClient* >(t)}; QList result; Q_ASSERT(group()); for (ClientList::ConstIterator it = group()->members().constBegin(); it != group()->members().constEnd(); ++it) if ((*it)->hasTransient(this, false)) result.append(*it); return result; } AbstractClient* Client::findModal(bool allow_itself) { for (auto it = transients().constBegin(); it != transients().constEnd(); ++it) if (AbstractClient* ret = (*it)->findModal(true)) return ret; if (isModal() && allow_itself) return this; return NULL; } // Client::window_group only holds the contents of the hint, // but it should be used only to find the group, not for anything else // Argument is only when some specific group needs to be set. void Client::checkGroup(Group* set_group, bool force) { Group* old_group = in_group; if (old_group != NULL) old_group->ref(); // turn off automatic deleting if (set_group != NULL) { if (set_group != in_group) { if (in_group != NULL) in_group->removeMember(this); in_group = set_group; in_group->addMember(this); } } else if (info->groupLeader() != XCB_WINDOW_NONE) { Group* new_group = workspace()->findGroup(info->groupLeader()); Client *t = qobject_cast(transientFor()); if (t != NULL && t->group() != new_group) { // move the window to the right group (e.g. a dialog provided // by different app, but transient for this one, so make it part of that group) new_group = t->group(); } if (new_group == NULL) // doesn't exist yet new_group = new Group(info->groupLeader()); if (new_group != in_group) { if (in_group != NULL) in_group->removeMember(this); in_group = new_group; in_group->addMember(this); } } else { if (Client *t = qobject_cast(transientFor())) { // doesn't have window group set, but is transient for something // so make it part of that group Group* new_group = t->group(); if (new_group != in_group) { if (in_group != NULL) in_group->removeMember(this); in_group = t->group(); in_group->addMember(this); } } else if (groupTransient()) { // group transient which actually doesn't have a group :( // try creating group with other windows with the same client leader Group* new_group = workspace()->findClientLeaderGroup(this); if (new_group == NULL) new_group = new Group(None); if (new_group != in_group) { if (in_group != NULL) in_group->removeMember(this); in_group = new_group; in_group->addMember(this); } } else { // Not transient without a group, put it in its client leader group. // This might be stupid if grouping was used for e.g. taskbar grouping // or minimizing together the whole group, but as long as it is used // only for dialogs it's better to keep windows from one app in one group. Group* new_group = workspace()->findClientLeaderGroup(this); if (in_group != NULL && in_group != new_group) { in_group->removeMember(this); in_group = NULL; } if (new_group == NULL) new_group = new Group(None); if (in_group != new_group) { in_group = new_group; in_group->addMember(this); } } } if (in_group != old_group || force) { for (auto it = transients().constBegin(); it != transients().constEnd(); ) { auto *c = *it; // group transients in the old group are no longer transient for it if (c->groupTransient() && c->group() != group()) { removeTransientFromList(c); it = transients().constBegin(); // restart, just in case something more has changed with the list } else ++it; } if (groupTransient()) { // no longer transient for ones in the old group if (old_group != NULL) { for (ClientList::ConstIterator it = old_group->members().constBegin(); it != old_group->members().constEnd(); ++it) (*it)->removeTransient(this); } // and make transient for all in the new group for (ClientList::ConstIterator it = group()->members().constBegin(); it != group()->members().constEnd(); ++it) { if (*it == this) break; // this means the window is only transient for windows mapped before it (*it)->addTransient(this); } } // group transient splashscreens should be transient even for windows // in group mapped later for (ClientList::ConstIterator it = group()->members().constBegin(); it != group()->members().constEnd(); ++it) { if (!(*it)->isSplash()) continue; if (!(*it)->groupTransient()) continue; if (*it == this || hasTransient(*it, true)) // TODO indirect? continue; addTransient(*it); } } if (old_group != NULL) old_group->deref(); // can be now deleted if empty checkGroupTransients(); checkActiveModal(); workspace()->updateClientLayer(this); } // used by Workspace::findClientLeaderGroup() void Client::changeClientLeaderGroup(Group* gr) { // transientFor() != NULL are in the group of their mainwindow, so keep them there if (transientFor() != NULL) return; // also don't change the group for window which have group set if (info->groupLeader()) return; checkGroup(gr); // change group } bool Client::check_active_modal = false; void Client::checkActiveModal() { // if the active window got new modal transient, activate it. // cannot be done in AddTransient(), because there may temporarily // exist loops, breaking findModal Client* check_modal = dynamic_cast(workspace()->mostRecentlyActivatedClient()); if (check_modal != NULL && check_modal->check_active_modal) { Client* new_modal = dynamic_cast(check_modal->findModal()); if (new_modal != NULL && new_modal != check_modal) { if (!new_modal->isManaged()) return; // postpone check until end of manage() workspace()->activateClient(new_modal); } check_modal->check_active_modal = false; } } } // namespace diff --git a/input.cpp b/input.cpp index bebe0e3e4..b1aa24e12 100644 --- a/input.cpp +++ b/input.cpp @@ -1,2426 +1,2426 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin Copyright (C) 2018 Roman Gilg Copyright (C) 2019 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 . *********************************************************************/ #include "input.h" #include "input_event.h" #include "input_event_spy.h" #include "keyboard_input.h" #include "pointer_input.h" #include "touch_input.h" #include "touch_hide_cursor_spy.h" #include "client.h" #include "effects.h" #include "gestures.h" #include "globalshortcuts.h" #include "logind.h" #include "main.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox/tabbox.h" #endif #include "unmanaged.h" #include "screenedge.h" #include "screens.h" #include "workspace.h" #include "libinput/connection.h" #include "libinput/device.h" #include "platform.h" #include "popup_input_filter.h" #include "shell_client.h" #include "wayland_server.h" #include "xwl/xwayland_interface.h" #include #include #include #include #include #include #include //screenlocker #include // Qt #include #include namespace KWin { InputEventFilter::InputEventFilter() = default; InputEventFilter::~InputEventFilter() { if (input()) { input()->uninstallInputEventFilter(this); } } bool InputEventFilter::pointerEvent(QMouseEvent *event, quint32 nativeButton) { Q_UNUSED(event) Q_UNUSED(nativeButton) return false; } bool InputEventFilter::wheelEvent(QWheelEvent *event) { Q_UNUSED(event) return false; } bool InputEventFilter::keyEvent(QKeyEvent *event) { Q_UNUSED(event) return false; } bool InputEventFilter::touchDown(quint32 id, const QPointF &point, quint32 time) { Q_UNUSED(id) Q_UNUSED(point) Q_UNUSED(time) return false; } bool InputEventFilter::touchMotion(quint32 id, const QPointF &point, quint32 time) { Q_UNUSED(id) Q_UNUSED(point) Q_UNUSED(time) return false; } bool InputEventFilter::touchUp(quint32 id, quint32 time) { Q_UNUSED(id) Q_UNUSED(time) return false; } bool InputEventFilter::pinchGestureBegin(int fingerCount, quint32 time) { Q_UNUSED(fingerCount) Q_UNUSED(time) return false; } bool InputEventFilter::pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time) { Q_UNUSED(scale) Q_UNUSED(angleDelta) Q_UNUSED(delta) Q_UNUSED(time) return false; } bool InputEventFilter::pinchGestureEnd(quint32 time) { Q_UNUSED(time) return false; } bool InputEventFilter::pinchGestureCancelled(quint32 time) { Q_UNUSED(time) return false; } bool InputEventFilter::swipeGestureBegin(int fingerCount, quint32 time) { Q_UNUSED(fingerCount) Q_UNUSED(time) return false; } bool InputEventFilter::swipeGestureUpdate(const QSizeF &delta, quint32 time) { Q_UNUSED(delta) Q_UNUSED(time) return false; } bool InputEventFilter::swipeGestureEnd(quint32 time) { Q_UNUSED(time) return false; } bool InputEventFilter::swipeGestureCancelled(quint32 time) { Q_UNUSED(time) return false; } bool InputEventFilter::switchEvent(SwitchEvent *event) { Q_UNUSED(event) return false; } void InputEventFilter::passToWaylandServer(QKeyEvent *event) { Q_ASSERT(waylandServer()); if (event->isAutoRepeat()) { return; } switch (event->type()) { case QEvent::KeyPress: waylandServer()->seat()->keyPressed(event->nativeScanCode()); break; case QEvent::KeyRelease: waylandServer()->seat()->keyReleased(event->nativeScanCode()); break; default: break; } } class VirtualTerminalFilter : public InputEventFilter { public: bool keyEvent(QKeyEvent *event) override { // really on press and not on release? X11 switches on press. if (event->type() == QEvent::KeyPress && !event->isAutoRepeat()) { const xkb_keysym_t keysym = event->nativeVirtualKey(); if (keysym >= XKB_KEY_XF86Switch_VT_1 && keysym <= XKB_KEY_XF86Switch_VT_12) { LogindIntegration::self()->switchVirtualTerminal(keysym - XKB_KEY_XF86Switch_VT_1 + 1); return true; } } return false; } }; class TerminateServerFilter : public InputEventFilter { public: bool keyEvent(QKeyEvent *event) override { if (event->type() == QEvent::KeyPress && !event->isAutoRepeat()) { if (event->nativeVirtualKey() == XKB_KEY_Terminate_Server) { qCWarning(KWIN_CORE) << "Request to terminate server"; QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection); return true; } } return false; } }; class LockScreenFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { if (!waylandServer()->isScreenLocked()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(event->timestamp()); if (event->type() == QEvent::MouseMove) { if (pointerSurfaceAllowed()) { // TODO: should the pointer position always stay in sync, i.e. not do the check? seat->setPointerPos(event->screenPos().toPoint()); } } else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { if (pointerSurfaceAllowed()) { // TODO: can we leak presses/releases here when we move the mouse in between from an allowed surface to // disallowed one or vice versa? event->type() == QEvent::MouseButtonPress ? seat->pointerButtonPressed(nativeButton) : seat->pointerButtonReleased(nativeButton); } } return true; } bool wheelEvent(QWheelEvent *event) override { if (!waylandServer()->isScreenLocked()) { return false; } auto seat = waylandServer()->seat(); if (pointerSurfaceAllowed()) { seat->setTimestamp(event->timestamp()); const Qt::Orientation orientation = event->angleDelta().x() == 0 ? Qt::Vertical : Qt::Horizontal; seat->pointerAxis(orientation, orientation == Qt::Horizontal ? event->angleDelta().x() : event->angleDelta().y()); } return true; } bool keyEvent(QKeyEvent * event) override { if (!waylandServer()->isScreenLocked()) { return false; } if (event->isAutoRepeat()) { // wayland client takes care of it return true; } // send event to KSldApp for global accel // if event is set to accepted it means a whitelisted shortcut was triggered // in that case we filter it out and don't process it further event->setAccepted(false); QCoreApplication::sendEvent(ScreenLocker::KSldApp::self(), event); if (event->isAccepted()) { return true; } // continue normal processing input()->keyboard()->update(); auto seat = waylandServer()->seat(); seat->setTimestamp(event->timestamp()); if (!keyboardSurfaceAllowed()) { // don't pass event to seat return true; } switch (event->type()) { case QEvent::KeyPress: seat->keyPressed(event->nativeScanCode()); break; case QEvent::KeyRelease: seat->keyReleased(event->nativeScanCode()); break; default: break; } return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { if (!waylandServer()->isScreenLocked()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); if (touchSurfaceAllowed()) { input()->touch()->insertId(id, seat->touchDown(pos)); } return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { if (!waylandServer()->isScreenLocked()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); if (touchSurfaceAllowed()) { const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId != -1) { seat->touchMove(kwaylandId, pos); } } return true; } bool touchUp(quint32 id, quint32 time) override { if (!waylandServer()->isScreenLocked()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); if (touchSurfaceAllowed()) { const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId != -1) { seat->touchUp(kwaylandId); input()->touch()->removeId(id); } } return true; } bool pinchGestureBegin(int fingerCount, quint32 time) override { Q_UNUSED(fingerCount) Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time) override { Q_UNUSED(scale) Q_UNUSED(angleDelta) Q_UNUSED(delta) Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool pinchGestureEnd(quint32 time) override { Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool pinchGestureCancelled(quint32 time) override { Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool swipeGestureBegin(int fingerCount, quint32 time) override { Q_UNUSED(fingerCount) Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool swipeGestureUpdate(const QSizeF &delta, quint32 time) override { Q_UNUSED(delta) Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool swipeGestureEnd(quint32 time) override { Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } bool swipeGestureCancelled(quint32 time) override { Q_UNUSED(time) // no touchpad multi-finger gestures on lock screen return waylandServer()->isScreenLocked(); } private: bool surfaceAllowed(KWayland::Server::SurfaceInterface *(KWayland::Server::SeatInterface::*method)() const) const { if (KWayland::Server::SurfaceInterface *s = (waylandServer()->seat()->*method)()) { if (Toplevel *t = waylandServer()->findClient(s)) { return t->isLockScreen() || t->isInputMethod(); } return false; } return true; } bool pointerSurfaceAllowed() const { return surfaceAllowed(&KWayland::Server::SeatInterface::focusedPointerSurface); } bool keyboardSurfaceAllowed() const { return surfaceAllowed(&KWayland::Server::SeatInterface::focusedKeyboardSurface); } bool touchSurfaceAllowed() const { return surfaceAllowed(&KWayland::Server::SeatInterface::focusedTouchSurface); } }; class EffectsFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) if (!effects) { return false; } return static_cast(effects)->checkInputWindowEvent(event); } bool keyEvent(QKeyEvent *event) override { if (!effects || !static_cast< EffectsHandlerImpl* >(effects)->hasKeyboardGrab()) { return false; } waylandServer()->seat()->setFocusedKeyboardSurface(nullptr); passToWaylandServer(event); static_cast< EffectsHandlerImpl* >(effects)->grabbedKeyboardEvent(event); return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { if (!effects) { return false; } return static_cast< EffectsHandlerImpl* >(effects)->touchDown(id, pos, time); } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { if (!effects) { return false; } return static_cast< EffectsHandlerImpl* >(effects)->touchMotion(id, pos, time); } bool touchUp(quint32 id, quint32 time) override { if (!effects) { return false; } return static_cast< EffectsHandlerImpl* >(effects)->touchUp(id, time); } }; class MoveResizeFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) AbstractClient *c = workspace()->moveResizeClient(); if (!c) { return false; } switch (event->type()) { case QEvent::MouseMove: c->updateMoveResize(event->screenPos().toPoint()); break; case QEvent::MouseButtonRelease: if (event->buttons() == Qt::NoButton) { c->endMoveResize(); } break; default: break; } return true; } bool wheelEvent(QWheelEvent *event) override { Q_UNUSED(event) // filter out while moving a window return workspace()->moveResizeClient() != nullptr; } bool keyEvent(QKeyEvent *event) override { AbstractClient *c = workspace()->moveResizeClient(); if (!c) { return false; } if (event->type() == QEvent::KeyPress) { c->keyPressEvent(event->key() | event->modifiers()); if (c->isMove() || c->isResize()) { // only update if mode didn't end c->updateMoveResize(input()->globalPointer()); } } return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(id) Q_UNUSED(pos) Q_UNUSED(time) AbstractClient *c = workspace()->moveResizeClient(); if (!c) { return false; } return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) AbstractClient *c = workspace()->moveResizeClient(); if (!c) { return false; } if (!m_set) { m_id = id; m_set = true; } if (m_id == id) { c->updateMoveResize(pos.toPoint()); } return true; } bool touchUp(quint32 id, quint32 time) override { Q_UNUSED(time) AbstractClient *c = workspace()->moveResizeClient(); if (!c) { return false; } if (m_id == id || !m_set) { c->endMoveResize(); m_set = false; // pass through to update decoration filter later on return false; } m_set = false; return true; } private: quint32 m_id = 0; bool m_set = false; }; class WindowSelectorFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) if (!m_active) { return false; } switch (event->type()) { case QEvent::MouseButtonRelease: if (event->buttons() == Qt::NoButton) { if (event->button() == Qt::RightButton) { cancel(); } else { accept(event->globalPos()); } } break; default: break; } return true; } bool wheelEvent(QWheelEvent *event) override { Q_UNUSED(event) // filter out while selecting a window return m_active; } bool keyEvent(QKeyEvent *event) override { Q_UNUSED(event) if (!m_active) { return false; } waylandServer()->seat()->setFocusedKeyboardSurface(nullptr); passToWaylandServer(event); if (event->type() == QEvent::KeyPress) { // x11 variant does this on key press, so do the same if (event->key() == Qt::Key_Escape) { cancel(); } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return || event->key() == Qt::Key_Space) { accept(input()->globalPointer()); } if (input()->supportsPointerWarping()) { int mx = 0; int my = 0; if (event->key() == Qt::Key_Left) { mx = -10; } if (event->key() == Qt::Key_Right) { mx = 10; } if (event->key() == Qt::Key_Up) { my = -10; } if (event->key() == Qt::Key_Down) { my = 10; } if (event->modifiers() & Qt::ControlModifier) { mx /= 10; my /= 10; } input()->warpPointer(input()->globalPointer() + QPointF(mx, my)); } } // filter out while selecting a window return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) if (!isActive()) { return false; } m_touchPoints.insert(id, pos); return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) if (!isActive()) { return false; } auto it = m_touchPoints.find(id); if (it != m_touchPoints.end()) { *it = pos; } return true; } bool touchUp(quint32 id, quint32 time) override { Q_UNUSED(time) if (!isActive()) { return false; } auto it = m_touchPoints.find(id); if (it != m_touchPoints.end()) { const auto pos = it.value(); m_touchPoints.erase(it); if (m_touchPoints.isEmpty()) { accept(pos); } } return true; } bool isActive() const { return m_active; } void start(std::function callback) { Q_ASSERT(!m_active); m_active = true; m_callback = callback; input()->keyboard()->update(); input()->cancelTouch(); } void start(std::function callback) { Q_ASSERT(!m_active); m_active = true; m_pointSelectionFallback = callback; input()->keyboard()->update(); input()->cancelTouch(); } private: void deactivate() { m_active = false; m_callback = std::function(); m_pointSelectionFallback = std::function(); input()->pointer()->removeWindowSelectionCursor(); input()->keyboard()->update(); m_touchPoints.clear(); } void cancel() { if (m_callback) { m_callback(nullptr); } if (m_pointSelectionFallback) { m_pointSelectionFallback(QPoint(-1, -1)); } deactivate(); } void accept(const QPoint &pos) { if (m_callback) { // TODO: this ignores shaped windows m_callback(input()->findToplevel(pos)); } if (m_pointSelectionFallback) { m_pointSelectionFallback(pos); } deactivate(); } void accept(const QPointF &pos) { accept(pos.toPoint()); } bool m_active = false; std::function m_callback; std::function m_pointSelectionFallback; QMap m_touchPoints; }; class GlobalShortcutFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton); if (event->type() == QEvent::MouseButtonPress) { if (input()->shortcuts()->processPointerPressed(event->modifiers(), event->buttons())) { return true; } } return false; } bool wheelEvent(QWheelEvent *event) override { if (event->modifiers() == Qt::NoModifier) { return false; } PointerAxisDirection direction = PointerAxisUp; if (event->angleDelta().x() < 0) { direction = PointerAxisRight; } else if (event->angleDelta().x() > 0) { direction = PointerAxisLeft; } else if (event->angleDelta().y() < 0) { direction = PointerAxisDown; } else if (event->angleDelta().y() > 0) { direction = PointerAxisUp; } return input()->shortcuts()->processAxis(event->modifiers(), direction); } bool keyEvent(QKeyEvent *event) override { if (event->type() == QEvent::KeyPress) { return input()->shortcuts()->processKey(static_cast(event)->modifiersRelevantForGlobalShortcuts(), event->key()); } return false; } bool swipeGestureBegin(int fingerCount, quint32 time) override { Q_UNUSED(time) input()->shortcuts()->processSwipeStart(fingerCount); return false; } bool swipeGestureUpdate(const QSizeF &delta, quint32 time) override { Q_UNUSED(time) input()->shortcuts()->processSwipeUpdate(delta); return false; } bool swipeGestureCancelled(quint32 time) override { Q_UNUSED(time) input()->shortcuts()->processSwipeCancel(); return false; } bool swipeGestureEnd(quint32 time) override { Q_UNUSED(time) input()->shortcuts()->processSwipeEnd(); return false; } }; namespace { enum class MouseAction { ModifierOnly, ModifierAndWindow }; std::pair performClientMouseAction(QMouseEvent *event, AbstractClient *client, MouseAction action = MouseAction::ModifierOnly) { Options::MouseCommand command = Options::MouseNothing; bool wasAction = false; if (static_cast(event)->modifiersRelevantForGlobalShortcuts() == options->commandAllModifier()) { if (!input()->pointer()->isConstrained() && !workspace()->globalShortcutsDisabled()) { wasAction = true; switch (event->button()) { case Qt::LeftButton: command = options->commandAll1(); break; case Qt::MiddleButton: command = options->commandAll2(); break; case Qt::RightButton: command = options->commandAll3(); break; default: // nothing break; } } } else { if (action == MouseAction::ModifierAndWindow) { command = client->getMouseCommand(event->button(), &wasAction); } } if (wasAction) { return std::make_pair(wasAction, !client->performMouseCommand(command, event->globalPos())); } return std::make_pair(wasAction, false); } std::pair performClientWheelAction(QWheelEvent *event, AbstractClient *c, MouseAction action = MouseAction::ModifierOnly) { bool wasAction = false; Options::MouseCommand command = Options::MouseNothing; if (static_cast(event)->modifiersRelevantForGlobalShortcuts() == options->commandAllModifier()) { if (!input()->pointer()->isConstrained() && !workspace()->globalShortcutsDisabled()) { wasAction = true; command = options->operationWindowMouseWheel(-1 * event->angleDelta().y()); } } else { if (action == MouseAction::ModifierAndWindow) { command = c->getWheelCommand(Qt::Vertical, &wasAction); } } if (wasAction) { return std::make_pair(wasAction, !c->performMouseCommand(command, event->globalPos())); } return std::make_pair(wasAction, false); } } class InternalWindowEventFilter : public InputEventFilter { bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) auto internal = input()->pointer()->internalWindow(); if (!internal) { return false; } // find client switch (event->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: { auto s = waylandServer()->findClient(internal); if (s && s->isDecorated()) { // only perform mouse commands on decorated internal windows const auto actionResult = performClientMouseAction(event, s); if (actionResult.first) { return actionResult.second; } } break; } default: break; } QMouseEvent e(event->type(), event->pos() - internal->position(), event->globalPos(), event->button(), event->buttons(), event->modifiers()); e.setAccepted(false); QCoreApplication::sendEvent(internal.data(), &e); return e.isAccepted(); } bool wheelEvent(QWheelEvent *event) override { auto internal = input()->pointer()->internalWindow(); if (!internal) { return false; } if (event->angleDelta().y() != 0) { auto s = waylandServer()->findClient(internal); if (s && s->isDecorated()) { // client window action only on vertical scrolling const auto actionResult = performClientWheelAction(event, s); if (actionResult.first) { return actionResult.second; } } } const QPointF localPos = event->globalPosF() - QPointF(internal->x(), internal->y()); const Qt::Orientation orientation = (event->angleDelta().x() != 0) ? Qt::Horizontal : Qt::Vertical; const int delta = event->angleDelta().x() != 0 ? event->angleDelta().x() : event->angleDelta().y(); QWheelEvent e(localPos, event->globalPosF(), QPoint(), event->angleDelta() * -1, delta * -1, orientation, event->buttons(), event->modifiers()); e.setAccepted(false); QCoreApplication::sendEvent(internal.data(), &e); return e.isAccepted(); } bool keyEvent(QKeyEvent *event) override { const auto &internalClients = waylandServer()->internalClients(); if (internalClients.isEmpty()) { return false; } QWindow *found = nullptr; auto it = internalClients.end(); do { it--; if (QWindow *w = (*it)->internalWindow()) { if (!w->isVisible()) { continue; } if (!screens()->geometry().contains(w->geometry())) { continue; } if (w->property("_q_showWithoutActivating").toBool()) { continue; } if (w->property("outputOnly").toBool()) { continue; } if (w->flags().testFlag(Qt::ToolTip)) { continue; } found = w; break; } } while (it != internalClients.begin()); if (!found) { return false; } auto xkb = input()->keyboard()->xkb(); Qt::Key key = xkb->toQtKey(xkb->toKeysym(event->nativeScanCode())); if (key == Qt::Key_Super_L || key == Qt::Key_Super_R) { // workaround for QTBUG-62102 key = Qt::Key_Meta; } QKeyEvent internalEvent(event->type(), key, event->modifiers(), event->nativeScanCode(), event->nativeVirtualKey(), event->nativeModifiers(), event->text()); internalEvent.setAccepted(false); if (QCoreApplication::sendEvent(found, &internalEvent)) { waylandServer()->seat()->setFocusedKeyboardSurface(nullptr); passToWaylandServer(event); return true; } return false; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { auto seat = waylandServer()->seat(); if (seat->isTouchSequence()) { // something else is getting the events return false; } auto touch = input()->touch(); if (touch->internalPressId() != -1) { // already on internal window, ignore further touch points, but filter out return true; } // a new touch point seat->setTimestamp(time); auto internal = touch->internalWindow(); if (!internal) { return false; } touch->setInternalPressId(id); // Qt's touch event API is rather complex, let's do fake mouse events instead m_lastGlobalTouchPos = pos; m_lastLocalTouchPos = pos - QPointF(internal->x(), internal->y()); QEnterEvent enterEvent(m_lastLocalTouchPos, m_lastLocalTouchPos, pos); QCoreApplication::sendEvent(internal.data(), &enterEvent); QMouseEvent e(QEvent::MouseButtonPress, m_lastLocalTouchPos, pos, Qt::LeftButton, Qt::LeftButton, input()->keyboardModifiers()); e.setAccepted(false); QCoreApplication::sendEvent(internal.data(), &e); return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { auto touch = input()->touch(); auto internal = touch->internalWindow(); if (!internal) { return false; } if (touch->internalPressId() == -1) { return false; } waylandServer()->seat()->setTimestamp(time); if (touch->internalPressId() != qint32(id)) { // ignore, but filter out return true; } m_lastGlobalTouchPos = pos; m_lastLocalTouchPos = pos - QPointF(internal->x(), internal->y()); QMouseEvent e(QEvent::MouseMove, m_lastLocalTouchPos, m_lastGlobalTouchPos, Qt::LeftButton, Qt::LeftButton, input()->keyboardModifiers()); QCoreApplication::instance()->sendEvent(internal.data(), &e); return true; } bool touchUp(quint32 id, quint32 time) override { auto touch = input()->touch(); auto internal = touch->internalWindow(); if (!internal) { return false; } if (touch->internalPressId() == -1) { return false; } waylandServer()->seat()->setTimestamp(time); if (touch->internalPressId() != qint32(id)) { // ignore, but filter out return true; } // send mouse up QMouseEvent e(QEvent::MouseButtonRelease, m_lastLocalTouchPos, m_lastGlobalTouchPos, Qt::LeftButton, Qt::MouseButtons(), input()->keyboardModifiers()); e.setAccepted(false); QCoreApplication::sendEvent(internal.data(), &e); QEvent leaveEvent(QEvent::Leave); QCoreApplication::sendEvent(internal.data(), &leaveEvent); m_lastGlobalTouchPos = QPointF(); m_lastLocalTouchPos = QPointF(); input()->touch()->setInternalPressId(-1); return true; } private: QPointF m_lastGlobalTouchPos; QPointF m_lastLocalTouchPos; }; class DecorationEventFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) auto decoration = input()->pointer()->decoration(); if (!decoration) { return false; } const QPointF p = event->globalPos() - decoration->client()->pos(); switch (event->type()) { case QEvent::MouseMove: { QHoverEvent e(QEvent::HoverMove, p, p); QCoreApplication::instance()->sendEvent(decoration->decoration(), &e); decoration->client()->processDecorationMove(p.toPoint(), event->globalPos()); return true; } case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: { const auto actionResult = performClientMouseAction(event, decoration->client()); if (actionResult.first) { return actionResult.second; } QMouseEvent e(event->type(), p, event->globalPos(), event->button(), event->buttons(), event->modifiers()); e.setAccepted(false); QCoreApplication::sendEvent(decoration->decoration(), &e); if (!e.isAccepted() && event->type() == QEvent::MouseButtonPress) { decoration->client()->processDecorationButtonPress(&e); } if (event->type() == QEvent::MouseButtonRelease) { decoration->client()->processDecorationButtonRelease(&e); } return true; } default: break; } return false; } bool wheelEvent(QWheelEvent *event) override { auto decoration = input()->pointer()->decoration(); if (!decoration) { return false; } if (event->angleDelta().y() != 0) { // client window action only on vertical scrolling const auto actionResult = performClientWheelAction(event, decoration->client()); if (actionResult.first) { return actionResult.second; } } const QPointF localPos = event->globalPosF() - decoration->client()->pos(); const Qt::Orientation orientation = (event->angleDelta().x() != 0) ? Qt::Horizontal : Qt::Vertical; const int delta = event->angleDelta().x() != 0 ? event->angleDelta().x() : event->angleDelta().y(); QWheelEvent e(localPos, event->globalPosF(), QPoint(), event->angleDelta(), delta, orientation, event->buttons(), event->modifiers()); e.setAccepted(false); QCoreApplication::sendEvent(decoration.data(), &e); if (e.isAccepted()) { return true; } if ((orientation == Qt::Vertical) && decoration->client()->titlebarPositionUnderMouse()) { decoration->client()->performMouseCommand(options->operationTitlebarMouseWheel(delta * -1), event->globalPosF().toPoint()); } return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { auto seat = waylandServer()->seat(); if (seat->isTouchSequence()) { return false; } if (input()->touch()->decorationPressId() != -1) { // already on a decoration, ignore further touch points, but filter out return true; } seat->setTimestamp(time); auto decoration = input()->touch()->decoration(); if (!decoration) { return false; } input()->touch()->setDecorationPressId(id); m_lastGlobalTouchPos = pos; m_lastLocalTouchPos = pos - decoration->client()->pos(); QHoverEvent hoverEvent(QEvent::HoverMove, m_lastLocalTouchPos, m_lastLocalTouchPos); QCoreApplication::sendEvent(decoration->decoration(), &hoverEvent); QMouseEvent e(QEvent::MouseButtonPress, m_lastLocalTouchPos, pos, Qt::LeftButton, Qt::LeftButton, input()->keyboardModifiers()); e.setAccepted(false); QCoreApplication::sendEvent(decoration->decoration(), &e); if (!e.isAccepted()) { decoration->client()->processDecorationButtonPress(&e); } return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) auto decoration = input()->touch()->decoration(); if (!decoration) { return false; } if (input()->touch()->decorationPressId() == -1) { return false; } if (input()->touch()->decorationPressId() != qint32(id)) { // ignore, but filter out return true; } m_lastGlobalTouchPos = pos; m_lastLocalTouchPos = pos - decoration->client()->pos(); QHoverEvent e(QEvent::HoverMove, m_lastLocalTouchPos, m_lastLocalTouchPos); QCoreApplication::instance()->sendEvent(decoration->decoration(), &e); decoration->client()->processDecorationMove(m_lastLocalTouchPos.toPoint(), pos.toPoint()); return true; } bool touchUp(quint32 id, quint32 time) override { Q_UNUSED(time); auto decoration = input()->touch()->decoration(); if (!decoration) { return false; } if (input()->touch()->decorationPressId() == -1) { return false; } if (input()->touch()->decorationPressId() != qint32(id)) { // ignore, but filter out return true; } // send mouse up QMouseEvent e(QEvent::MouseButtonRelease, m_lastLocalTouchPos, m_lastGlobalTouchPos, Qt::LeftButton, Qt::MouseButtons(), input()->keyboardModifiers()); e.setAccepted(false); QCoreApplication::sendEvent(decoration->decoration(), &e); decoration->client()->processDecorationButtonRelease(&e); QHoverEvent leaveEvent(QEvent::HoverLeave, QPointF(), QPointF()); QCoreApplication::sendEvent(decoration->decoration(), &leaveEvent); m_lastGlobalTouchPos = QPointF(); m_lastLocalTouchPos = QPointF(); input()->touch()->setDecorationPressId(-1); return true; } private: QPointF m_lastGlobalTouchPos; QPointF m_lastLocalTouchPos; }; #ifdef KWIN_BUILD_TABBOX class TabBoxInputFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 button) override { Q_UNUSED(button) if (!TabBox::TabBox::self() || !TabBox::TabBox::self()->isGrabbed()) { return false; } return TabBox::TabBox::self()->handleMouseEvent(event); } bool keyEvent(QKeyEvent *event) override { if (!TabBox::TabBox::self() || !TabBox::TabBox::self()->isGrabbed()) { return false; } auto seat = waylandServer()->seat(); seat->setFocusedKeyboardSurface(nullptr); input()->pointer()->setEnableConstraints(false); // pass the key event to the seat, so that it has a proper model of the currently hold keys // this is important for combinations like alt+shift to ensure that shift is not considered pressed passToWaylandServer(event); if (event->type() == QEvent::KeyPress) { TabBox::TabBox::self()->keyPress(event->modifiers() | event->key()); } else if (static_cast(event)->modifiersRelevantForGlobalShortcuts() == Qt::NoModifier) { TabBox::TabBox::self()->modifiersReleased(); } return true; } bool wheelEvent(QWheelEvent *event) override { if (!TabBox::TabBox::self() || !TabBox::TabBox::self()->isGrabbed()) { return false; } return TabBox::TabBox::self()->handleWheelEvent(event); } }; #endif class ScreenEdgeInputFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) ScreenEdges::self()->isEntered(event); // always forward return false; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) // TODO: better check whether a touch sequence is in progress if (m_touchInProgress || waylandServer()->seat()->isTouchSequence()) { // cancel existing touch ScreenEdges::self()->gestureRecognizer()->cancelSwipeGesture(); m_touchInProgress = false; m_id = 0; return false; } if (ScreenEdges::self()->gestureRecognizer()->startSwipeGesture(pos) > 0) { m_touchInProgress = true; m_id = id; m_lastPos = pos; return true; } return false; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) if (m_touchInProgress && m_id == id) { ScreenEdges::self()->gestureRecognizer()->updateSwipeGesture(QSizeF(pos.x() - m_lastPos.x(), pos.y() - m_lastPos.y())); m_lastPos = pos; return true; } return false; } bool touchUp(quint32 id, quint32 time) override { Q_UNUSED(time) if (m_touchInProgress && m_id == id) { ScreenEdges::self()->gestureRecognizer()->endSwipeGesture(); m_touchInProgress = false; return true; } return false; } private: bool m_touchInProgress = false; quint32 m_id = 0; QPointF m_lastPos; }; /** * This filter implements window actions. If the event should not be passed to the * current pointer window it will filter out the event - **/ + */ class WindowActionInputFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { Q_UNUSED(nativeButton) if (event->type() != QEvent::MouseButtonPress) { return false; } AbstractClient *c = dynamic_cast(input()->pointer()->focus().data()); if (!c) { return false; } const auto actionResult = performClientMouseAction(event, c, MouseAction::ModifierAndWindow); if (actionResult.first) { return actionResult.second; } return false; } bool wheelEvent(QWheelEvent *event) override { if (event->angleDelta().y() == 0) { // only actions on vertical scroll return false; } AbstractClient *c = dynamic_cast(input()->pointer()->focus().data()); if (!c) { return false; } const auto actionResult = performClientWheelAction(event, c, MouseAction::ModifierAndWindow); if (actionResult.first) { return actionResult.second; } return false; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(id) Q_UNUSED(time) auto seat = waylandServer()->seat(); if (seat->isTouchSequence()) { return false; } AbstractClient *c = dynamic_cast(input()->touch()->focus().data()); if (!c) { return false; } bool wasAction = false; const Options::MouseCommand command = c->getMouseCommand(Qt::LeftButton, &wasAction); if (wasAction) { return !c->performMouseCommand(command, pos.toPoint()); } return false; } }; /** * The remaining default input filter which forwards events to other windows - **/ + */ class ForwardInputFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { auto seat = waylandServer()->seat(); seat->setTimestamp(event->timestamp()); switch (event->type()) { case QEvent::MouseMove: { seat->setPointerPos(event->globalPos()); MouseEvent *e = static_cast(event); if (e->delta() != QSizeF()) { seat->relativePointerMotion(e->delta(), e->deltaUnaccelerated(), e->timestampMicroseconds()); } break; } case QEvent::MouseButtonPress: seat->pointerButtonPressed(nativeButton); break; case QEvent::MouseButtonRelease: seat->pointerButtonReleased(nativeButton); break; default: break; } return true; } bool wheelEvent(QWheelEvent *event) override { auto seat = waylandServer()->seat(); seat->setTimestamp(event->timestamp()); auto _event = static_cast(event); KWayland::Server::PointerAxisSource source; switch (_event->axisSource()) { case KWin::InputRedirection::PointerAxisSourceWheel: source = KWayland::Server::PointerAxisSource::Wheel; break; case KWin::InputRedirection::PointerAxisSourceFinger: source = KWayland::Server::PointerAxisSource::Finger; break; case KWin::InputRedirection::PointerAxisSourceContinuous: source = KWayland::Server::PointerAxisSource::Continuous; break; case KWin::InputRedirection::PointerAxisSourceWheelTilt: source = KWayland::Server::PointerAxisSource::WheelTilt; break; case KWin::InputRedirection::PointerAxisSourceUnknown: default: source = KWayland::Server::PointerAxisSource::Unknown; break; } seat->pointerAxisV5(_event->orientation(), _event->delta(), _event->discreteDelta(), source); return true; } bool keyEvent(QKeyEvent *event) override { if (!workspace()) { return false; } if (event->isAutoRepeat()) { // handled by Wayland client return false; } auto seat = waylandServer()->seat(); input()->keyboard()->update(); seat->setTimestamp(event->timestamp()); passToWaylandServer(event); return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); input()->touch()->insertId(id, seat->touchDown(pos)); return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId != -1) { seat->touchMove(kwaylandId, pos); } return true; } bool touchUp(quint32 id, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId != -1) { seat->touchUp(kwaylandId); input()->touch()->removeId(id); } return true; } bool pinchGestureBegin(int fingerCount, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->startPointerPinchGesture(fingerCount); return true; } bool pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->updatePointerPinchGesture(delta, scale, angleDelta); return true; } bool pinchGestureEnd(quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->endPointerPinchGesture(); return true; } bool pinchGestureCancelled(quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->cancelPointerPinchGesture(); return true; } bool swipeGestureBegin(int fingerCount, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->startPointerSwipeGesture(fingerCount); return true; } bool swipeGestureUpdate(const QSizeF &delta, quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->updatePointerSwipeGesture(delta); return true; } bool swipeGestureEnd(quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->endPointerSwipeGesture(); return true; } bool swipeGestureCancelled(quint32 time) override { if (!workspace()) { return false; } auto seat = waylandServer()->seat(); seat->setTimestamp(time); seat->cancelPointerSwipeGesture(); return true; } }; class DragAndDropInputFilter : public InputEventFilter { public: bool pointerEvent(QMouseEvent *event, quint32 nativeButton) override { auto seat = waylandServer()->seat(); if (!seat->isDragPointer()) { return false; } if (seat->isDragTouch()) { return true; } seat->setTimestamp(event->timestamp()); switch (event->type()) { case QEvent::MouseMove: { const auto pos = input()->globalPointer(); seat->setPointerPos(pos); const auto eventPos = event->globalPos(); // TODO: use InputDeviceHandler::at() here and check isClient()? Toplevel *t = input()->findManagedToplevel(eventPos); if (auto *xwl = xwayland()) { const auto ret = xwl->dragMoveFilter(t, eventPos); if (ret == Xwl::DragEventReply::Ignore) { return false; } else if (ret == Xwl::DragEventReply::Take) { break; } } if (t) { // TODO: consider decorations if (t->surface() != seat->dragSurface()) { if (AbstractClient *c = qobject_cast(t)) { workspace()->activateClient(c); } seat->setDragTarget(t->surface(), t->inputTransformation()); } } else { // no window at that place, if we have a surface we need to reset seat->setDragTarget(nullptr); } break; } case QEvent::MouseButtonPress: seat->pointerButtonPressed(nativeButton); break; case QEvent::MouseButtonRelease: seat->pointerButtonReleased(nativeButton); break; default: break; } // TODO: should we pass through effects? return true; } bool touchDown(quint32 id, const QPointF &pos, quint32 time) override { auto seat = waylandServer()->seat(); if (seat->isDragPointer()) { return true; } if (!seat->isDragTouch()) { return false; } if (m_touchId != id) { return true; } seat->setTimestamp(time); input()->touch()->insertId(id, seat->touchDown(pos)); return true; } bool touchMotion(quint32 id, const QPointF &pos, quint32 time) override { auto seat = waylandServer()->seat(); if (seat->isDragPointer()) { return true; } if (!seat->isDragTouch()) { return false; } if (m_touchId < 0) { // We take for now the first id appearing as a move after a drag // started. We can optimize by specifying the id the drag is // associated with by implementing a key-value getter in KWayland. m_touchId = id; } if (m_touchId != id) { return true; } seat->setTimestamp(time); const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId == -1) { return true; } seat->touchMove(kwaylandId, pos); if (Toplevel *t = input()->findToplevel(pos.toPoint())) { // TODO: consider decorations if (t->surface() != seat->dragSurface()) { if (AbstractClient *c = qobject_cast(t)) { workspace()->activateClient(c); } seat->setDragTarget(t->surface(), pos, t->inputTransformation()); } } else { // no window at that place, if we have a surface we need to reset seat->setDragTarget(nullptr); } return true; } bool touchUp(quint32 id, quint32 time) override { auto seat = waylandServer()->seat(); if (!seat->isDragTouch()) { return false; } seat->setTimestamp(time); const qint32 kwaylandId = input()->touch()->mappedId(id); if (kwaylandId != -1) { seat->touchUp(kwaylandId); input()->touch()->removeId(id); } if (m_touchId == id) { m_touchId = -1; } return true; } private: qint32 m_touchId = -1; }; KWIN_SINGLETON_FACTORY(InputRedirection) static const QString s_touchpadComponent = QStringLiteral("kcm_touchpad"); InputRedirection::InputRedirection(QObject *parent) : QObject(parent) , m_keyboard(new KeyboardInputRedirection(this)) , m_pointer(new PointerInputRedirection(this)) , m_touch(new TouchInputRedirection(this)) , m_shortcuts(new GlobalShortcutsManager(this)) { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); if (Application::usesLibinput()) { if (LogindIntegration::self()->hasSessionControl()) { setupLibInput(); } else { LibInput::Connection::createThread(); if (LogindIntegration::self()->isConnected()) { LogindIntegration::self()->takeControl(); } else { connect(LogindIntegration::self(), &LogindIntegration::connectedChanged, LogindIntegration::self(), &LogindIntegration::takeControl); } connect(LogindIntegration::self(), &LogindIntegration::hasSessionControlChanged, this, [this] (bool sessionControl) { if (sessionControl) { setupLibInput(); } } ); } } connect(kwinApp(), &Application::workspaceCreated, this, &InputRedirection::setupWorkspace); reconfigure(); } InputRedirection::~InputRedirection() { s_self = NULL; qDeleteAll(m_filters); qDeleteAll(m_spies); } void InputRedirection::installInputEventFilter(InputEventFilter *filter) { Q_ASSERT(!m_filters.contains(filter)); m_filters << filter; } void InputRedirection::prependInputEventFilter(InputEventFilter *filter) { Q_ASSERT(!m_filters.contains(filter)); m_filters.prepend(filter); } void InputRedirection::uninstallInputEventFilter(InputEventFilter *filter) { m_filters.removeOne(filter); } void InputRedirection::installInputEventSpy(InputEventSpy *spy) { m_spies << spy; } void InputRedirection::uninstallInputEventSpy(InputEventSpy *spy) { m_spies.removeOne(spy); } void InputRedirection::init() { m_shortcuts->init(); } void InputRedirection::setupWorkspace() { if (waylandServer()) { using namespace KWayland::Server; FakeInputInterface *fakeInput = waylandServer()->display()->createFakeInput(this); fakeInput->create(); connect(fakeInput, &FakeInputInterface::deviceCreated, this, [this] (FakeInputDevice *device) { connect(device, &FakeInputDevice::authenticationRequested, this, [this, device] (const QString &application, const QString &reason) { Q_UNUSED(application) Q_UNUSED(reason) // TODO: make secure device->setAuthentication(true); } ); connect(device, &FakeInputDevice::pointerMotionRequested, this, [this] (const QSizeF &delta) { // TODO: Fix time m_pointer->processMotion(globalPointer() + QPointF(delta.width(), delta.height()), 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::pointerMotionAbsoluteRequested, this, [this] (const QPointF &pos) { // TODO: Fix time m_pointer->processMotion(pos, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::pointerButtonPressRequested, this, [this] (quint32 button) { // TODO: Fix time m_pointer->processButton(button, InputRedirection::PointerButtonPressed, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::pointerButtonReleaseRequested, this, [this] (quint32 button) { // TODO: Fix time m_pointer->processButton(button, InputRedirection::PointerButtonReleased, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::pointerAxisRequested, this, [this] (Qt::Orientation orientation, qreal delta) { // TODO: Fix time InputRedirection::PointerAxis axis; switch (orientation) { case Qt::Horizontal: axis = InputRedirection::PointerAxisHorizontal; break; case Qt::Vertical: axis = InputRedirection::PointerAxisVertical; break; default: Q_UNREACHABLE(); break; } // TODO: Fix time m_pointer->processAxis(axis, delta, 0, InputRedirection::PointerAxisSourceUnknown, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchDownRequested, this, [this] (quint32 id, const QPointF &pos) { // TODO: Fix time m_touch->processDown(id, pos, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchMotionRequested, this, [this] (quint32 id, const QPointF &pos) { // TODO: Fix time m_touch->processMotion(id, pos, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchUpRequested, this, [this] (quint32 id) { // TODO: Fix time m_touch->processUp(id, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchCancelRequested, this, [this] () { m_touch->cancel(); } ); connect(device, &FakeInputDevice::touchFrameRequested, this, [this] () { m_touch->frame(); } ); } ); connect(workspace(), &Workspace::configChanged, this, &InputRedirection::reconfigure); m_keyboard->init(); m_pointer->init(); m_touch->init(); } setupInputFilters(); } void InputRedirection::setupInputFilters() { const bool hasGlobalShortcutSupport = !waylandServer() || waylandServer()->hasGlobalShortcutSupport(); if (LogindIntegration::self()->hasSessionControl() && hasGlobalShortcutSupport) { installInputEventFilter(new VirtualTerminalFilter); } if (waylandServer()) { installInputEventSpy(new TouchHideCursorSpy); if (hasGlobalShortcutSupport) { installInputEventFilter(new TerminateServerFilter); } installInputEventFilter(new DragAndDropInputFilter); installInputEventFilter(new LockScreenFilter); installInputEventFilter(new PopupInputFilter); m_windowSelector = new WindowSelectorFilter; installInputEventFilter(m_windowSelector); } if (hasGlobalShortcutSupport) { installInputEventFilter(new ScreenEdgeInputFilter); } installInputEventFilter(new EffectsFilter); installInputEventFilter(new MoveResizeFilter); #ifdef KWIN_BUILD_TABBOX installInputEventFilter(new TabBoxInputFilter); #endif if (hasGlobalShortcutSupport) { installInputEventFilter(new GlobalShortcutFilter); } installInputEventFilter(new DecorationEventFilter); installInputEventFilter(new InternalWindowEventFilter); if (waylandServer()) { installInputEventFilter(new WindowActionInputFilter); installInputEventFilter(new ForwardInputFilter); } } void InputRedirection::reconfigure() { if (Application::usesLibinput()) { auto inputConfig = kwinApp()->inputConfig(); inputConfig->reparseConfiguration(); const auto config = inputConfig->group(QStringLiteral("Keyboard")); const int delay = config.readEntry("RepeatDelay", 660); const int rate = config.readEntry("RepeatRate", 25); const bool enabled = config.readEntry("KeyboardRepeating", 0) == 0; waylandServer()->seat()->setKeyRepeatInfo(enabled ? rate : 0, delay); } } static KWayland::Server::SeatInterface *findSeat() { auto server = waylandServer(); if (!server) { return nullptr; } return server->seat(); } void InputRedirection::setupLibInput() { if (!Application::usesLibinput()) { return; } if (m_libInput) { return; } LibInput::Connection *conn = LibInput::Connection::create(this); m_libInput = conn; if (conn) { if (waylandServer()) { // create relative pointer manager waylandServer()->display()->createRelativePointerManager(KWayland::Server::RelativePointerInterfaceVersion::UnstableV1, waylandServer()->display())->create(); } conn->setInputConfig(kwinApp()->inputConfig()); conn->updateLEDs(m_keyboard->xkb()->leds()); waylandServer()->updateKeyState(m_keyboard->xkb()->leds()); connect(m_keyboard, &KeyboardInputRedirection::ledsChanged, waylandServer(), &WaylandServer::updateKeyState); connect(m_keyboard, &KeyboardInputRedirection::ledsChanged, conn, &LibInput::Connection::updateLEDs); connect(conn, &LibInput::Connection::eventsRead, this, [this] { m_libInput->processEvents(); }, Qt::QueuedConnection ); conn->setup(); connect(conn, &LibInput::Connection::pointerButtonChanged, m_pointer, &PointerInputRedirection::processButton); connect(conn, &LibInput::Connection::pointerAxisChanged, m_pointer, &PointerInputRedirection::processAxis); connect(conn, &LibInput::Connection::pinchGestureBegin, m_pointer, &PointerInputRedirection::processPinchGestureBegin); connect(conn, &LibInput::Connection::pinchGestureUpdate, m_pointer, &PointerInputRedirection::processPinchGestureUpdate); connect(conn, &LibInput::Connection::pinchGestureEnd, m_pointer, &PointerInputRedirection::processPinchGestureEnd); connect(conn, &LibInput::Connection::pinchGestureCancelled, m_pointer, &PointerInputRedirection::processPinchGestureCancelled); connect(conn, &LibInput::Connection::swipeGestureBegin, m_pointer, &PointerInputRedirection::processSwipeGestureBegin); connect(conn, &LibInput::Connection::swipeGestureUpdate, m_pointer, &PointerInputRedirection::processSwipeGestureUpdate); connect(conn, &LibInput::Connection::swipeGestureEnd, m_pointer, &PointerInputRedirection::processSwipeGestureEnd); connect(conn, &LibInput::Connection::swipeGestureCancelled, m_pointer, &PointerInputRedirection::processSwipeGestureCancelled); connect(conn, &LibInput::Connection::keyChanged, m_keyboard, &KeyboardInputRedirection::processKey); connect(conn, &LibInput::Connection::pointerMotion, this, [this] (const QSizeF &delta, const QSizeF &deltaNonAccel, uint32_t time, quint64 timeMicroseconds, LibInput::Device *device) { m_pointer->processMotion(m_pointer->pos() + QPointF(delta.width(), delta.height()), delta, deltaNonAccel, time, timeMicroseconds, device); } ); connect(conn, &LibInput::Connection::pointerMotionAbsolute, this, [this] (QPointF orig, QPointF screen, uint32_t time, LibInput::Device *device) { Q_UNUSED(orig) m_pointer->processMotion(screen, time, device); } ); connect(conn, &LibInput::Connection::touchDown, m_touch, &TouchInputRedirection::processDown); connect(conn, &LibInput::Connection::touchUp, m_touch, &TouchInputRedirection::processUp); connect(conn, &LibInput::Connection::touchMotion, m_touch, &TouchInputRedirection::processMotion); connect(conn, &LibInput::Connection::touchCanceled, m_touch, &TouchInputRedirection::cancel); connect(conn, &LibInput::Connection::touchFrame, m_touch, &TouchInputRedirection::frame); auto handleSwitchEvent = [this] (SwitchEvent::State state, quint32 time, quint64 timeMicroseconds, LibInput::Device *device) { SwitchEvent event(state, time, timeMicroseconds, device); processSpies(std::bind(&InputEventSpy::switchEvent, std::placeholders::_1, &event)); processFilters(std::bind(&InputEventFilter::switchEvent, std::placeholders::_1, &event)); }; connect(conn, &LibInput::Connection::switchToggledOn, this, std::bind(handleSwitchEvent, SwitchEvent::State::On, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); connect(conn, &LibInput::Connection::switchToggledOff, this, std::bind(handleSwitchEvent, SwitchEvent::State::Off, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); if (screens()) { setupLibInputWithScreens(); } else { connect(kwinApp(), &Application::screensCreated, this, &InputRedirection::setupLibInputWithScreens); } if (auto s = findSeat()) { // Workaround for QTBUG-54371: if there is no real keyboard Qt doesn't request virtual keyboard s->setHasKeyboard(true); s->setHasPointer(conn->hasPointer()); s->setHasTouch(conn->hasTouch()); connect(conn, &LibInput::Connection::hasAlphaNumericKeyboardChanged, this, [this] (bool set) { if (m_libInput->isSuspended()) { return; } // TODO: this should update the seat, only workaround for QTBUG-54371 emit hasAlphaNumericKeyboardChanged(set); } ); connect(conn, &LibInput::Connection::hasTabletModeSwitchChanged, this, [this] (bool set) { if (m_libInput->isSuspended()) { return; } emit hasTabletModeSwitchChanged(set); } ); connect(conn, &LibInput::Connection::hasPointerChanged, this, [this, s] (bool set) { if (m_libInput->isSuspended()) { return; } s->setHasPointer(set); } ); connect(conn, &LibInput::Connection::hasTouchChanged, this, [this, s] (bool set) { if (m_libInput->isSuspended()) { return; } s->setHasTouch(set); } ); } connect(LogindIntegration::self(), &LogindIntegration::sessionActiveChanged, m_libInput, [this] (bool active) { if (!active) { m_libInput->deactivate(); } } ); } setupTouchpadShortcuts(); } void InputRedirection::setupTouchpadShortcuts() { if (!m_libInput) { return; } QAction *touchpadToggleAction = new QAction(this); QAction *touchpadOnAction = new QAction(this); QAction *touchpadOffAction = new QAction(this); touchpadToggleAction->setObjectName(QStringLiteral("Toggle Touchpad")); touchpadToggleAction->setProperty("componentName", s_touchpadComponent); touchpadOnAction->setObjectName(QStringLiteral("Enable Touchpad")); touchpadOnAction->setProperty("componentName", s_touchpadComponent); touchpadOffAction->setObjectName(QStringLiteral("Disable Touchpad")); touchpadOffAction->setProperty("componentName", s_touchpadComponent); KGlobalAccel::self()->setDefaultShortcut(touchpadToggleAction, QList{Qt::Key_TouchpadToggle}); KGlobalAccel::self()->setShortcut(touchpadToggleAction, QList{Qt::Key_TouchpadToggle}); KGlobalAccel::self()->setDefaultShortcut(touchpadOnAction, QList{Qt::Key_TouchpadOn}); KGlobalAccel::self()->setShortcut(touchpadOnAction, QList{Qt::Key_TouchpadOn}); KGlobalAccel::self()->setDefaultShortcut(touchpadOffAction, QList{Qt::Key_TouchpadOff}); KGlobalAccel::self()->setShortcut(touchpadOffAction, QList{Qt::Key_TouchpadOff}); #ifndef KWIN_BUILD_TESTING registerShortcut(Qt::Key_TouchpadToggle, touchpadToggleAction); registerShortcut(Qt::Key_TouchpadOn, touchpadOnAction); registerShortcut(Qt::Key_TouchpadOff, touchpadOffAction); #endif connect(touchpadToggleAction, &QAction::triggered, m_libInput, &LibInput::Connection::toggleTouchpads); connect(touchpadOnAction, &QAction::triggered, m_libInput, &LibInput::Connection::enableTouchpads); connect(touchpadOffAction, &QAction::triggered, m_libInput, &LibInput::Connection::disableTouchpads); } bool InputRedirection::hasAlphaNumericKeyboard() { if (m_libInput) { return m_libInput->hasAlphaNumericKeyboard(); } return true; } bool InputRedirection::hasTabletModeSwitch() { if (m_libInput) { return m_libInput->hasTabletModeSwitch(); } return false; } void InputRedirection::setupLibInputWithScreens() { if (!screens() || !m_libInput) { return; } m_libInput->setScreenSize(screens()->size()); m_libInput->updateScreens(); connect(screens(), &Screens::sizeChanged, this, [this] { m_libInput->setScreenSize(screens()->size()); } ); connect(screens(), &Screens::changed, m_libInput, &LibInput::Connection::updateScreens); } void InputRedirection::processPointerMotion(const QPointF &pos, uint32_t time) { m_pointer->processMotion(pos, time); } void InputRedirection::processPointerButton(uint32_t button, InputRedirection::PointerButtonState state, uint32_t time) { m_pointer->processButton(button, state, time); } void InputRedirection::processPointerAxis(InputRedirection::PointerAxis axis, qreal delta, qint32 discreteDelta, PointerAxisSource source, uint32_t time) { m_pointer->processAxis(axis, delta, discreteDelta, source, time); } void InputRedirection::processKeyboardKey(uint32_t key, InputRedirection::KeyboardKeyState state, uint32_t time) { m_keyboard->processKey(key, state, time); } void InputRedirection::processKeyboardModifiers(uint32_t modsDepressed, uint32_t modsLatched, uint32_t modsLocked, uint32_t group) { m_keyboard->processModifiers(modsDepressed, modsLatched, modsLocked, group); } void InputRedirection::processKeymapChange(int fd, uint32_t size) { m_keyboard->processKeymapChange(fd, size); } void InputRedirection::processTouchDown(qint32 id, const QPointF &pos, quint32 time) { m_touch->processDown(id, pos, time); } void InputRedirection::processTouchUp(qint32 id, quint32 time) { m_touch->processUp(id, time); } void InputRedirection::processTouchMotion(qint32 id, const QPointF &pos, quint32 time) { m_touch->processMotion(id, pos, time); } void InputRedirection::cancelTouch() { m_touch->cancel(); } void InputRedirection::touchFrame() { m_touch->frame(); } Qt::MouseButtons InputRedirection::qtButtonStates() const { return m_pointer->buttons(); } static bool acceptsInput(Toplevel *t, const QPoint &pos) { const QRegion input = t->inputShape(); if (input.isEmpty()) { return true; } return input.translated(t->pos()).contains(pos); } Toplevel *InputRedirection::findToplevel(const QPoint &pos) { if (!Workspace::self()) { return nullptr; } const bool isScreenLocked = waylandServer() && waylandServer()->isScreenLocked(); // TODO: check whether the unmanaged wants input events at all if (!isScreenLocked) { // if an effect overrides the cursor we don't have a window to focus if (effects && static_cast(effects)->isMouseInterception()) { return nullptr; } const UnmanagedList &unmanaged = Workspace::self()->unmanagedList(); foreach (Unmanaged *u, unmanaged) { if (u->geometry().contains(pos) && acceptsInput(u, pos)) { return u; } } } return findManagedToplevel(pos); } Toplevel *InputRedirection::findManagedToplevel(const QPoint &pos) { if (!Workspace::self()) { return nullptr; } const bool isScreenLocked = waylandServer() && waylandServer()->isScreenLocked(); const ToplevelList &stacking = Workspace::self()->stackingOrder(); if (stacking.isEmpty()) { return NULL; } auto it = stacking.end(); do { --it; Toplevel *t = (*it); if (t->isDeleted()) { // a deleted window doesn't get mouse events continue; } if (AbstractClient *c = dynamic_cast(t)) { if (!c->isOnCurrentActivity() || !c->isOnCurrentDesktop() || c->isMinimized() || !c->isCurrentTab() || c->isHiddenInternal()) { continue; } } if (!t->readyForPainting()) { continue; } if (isScreenLocked) { if (!t->isLockScreen() && !t->isInputMethod()) { continue; } } if (t->inputGeometry().contains(pos) && acceptsInput(t, pos)) { return t; } } while (it != stacking.begin()); return NULL; } Qt::KeyboardModifiers InputRedirection::keyboardModifiers() const { return m_keyboard->modifiers(); } Qt::KeyboardModifiers InputRedirection::modifiersRelevantForGlobalShortcuts() const { return m_keyboard->modifiersRelevantForGlobalShortcuts(); } void InputRedirection::registerShortcut(const QKeySequence &shortcut, QAction *action) { Q_UNUSED(shortcut) kwinApp()->platform()->setupActionForGlobalAccel(action); } void InputRedirection::registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) { m_shortcuts->registerPointerShortcut(action, modifiers, pointerButtons); } void InputRedirection::registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) { m_shortcuts->registerAxisShortcut(action, modifiers, axis); } void InputRedirection::registerTouchpadSwipeShortcut(SwipeDirection direction, QAction *action) { m_shortcuts->registerTouchpadSwipe(action, direction); } void InputRedirection::registerGlobalAccel(KGlobalAccelInterface *interface) { m_shortcuts->setKGlobalAccelInterface(interface); } void InputRedirection::warpPointer(const QPointF &pos) { m_pointer->warp(pos); } bool InputRedirection::supportsPointerWarping() const { return m_pointer->supportsWarping(); } QPointF InputRedirection::globalPointer() const { return m_pointer->pos(); } void InputRedirection::startInteractiveWindowSelection(std::function callback, const QByteArray &cursorName) { if (!m_windowSelector || m_windowSelector->isActive()) { callback(nullptr); return; } m_windowSelector->start(callback); m_pointer->setWindowSelectionCursor(cursorName); } void InputRedirection::startInteractivePositionSelection(std::function callback) { if (!m_windowSelector || m_windowSelector->isActive()) { callback(QPoint(-1, -1)); return; } m_windowSelector->start(callback); m_pointer->setWindowSelectionCursor(QByteArray()); } bool InputRedirection::isSelectingWindow() const { return m_windowSelector ? m_windowSelector->isActive() : false; } InputDeviceHandler::InputDeviceHandler(InputRedirection *input) : QObject(input) { } InputDeviceHandler::~InputDeviceHandler() = default; void InputDeviceHandler::init() { connect(workspace(), &Workspace::stackingOrderChanged, this, &InputDeviceHandler::update); connect(workspace(), &Workspace::clientMinimizedChanged, this, &InputDeviceHandler::update); connect(VirtualDesktopManager::self(), &VirtualDesktopManager::currentChanged, this, &InputDeviceHandler::update); } bool InputDeviceHandler::setAt(Toplevel *toplevel) { if (m_at.at == toplevel) { return false; } auto old = m_at.at; disconnect(m_at.surfaceCreatedConnection); m_at.surfaceCreatedConnection = QMetaObject::Connection(); m_at.at = toplevel; emit atChanged(old, toplevel); return true; } void InputDeviceHandler::setFocus(Toplevel *toplevel) { m_focus.focus = toplevel; //TODO: call focusUpdate? } void InputDeviceHandler::setDecoration(QPointer decoration) { auto oldDeco = m_focus.decoration; m_focus.decoration = decoration; cleanupDecoration(oldDeco.data(), m_focus.decoration.data()); emit decorationChanged(); } void InputDeviceHandler::setInternalWindow(QWindow *window) { m_focus.internalWindow = window; //TODO: call internalWindowUpdate? } void InputDeviceHandler::updateFocus() { auto oldFocus = m_focus.focus; if (m_at.at && !m_at.at->surface()) { // The surface has not yet been created (special XWayland case). // Therefore listen for its creation. if (!m_at.surfaceCreatedConnection) { m_at.surfaceCreatedConnection = connect(m_at.at, &Toplevel::surfaceChanged, this, &InputDeviceHandler::update); } m_focus.focus = nullptr; } else { m_focus.focus = m_at.at; } focusUpdate(oldFocus, m_focus.focus); } bool InputDeviceHandler::updateDecoration() { const auto oldDeco = m_focus.decoration; m_focus.decoration = nullptr; auto *ac = qobject_cast(m_at.at); if (ac && ac->decoratedClient()) { const QRect clientRect = QRect(ac->clientPos(), ac->clientSize()).translated(ac->pos()); if (!clientRect.contains(position().toPoint())) { // input device above decoration m_focus.decoration = ac->decoratedClient(); } } if (m_focus.decoration == oldDeco) { // no change to decoration return false; } cleanupDecoration(oldDeco.data(), m_focus.decoration.data()); emit decorationChanged(); return true; } void InputDeviceHandler::updateInternalWindow(QWindow *window) { if (m_focus.internalWindow == window) { // no change return; } const auto oldInternal = m_focus.internalWindow; m_focus.internalWindow = window; cleanupInternalWindow(oldInternal, window); } void InputDeviceHandler::update() { if (!m_inited) { return; } Toplevel *toplevel = nullptr; QWindow *internalWindow = nullptr; if (!positionValid()) { const auto pos = position().toPoint(); internalWindow = findInternalWindow(pos); if (internalWindow) { toplevel = waylandServer()->findClient(internalWindow); } else { toplevel = input()->findToplevel(pos); } } // Always set the toplevel at the position of the input device. setAt(toplevel); if (focusUpdatesBlocked()) { return; } if (internalWindow) { if (m_focus.internalWindow != internalWindow) { // changed internal window updateDecoration(); updateInternalWindow(internalWindow); updateFocus(); } else if (updateDecoration()) { // went onto or off from decoration, update focus updateFocus(); } return; } updateInternalWindow(nullptr); if (m_focus.focus != m_at.at) { // focus change updateDecoration(); updateFocus(); return; } // check if switched to/from decoration while staying on the same Toplevel if (updateDecoration()) { // went onto or off from decoration, update focus updateFocus(); } } QWindow* InputDeviceHandler::findInternalWindow(const QPoint &pos) const { if (waylandServer()->isScreenLocked()) { return nullptr; } const auto &internalClients = waylandServer()->internalClients(); if (internalClients.isEmpty()) { return nullptr; } auto it = internalClients.end(); do { --it; QWindow *w = (*it)->internalWindow(); if (!w || !w->isVisible()) { continue; } if (!(*it)->geometry().contains(pos)) { continue; } // check input mask const QRegion mask = w->mask().translated(w->geometry().topLeft()); if (!mask.isEmpty() && !mask.contains(pos)) { continue; } if (w->property("outputOnly").toBool()) { continue; } return w; } while (it != internalClients.begin()); return nullptr; } } // namespace diff --git a/input.h b/input.h index 41412f502..189b019e3 100644 --- a/input.h +++ b/input.h @@ -1,496 +1,496 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin Copyright (C) 2018 Roman Gilg Copyright (C) 2019 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 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 PointerAxisSource { PointerAxisSourceUnknown, PointerAxisSourceWheel, PointerAxisSourceFinger, PointerAxisSourceContinuous, PointerAxisSourceWheelTilt }; enum KeyboardKeyState { KeyboardKeyReleased, KeyboardKeyPressed, KeyboardKeyAutoRepeat }; ~InputRedirection() override; 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, qint32 discreteDelta, PointerAxisSource source, 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); Toplevel *findManagedToplevel(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 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: ~InputDeviceHandler() override; 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.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; struct { QPointer at; QMetaObject::Connection surfaceCreatedConnection; } 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) Q_DECLARE_METATYPE(KWin::InputRedirection::PointerAxisSource) #endif // KWIN_INPUT_H diff --git a/input_event_spy.h b/input_event_spy.h index 32ba36ba3..eafaef482 100644 --- a/input_event_spy.h +++ b/input_event_spy.h @@ -1,92 +1,92 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2016 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_INPUT_EVENT_SPY_H #define KWIN_INPUT_EVENT_SPY_H #include #include class QPointF; class QSizeF; namespace KWin { class KeyEvent; class MouseEvent; class WheelEvent; class SwitchEvent; /** * Base class for spying on input events inside InputRedirection. * * This class is quite similar to InputEventFilter, except that it does not * support event filtering. Each InputEventSpy gets to see all input events, * the processing happens prior to sending events through the InputEventFilters. * * Deleting an instance of InputEventSpy automatically uninstalls it from * InputRedirection. - **/ + */ class KWIN_EXPORT InputEventSpy { public: InputEventSpy(); virtual ~InputEventSpy(); /** * Event spy for pointer events which can be described by a MouseEvent. * * @param event The event information about the move or button press/release - **/ + */ virtual void pointerEvent(MouseEvent *event); /** * Event spy for pointer axis events. * * @param event The event information about the axis event - **/ + */ virtual void wheelEvent(WheelEvent *event); /** * Event spy for keyboard events. * * @param event The event information about the key event - **/ + */ virtual void keyEvent(KeyEvent *event); virtual void touchDown(quint32 id, const QPointF &pos, quint32 time); virtual void touchMotion(quint32 id, const QPointF &pos, quint32 time); virtual void touchUp(quint32 id, quint32 time); virtual void pinchGestureBegin(int fingerCount, quint32 time); virtual void pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time); virtual void pinchGestureEnd(quint32 time); virtual void pinchGestureCancelled(quint32 time); virtual void swipeGestureBegin(int fingerCount, quint32 time); virtual void swipeGestureUpdate(const QSizeF &delta, quint32 time); virtual void swipeGestureEnd(quint32 time); virtual void swipeGestureCancelled(quint32 time); virtual void switchEvent(SwitchEvent *event); }; } // namespace KWin #endif diff --git a/kcmkwin/common/effectsmodel.h b/kcmkwin/common/effectsmodel.h index 7ecc81c86..bb49dc809 100644 --- a/kcmkwin/common/effectsmodel.h +++ b/kcmkwin/common/effectsmodel.h @@ -1,270 +1,270 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Antonis Tsiapaliokas 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 . *********************************************************************/ #pragma once #include #include #include #include #include #include #include namespace KWin { class KWIN_EXPORT EffectsModel : public QAbstractItemModel { Q_OBJECT public: /** * This enum type is used to specify data roles. - **/ + */ enum AdditionalRoles { /** * The user-friendly name of the effect. - **/ + */ NameRole = Qt::UserRole + 1, /** * The description of the effect. - **/ + */ DescriptionRole, /** * The name of the effect's author. If there are several authors, they * will be comma separated. - **/ + */ AuthorNameRole, /** * The email of the effect's author. If there are several authors, the * emails will be comma separated. - **/ + */ AuthorEmailRole, /** * The license of the effect. - **/ + */ LicenseRole, /** * The version of the effect. - **/ + */ VersionRole, /** * The category of the effect. - **/ + */ CategoryRole, /** * The service name(plugin name) of the effect. - **/ + */ ServiceNameRole, /** * The icon name of the effect. - **/ + */ IconNameRole, /** * Whether the effect is enabled or disabled. - **/ + */ StatusRole, /** * Link to a video demonstration of the effect. - **/ + */ VideoRole, /** * Link to the home page of the effect. - **/ + */ WebsiteRole, /** * Whether the effect is supported. - **/ + */ SupportedRole, /** * The exclusive group of the effect. - **/ + */ ExclusiveRole, /** * Whether the effect is internal. - **/ + */ InternalRole, /** * Whether the effect has a KCM. - **/ + */ ConfigurableRole, /** * Whether this is a scripted effect. - **/ + */ ScriptedRole, /** * Whether the effect is enabled by default. - **/ + */ EnabledByDefaultRole }; /** * This enum type is used to specify the status of a given effect. - **/ + */ enum class Status { /** * The effect is disabled. - **/ + */ Disabled = Qt::Unchecked, /** * An enable function is used to determine whether the effect is enabled. * For example, such function can be useful to disable the blur effect * when running in a virtual machine. - **/ + */ EnabledUndeterminded = Qt::PartiallyChecked, /** * The effect is enabled. - **/ + */ Enabled = Qt::Checked }; explicit EffectsModel(QObject *parent = nullptr); // Reimplemented from QAbstractItemModel. QHash roleNames() const override; QModelIndex index(int row, int column, const QModelIndex &parent = {}) const override; QModelIndex parent(const QModelIndex &child) const override; int rowCount(const QModelIndex &parent = {}) const override; int columnCount(const QModelIndex &parent = {}) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; /** * Changes the status of a given effect. * * @param rowIndex An effect represented by the given index. * @param effectState The new state. * @note In order to actually apply the change, you have to call save(). - **/ + */ void updateEffectStatus(const QModelIndex &rowIndex, Status effectState); /** * This enum type is used to specify load options. - **/ + */ enum class LoadOptions { None, /** * Do not discard unsaved changes when reloading the model. - **/ + */ KeepDirty }; /** * Loads effects. * * You have to call this method in order to populate the model. - **/ + */ void load(LoadOptions options = LoadOptions::None); /** * Saves status of each modified effect. - **/ + */ void save(); /** * Resets the status of each effect to the default state. * * @note In order to actually apply the change, you have to call save(). - **/ + */ void defaults(); /** * Whether the model has unsaved changes. - **/ + */ bool needsSave() const; /** * Finds an effect with the given plugin id. - **/ + */ QModelIndex findByPluginId(const QString &pluginId) const; /** * Shows a configuration dialog for a given effect. * * @param index An effect represented by the given index. * @param transientParent The transient parent of the configuration dialog. - **/ + */ void requestConfigure(const QModelIndex &index, QWindow *transientParent); Q_SIGNALS: /** * This signal is emitted when the model is loaded or reloaded. * * @see load - **/ + */ void loaded(); protected: enum class Kind { BuiltIn, Binary, Scripted }; struct EffectData { QString name; QString description; QString authorName; QString authorEmail; QString license; QString version; QString untranslatedCategory; QString category; QString serviceName; QString iconName; Status status; Status originalStatus; bool enabledByDefault; bool enabledByDefaultFunction; QUrl video; QUrl website; bool supported; QString exclusiveGroup; bool internal; bool configurable; Kind kind; bool changed = false; }; /** * Returns whether the given effect should be stored in the model. * * @param data The effect. * @returns @c true if the effect should be stored, otherwise @c false. - **/ + */ virtual bool shouldStore(const EffectData &data) const; private: void loadBuiltInEffects(const KConfigGroup &kwinConfig, const KPluginInfo::List &configs); void loadJavascriptEffects(const KConfigGroup &kwinConfig); void loadPluginEffects(const KConfigGroup &kwinConfig, const KPluginInfo::List &configs); QVector m_effects; QVector m_pendingEffects; int m_lastSerial = -1; Q_DISABLE_COPY(EffectsModel) }; } diff --git a/kcmkwin/kwindesktop/desktopsmodel.h b/kcmkwin/kwindesktop/desktopsmodel.h index 376ea3554..e2626fe61 100644 --- a/kcmkwin/kwindesktop/desktopsmodel.h +++ b/kcmkwin/kwindesktop/desktopsmodel.h @@ -1,129 +1,129 @@ /* * Copyright (C) 2018 Eike Hein * Copyright (C) 2018 Marco Martin * * 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 DESKTOPSMODEL_H #define DESKTOPSMODEL_H #include #include "../virtualdesktopsdbustypes.h" class QDBusArgument; class QDBusMessage; class QDBusServiceWatcher; namespace KWin { /** * @short An item model around KWin's D-Bus API for virtual desktops. * * The model initially gets the state from KWin and populates. * * As long as the user makes no changes, KWin-side changes are directly * exposed in the model. * * If the user makes changes (see the `userModified` property), it stops * exposing KWin-side changes live, but it keeps track of the KWin-side * changes, so it can figure out and apply the delta when `syncWithServer` * is called. * * When KWin-side changes happen while the model is user-modified, the * model signals this via the `serverModified` property. A call to * `syncWithServer` will overwrite the KWin-side changes. * * After synchronization, the model tracks Kwin-side changes again, * until the user makes further changes. * * @author Eike Hein - **/ + */ class DesktopsModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(bool ready READ ready NOTIFY readyChanged) Q_PROPERTY(QString error READ error NOTIFY errorChanged) Q_PROPERTY(bool userModified READ userModified NOTIFY userModifiedChanged) Q_PROPERTY(bool serverModified READ serverModified NOTIFY serverModifiedChanged) Q_PROPERTY(int rows READ rows WRITE setRows NOTIFY rowsChanged) public: enum AdditionalRoles { Id = Qt::UserRole + 1, DesktopRow }; Q_ENUM(AdditionalRoles) explicit DesktopsModel(QObject *parent = nullptr); ~DesktopsModel() override; QHash roleNames() const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int rowCount(const QModelIndex &parent = {}) const override; bool ready() const; QString error() const; bool userModified() const; bool serverModified() const; int rows() const; void setRows(int rows); Q_INVOKABLE void createDesktop(const QString &name); Q_INVOKABLE void removeDesktop(const QString &id); Q_INVOKABLE void setDesktopName(const QString &id, const QString &name); Q_INVOKABLE void syncWithServer(); Q_SIGNALS: void readyChanged() const; void errorChanged() const; void userModifiedChanged() const; void serverModifiedChanged() const; void rowsChanged() const; protected Q_SLOTS: void reset(); void getAllAndConnect(const QDBusMessage &msg); void desktopCreated(const QString &id, const KWin::DBusDesktopDataStruct &data); void desktopRemoved(const QString &id); void desktopDataChanged(const QString &id, const KWin::DBusDesktopDataStruct &data); void desktopRowsChanged(uint rows); void updateModifiedState(bool server = false); void handleCallError(); private: QDBusServiceWatcher *m_serviceWatcher; QString m_error; bool m_userModified; bool m_serverModified; QStringList m_serverSideDesktops; QHash m_serverSideNames; int m_serverSideRows; QStringList m_desktops; QHash m_names; int m_rows; bool m_synchronizing; }; } #endif diff --git a/kcmkwin/kwinscripts/module.h b/kcmkwin/kwinscripts/module.h index 1a14d4ea4..983d37b4a 100644 --- a/kcmkwin/kwinscripts/module.h +++ b/kcmkwin/kwinscripts/module.h @@ -1,73 +1,73 @@ /* * Copyright (c) 2011 Tamas Krutki * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MODULE_H #define MODULE_H #include #include namespace Ui { class Module; } class KJob; class Module : public KCModule { Q_OBJECT public: /** * Constructor. * * @param parent Parent widget of the module * @param args Arguments for the module - **/ + */ explicit Module(QWidget *parent, const QVariantList &args = QVariantList()); /** * Destructor. - **/ + */ ~Module() override; void load() override; void save() override; void defaults() override; protected Q_SLOTS: /** * Called when the import script button is clicked. - **/ + */ void importScript(); void importScriptInstallFinished(KJob *job); private: /** * UI - **/ + */ Ui::Module *ui; /** * Updates the contents of the list view. - **/ + */ void updateListViewContents(); KSharedConfigPtr m_kwinConfig; }; #endif // MODULE_H diff --git a/kcmkwin/kwintabbox/layoutpreview.h b/kcmkwin/kwintabbox/layoutpreview.h index 5639682ad..7f77a5b09 100644 --- a/kcmkwin/kwintabbox/layoutpreview.h +++ b/kcmkwin/kwintabbox/layoutpreview.h @@ -1,145 +1,145 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009, 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_TABBOX_LAYOUTPREVIEW_H #define KWIN_TABBOX_LAYOUTPREVIEW_H #include #include #include #include namespace KWin { namespace TabBox { class SwitcherItem; class LayoutPreview : public QObject { Q_OBJECT public: explicit LayoutPreview(const QString &path, QObject *parent = nullptr); ~LayoutPreview() override; bool eventFilter(QObject *object, QEvent *event) override; private: SwitcherItem *m_item; }; class ExampleClientModel : public QAbstractListModel { Q_OBJECT public: explicit ExampleClientModel(QObject *parent = nullptr); ~ExampleClientModel() override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QHash roleNames() const override; Q_INVOKABLE QString longestCaption() const; private: void init(); QList m_services; KService::Ptr m_fileManager; KService::Ptr m_browser; KService::Ptr m_email; KService::Ptr m_systemSettings; }; class SwitcherItem : public QObject { Q_OBJECT Q_PROPERTY(QAbstractItemModel *model READ model NOTIFY modelChanged) Q_PROPERTY(QRect screenGeometry READ screenGeometry NOTIFY screenGeometryChanged) Q_PROPERTY(bool visible READ isVisible NOTIFY visibleChanged) Q_PROPERTY(bool allDesktops READ isAllDesktops NOTIFY allDesktopsChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) /** * The main QML item that will be displayed in the Dialog - **/ + */ Q_PROPERTY(QObject *item READ item WRITE setItem NOTIFY itemChanged) Q_CLASSINFO("DefaultProperty", "item") public: SwitcherItem(QObject *parent = nullptr); ~SwitcherItem() override; QAbstractItemModel *model() const; QRect screenGeometry() const; bool isVisible() const; bool isAllDesktops() const; int currentIndex() const; void setCurrentIndex(int index); QObject *item() const; void setItem(QObject *item); void setVisible(bool visible); void incrementIndex(); void decrementIndex(); Q_SIGNALS: void visibleChanged(); void currentIndexChanged(int index); void modelChanged(); void allDesktopsChanged(); void screenGeometryChanged(); void itemChanged(); private: QAbstractItemModel *m_model; QObject *m_item; int m_currentIndex; bool m_visible; }; inline QAbstractItemModel *SwitcherItem::model() const { return m_model; } inline bool SwitcherItem::isVisible() const { return m_visible; } inline bool SwitcherItem::isAllDesktops() const { return true; } inline int SwitcherItem::currentIndex() const { return m_currentIndex; } inline QObject *SwitcherItem::item() const { return m_item; } } // namespace TabBox } // namespace KWin #endif // KWIN_TABBOX_LAYOUTPREVIEW_H diff --git a/keyboard_input.h b/keyboard_input.h index a744e18c3..c2f4c2592 100644 --- a/keyboard_input.h +++ b/keyboard_input.h @@ -1,104 +1,104 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013, 2016 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_KEYBOARD_INPUT_H #define KWIN_KEYBOARD_INPUT_H #include "input.h" #include "xkb.h" #include #include #include #include class QWindow; struct xkb_context; struct xkb_keymap; struct xkb_state; struct xkb_compose_table; struct xkb_compose_state; typedef uint32_t xkb_mod_index_t; typedef uint32_t xkb_led_index_t; typedef uint32_t xkb_keysym_t; typedef uint32_t xkb_layout_index_t; namespace KWin { class InputRedirection; class KeyboardLayout; class ModifiersChangedSpy; class Toplevel; namespace LibInput { class Device; } class KWIN_EXPORT KeyboardInputRedirection : public QObject { Q_OBJECT public: explicit KeyboardInputRedirection(InputRedirection *parent); ~KeyboardInputRedirection() override; void init(); void update(); /** * @internal - **/ + */ void processKey(uint32_t key, InputRedirection::KeyboardKeyState state, uint32_t time, LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processModifiers(uint32_t modsDepressed, uint32_t modsLatched, uint32_t modsLocked, uint32_t group); /** * @internal - **/ + */ void processKeymapChange(int fd, uint32_t size); Xkb *xkb() const { return m_xkb.data(); } Qt::KeyboardModifiers modifiers() const { return m_xkb->modifiers(); } Qt::KeyboardModifiers modifiersRelevantForGlobalShortcuts() const { return m_xkb->modifiersRelevantForGlobalShortcuts(); } Q_SIGNALS: void ledsChanged(KWin::Xkb::LEDs); private: InputRedirection *m_input; bool m_inited = false; QScopedPointer m_xkb; QMetaObject::Connection m_activeClientSurfaceChangedConnection; ModifiersChangedSpy *m_modifiersChangedSpy = nullptr; KeyboardLayout *m_keyboardLayout = nullptr; }; } #endif diff --git a/layers.cpp b/layers.cpp index 07156d961..c64b0f26c 100644 --- a/layers.cpp +++ b/layers.cpp @@ -1,880 +1,880 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ // SELI zmenit doc /* This file contains things relevant to stacking order and layers. Design: Normal unconstrained stacking order, as requested by the user (by clicking on windows to raise them, etc.), is in Workspace::unconstrained_stacking_order. That list shouldn't be used at all, except for building Workspace::stacking_order. The building is done in Workspace::constrainedStackingOrder(). Only Workspace::stackingOrder() should be used to get the stacking order, because it also checks the stacking order is up to date. All clients are also stored in Workspace::clients (except for isDesktop() clients, as those are very special, and are stored in Workspace::desktops), in the order the clients were created. Every window has one layer assigned in which it is. There are 7 layers, from bottom : DesktopLayer, BelowLayer, NormalLayer, DockLayer, AboveLayer, NotificationLayer, ActiveLayer, CriticalNotificationLayer, and OnScreenDisplayLayer (see also NETWM sect.7.10.). The layer a window is in depends on the window type, and on other things like whether the window is active. We extend the layers provided in NETWM by the NotificationLayer, OnScreenDisplayLayer, and CriticalNotificationLayer. The NoficationLayer contains notification windows which are kept above all windows except the active fullscreen window. The CriticalNotificationLayer contains notification windows which are important enough to keep them even above fullscreen windows. The OnScreenDisplayLayer is used for eg. volume and brightness change feedback and is kept above all windows since it provides immediate response to a user action. NET::Splash clients belong to the Normal layer. NET::TopMenu clients belong to Dock layer. Clients that are both NET::Dock and NET::KeepBelow are in the Normal layer in order to keep the 'allow window to cover the panel' Kicker setting to work as intended (this may look like a slight spec violation, but a) I have no better idea, b) the spec allows adjusting the stacking order if the WM thinks it's a good idea . We put all NET::KeepAbove above all Docks too, even though the spec suggests putting them in the same layer. Most transients are in the same layer as their mainwindow, see Workspace::constrainedStackingOrder(), they may also be in higher layers, but they should never be below their mainwindow. When some client attribute changes (above/below flag, transiency...), Workspace::updateClientLayer() should be called in order to make sure it's moved to the appropriate layer ClientList if needed. Currently the things that affect client in which layer a client belongs: KeepAbove/Keep Below flags, window type, fullscreen state and whether the client is active, mainclient (transiency). Make sure updateStackingOrder() is called in order to make Workspace::stackingOrder() up to date and propagated to the world. Using Workspace::blockStackingUpdates() (or the StackingUpdatesBlocker helper class) it's possible to temporarily disable updates and the stacking order will be updated once after it's allowed again. */ #include "utils.h" #include "client.h" #include "focuschain.h" #include "netinfo.h" #include "workspace.h" #include "tabbox.h" #include "group.h" #include "rules.h" #include "screens.h" #include "unmanaged.h" #include "deleted.h" #include "effects.h" #include "composite.h" #include "screenedge.h" #include "shell_client.h" #include "wayland_server.h" #include #include namespace KWin { //******************************* // Workspace //******************************* void Workspace::updateClientLayer(AbstractClient* c) { if (c) c->updateLayer(); } void Workspace::updateStackingOrder(bool propagate_new_clients) { if (block_stacking_updates > 0) { if (propagate_new_clients) blocked_propagating_new_clients = true; return; } ToplevelList new_stacking_order = constrainedStackingOrder(); bool changed = (force_restacking || new_stacking_order != stacking_order); force_restacking = false; stacking_order = new_stacking_order; if (changed || propagate_new_clients) { propagateClients(propagate_new_clients); emit stackingOrderChanged(); if (m_compositor) { m_compositor->addRepaintFull(); } if (active_client) active_client->updateMouseGrab(); } } /** * Some fullscreen effects have to raise the screenedge on top of an input window, thus all windows * this function puts them back where they belong for regular use and is some cheap variant of * the regular propagateClients function in that it completely ignores managed clients and everything * else and also does not update the NETWM property. * Called from Effects::destroyInputWindow so far. - **/ + */ void Workspace::stackScreenEdgesUnderOverrideRedirect() { if (!rootInfo()) { return; } Xcb::restackWindows(QVector() << rootInfo()->supportWindow() << ScreenEdges::self()->windows()); } /** * Propagates the managed clients to the world. * Called ONLY from updateStackingOrder(). - **/ + */ void Workspace::propagateClients(bool propagate_new_clients) { if (!rootInfo()) { return; } // restack the windows according to the stacking order // supportWindow > electric borders > clients > hidden clients QVector newWindowStack; // Stack all windows under the support window. The support window is // not used for anything (besides the NETWM property), and it's not shown, // but it was lowered after kwin startup. Stacking all clients below // it ensures that no client will be ever shown above override-redirect // windows (e.g. popups). newWindowStack << rootInfo()->supportWindow(); newWindowStack << ScreenEdges::self()->windows(); newWindowStack << manual_overlays; newWindowStack.reserve(newWindowStack.size() + 2*stacking_order.size()); // *2 for inputWindow for (int i = stacking_order.size() - 1; i >= 0; --i) { Client *client = qobject_cast(stacking_order.at(i)); if (!client || client->hiddenPreview()) { continue; } if (client->inputId()) // Stack the input window above the frame newWindowStack << client->inputId(); newWindowStack << client->frameId(); } // when having hidden previews, stack hidden windows below everything else // (as far as pure X stacking order is concerned), in order to avoid having // these windows that should be unmapped to interfere with other windows for (int i = stacking_order.size() - 1; i >= 0; --i) { Client *client = qobject_cast(stacking_order.at(i)); if (!client || !client->hiddenPreview()) continue; newWindowStack << client->frameId(); } // TODO isn't it too inefficient to restack always all clients? // TODO don't restack not visible windows? assert(newWindowStack.at(0) == rootInfo()->supportWindow()); Xcb::restackWindows(newWindowStack); int pos = 0; xcb_window_t *cl(nullptr); if (propagate_new_clients) { cl = new xcb_window_t[ manual_overlays.count() + desktops.count() + clients.count()]; for (const auto win : manual_overlays) { cl[pos++] = win; } // TODO this is still not completely in the map order for (ClientList::ConstIterator it = desktops.constBegin(); it != desktops.constEnd(); ++it) cl[pos++] = (*it)->window(); for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) cl[pos++] = (*it)->window(); rootInfo()->setClientList(cl, pos); delete [] cl; } cl = new xcb_window_t[ manual_overlays.count() + stacking_order.count()]; pos = 0; for (ToplevelList::ConstIterator it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { if ((*it)->isClient()) cl[pos++] = (*it)->window(); } for (const auto win : manual_overlays) { cl[pos++] = win; } rootInfo()->setClientListStacking(cl, pos); delete [] cl; // Make the cached stacking order invalid here, in case we need the new stacking order before we get // the matching event, due to X being asynchronous. markXStackingOrderAsDirty(); } /** * Returns topmost visible client. Windows on the dock, the desktop * or of any other special kind are excluded. Also if the window * doesn't accept focus it's excluded. - **/ + */ // TODO misleading name for this method, too many slightly different ways to use it AbstractClient* Workspace::topClientOnDesktop(int desktop, int screen, bool unconstrained, bool only_normal) const { // TODO Q_ASSERT( block_stacking_updates == 0 ); ToplevelList list; if (!unconstrained) list = stacking_order; else list = unconstrained_stacking_order; for (int i = list.size() - 1; i >= 0; --i) { AbstractClient *c = qobject_cast(list.at(i)); if (!c) { continue; } if (c->isOnDesktop(desktop) && c->isShown(false) && c->isOnCurrentActivity()) { if (screen != -1 && c->screen() != screen) continue; if (!only_normal) return c; if (c->wantsTabFocus() && !c->isSpecialWindow()) return c; } } return 0; } AbstractClient* Workspace::findDesktop(bool topmost, int desktop) const { // TODO Q_ASSERT( block_stacking_updates == 0 ); if (topmost) { for (int i = stacking_order.size() - 1; i >= 0; i--) { AbstractClient *c = qobject_cast(stacking_order.at(i)); if (c && c->isOnDesktop(desktop) && c->isDesktop() && c->isShown(true)) return c; } } else { // bottom-most foreach (Toplevel * c, stacking_order) { AbstractClient *client = qobject_cast(c); if (client && c->isOnDesktop(desktop) && c->isDesktop() && client->isShown(true)) return client; } } return NULL; } void Workspace::raiseOrLowerClient(AbstractClient *c) { if (!c) return; AbstractClient* topmost = NULL; // TODO Q_ASSERT( block_stacking_updates == 0 ); if (most_recently_raised && stacking_order.contains(most_recently_raised) && most_recently_raised->isShown(true) && c->isOnCurrentDesktop()) topmost = most_recently_raised; else topmost = topClientOnDesktop(c->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : c->desktop(), options->isSeparateScreenFocus() ? c->screen() : -1); if (c == topmost) lowerClient(c); else raiseClient(c); } void Workspace::lowerClient(AbstractClient* c, bool nogroup) { if (!c) return; c->cancelAutoRaise(); StackingUpdatesBlocker blocker(this); unconstrained_stacking_order.removeAll(c); unconstrained_stacking_order.prepend(c); if (!nogroup && c->isTransient()) { // lower also all windows in the group, in their reversed stacking order ClientList wins; if (auto group = c->group()) { wins = ensureStackingOrder(group->members()); } for (int i = wins.size() - 1; i >= 0; --i) { if (wins[ i ] != c) lowerClient(wins[ i ], true); } } if (c == most_recently_raised) most_recently_raised = 0; } void Workspace::lowerClientWithinApplication(AbstractClient* c) { if (!c) return; c->cancelAutoRaise(); StackingUpdatesBlocker blocker(this); unconstrained_stacking_order.removeAll(c); bool lowered = false; // first try to put it below the bottom-most window of the application for (ToplevelList::Iterator it = unconstrained_stacking_order.begin(); it != unconstrained_stacking_order.end(); ++it) { AbstractClient *client = qobject_cast(*it); if (!client) { continue; } if (AbstractClient::belongToSameApplication(client, c)) { unconstrained_stacking_order.insert(it, c); lowered = true; break; } } if (!lowered) unconstrained_stacking_order.prepend(c); // ignore mainwindows } void Workspace::raiseClient(AbstractClient* c, bool nogroup) { if (!c) return; c->cancelAutoRaise(); StackingUpdatesBlocker blocker(this); if (!nogroup && c->isTransient()) { QList transients; AbstractClient *transient_parent = c; while ((transient_parent = transient_parent->transientFor())) transients << transient_parent; foreach (transient_parent, transients) raiseClient(transient_parent, true); } unconstrained_stacking_order.removeAll(c); unconstrained_stacking_order.append(c); if (!c->isSpecialWindow()) { most_recently_raised = c; } } void Workspace::raiseClientWithinApplication(AbstractClient* c) { if (!c) return; c->cancelAutoRaise(); StackingUpdatesBlocker blocker(this); // ignore mainwindows // first try to put it above the top-most window of the application for (int i = unconstrained_stacking_order.size() - 1; i > -1 ; --i) { AbstractClient *other = qobject_cast(unconstrained_stacking_order.at(i)); if (!other) { continue; } if (other == c) // don't lower it just because it asked to be raised return; if (AbstractClient::belongToSameApplication(other, c)) { unconstrained_stacking_order.removeAll(c); unconstrained_stacking_order.insert(unconstrained_stacking_order.indexOf(other) + 1, c); // insert after the found one break; } } } void Workspace::raiseClientRequest(KWin::AbstractClient *c, NET::RequestSource src, xcb_timestamp_t timestamp) { if (src == NET::FromTool || allowFullClientRaising(c, timestamp)) raiseClient(c); else { raiseClientWithinApplication(c); c->demandAttention(); } } void Workspace::lowerClientRequest(KWin::Client *c, NET::RequestSource src, xcb_timestamp_t /*timestamp*/) { // If the client has support for all this focus stealing prevention stuff, // do only lowering within the application, as that's the more logical // variant of lowering when application requests it. // No demanding of attention here of course. if (src == NET::FromTool || !c->hasUserTimeSupport()) lowerClient(c); else lowerClientWithinApplication(c); } void Workspace::lowerClientRequest(KWin::AbstractClient *c) { lowerClientWithinApplication(c); } void Workspace::restack(AbstractClient* c, AbstractClient* under, bool force) { assert(unconstrained_stacking_order.contains(under)); if (!force && !AbstractClient::belongToSameApplication(under, c)) { // put in the stacking order below _all_ windows belonging to the active application for (int i = 0; i < unconstrained_stacking_order.size(); ++i) { AbstractClient *other = qobject_cast(unconstrained_stacking_order.at(i)); if (other && other->layer() == c->layer() && AbstractClient::belongToSameApplication(under, other)) { under = (c == other) ? 0 : other; break; } } } if (under) { unconstrained_stacking_order.removeAll(c); unconstrained_stacking_order.insert(unconstrained_stacking_order.indexOf(under), c); } assert(unconstrained_stacking_order.contains(c)); FocusChain::self()->moveAfterClient(c, under); updateStackingOrder(); } void Workspace::restackClientUnderActive(AbstractClient* c) { if (!active_client || active_client == c || active_client->layer() != c->layer()) { raiseClient(c); return; } restack(c, active_client); } void Workspace::restoreSessionStackingOrder(Client* c) { if (c->sessionStackingOrder() < 0) return; StackingUpdatesBlocker blocker(this); unconstrained_stacking_order.removeAll(c); for (ToplevelList::Iterator it = unconstrained_stacking_order.begin(); // from bottom it != unconstrained_stacking_order.end(); ++it) { Client *current = qobject_cast(*it); if (!current) { continue; } if (current->sessionStackingOrder() > c->sessionStackingOrder()) { unconstrained_stacking_order.insert(it, c); return; } } unconstrained_stacking_order.append(c); } /** * Returns a stacking order based upon \a list that fulfills certain contained. - **/ + */ ToplevelList Workspace::constrainedStackingOrder() { ToplevelList layer[ NumLayers ]; // build the order from layers QVector< QMap > minimum_layer(screens()->count()); for (ToplevelList::ConstIterator it = unconstrained_stacking_order.constBegin(), end = unconstrained_stacking_order.constEnd(); it != end; ++it) { Layer l = (*it)->layer(); const int screen = (*it)->screen(); Client *c = qobject_cast(*it); QMap< Group*, Layer >::iterator mLayer = minimum_layer[screen].find(c ? c->group() : NULL); if (mLayer != minimum_layer[screen].end()) { // If a window is raised above some other window in the same window group // which is in the ActiveLayer (i.e. it's fulscreened), make sure it stays // above that window (see #95731). if (*mLayer == ActiveLayer && (l > BelowLayer)) l = ActiveLayer; *mLayer = l; } else if (c) { minimum_layer[screen].insertMulti(c->group(), l); } layer[ l ].append(*it); } ToplevelList stacking; for (Layer lay = FirstLayer; lay < NumLayers; ++lay) stacking += layer[ lay ]; // now keep transients above their mainwindows // TODO this could(?) use some optimization for (int i = stacking.size() - 1; i >= 0;) { // Index of the main window for the current transient window. int i2 = -1; // If the current transient has "child" transients, we'd like to restart // construction of the constrained stacking order from the position where // the current transient will be moved. bool hasTransients = false; // Find topmost client this one is transient for. if (auto *client = qobject_cast(stacking[i])) { if (!client->isTransient()) { --i; continue; } for (i2 = stacking.size() - 1; i2 >= 0; --i2) { auto *c2 = qobject_cast(stacking[i2]); if (!c2) { continue; } if (c2 == client) { i2 = -1; // Don't reorder, already on top of its main window. break; } if (c2->hasTransient(client, true) && keepTransientAbove(c2, client)) { break; } } hasTransients = !client->transients().isEmpty(); // If the current transient doesn't have any "alive" transients, check // whether it has deleted transients that have to be raised. const bool searchForDeletedTransients = !hasTransients && !deletedList().isEmpty(); if (searchForDeletedTransients) { for (int j = i + 1; j < stacking.count(); ++j) { auto *deleted = qobject_cast(stacking[j]); if (!deleted) { continue; } if (deleted->wasTransientFor(client)) { hasTransients = true; break; } } } } else if (auto *deleted = qobject_cast(stacking[i])) { if (!deleted->wasTransient()) { --i; continue; } for (i2 = stacking.size() - 1; i2 >= 0; --i2) { Toplevel *c2 = stacking[i2]; if (c2 == deleted) { i2 = -1; // Don't reorder, already on top of its main window. break; } if (deleted->wasTransientFor(c2) && keepDeletedTransientAbove(c2, deleted)) { break; } } hasTransients = !deleted->transients().isEmpty(); } if (i2 == -1) { --i; continue; } Toplevel *current = stacking[i]; stacking.removeAt(i); --i; // move onto the next item (for next for () iteration) --i2; // adjust index of the mainwindow after the remove above if (hasTransients) { // this one now can be possibly above its transients, i = i2; // so go again higher in the stack order and possibly move those transients again } ++i2; // insert after (on top of) the mainwindow, it's ok if it2 is now stacking.end() stacking.insert(i2, current); } return stacking; } void Workspace::blockStackingUpdates(bool block) { if (block) { if (block_stacking_updates == 0) blocked_propagating_new_clients = false; ++block_stacking_updates; } else // !block if (--block_stacking_updates == 0) { updateStackingOrder(blocked_propagating_new_clients); if (effects) static_cast(effects)->checkInputWindowStacking(); } } namespace { template QList ensureStackingOrderInList(const ToplevelList &stackingOrder, const QList &list) { static_assert(std::is_base_of::value, "U must be derived from T"); // TODO Q_ASSERT( block_stacking_updates == 0 ); if (list.count() < 2) return list; // TODO is this worth optimizing? QList result = list; for (auto it = stackingOrder.begin(); it != stackingOrder.end(); ++it) { T *c = qobject_cast(*it); if (!c) { continue; } if (result.removeAll(c) != 0) result.append(c); } return result; } } // Ensure list is in stacking order ClientList Workspace::ensureStackingOrder(const ClientList& list) const { return ensureStackingOrderInList(stacking_order, list); } QList Workspace::ensureStackingOrder(const QList &list) const { return ensureStackingOrderInList(stacking_order, list); } // check whether a transient should be actually kept above its mainwindow // there may be some special cases where this rule shouldn't be enfored bool Workspace::keepTransientAbove(const AbstractClient* mainwindow, const AbstractClient* transient) { // #93832 - don't keep splashscreens above dialogs if (transient->isSplash() && mainwindow->isDialog()) return false; // This is rather a hack for #76026. Don't keep non-modal dialogs above // the mainwindow, but only if they're group transient (since only such dialogs // have taskbar entry in Kicker). A proper way of doing this (both kwin and kicker) // needs to be found. if (transient->isDialog() && !transient->isModal() && transient->groupTransient()) return false; // #63223 - don't keep transients above docks, because the dock is kept high, // and e.g. dialogs for them would be too high too // ignore this if the transient has a placement hint which indicates it should go above it's parent if (mainwindow->isDock() && !transient->hasTransientPlacementHint()) return false; return true; } bool Workspace::keepDeletedTransientAbove(const Toplevel *mainWindow, const Deleted *transient) const { // #93832 - Don't keep splashscreens above dialogs. if (transient->isSplash() && mainWindow->isDialog()) { return false; } if (transient->wasX11Client()) { // If a group transient was active, we should keep it above no matter // what, because at the time when the transient was closed, it was above // the main window. if (transient->wasGroupTransient() && transient->wasActive()) { return true; } // This is rather a hack for #76026. Don't keep non-modal dialogs above // the mainwindow, but only if they're group transient (since only such // dialogs have taskbar entry in Kicker). A proper way of doing this // (both kwin and kicker) needs to be found. if (transient->wasGroupTransient() && transient->isDialog() && !transient->isModal()) { return false; } // #63223 - Don't keep transients above docks, because the dock is kept // high, and e.g. dialogs for them would be too high too. if (mainWindow->isDock()) { return false; } } return true; } // Returns all windows in their stacking order on the root window. ToplevelList Workspace::xStackingOrder() const { if (m_xStackingDirty) { const_cast(this)->updateXStackingOrder(); } return x_stacking; } void Workspace::updateXStackingOrder() { x_stacking.clear(); std::unique_ptr tree{std::move(m_xStackingQueryTree)}; // use our own stacking order, not the X one, as they may differ foreach (Toplevel * c, stacking_order) x_stacking.append(c); if (tree && !tree->isNull()) { xcb_window_t *windows = tree->children(); const auto count = tree->data()->children_len; int foundUnmanagedCount = unmanaged.count(); for (unsigned int i = 0; i < count; ++i) { for (auto it = unmanaged.constBegin(); it != unmanaged.constEnd(); ++it) { Unmanaged *u = *it; if (u->window() == windows[i]) { x_stacking.append(u); foundUnmanagedCount--; break; } } if (foundUnmanagedCount == 0) { break; } } } if (waylandServer()) { const auto clients = waylandServer()->internalClients(); for (auto c: clients) { if (c->isShown(false)) { x_stacking << c; } } } m_xStackingDirty = false; } //******************************* // Client //******************************* void Client::restackWindow(xcb_window_t above, int detail, NET::RequestSource src, xcb_timestamp_t timestamp, bool send_event) { Client *other = 0; if (detail == XCB_STACK_MODE_OPPOSITE) { other = workspace()->findClient(Predicate::WindowMatch, above); if (!other) { workspace()->raiseOrLowerClient(this); return; } ToplevelList::const_iterator it = workspace()->stackingOrder().constBegin(), end = workspace()->stackingOrder().constEnd(); while (it != end) { if (*it == this) { detail = XCB_STACK_MODE_ABOVE; break; } else if (*it == other) { detail = XCB_STACK_MODE_BELOW; break; } ++it; } } else if (detail == XCB_STACK_MODE_TOP_IF) { other = workspace()->findClient(Predicate::WindowMatch, above); if (other && other->geometry().intersects(geometry())) workspace()->raiseClientRequest(this, src, timestamp); return; } else if (detail == XCB_STACK_MODE_BOTTOM_IF) { other = workspace()->findClient(Predicate::WindowMatch, above); if (other && other->geometry().intersects(geometry())) workspace()->lowerClientRequest(this, src, timestamp); return; } if (!other) other = workspace()->findClient(Predicate::WindowMatch, above); if (other && detail == XCB_STACK_MODE_ABOVE) { ToplevelList::const_iterator it = workspace()->stackingOrder().constEnd(), begin = workspace()->stackingOrder().constBegin(); while (--it != begin) { if (*it == other) { // the other one is top on stack it = begin; // invalidate src = NET::FromTool; // force break; } Client *c = qobject_cast(*it); if (!c || !( (*it)->isNormalWindow() && c->isShown(true) && (*it)->isOnCurrentDesktop() && (*it)->isOnCurrentActivity() && (*it)->isOnScreen(screen()) )) continue; // irrelevant clients if (*(it - 1) == other) break; // "it" is the one above the target one, stack below "it" } if (it != begin && (*(it - 1) == other)) other = qobject_cast(*it); else other = 0; } if (other) workspace()->restack(this, other); else if (detail == XCB_STACK_MODE_BELOW) workspace()->lowerClientRequest(this, src, timestamp); else if (detail == XCB_STACK_MODE_ABOVE) workspace()->raiseClientRequest(this, src, timestamp); if (send_event) sendSyntheticConfigureNotify(); } void Client::doSetKeepAbove() { // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Layer); } void Client::doSetKeepBelow() { // Update states of all other windows in this group if (tabGroup()) tabGroup()->updateStates(this, TabGroup::Layer); } bool Client::belongsToDesktop() const { foreach (const Client *c, group()->members()) { if (c->isDesktop()) return true; } return false; } } // namespace diff --git a/libinput/connection.cpp b/libinput/connection.cpp index bb299d4ce..3e44d7766 100644 --- a/libinput/connection.cpp +++ b/libinput/connection.cpp @@ -1,664 +1,664 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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 . *********************************************************************/ #include "connection.h" #include "context.h" #include "device.h" #include "events.h" #ifndef KWIN_BUILD_TESTING #include "../screens.h" #endif #include "../logind.h" #include "../udev.h" #include "libinput_logging.h" #include #include #include #include #include #include #include #include namespace KWin { namespace LibInput { class ConnectionAdaptor : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KWin.InputDeviceManager") Q_PROPERTY(QStringList devicesSysNames READ devicesSysNames CONSTANT) private: Connection *m_con; public: ConnectionAdaptor(Connection *con) : m_con(con) { connect(con, &Connection::deviceAddedSysName, this, &ConnectionAdaptor::deviceAdded, Qt::QueuedConnection); connect(con, &Connection::deviceRemovedSysName, this, &ConnectionAdaptor::deviceRemoved, Qt::QueuedConnection); QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/kde/KWin/InputDevice"), QStringLiteral("org.kde.KWin.InputDeviceManager"), this, QDBusConnection::ExportAllProperties | QDBusConnection::ExportAllSignals ); } ~ConnectionAdaptor() override { QDBusConnection::sessionBus().unregisterObject(QStringLiteral("/org/kde/KWin/InputDeviceManager")); } QStringList devicesSysNames() { // TODO: is this allowed? directly calling function of object in another thread!? // otherwise use signal-slot mechanism return m_con->devicesSysNames(); } Q_SIGNALS: void deviceAdded(QString sysName); void deviceRemoved(QString sysName); }; Connection *Connection::s_self = nullptr; QPointer Connection::s_thread; static ConnectionAdaptor *s_adaptor = nullptr; static Context *s_context = nullptr; static quint32 toLibinputLEDS(Xkb::LEDs leds) { quint32 libinputLeds = 0; if (leds.testFlag(Xkb::LED::NumLock)) { libinputLeds = libinputLeds | LIBINPUT_LED_NUM_LOCK; } if (leds.testFlag(Xkb::LED::CapsLock)) { libinputLeds = libinputLeds | LIBINPUT_LED_CAPS_LOCK; } if (leds.testFlag(Xkb::LED::ScrollLock)) { libinputLeds = libinputLeds | LIBINPUT_LED_SCROLL_LOCK; } return libinputLeds; } Connection::Connection(QObject *parent) : Connection(nullptr, parent) { // only here to fix build, using will crash, BUG 343529 } void Connection::createThread() { if (s_thread) { return; } s_thread = new QThread(); s_thread->setObjectName(QStringLiteral("libinput-connection")); s_thread->start(); } Connection *Connection::create(QObject *parent) { Q_ASSERT(!s_self); static Udev s_udev; if (!s_udev.isValid()) { qCWarning(KWIN_LIBINPUT) << "Failed to initialize udev"; return nullptr; } if (!s_context) { s_context = new Context(s_udev); if (!s_context->isValid()) { qCWarning(KWIN_LIBINPUT) << "Failed to create context from udev"; delete s_context; s_context = nullptr; return nullptr; } if (!s_context->assignSeat(LogindIntegration::self()->seat().toUtf8().constData())) { qCWarning(KWIN_LIBINPUT) << "Failed to assign seat" << LogindIntegration::self()->seat(); delete s_context; s_context = nullptr; return nullptr; } } Connection::createThread(); s_self = new Connection(s_context); s_self->moveToThread(s_thread); QObject::connect(s_thread, &QThread::finished, s_self, &QObject::deleteLater); QObject::connect(s_thread, &QThread::finished, s_thread, &QObject::deleteLater); QObject::connect(parent, &QObject::destroyed, s_thread, &QThread::quit); if (!s_adaptor) { s_adaptor = new ConnectionAdaptor(s_self); } return s_self; } Connection::Connection(Context *input, QObject *parent) : QObject(parent) , m_input(input) , m_notifier(nullptr) , m_mutex(QMutex::Recursive) , m_leds() { Q_ASSERT(m_input); // need to connect to KGlobalSettings as the mouse KCM does not emit a dedicated signal QDBusConnection::sessionBus().connect(QString(), QStringLiteral("/KGlobalSettings"), QStringLiteral("org.kde.KGlobalSettings"), QStringLiteral("notifyChange"), this, SLOT(slotKGlobalSettingsNotifyChange(int,int))); } Connection::~Connection() { delete s_adaptor; s_adaptor = nullptr; s_self = nullptr; delete s_context; s_context = nullptr; } void Connection::setup() { QMetaObject::invokeMethod(this, "doSetup", Qt::QueuedConnection); } void Connection::doSetup() { connect(s_self, &Connection::deviceAdded, s_self, [](Device* device) { emit s_self->deviceAddedSysName(device->sysName()); }); connect(s_self, &Connection::deviceRemoved, s_self, [](Device* device) { emit s_self->deviceRemovedSysName(device->sysName()); }); Q_ASSERT(!m_notifier); m_notifier = new QSocketNotifier(m_input->fileDescriptor(), QSocketNotifier::Read, this); connect(m_notifier, &QSocketNotifier::activated, this, &Connection::handleEvent); LogindIntegration *logind = LogindIntegration::self(); connect(logind, &LogindIntegration::sessionActiveChanged, this, [this](bool active) { if (active) { if (!m_input->isSuspended()) { return; } m_input->resume(); wasSuspended = true; } else { deactivate(); } } ); handleEvent(); } void Connection::deactivate() { if (m_input->isSuspended()) { return; } m_keyboardBeforeSuspend = hasKeyboard(); m_alphaNumericKeyboardBeforeSuspend = hasAlphaNumericKeyboard(); m_pointerBeforeSuspend = hasPointer(); m_touchBeforeSuspend = hasTouch(); m_tabletModeSwitchBeforeSuspend = hasTabletModeSwitch(); m_input->suspend(); handleEvent(); } void Connection::handleEvent() { QMutexLocker locker(&m_mutex); const bool wasEmpty = m_eventQueue.isEmpty(); do { m_input->dispatch(); Event *event = m_input->event(); if (!event) { break; } m_eventQueue << event; } while (true); if (wasEmpty && !m_eventQueue.isEmpty()) { emit eventsRead(); } } void Connection::processEvents() { QMutexLocker locker(&m_mutex); while (!m_eventQueue.isEmpty()) { QScopedPointer event(m_eventQueue.takeFirst()); switch (event->type()) { case LIBINPUT_EVENT_DEVICE_ADDED: { auto device = new Device(event->nativeDevice()); device->moveToThread(s_thread); m_devices << device; if (device->isKeyboard()) { m_keyboard++; if (device->isAlphaNumericKeyboard()) { m_alphaNumericKeyboard++; if (m_alphaNumericKeyboard == 1) { emit hasAlphaNumericKeyboardChanged(true); } } if (m_keyboard == 1) { emit hasKeyboardChanged(true); } } if (device->isPointer()) { m_pointer++; if (m_pointer == 1) { emit hasPointerChanged(true); } } if (device->isTouch()) { m_touch++; if (m_touch == 1) { emit hasTouchChanged(true); } } if (device->isTabletModeSwitch()) { m_tabletModeSwitch++; if (m_tabletModeSwitch == 1) { emit hasTabletModeSwitchChanged(true); } } applyDeviceConfig(device); applyScreenToDevice(device); // enable possible leds libinput_device_led_update(device->device(), static_cast(toLibinputLEDS(m_leds))); emit deviceAdded(device); break; } case LIBINPUT_EVENT_DEVICE_REMOVED: { auto it = std::find_if(m_devices.begin(), m_devices.end(), [&event] (Device *d) { return event->device() == d; } ); if (it == m_devices.end()) { // we don't know this device break; } auto device = *it; m_devices.erase(it); emit deviceRemoved(device); if (device->isKeyboard()) { m_keyboard--; if (device->isAlphaNumericKeyboard()) { m_alphaNumericKeyboard--; if (m_alphaNumericKeyboard == 0) { emit hasAlphaNumericKeyboardChanged(false); } } if (m_keyboard == 0) { emit hasKeyboardChanged(false); } } if (device->isPointer()) { m_pointer--; if (m_pointer == 0) { emit hasPointerChanged(false); } } if (device->isTouch()) { m_touch--; if (m_touch == 0) { emit hasTouchChanged(false); } } if (device->isTabletModeSwitch()) { m_tabletModeSwitch--; if (m_tabletModeSwitch == 0) { emit hasTabletModeSwitchChanged(false); } } device->deleteLater(); break; } case LIBINPUT_EVENT_KEYBOARD_KEY: { KeyEvent *ke = static_cast(event.data()); emit keyChanged(ke->key(), ke->state(), ke->time(), ke->device()); break; } case LIBINPUT_EVENT_POINTER_AXIS: { PointerEvent *pe = static_cast(event.data()); const auto axes = pe->axis(); for (const InputRedirection::PointerAxis &axis : axes) { emit pointerAxisChanged(axis, pe->axisValue(axis), pe->discreteAxisValue(axis), pe->axisSource(), pe->time(), pe->device()); } break; } case LIBINPUT_EVENT_POINTER_BUTTON: { PointerEvent *pe = static_cast(event.data()); emit pointerButtonChanged(pe->button(), pe->buttonState(), pe->time(), pe->device()); break; } case LIBINPUT_EVENT_POINTER_MOTION: { PointerEvent *pe = static_cast(event.data()); auto delta = pe->delta(); auto deltaNonAccel = pe->deltaUnaccelerated(); quint32 latestTime = pe->time(); quint64 latestTimeUsec = pe->timeMicroseconds(); auto it = m_eventQueue.begin(); while (it != m_eventQueue.end()) { if ((*it)->type() == LIBINPUT_EVENT_POINTER_MOTION) { QScopedPointer p(static_cast(*it)); delta += p->delta(); deltaNonAccel += p->deltaUnaccelerated(); latestTime = p->time(); latestTimeUsec = p->timeMicroseconds(); it = m_eventQueue.erase(it); } else { break; } } emit pointerMotion(delta, deltaNonAccel, latestTime, latestTimeUsec, pe->device()); break; } case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: { PointerEvent *pe = static_cast(event.data()); emit pointerMotionAbsolute(pe->absolutePos(), pe->absolutePos(m_size), pe->time(), pe->device()); break; } case LIBINPUT_EVENT_TOUCH_DOWN: { #ifndef KWIN_BUILD_TESTING TouchEvent *te = static_cast(event.data()); const auto &geo = screens()->geometry(te->device()->screenId()); emit touchDown(te->id(), geo.topLeft() + te->absolutePos(geo.size()), te->time(), te->device()); break; #endif } case LIBINPUT_EVENT_TOUCH_UP: { TouchEvent *te = static_cast(event.data()); emit touchUp(te->id(), te->time(), te->device()); break; } case LIBINPUT_EVENT_TOUCH_MOTION: { #ifndef KWIN_BUILD_TESTING TouchEvent *te = static_cast(event.data()); const auto &geo = screens()->geometry(te->device()->screenId()); emit touchMotion(te->id(), geo.topLeft() + te->absolutePos(geo.size()), te->time(), te->device()); break; #endif } case LIBINPUT_EVENT_TOUCH_CANCEL: { emit touchCanceled(event->device()); break; } case LIBINPUT_EVENT_TOUCH_FRAME: { emit touchFrame(event->device()); break; } case LIBINPUT_EVENT_GESTURE_PINCH_BEGIN: { PinchGestureEvent *pe = static_cast(event.data()); emit pinchGestureBegin(pe->fingerCount(), pe->time(), pe->device()); break; } case LIBINPUT_EVENT_GESTURE_PINCH_UPDATE: { PinchGestureEvent *pe = static_cast(event.data()); emit pinchGestureUpdate(pe->scale(), pe->angleDelta(), pe->delta(), pe->time(), pe->device()); break; } case LIBINPUT_EVENT_GESTURE_PINCH_END: { PinchGestureEvent *pe = static_cast(event.data()); if (pe->isCancelled()) { emit pinchGestureCancelled(pe->time(), pe->device()); } else { emit pinchGestureEnd(pe->time(), pe->device()); } break; } case LIBINPUT_EVENT_GESTURE_SWIPE_BEGIN: { SwipeGestureEvent *se = static_cast(event.data()); emit swipeGestureBegin(se->fingerCount(), se->time(), se->device()); break; } case LIBINPUT_EVENT_GESTURE_SWIPE_UPDATE: { SwipeGestureEvent *se = static_cast(event.data()); emit swipeGestureUpdate(se->delta(), se->time(), se->device()); break; } case LIBINPUT_EVENT_GESTURE_SWIPE_END: { SwipeGestureEvent *se = static_cast(event.data()); if (se->isCancelled()) { emit swipeGestureCancelled(se->time(), se->device()); } else { emit swipeGestureEnd(se->time(), se->device()); } break; } case LIBINPUT_EVENT_SWITCH_TOGGLE: { SwitchEvent *se = static_cast(event.data()); switch (se->state()) { case SwitchEvent::State::Off: emit switchToggledOff(se->time(), se->timeMicroseconds(), se->device()); break; case SwitchEvent::State::On: emit switchToggledOn(se->time(), se->timeMicroseconds(), se->device()); break; default: Q_UNREACHABLE(); } break; } default: // nothing break; } } if (wasSuspended) { if (m_keyboardBeforeSuspend && !m_keyboard) { emit hasKeyboardChanged(false); } if (m_alphaNumericKeyboardBeforeSuspend && !m_alphaNumericKeyboard) { emit hasAlphaNumericKeyboardChanged(false); } if (m_pointerBeforeSuspend && !m_pointer) { emit hasPointerChanged(false); } if (m_touchBeforeSuspend && !m_touch) { emit hasTouchChanged(false); } if (m_tabletModeSwitchBeforeSuspend && !m_tabletModeSwitch) { emit hasTabletModeSwitchChanged(false); } wasSuspended = false; } } void Connection::setScreenSize(const QSize &size) { m_size = size; } void Connection::updateScreens() { QMutexLocker locker(&m_mutex); for (auto device: qAsConst(m_devices)) { applyScreenToDevice(device); } } void Connection::applyScreenToDevice(Device *device) { #ifndef KWIN_BUILD_TESTING QMutexLocker locker(&m_mutex); if (!device->isTouch()) { return; } int id = -1; // let's try to find a screen for it if (screens()->count() == 1) { id = 0; } if (id == -1 && !device->outputName().isEmpty()) { // we have an output name, try to find a screen with matching name for (int i = 0; i < screens()->count(); i++) { if (screens()->name(i) == device->outputName()) { id = i; break; } } } if (id == -1) { // do we have an internal screen? int internalId = -1; for (int i = 0; i < screens()->count(); i++) { if (screens()->isInternal(i)) { internalId = i; break; } } auto testScreenMatches = [device] (int id) { const auto &size = device->size(); const auto &screenSize = screens()->physicalSize(id); return std::round(size.width()) == std::round(screenSize.width()) && std::round(size.height()) == std::round(screenSize.height()); }; if (internalId != -1 && testScreenMatches(internalId)) { id = internalId; } // let's compare all screens for size for (int i = 0; i < screens()->count(); i++) { if (testScreenMatches(i)) { id = i; break; } } if (id == -1) { // still not found if (internalId != -1) { // we have an internal id, so let's use that id = internalId; } else { // just take first screen, we have no clue id = 0; } } } device->setScreenId(id); device->setOrientation(screens()->orientation(id)); #else Q_UNUSED(device) #endif } bool Connection::isSuspended() const { if (!s_context) { return false; } return s_context->isSuspended(); } void Connection::applyDeviceConfig(Device *device) { // pass configuration to Device device->setConfig(m_config->group("Libinput").group(QString::number(device->vendor())).group(QString::number(device->product())).group(device->name())); device->loadConfiguration(); } void Connection::slotKGlobalSettingsNotifyChange(int type, int arg) { - if (type == 3 /**SettingsChanged**/ && arg == 0 /** SETTINGS_MOUSE **/) { + if (type == 3 /**SettingsChanged**/ && arg == 0 /** SETTINGS_MOUSE */) { m_config->reparseConfiguration(); for (auto it = m_devices.constBegin(), end = m_devices.constEnd(); it != end; ++it) { if ((*it)->isPointer()) { applyDeviceConfig(*it); } } } } void Connection::toggleTouchpads() { bool changed = false; m_touchpadsEnabled = !m_touchpadsEnabled; for (auto it = m_devices.constBegin(); it != m_devices.constEnd(); ++it) { auto device = *it; if (!device->isTouchpad()) { continue; } const bool old = device->isEnabled(); device->setEnabled(m_touchpadsEnabled); if (old != device->isEnabled()) { changed = true; } } if (changed) { // send OSD message QDBusMessage msg = QDBusMessage::createMethodCall( QStringLiteral("org.kde.plasmashell"), QStringLiteral("/org/kde/osdService"), QStringLiteral("org.kde.osdService"), QStringLiteral("touchpadEnabledChanged") ); msg.setArguments({m_touchpadsEnabled}); QDBusConnection::sessionBus().asyncCall(msg); } } void Connection::enableTouchpads() { if (m_touchpadsEnabled) { return; } toggleTouchpads(); } void Connection::disableTouchpads() { if (!m_touchpadsEnabled) { return; } toggleTouchpads(); } void Connection::updateLEDs(Xkb::LEDs leds) { if (m_leds == leds) { return; } m_leds = leds; // update on devices const libinput_led l = static_cast(toLibinputLEDS(leds)); for (auto it = m_devices.constBegin(), end = m_devices.constEnd(); it != end; ++it) { libinput_device_led_update((*it)->device(), l); } } QStringList Connection::devicesSysNames() const { QStringList sl; foreach (Device *d, m_devices) { sl.append(d->sysName()); } return sl; } } } #include "connection.moc" diff --git a/libinput/connection.h b/libinput/connection.h index 83c5cf0aa..ca7ba10be 100644 --- a/libinput/connection.h +++ b/libinput/connection.h @@ -1,173 +1,173 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_LIBINPUT_CONNECTION_H #define KWIN_LIBINPUT_CONNECTION_H #include "../input.h" #include "../keyboard_input.h" #include #include #include #include #include #include #include class QSocketNotifier; class QThread; namespace KWin { namespace LibInput { class Event; class Device; class Context; class KWIN_EXPORT Connection : public QObject { Q_OBJECT public: ~Connection() override; void setInputConfig(const KSharedConfigPtr &config) { m_config = config; } void setup(); /** * Sets the screen @p size. This is needed for mapping absolute pointer events to * the screen data. - **/ + */ void setScreenSize(const QSize &size); void updateScreens(); bool hasKeyboard() const { return m_keyboard > 0; } bool hasAlphaNumericKeyboard() const { return m_alphaNumericKeyboard > 0; } bool hasTouch() const { return m_touch > 0; } bool hasPointer() const { return m_pointer > 0; } bool hasTabletModeSwitch() const { return m_tabletModeSwitch > 0; } bool isSuspended() const; void deactivate(); void processEvents(); void toggleTouchpads(); void enableTouchpads(); void disableTouchpads(); QVector devices() const { return m_devices; } QStringList devicesSysNames() const; void updateLEDs(KWin::Xkb::LEDs leds); static void createThread(); Q_SIGNALS: void keyChanged(quint32 key, KWin::InputRedirection::KeyboardKeyState, quint32 time, KWin::LibInput::Device *device); void pointerButtonChanged(quint32 button, KWin::InputRedirection::PointerButtonState state, quint32 time, KWin::LibInput::Device *device); void pointerMotionAbsolute(QPointF orig, QPointF screen, quint32 time, KWin::LibInput::Device *device); void pointerMotion(const QSizeF &delta, const QSizeF &deltaNonAccelerated, quint32 time, quint64 timeMicroseconds, KWin::LibInput::Device *device); void pointerAxisChanged(KWin::InputRedirection::PointerAxis axis, qreal delta, qint32 discreteDelta, KWin::InputRedirection::PointerAxisSource source, quint32 time, KWin::LibInput::Device *device); void touchFrame(KWin::LibInput::Device *device); void touchCanceled(KWin::LibInput::Device *device); void touchDown(qint32 id, const QPointF &absolutePos, quint32 time, KWin::LibInput::Device *device); void touchUp(qint32 id, quint32 time, KWin::LibInput::Device *device); void touchMotion(qint32 id, const QPointF &absolutePos, quint32 time, KWin::LibInput::Device *device); void hasKeyboardChanged(bool); void hasAlphaNumericKeyboardChanged(bool); void hasPointerChanged(bool); void hasTouchChanged(bool); void hasTabletModeSwitchChanged(bool); void deviceAdded(KWin::LibInput::Device *); void deviceRemoved(KWin::LibInput::Device *); void deviceAddedSysName(QString); void deviceRemovedSysName(QString); void swipeGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device); void swipeGestureUpdate(const QSizeF &delta, quint32 time, KWin::LibInput::Device *device); void swipeGestureEnd(quint32 time, KWin::LibInput::Device *device); void swipeGestureCancelled(quint32 time, KWin::LibInput::Device *device); void pinchGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device); void pinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time, KWin::LibInput::Device *device); void pinchGestureEnd(quint32 time, KWin::LibInput::Device *device); void pinchGestureCancelled(quint32 time, KWin::LibInput::Device *device); void switchToggledOn(quint32 time, quint64 timeMicroseconds, KWin::LibInput::Device *device); void switchToggledOff(quint32 time, quint64 timeMicroseconds, KWin::LibInput::Device *device); void eventsRead(); private Q_SLOTS: void doSetup(); void slotKGlobalSettingsNotifyChange(int type, int arg); private: Connection(Context *input, QObject *parent = nullptr); void handleEvent(); void applyDeviceConfig(Device *device); void applyScreenToDevice(Device *device); Context *m_input; QSocketNotifier *m_notifier; QSize m_size; int m_keyboard = 0; int m_alphaNumericKeyboard = 0; int m_pointer = 0; int m_touch = 0; int m_tabletModeSwitch = 0; bool m_keyboardBeforeSuspend = false; bool m_alphaNumericKeyboardBeforeSuspend = false; bool m_pointerBeforeSuspend = false; bool m_touchBeforeSuspend = false; bool m_tabletModeSwitchBeforeSuspend = false; QMutex m_mutex; QVector m_eventQueue; bool wasSuspended = false; QVector m_devices; KSharedConfigPtr m_config; bool m_touchpadsEnabled = true; Xkb::LEDs m_leds; KWIN_SINGLETON(Connection) static QPointer s_thread; }; } } #endif diff --git a/libinput/context.h b/libinput/context.h index b4843f47e..309873c9f 100644 --- a/libinput/context.h +++ b/libinput/context.h @@ -1,80 +1,80 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_LIBINPUT_CONTEXT_H #define KWIN_LIBINPUT_CONTEXT_H #include namespace KWin { class Udev; namespace LibInput { class Event; class Context { public: Context(const Udev &udev); ~Context(); bool assignSeat(const char *seat); bool isValid() const { return m_libinput != nullptr; } bool isSuspended() const { return m_suspended; } int fileDescriptor(); void dispatch(); void suspend(); void resume(); operator libinput*() { return m_libinput; } operator libinput*() const { return m_libinput; } /** * Gets the next event, if there is no new event @c null is returned. * The caller takes ownership of the returned pointer. - **/ + */ Event *event(); static int openRestrictedCallback(const char *path, int flags, void *user_data); static void closeRestrictedCallBack(int fd, void *user_data); static const struct libinput_interface s_interface; private: int openRestricted(const char *path, int flags); void closeRestricted(int fd); struct libinput *m_libinput; bool m_suspended; }; } } #endif diff --git a/libinput/device.h b/libinput/device.h index 04c103e1c..5c6b735f3 100644 --- a/libinput/device.h +++ b/libinput/device.h @@ -1,582 +1,582 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2016 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_LIBINPUT_DEVICE_H #define KWIN_LIBINPUT_DEVICE_H #include #include #include #include #include #include #include "kwin_export.h" struct libinput_device; namespace KWin { namespace LibInput { enum class ConfigKey; class KWIN_EXPORT Device : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KWin.InputDevice") // // general Q_PROPERTY(bool keyboard READ isKeyboard CONSTANT) Q_PROPERTY(bool alphaNumericKeyboard READ isAlphaNumericKeyboard CONSTANT) Q_PROPERTY(bool pointer READ isPointer CONSTANT) Q_PROPERTY(bool touchpad READ isTouchpad CONSTANT) Q_PROPERTY(bool touch READ isTouch CONSTANT) Q_PROPERTY(bool tabletTool READ isTabletTool CONSTANT) Q_PROPERTY(bool tabletPad READ isTabletPad CONSTANT) Q_PROPERTY(bool gestureSupport READ supportsGesture CONSTANT) Q_PROPERTY(QString name READ name CONSTANT) Q_PROPERTY(QString sysName READ sysName CONSTANT) Q_PROPERTY(QString outputName READ outputName CONSTANT) Q_PROPERTY(QSizeF size READ size CONSTANT) Q_PROPERTY(quint32 product READ product CONSTANT) Q_PROPERTY(quint32 vendor READ vendor CONSTANT) Q_PROPERTY(bool supportsDisableEvents READ supportsDisableEvents CONSTANT) Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged) // // advanced Q_PROPERTY(int supportedButtons READ supportedButtons CONSTANT) Q_PROPERTY(bool supportsCalibrationMatrix READ supportsCalibrationMatrix CONSTANT) Q_PROPERTY(bool supportsLeftHanded READ supportsLeftHanded CONSTANT) Q_PROPERTY(bool leftHandedEnabledByDefault READ leftHandedEnabledByDefault CONSTANT) Q_PROPERTY(bool leftHanded READ isLeftHanded WRITE setLeftHanded NOTIFY leftHandedChanged) Q_PROPERTY(bool supportsDisableEventsOnExternalMouse READ supportsDisableEventsOnExternalMouse CONSTANT) Q_PROPERTY(bool supportsDisableWhileTyping READ supportsDisableWhileTyping CONSTANT) Q_PROPERTY(bool disableWhileTypingEnabledByDefault READ disableWhileTypingEnabledByDefault CONSTANT) Q_PROPERTY(bool disableWhileTyping READ isDisableWhileTyping WRITE setDisableWhileTyping NOTIFY disableWhileTypingChanged) // // acceleration speed and profile Q_PROPERTY(bool supportsPointerAcceleration READ supportsPointerAcceleration CONSTANT) Q_PROPERTY(qreal defaultPointerAcceleration READ defaultPointerAcceleration CONSTANT) Q_PROPERTY(qreal pointerAcceleration READ pointerAcceleration WRITE setPointerAcceleration NOTIFY pointerAccelerationChanged) Q_PROPERTY(bool supportsPointerAccelerationProfileFlat READ supportsPointerAccelerationProfileFlat CONSTANT) Q_PROPERTY(bool defaultPointerAccelerationProfileFlat READ defaultPointerAccelerationProfileFlat CONSTANT) Q_PROPERTY(bool pointerAccelerationProfileFlat READ pointerAccelerationProfileFlat WRITE setPointerAccelerationProfileFlat NOTIFY pointerAccelerationProfileChanged) Q_PROPERTY(bool supportsPointerAccelerationProfileAdaptive READ supportsPointerAccelerationProfileAdaptive CONSTANT) Q_PROPERTY(bool defaultPointerAccelerationProfileAdaptive READ defaultPointerAccelerationProfileAdaptive CONSTANT) Q_PROPERTY(bool pointerAccelerationProfileAdaptive READ pointerAccelerationProfileAdaptive WRITE setPointerAccelerationProfileAdaptive NOTIFY pointerAccelerationProfileChanged) // // tapping Q_PROPERTY(int tapFingerCount READ tapFingerCount CONSTANT) Q_PROPERTY(bool tapToClickEnabledByDefault READ tapToClickEnabledByDefault CONSTANT) Q_PROPERTY(bool tapToClick READ isTapToClick WRITE setTapToClick NOTIFY tapToClickChanged) Q_PROPERTY(bool supportsLmrTapButtonMap READ supportsLmrTapButtonMap CONSTANT) Q_PROPERTY(bool lmrTapButtonMapEnabledByDefault READ lmrTapButtonMapEnabledByDefault CONSTANT) Q_PROPERTY(bool lmrTapButtonMap READ lmrTapButtonMap WRITE setLmrTapButtonMap NOTIFY tapButtonMapChanged) Q_PROPERTY(bool tapAndDragEnabledByDefault READ tapAndDragEnabledByDefault CONSTANT) Q_PROPERTY(bool tapAndDrag READ isTapAndDrag WRITE setTapAndDrag NOTIFY tapAndDragChanged) Q_PROPERTY(bool tapDragLockEnabledByDefault READ tapDragLockEnabledByDefault CONSTANT) Q_PROPERTY(bool tapDragLock READ isTapDragLock WRITE setTapDragLock NOTIFY tapDragLockChanged) Q_PROPERTY(bool supportsMiddleEmulation READ supportsMiddleEmulation CONSTANT) Q_PROPERTY(bool middleEmulationEnabledByDefault READ middleEmulationEnabledByDefault CONSTANT) Q_PROPERTY(bool middleEmulation READ isMiddleEmulation WRITE setMiddleEmulation NOTIFY middleEmulationChanged) // // scrolling Q_PROPERTY(bool supportsNaturalScroll READ supportsNaturalScroll CONSTANT) Q_PROPERTY(bool naturalScrollEnabledByDefault READ naturalScrollEnabledByDefault CONSTANT) Q_PROPERTY(bool naturalScroll READ isNaturalScroll WRITE setNaturalScroll NOTIFY naturalScrollChanged) Q_PROPERTY(bool supportsScrollTwoFinger READ supportsScrollTwoFinger CONSTANT) Q_PROPERTY(bool scrollTwoFingerEnabledByDefault READ scrollTwoFingerEnabledByDefault CONSTANT) Q_PROPERTY(bool scrollTwoFinger READ isScrollTwoFinger WRITE setScrollTwoFinger NOTIFY scrollMethodChanged) Q_PROPERTY(bool supportsScrollEdge READ supportsScrollEdge CONSTANT) Q_PROPERTY(bool scrollEdgeEnabledByDefault READ scrollEdgeEnabledByDefault CONSTANT) Q_PROPERTY(bool scrollEdge READ isScrollEdge WRITE setScrollEdge NOTIFY scrollMethodChanged) Q_PROPERTY(bool supportsScrollOnButtonDown READ supportsScrollOnButtonDown CONSTANT) Q_PROPERTY(bool scrollOnButtonDownEnabledByDefault READ scrollOnButtonDownEnabledByDefault CONSTANT) Q_PROPERTY(quint32 defaultScrollButton READ defaultScrollButton CONSTANT) Q_PROPERTY(bool scrollOnButtonDown READ isScrollOnButtonDown WRITE setScrollOnButtonDown NOTIFY scrollMethodChanged) Q_PROPERTY(quint32 scrollButton READ scrollButton WRITE setScrollButton NOTIFY scrollButtonChanged) // switches Q_PROPERTY(bool switchDevice READ isSwitch CONSTANT) Q_PROPERTY(bool lidSwitch READ isLidSwitch CONSTANT) Q_PROPERTY(bool tabletModeSwitch READ isTabletModeSwitch CONSTANT) // Click Methods Q_PROPERTY(bool supportsClickMethodAreas READ supportsClickMethodAreas CONSTANT) Q_PROPERTY(bool defaultClickMethodAreas READ defaultClickMethodAreas CONSTANT) Q_PROPERTY(bool clickMethodAreas READ isClickMethodAreas WRITE setClickMethodAreas NOTIFY clickMethodChanged) Q_PROPERTY(bool supportsClickMethodClickfinger READ supportsClickMethodClickfinger CONSTANT) Q_PROPERTY(bool defaultClickMethodClickfinger READ defaultClickMethodClickfinger CONSTANT) Q_PROPERTY(bool clickMethodClickfinger READ isClickMethodClickfinger WRITE setClickMethodClickfinger NOTIFY clickMethodChanged) public: explicit Device(libinput_device *device, QObject *parent = nullptr); ~Device() override; bool isKeyboard() const { return m_keyboard; } bool isAlphaNumericKeyboard() const { return m_alphaNumericKeyboard; } bool isPointer() const { return m_pointer; } bool isTouchpad() const{ return m_pointer && // ignore all combined devices. E.g. a touchpad on a keyboard we don't want to toggle // as that would result in the keyboard going off as well !(m_keyboard || m_touch || m_tabletPad || m_tabletTool) && // is this a touch pad? We don't really know, let's do some assumptions (m_tapFingerCount > 0 || m_supportsDisableWhileTyping || m_supportsDisableEventsOnExternalMouse); } bool isTouch() const { return m_touch; } bool isTabletTool() const { return m_tabletTool; } bool isTabletPad() const { return m_tabletPad; } bool supportsGesture() const { return m_supportsGesture; } QString name() const { return m_name; } QString sysName() const { return m_sysName; } QString outputName() const { return m_outputName; } QSizeF size() const { return m_size; } quint32 product() const { return m_product; } quint32 vendor() const { return m_vendor; } Qt::MouseButtons supportedButtons() const { return m_supportedButtons; } int tapFingerCount() const { return m_tapFingerCount; } bool tapToClickEnabledByDefault() const { return m_tapToClickEnabledByDefault; } bool isTapToClick() const { return m_tapToClick; } /** * Set the Device to tap to click if @p set is @c true. - **/ + */ void setTapToClick(bool set); bool tapAndDragEnabledByDefault() const { return m_tapAndDragEnabledByDefault; } bool isTapAndDrag() const { return m_tapAndDrag; } void setTapAndDrag(bool set); bool tapDragLockEnabledByDefault() const { return m_tapDragLockEnabledByDefault; } bool isTapDragLock() const { return m_tapDragLock; } void setTapDragLock(bool set); bool supportsDisableWhileTyping() const { return m_supportsDisableWhileTyping; } bool disableWhileTypingEnabledByDefault() const { return m_disableWhileTypingEnabledByDefault; } bool supportsPointerAcceleration() const { return m_supportsPointerAcceleration; } bool supportsLeftHanded() const { return m_supportsLeftHanded; } bool supportsCalibrationMatrix() const { return m_supportsCalibrationMatrix; } bool supportsDisableEvents() const { return m_supportsDisableEvents; } bool supportsDisableEventsOnExternalMouse() const { return m_supportsDisableEventsOnExternalMouse; } bool supportsMiddleEmulation() const { return m_supportsMiddleEmulation; } bool supportsNaturalScroll() const { return m_supportsNaturalScroll; } bool supportsScrollTwoFinger() const { return (m_supportedScrollMethods & LIBINPUT_CONFIG_SCROLL_2FG); } bool supportsScrollEdge() const { return (m_supportedScrollMethods & LIBINPUT_CONFIG_SCROLL_EDGE); } bool supportsScrollOnButtonDown() const { return (m_supportedScrollMethods & LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN); } bool leftHandedEnabledByDefault() const { return m_leftHandedEnabledByDefault; } bool middleEmulationEnabledByDefault() const { return m_middleEmulationEnabledByDefault; } bool naturalScrollEnabledByDefault() const { return m_naturalScrollEnabledByDefault; } enum libinput_config_scroll_method defaultScrollMethod() const { return m_defaultScrollMethod; } quint32 defaultScrollMethodToInt() const { return (quint32) m_defaultScrollMethod; } bool scrollTwoFingerEnabledByDefault() const { return m_defaultScrollMethod == LIBINPUT_CONFIG_SCROLL_2FG; } bool scrollEdgeEnabledByDefault() const { return m_defaultScrollMethod == LIBINPUT_CONFIG_SCROLL_EDGE; } bool scrollOnButtonDownEnabledByDefault() const { return m_defaultScrollMethod == LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN; } bool supportsLmrTapButtonMap() const { return m_tapFingerCount > 1; } bool lmrTapButtonMapEnabledByDefault() const { return m_defaultTapButtonMap == LIBINPUT_CONFIG_TAP_MAP_LMR; } void setLmrTapButtonMap(bool set); bool lmrTapButtonMap() const { return m_tapButtonMap & LIBINPUT_CONFIG_TAP_MAP_LMR; } quint32 defaultScrollButton() const { return m_defaultScrollButton; } bool isMiddleEmulation() const { return m_middleEmulation; } void setMiddleEmulation(bool set); bool isNaturalScroll() const { return m_naturalScroll; } void setNaturalScroll(bool set); void setScrollMethod(bool set, enum libinput_config_scroll_method method); bool isScrollTwoFinger() const { return m_scrollMethod & LIBINPUT_CONFIG_SCROLL_2FG; } void setScrollTwoFinger(bool set) { setScrollMethod(set, LIBINPUT_CONFIG_SCROLL_2FG); } bool isScrollEdge() const { return m_scrollMethod & LIBINPUT_CONFIG_SCROLL_EDGE; } void setScrollEdge(bool set) { setScrollMethod(set, LIBINPUT_CONFIG_SCROLL_EDGE); } bool isScrollOnButtonDown() const { return m_scrollMethod & LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN; } void setScrollOnButtonDown(bool set) { setScrollMethod(set, LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN); } void activateScrollMethodFromInt(quint32 method) { setScrollMethod(true, (libinput_config_scroll_method) method); } quint32 scrollButton() const { return m_scrollButton; } void setScrollButton(quint32 button); void setDisableWhileTyping(bool set); bool isDisableWhileTyping() const { return m_disableWhileTyping; } bool isLeftHanded() const { return m_leftHanded; } /** * Sets the Device to left handed mode if @p set is @c true. * If @p set is @c false the device is set to right handed mode - **/ + */ void setLeftHanded(bool set); qreal defaultPointerAcceleration() const { return m_defaultPointerAcceleration; } qreal pointerAcceleration() const { return m_pointerAcceleration; } /** * @param acceleration mapped to range [-1,1] with -1 being the slowest, 1 being the fastest supported acceleration. - **/ + */ void setPointerAcceleration(qreal acceleration); void setPointerAccelerationFromString(QString acceleration) { setPointerAcceleration(acceleration.toDouble()); } QString defaultPointerAccelerationToString() const { return QString::number(m_pointerAcceleration, 'f', 3); } bool supportsPointerAccelerationProfileFlat() const { return (m_supportedPointerAccelerationProfiles & LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT); } bool supportsPointerAccelerationProfileAdaptive() const { return (m_supportedPointerAccelerationProfiles & LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE); } bool defaultPointerAccelerationProfileFlat() const { return (m_defaultPointerAccelerationProfile & LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT); } bool defaultPointerAccelerationProfileAdaptive() const { return (m_defaultPointerAccelerationProfile & LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE); } bool pointerAccelerationProfileFlat() const { return (m_pointerAccelerationProfile & LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT); } bool pointerAccelerationProfileAdaptive() const { return (m_pointerAccelerationProfile & LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE); } void setPointerAccelerationProfile(bool set, enum libinput_config_accel_profile profile); void setPointerAccelerationProfileFlat(bool set) { setPointerAccelerationProfile(set, LIBINPUT_CONFIG_ACCEL_PROFILE_FLAT); } void setPointerAccelerationProfileAdaptive(bool set) { setPointerAccelerationProfile(set, LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE); } void setPointerAccelerationProfileFromInt(quint32 profile) { setPointerAccelerationProfile(true, (libinput_config_accel_profile) profile); } quint32 defaultPointerAccelerationProfileToInt() const { return (quint32) m_defaultPointerAccelerationProfile; } bool supportsClickMethodAreas() const { return (m_supportedClickMethods & LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS); } bool defaultClickMethodAreas() const { return (m_defaultClickMethod == LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS); } bool isClickMethodAreas() const { return (m_clickMethod == LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS); } bool supportsClickMethodClickfinger() const { return (m_supportedClickMethods & LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER); } bool defaultClickMethodClickfinger() const { return (m_defaultClickMethod == LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER); } bool isClickMethodClickfinger() const { return (m_clickMethod == LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER); } void setClickMethod(bool set, enum libinput_config_click_method method); void setClickMethodAreas(bool set) { setClickMethod(set, LIBINPUT_CONFIG_CLICK_METHOD_BUTTON_AREAS); } void setClickMethodClickfinger(bool set) { setClickMethod(set, LIBINPUT_CONFIG_CLICK_METHOD_CLICKFINGER); } void setClickMethodFromInt(quint32 method) { setClickMethod(true, (libinput_config_click_method) method); } quint32 defaultClickMethodToInt() const { return (quint32) m_defaultClickMethod; } bool isEnabled() const { return m_enabled; } void setEnabled(bool enabled); libinput_device *device() const { return m_device; } /** * Sets the @p config to load the Device configuration from and to store each * successful Device configuration. - **/ + */ void setConfig(const KConfigGroup &config) { m_config = config; } /** * The id of the screen in KWin identifiers. Set from KWin through setScreenId. - **/ + */ int screenId() const { return m_screenId; } /** * Sets the KWin screen id for the device - **/ + */ void setScreenId(int screenId) { m_screenId = screenId; } void setOrientation(Qt::ScreenOrientation orientation); /** * Loads the configuration and applies it to the Device - **/ + */ void loadConfiguration(); bool isSwitch() const { return m_switch; } bool isLidSwitch() const { return m_lidSwitch; } bool isTabletModeSwitch() const { return m_tabletSwitch; } /** * All created Devices - **/ + */ static QVector devices() { return s_devices; } /** * Gets the Device for @p native. @c null if there is no Device for @p native. - **/ + */ static Device *getDevice(libinput_device *native); Q_SIGNALS: void tapButtonMapChanged(); void leftHandedChanged(); void disableWhileTypingChanged(); void pointerAccelerationChanged(); void pointerAccelerationProfileChanged(); void enabledChanged(); void tapToClickChanged(); void tapAndDragChanged(); void tapDragLockChanged(); void middleEmulationChanged(); void naturalScrollChanged(); void scrollMethodChanged(); void scrollButtonChanged(); void clickMethodChanged(); private: template void writeEntry(const ConfigKey &key, const T &value); template void readEntry(const QByteArray &key, const Setter &s, const T &defaultValue = T()); libinput_device *m_device; bool m_keyboard; bool m_alphaNumericKeyboard = false; bool m_pointer; bool m_touch; bool m_tabletTool; bool m_tabletPad; bool m_supportsGesture; bool m_switch = false; bool m_lidSwitch = false; bool m_tabletSwitch = false; QString m_name; QString m_sysName; QString m_outputName; QSizeF m_size; quint32 m_product; quint32 m_vendor; Qt::MouseButtons m_supportedButtons = Qt::NoButton; int m_tapFingerCount; enum libinput_config_tap_button_map m_defaultTapButtonMap; enum libinput_config_tap_button_map m_tapButtonMap; bool m_tapToClickEnabledByDefault; bool m_tapToClick; bool m_tapAndDragEnabledByDefault; bool m_tapAndDrag; bool m_tapDragLockEnabledByDefault; bool m_tapDragLock; bool m_supportsDisableWhileTyping; bool m_supportsPointerAcceleration; bool m_supportsLeftHanded; bool m_supportsCalibrationMatrix; bool m_supportsDisableEvents; bool m_supportsDisableEventsOnExternalMouse; bool m_supportsMiddleEmulation; bool m_supportsNaturalScroll; quint32 m_supportedScrollMethods; bool m_supportsScrollEdge; bool m_supportsScrollOnButtonDown; bool m_leftHandedEnabledByDefault; bool m_middleEmulationEnabledByDefault; bool m_naturalScrollEnabledByDefault; enum libinput_config_scroll_method m_defaultScrollMethod; quint32 m_defaultScrollButton; bool m_disableWhileTypingEnabledByDefault; bool m_disableWhileTyping; bool m_middleEmulation; bool m_leftHanded; bool m_naturalScroll; enum libinput_config_scroll_method m_scrollMethod; quint32 m_scrollButton; qreal m_defaultPointerAcceleration; qreal m_pointerAcceleration; quint32 m_supportedPointerAccelerationProfiles; enum libinput_config_accel_profile m_defaultPointerAccelerationProfile; enum libinput_config_accel_profile m_pointerAccelerationProfile; bool m_enabled; KConfigGroup m_config; bool m_loading = false; int m_screenId = 0; Qt::ScreenOrientation m_orientation = Qt::PrimaryOrientation; QMatrix4x4 m_defaultCalibrationMatrix; quint32 m_supportedClickMethods; enum libinput_config_click_method m_defaultClickMethod; enum libinput_config_click_method m_clickMethod; static QVector s_devices; }; } } Q_DECLARE_METATYPE(KWin::LibInput::Device*) #endif diff --git a/libkwineffects/anidata_p.h b/libkwineffects/anidata_p.h index 89f3f47d3..d1c5b4f42 100644 --- a/libkwineffects/anidata_p.h +++ b/libkwineffects/anidata_p.h @@ -1,108 +1,108 @@ /******************************************************************** 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 ANIDATA_H #define ANIDATA_H #include "kwinanimationeffect.h" #include namespace KWin { /** * Wraps effects->setActiveFullScreenEffect for the duration of it's lifespan - **/ + */ class FullScreenEffectLock { public: FullScreenEffectLock(Effect *effect); ~FullScreenEffectLock(); private: Q_DISABLE_COPY(FullScreenEffectLock) }; typedef QSharedPointer FullScreenEffectLockPtr; /** * Keeps windows alive during animation after they got closed - **/ + */ class KeepAliveLock { public: KeepAliveLock(EffectWindow *w); ~KeepAliveLock(); private: EffectWindow *m_window; Q_DISABLE_COPY(KeepAliveLock) }; typedef QSharedPointer KeepAliveLockPtr; /** * References the previous window pixmap to prevent discarding. - **/ + */ class PreviousWindowPixmapLock { public: PreviousWindowPixmapLock(EffectWindow *w); ~PreviousWindowPixmapLock(); private: EffectWindow *m_window; Q_DISABLE_COPY(PreviousWindowPixmapLock) }; typedef QSharedPointer PreviousWindowPixmapLockPtr; class KWINEFFECTS_EXPORT AniData { public: AniData(); AniData(AnimationEffect::Attribute a, int meta, const FPx2 &to, int delay, const FPx2 &from, bool waitAtSource, FullScreenEffectLockPtr=FullScreenEffectLockPtr(), bool keepAlive = true, PreviousWindowPixmapLockPtr previousWindowPixmapLock = {}); bool isActive() const; inline bool isOneDimensional() const { return from[0] == from[1] && to[0] == to[1]; } quint64 id{0}; QString debugInfo() const; AnimationEffect::Attribute attribute; int customCurve; FPx2 from, to; TimeLine timeLine; uint meta; qint64 startTime; QSharedPointer fullScreenEffectLock; bool waitAtSource; bool keepAlive; KeepAliveLockPtr keepAliveLock; PreviousWindowPixmapLockPtr previousWindowPixmapLock; AnimationEffect::TerminationFlags terminationFlags; }; } // namespace QDebug operator<<(QDebug dbg, const KWin::AniData &a); #endif // ANIDATA_H diff --git a/libkwineffects/kwinanimationeffect.h b/libkwineffects/kwinanimationeffect.h index 8211b9dc9..3e9a7ea71 100644 --- a/libkwineffects/kwinanimationeffect.h +++ b/libkwineffects/kwinanimationeffect.h @@ -1,419 +1,419 @@ /******************************************************************** 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.f[0]; f[1] = other.f[1]; valid = other.valid; return *this; } 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: 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() override; bool isActive() const override; /** * 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 override; void prePaintScreen( ScreenPrePaintData& data, int time ) override; void prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) override; void paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) override; void postPaintScreen() override; /** * 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 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 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 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 - **/ + */ typedef QMap, QRect> > AniMap; /** * @internal - **/ + */ 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) Q_DISABLE_COPY(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 d53a8763a..a91286645 100644 --- a/libkwineffects/kwineffects.h +++ b/libkwineffects/kwineffects.h @@ -1,3953 +1,3953 @@ /******************************************************************** 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 228 #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. - **/ + */ ~Effect() override; /** * 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(); ~EffectPluginFactory() override; /** * 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); ~EffectsHandler() override; // 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 effect The effect * @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 QAction::triggered * signal gets invoked. * * To unregister the touch screen action either delete the @p action or * invoke 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; /** * Finds the EffectWindow for the internal window @p w. * If there is no such window @c null is returned. * * On Wayland this returns the internal window. On X11 it returns an Unamanged with the * window id matching that of the provided window @p w. * * @since 5.16 - **/ + */ Q_SCRIPTABLE virtual KWin::EffectWindow *findWindow(QWindow *w) const = 0; /** * Finds the EffectWindow for the Toplevel with KWin internal @p id. * If there is no such window @c null is returned. * * @since 5.16 - **/ + */ Q_SCRIPTABLE virtual KWin::EffectWindow *findWindow(const QUuid &id) 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 removeSupportProperty. When an Effect is * destroyed it is automatically taken care of removing the support. It is not * required to call 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. * @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 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 * 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 * isUserMove or isUserResize. * Whenever the geometry is updated the signal @ref windowStepUserMovedResized * is emitted with the current geometry. * The move/resize operation ends with the signal @ref 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 * @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 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 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 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 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 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 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 signal is emitted just before the screen locker tries to grab keys and lock the screen * Effects should release any grabs immediately * @since 5.17 - **/ + */ void screenAboutToLock(); /** * 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 windowAdded and hidden with 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 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 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(KWin::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(KWin::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(KWin::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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is a window with a critical notification. * using the non-standard _KDE_NET_WM_WINDOW_TYPE_CRITICAL_NOTIFICATION - **/ + */ Q_PROPERTY(bool criticalNotification READ isCriticalNotification) /** * 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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See https://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 https://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) /** * KWin internal window. Specific to Wayland platform. * * If the EffectWindow does not reference an internal window, this property is @c null. * @since 5.16 - **/ + */ Q_PROPERTY(QWindow *internalWindow READ internalWindow CONSTANT) /** * Whether this EffectWindow represents the outline. * * When compositing is turned on, the outline is an actual window. * * @since 5.16 - **/ + */ Q_PROPERTY(bool outline READ isOutline 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); ~EffectWindow() override; 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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ virtual bool isNotification() const = 0; /** * Returns whether the window is a window with a critical notification. * using the non-standard _KDE_NET_WM_WINDOW_TYPE_CRITICAL_NOTIFICATION - **/ + */ virtual bool isCriticalNotification() 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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ virtual bool isDNDIcon() const = 0; /** * Returns the NETWM window type * See https://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; /** * @since 5.16 - **/ + */ virtual QWindow *internalWindow() const = 0; /** * @since 5.16 - **/ + */ virtual bool isOutline() 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 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 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); ~WindowPaintData() override; /** * 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); ~ScreenPaintData() override; /** * 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/kwinglobals.h b/libkwineffects/kwinglobals.h index 2aa778346..649575444 100644 --- a/libkwineffects/kwinglobals.h +++ b/libkwineffects/kwinglobals.h @@ -1,255 +1,255 @@ /******************************************************************** 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_LIB_KWINGLOBALS_H #define KWIN_LIB_KWINGLOBALS_H #include #include #include #include #include #include #include #define KWIN_QT5_PORTING 0 namespace KWin { enum CompositingType { NoCompositing = 0, /** * Used as a flag whether OpenGL based compositing is used. * The flag is or-ed to the enum values of the specific OpenGL types. * The actual Compositors use the or @c OpenGL2Compositing * flags. If you need to know whether OpenGL is used, either and the flag or * use EffectsHandler::isOpenGLCompositing(). - **/ + */ OpenGLCompositing = 1, XRenderCompositing = 1<<1, QPainterCompositing = 1<< 2, OpenGL2Compositing = 1<<3 | OpenGLCompositing }; enum OpenGLPlatformInterface { NoOpenGLPlatformInterface = 0, GlxPlatformInterface, EglPlatformInterface }; enum clientAreaOption { PlacementArea, // geometry where a window will be initially placed after being mapped MovementArea, // ??? window movement snapping area? ignore struts MaximizeArea, // geometry to which a window will be maximized MaximizeFullArea, // like MaximizeArea, but ignore struts - used e.g. for topmenu FullScreenArea, // area for fullscreen windows // these below don't depend on xinerama settings WorkArea, // whole workarea (all screens together) FullArea, // whole area (all screens together), ignore struts ScreenArea // one whole screen, ignore struts }; enum ElectricBorder { ElectricTop, ElectricTopRight, ElectricRight, ElectricBottomRight, ElectricBottom, ElectricBottomLeft, ElectricLeft, ElectricTopLeft, ELECTRIC_COUNT, ElectricNone }; // TODO: Hardcoding is bad, need to add some way of registering global actions to these. // When designing the new system we must keep in mind that we have conditional actions // such as "only when moving windows" desktop switching that the current global action // system doesn't support. enum ElectricBorderAction { ElectricActionNone, // No special action, not set, desktop switch or an effect ElectricActionShowDesktop, // Show desktop or restore ElectricActionLockScreen, // Lock screen ElectricActionKRunner, // Open KRunner ElectricActionActivityManager, // Activity Manager ElectricActionApplicationLauncher, // Application Launcher ELECTRIC_ACTION_COUNT }; // DesktopMode and WindowsMode are based on the order in which the desktop // or window were viewed. // DesktopListMode lists them in the order created. enum TabBoxMode { TabBoxDesktopMode, // Focus chain of desktops TabBoxDesktopListMode, // Static desktop order TabBoxWindowsMode, // Primary window switching mode TabBoxWindowsAlternativeMode, // Secondary window switching mode TabBoxCurrentAppWindowsMode, // Same as primary window switching mode but only for windows of current application TabBoxCurrentAppWindowsAlternativeMode // Same as secondary switching mode but only for windows of current application }; enum KWinOption { CloseButtonCorner, SwitchDesktopOnScreenEdge, SwitchDesktopOnScreenEdgeMovingWindows }; /** * @brief The direction in which a pointer axis is moved. - **/ + */ enum PointerAxisDirection { PointerAxisUp, PointerAxisDown, PointerAxisLeft, PointerAxisRight }; /** * @brief Directions for swipe gestures * @since 5.10 - **/ + */ enum class SwipeDirection { Invalid, Down, Left, Up, Right }; inline KWIN_EXPORT xcb_connection_t *connection() { static xcb_connection_t *s_con = nullptr; if (!s_con) { s_con = reinterpret_cast(qApp->property("x11Connection").value()); } Q_ASSERT(qApp); return s_con; } inline KWIN_EXPORT xcb_window_t rootWindow() { static xcb_window_t s_rootWindow = XCB_WINDOW_NONE; if (s_rootWindow == XCB_WINDOW_NONE) { s_rootWindow = qApp->property("x11RootWindow").value(); } return s_rootWindow; } inline KWIN_EXPORT xcb_timestamp_t xTime() { return qApp->property("x11Time").value(); } inline KWIN_EXPORT xcb_screen_t *defaultScreen() { static xcb_screen_t *s_screen = nullptr; if (s_screen) { return s_screen; } int screen = qApp->property("x11ScreenNumber").toInt(); for (xcb_screen_iterator_t it = xcb_setup_roots_iterator(xcb_get_setup(connection())); it.rem; --screen, xcb_screen_next(&it)) { if (screen == 0) { s_screen = it.data; } } return s_screen; } inline KWIN_DEPRECATED_EXPORT int displayWidth() { xcb_screen_t *screen = defaultScreen(); return screen ? screen->width_in_pixels : 0; } inline KWIN_DEPRECATED_EXPORT int displayHeight() { xcb_screen_t *screen = defaultScreen(); return screen ? screen->height_in_pixels : 0; } /** * Short wrapper for a cursor image provided by the Platform. * @since 5.9 - **/ + */ class PlatformCursorImage { public: explicit PlatformCursorImage() : m_image() , m_hotSpot() { } explicit PlatformCursorImage(const QImage &image, const QPoint &hotSpot) : m_image(image) , m_hotSpot(hotSpot) { } virtual ~PlatformCursorImage() = default; QImage image() const { return m_image; } QPoint hotSpot() const { return m_hotSpot; } private: QImage m_image; QPoint m_hotSpot; }; } // namespace #define KWIN_SINGLETON_VARIABLE(ClassName, variableName) \ public: \ static ClassName *create(QObject *parent = nullptr);\ static ClassName *self() { return variableName; }\ protected: \ explicit ClassName(QObject *parent = nullptr); \ private: \ static ClassName *variableName; #define KWIN_SINGLETON(ClassName) KWIN_SINGLETON_VARIABLE(ClassName, s_self) #define KWIN_SINGLETON_FACTORY_VARIABLE_FACTORED(ClassName, FactoredClassName, variableName) \ ClassName *ClassName::variableName = nullptr; \ ClassName *ClassName::create(QObject *parent) \ { \ Q_ASSERT(!variableName); \ variableName = new FactoredClassName(parent); \ return variableName; \ } #define KWIN_SINGLETON_FACTORY_VARIABLE(ClassName, variableName) KWIN_SINGLETON_FACTORY_VARIABLE_FACTORED(ClassName, ClassName, variableName) #define KWIN_SINGLETON_FACTORY_FACTORED(ClassName, FactoredClassName) KWIN_SINGLETON_FACTORY_VARIABLE_FACTORED(ClassName, FactoredClassName, s_self) #define KWIN_SINGLETON_FACTORY(ClassName) KWIN_SINGLETON_FACTORY_VARIABLE(ClassName, s_self) #endif diff --git a/libkwineffects/kwinglplatform.h b/libkwineffects/kwinglplatform.h index c9c83ef72..0d0858a94 100644 --- a/libkwineffects/kwinglplatform.h +++ b/libkwineffects/kwinglplatform.h @@ -1,439 +1,439 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 Fredrik Höglund 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_GLPLATFORM_H #define KWIN_GLPLATFORM_H #include #include #include #include namespace KWin { // forward declare method void cleanupGL(); inline qint64 kVersionNumber(qint64 major, qint64 minor, qint64 patch = 0) { return ((major & 0xffff) << 32) | ((minor & 0xffff) << 16) | (patch & 0xffff); } enum GLFeature { /** * Set when a texture bound to a pixmap uses the same storage as the pixmap, * and thus doesn't need to be rebound when the contents of the pixmap * has changed. - **/ + */ LooseBinding, /** * Set if the driver supports the following extensions: * - GL_ARB_shader_objects * - GL_ARB_fragment_shader * - GL_ARB_vertex_shader * - GL_ARB_shading_language_100 - **/ + */ GLSL, /** * If set, assume the following: * - No flow control or branches * - No loops, unless the loops have a fixed iteration count and can be unrolled * - No functions, unless they can be inlined * - No indirect indexing of arrays * - No support for gl_ClipVertex or gl_FrontFacing * - No texture fetches in vertex shaders * - Max 32 texture fetches in fragment shaders * - Max 4 texture indirections - **/ + */ LimitedGLSL, /** * Set when the driver supports GL_ARB_texture_non_power_of_two. - **/ + */ TextureNPOT, /** * If set, the driver supports GL_ARB_texture_non_power_of_two with the * GL_ARB_texture_rectangle limitations. * * This means no support for mipmap filters, and that only the following * wrap modes are supported: * - GL_CLAMP * - GL_CLAMP_TO_EDGE * - GL_CLAMP_TO_BORDER - **/ + */ LimitedNPOT }; enum Driver { Driver_R100, // Technically "Radeon" Driver_R200, Driver_R300C, Driver_R300G, Driver_R600C, Driver_R600G, Driver_Nouveau, Driver_Intel, Driver_NVidia, Driver_Catalyst, Driver_Swrast, Driver_Softpipe, Driver_Llvmpipe, Driver_VirtualBox, Driver_VMware, Driver_Qualcomm, Driver_RadeonSI, Driver_Unknown }; enum ChipClass { // Radeon R100 = 0, // GL1.3 DX7 2000 R200, // GL1.4 DX8.1 SM 1.4 2001 R300, // GL2.0 DX9 SM 2.0 2002 R400, // GL2.0 DX9b SM 2.0b 2004 R500, // GL2.0 DX9c SM 3.0 2005 R600, // GL3.3 DX10 SM 4.0 2006 R700, // GL3.3 DX10.1 SM 4.1 2008 Evergreen, // GL4.0 CL1.0 DX11 SM 5.0 2009 NorthernIslands, // GL4.0 CL1.1 DX11 SM 5.0 2010 SouthernIslands, // GL4.5 CL1.2 DX11.1 SM 5.1 2012 SeaIslands, // GL4.5 CL2.0 DX12 SM 6.0 2013 VolcanicIslands, // GL4.5 CL2.0 DX12 SM 6.0 2015 ArcticIslands, // GL4.5 CL2.0 DX12 SM 6.0 2016 Vega, // GL4.6 CL2.0 DX12 SM 6.0 2017 UnknownRadeon = 999, // NVIDIA NV10 = 1000, // GL1.2 DX7 1999 NV20, // GL1.3 DX8 SM 1.1 2001 NV30, // GL1.5 DX9a SM 2.0 2003 NV40, // GL2.1 DX9c SM 3.0 2004 G80, // GL3.3 DX10 SM 4.0 2006 GF100, // GL4.1 CL1.1 DX11 SM 5.0 2010 UnknownNVidia = 1999, // Intel I8XX = 2000, // GL1.3 DX7 2001 I915, // GL1.4/1.5 DX9/DX9c SM 2.0 2004 I965, // GL2.0/2.1 DX9/DX10 SM 3.0/4.0 2006 SandyBridge, // GL3.1 CL1.1 DX10.1 SM 4.0 2010 IvyBridge, // GL4.0 CL1.1 DX11 SM 5.0 2012 Haswell, // GL4.0 CL1.2 DX11.1 SM 5.0 2013 UnknownIntel = 2999, // Qualcomm Adreno // from https://en.wikipedia.org/wiki/Adreno Adreno1XX = 3000, // GLES1.1 Adreno2XX, // GLES2.0 DX9c Adreno3XX, // GLES3.0 CL1.1 DX11.1 Adreno4XX, // GLES3.1 CL1.2 DX11.2 Adreno5XX, // GLES3.1 CL2.0 DX11.2 UnknownAdreno = 3999, UnknownChipClass = 99999 }; class KWINGLUTILS_EXPORT GLPlatform { public: ~GLPlatform(); /** * Runs the detection code using the current OpenGL context. - **/ + */ void detect(OpenGLPlatformInterface platformInterface); /** * Prints the results of the detection code. - **/ + */ void printResults() const; /** * Returns a pointer to the GLPlatform instance. - **/ + */ static GLPlatform *instance(); /** * Returns true if the driver support the given feature, and false otherwise. - **/ + */ bool supports(GLFeature feature) const; /** * Returns the OpenGL version. - **/ + */ qint64 glVersion() const; /** * Returns the GLSL version if the driver supports GLSL, and 0 otherwise. - **/ + */ qint64 glslVersion() const; /** * Returns the Mesa version if the driver is a Mesa driver, and 0 otherwise. - **/ + */ qint64 mesaVersion() const; /** * Returns the Gallium version if the driver is a Gallium driver, and 0 otherwise. - **/ + */ qint64 galliumVersion() const; /** * Returns the X server version. * * Note that the version number changed from 7.2 to 1.3 in the first release * following the doupling of the X server from the katamari. * * For non X.org servers, this method returns 0. - **/ + */ qint64 serverVersion() const; /** * Returns the Linux kernel version. * * If the kernel is not a Linux kernel, this method returns 0. - **/ + */ qint64 kernelVersion() const; /** * Returns the driver version. * * For Mesa drivers, this is the same as the Mesa version number. - **/ + */ qint64 driverVersion() const; /** * Returns the driver. - **/ + */ Driver driver() const; /** * Returns the chip class. - **/ + */ ChipClass chipClass() const; /** * Returns true if the driver is a Mesa driver, and false otherwise. - **/ + */ bool isMesaDriver() const; /** * Returns true if the driver is a Gallium driver, and false otherwise. - **/ + */ bool isGalliumDriver() const; /** * Returns true if the GPU is a Radeon GPU, and false otherwise. - **/ + */ bool isRadeon() const; /** * Returns true if the GPU is an NVIDIA GPU, and false otherwise. - **/ + */ bool isNvidia() const; /** * Returns true if the GPU is an Intel GPU, and false otherwise. - **/ + */ bool isIntel() const; /** * @returns @c true if the "GPU" is a VirtualBox GPU, and @c false otherwise. * @since 4.10 - **/ + */ bool isVirtualBox() const; /** * @returns @c true if the "GPU" is a VMWare GPU, and @c false otherwise. * @since 4.10 - **/ + */ bool isVMware() const; /** * @returns @c true if OpenGL is emulated in software. * @since 4.7 - **/ + */ bool isSoftwareEmulation() const; /** * @returns @c true if the driver is known to be from a virtual machine. * @since 4.10 - **/ + */ bool isVirtualMachine() const; /** * @returns @c true if the GPU is a Qualcomm Adreno GPU, and false otherwise * @since 5.8 - **/ + */ bool isAdreno() const; /** * @returns the GL_VERSION string as provided by the driver. * @since 4.9 - **/ + */ const QByteArray &glVersionString() const; /** * @returns the GL_RENDERER string as provided by the driver. * @since 4.9 - **/ + */ const QByteArray &glRendererString() const; /** * @returns the GL_VENDOR string as provided by the driver. * @since 4.9 - **/ + */ const QByteArray &glVendorString() const; /** * @returns the GL_SHADING_LANGUAGE_VERSION string as provided by the driver. * If the driver does not support the OpenGL Shading Language a null bytearray is returned. * @since 4.9 - **/ + */ const QByteArray &glShadingLanguageVersionString() const; /** * @returns Whether the driver supports loose texture binding. * @since 4.9 - **/ + */ bool isLooseBinding() const; /** * @returns Whether OpenGL ES is used - **/ + */ bool isGLES() const; /** * @returns The CompositingType recommended by the driver. * @since 4.10 - **/ + */ CompositingType recommendedCompositor() const; /** * Returns true if glMapBufferRange() is likely to perform worse than glBufferSubData() * when updating an unused range of a buffer object, and false otherwise. * * @since 4.11 - **/ + */ bool preferBufferSubData() const; /** * @returns The OpenGLPlatformInterface currently used * @since 5.0 - **/ + */ OpenGLPlatformInterface platformInterface() const; /** * @returns a human readable form of the @p version as a QString. * @since 4.9 * @see glVersion * @see glslVersion * @see driverVersion * @see mesaVersion * @see galliumVersion * @see kernelVersion * @see serverVersion - **/ + */ static QString versionToString(qint64 version); /** * @returns a human readable form of the @p version as a QByteArray. * @since 5.5 * @see glVersion * @see glslVersion * @see driverVersion * @see mesaVersion * @see galliumVersion * @see kernelVersion * @see serverVersion - **/ + */ static QByteArray versionToString8(qint64 version); /** * @returns a human readable form for the @p driver as a QString. * @since 4.9 * @see driver - **/ + */ static QString driverToString(Driver driver); /** * @returns a human readable form for the @p driver as a QByteArray. * @since 5.5 * @see driver - **/ + */ static QByteArray driverToString8(Driver driver); /** * @returns a human readable form for the @p chipClass as a QString. * @since 4.9 * @see chipClass - **/ + */ static QString chipClassToString(ChipClass chipClass); /** * @returns a human readable form for the @p chipClass as a QByteArray. * @since 5.5 * @see chipClass - **/ + */ static QByteArray chipClassToString8(ChipClass chipClass); private: GLPlatform(); friend void KWin::cleanupGL(); static void cleanup(); private: QByteArray m_renderer; QByteArray m_vendor; QByteArray m_version; QByteArray m_glsl_version; QByteArray m_chipset; QSet m_extensions; Driver m_driver; ChipClass m_chipClass; CompositingType m_recommendedCompositor; qint64 m_glVersion; qint64 m_glslVersion; qint64 m_mesaVersion; qint64 m_driverVersion; qint64 m_galliumVersion; qint64 m_serverVersion; qint64 m_kernelVersion; bool m_looseBinding: 1; bool m_supportsGLSL: 1; bool m_limitedGLSL: 1; bool m_textureNPOT: 1; bool m_limitedNPOT: 1; bool m_virtualMachine: 1; bool m_preferBufferSubData: 1; OpenGLPlatformInterface m_platformInterface; bool m_gles: 1; static GLPlatform *s_platform; }; inline GLPlatform *GLPlatform::instance() { if (!s_platform) s_platform = new GLPlatform; return s_platform; } } // namespace KWin #endif // KWIN_GLPLATFORM_H diff --git a/libkwineffects/kwingltexture.h b/libkwineffects/kwingltexture.h index a746f4e65..98b409848 100644 --- a/libkwineffects/kwingltexture.h +++ b/libkwineffects/kwingltexture.h @@ -1,153 +1,153 @@ /******************************************************************** 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_GLTEXTURE_H #define KWIN_GLTEXTURE_H #include #include #include #include #include #include #include class QImage; class QPixmap; /** @addtogroup kwineffects */ /** @{ */ namespace KWin { class GLVertexBuffer; class GLTexturePrivate; enum TextureCoordinateType { NormalizedCoordinates = 0, UnnormalizedCoordinates }; class KWINGLUTILS_EXPORT GLTexture { public: GLTexture(); GLTexture(const GLTexture& tex); explicit GLTexture(const QImage& image, GLenum target = GL_TEXTURE_2D); explicit GLTexture(const QPixmap& pixmap, GLenum target = GL_TEXTURE_2D); explicit GLTexture(const QString& fileName); GLTexture(GLenum internalFormat, int width, int height, int levels = 1); explicit GLTexture(GLenum internalFormat, const QSize &size, int levels = 1); virtual ~GLTexture(); GLTexture & operator = (const GLTexture& tex); bool isNull() const; QSize size() const; int width() const; int height() const; /** * @since 4.7 - **/ + */ bool isYInverted() const; /** * @since 4.8 - **/ + */ void setYInverted(bool inverted); /** * Specifies which component of a texel is placed in each respective * component of the vector returned to the shader. * * Valid values are GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, GL_ONE and GL_ZERO. * * @see swizzleSupported() * @since 5.2 - **/ + */ void setSwizzle(GLenum red, GLenum green, GLenum blue, GLenum alpha); /** * Returns a matrix that transforms texture coordinates of the given type, * taking the texture target and the y-inversion flag into account. * * @since 4.11 - **/ + */ QMatrix4x4 matrix(TextureCoordinateType type) const; void update(const QImage& image, const QPoint &offset = QPoint(0, 0), const QRect &src = QRect()); virtual void discard(); void bind(); void unbind(); void render(QRegion region, const QRect& rect, bool hardwareClipping = false); GLuint texture() const; GLenum target() const; GLenum filter() const; GLenum internalFormat() const; /** @short * Make the texture fully transparent * Warning: this clobbers the current framebuffer binding except on fglrx - **/ + */ void clear(); bool isDirty() const; void setFilter(GLenum filter); void setWrapMode(GLenum mode); void setDirty(); void generateMipmaps(); static bool framebufferObjectSupported(); /** * Returns true if texture swizzle is supported, and false otherwise * * Texture swizzle requires OpenGL 3.3, GL_ARB_texture_swizzle, or OpenGL ES 3.0. * * @since 5.2 - **/ + */ static bool supportsSwizzle(); /** * Returns @c true if texture formats R* are supported, and @c false otherwise. * * This requires OpenGL 3.0, GL_ARB_texture_rg or OpenGL ES 3.0 or GL_EXT_texture_rg. * * @since 5.2.1 - **/ + */ static bool supportsFormatRG(); protected: QExplicitlySharedDataPointer d_ptr; GLTexture(GLTexturePrivate& dd); private: Q_DECLARE_PRIVATE(GLTexture) }; } // namespace /** @} */ #endif diff --git a/libkwineffects/kwinglutils.h b/libkwineffects/kwinglutils.h index d0af7b153..a8252ad04 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 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 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 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 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/libkwineffects/kwinxrenderutils.h b/libkwineffects/kwinxrenderutils.h index f26e98846..ecf9319ea 100644 --- a/libkwineffects/kwinxrenderutils.h +++ b/libkwineffects/kwinxrenderutils.h @@ -1,194 +1,194 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 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_XRENDERUTILS_H #define KWIN_XRENDERUTILS_H // KWin #include // Qt #include #include #include // XCB #include class QColor; class QPixmap; /** @addtogroup kwineffects */ /** @{ */ namespace KWin { /** * dumps a QColor into a xcb_render_color_t - **/ + */ KWINXRENDERUTILS_EXPORT xcb_render_color_t preMultiply(const QColor &c, float opacity = 1.0); /** @internal */ class KWINXRENDERUTILS_EXPORT XRenderPictureData : public QSharedData { public: explicit XRenderPictureData(xcb_render_picture_t pic = XCB_RENDER_PICTURE_NONE); ~XRenderPictureData(); xcb_render_picture_t value(); private: xcb_render_picture_t picture; Q_DISABLE_COPY(XRenderPictureData) }; /** * @short Wrapper around XRender Picture. * * This class wraps XRender's Picture, providing proper initialization, * convenience constructors and freeing of resources. * It should otherwise act exactly like the Picture type. - **/ + */ class KWINXRENDERUTILS_EXPORT XRenderPicture { public: explicit XRenderPicture(xcb_render_picture_t pic = XCB_RENDER_PICTURE_NONE); explicit XRenderPicture(const QImage &img); XRenderPicture(xcb_pixmap_t pix, int depth); operator xcb_render_picture_t(); private: void fromImage(const QImage &img); QExplicitlySharedDataPointer< XRenderPictureData > d; }; class KWINXRENDERUTILS_EXPORT XFixesRegion { public: explicit XFixesRegion(const QRegion ®ion); virtual ~XFixesRegion(); operator xcb_xfixes_region_t(); private: xcb_xfixes_region_t m_region; }; inline XRenderPictureData::XRenderPictureData(xcb_render_picture_t pic) : picture(pic) { } inline xcb_render_picture_t XRenderPictureData::value() { return picture; } inline XRenderPicture::XRenderPicture(xcb_render_picture_t pic) : d(new XRenderPictureData(pic)) { } inline XRenderPicture::operator xcb_render_picture_t() { return d->value(); } inline XFixesRegion::operator xcb_xfixes_region_t() { return m_region; } /** * Static 1x1 picture used to deliver a black pixel with given opacity (for blending performance) * Call and Use, the PixelPicture will stay, but may change it's opacity meanwhile. It's NOT threadsafe either - **/ + */ KWINXRENDERUTILS_EXPORT XRenderPicture xRenderBlendPicture(double opacity); /** * Creates a 1x1 Picture filled with c - **/ + */ KWINXRENDERUTILS_EXPORT XRenderPicture xRenderFill(const xcb_render_color_t &c); KWINXRENDERUTILS_EXPORT XRenderPicture xRenderFill(const QColor &c); /** * Allows to render a window into a (transparent) pixmap * NOTICE: the result can be queried as xRenderWindowOffscreenTarget() * NOTICE: it may be 0 * NOTICE: when done call setXRenderWindowOffscreen(false) to continue normal render process - **/ + */ KWINXRENDERUTILS_EXPORT void setXRenderOffscreen(bool b); /** * Allows to define a persistent effect member as render target * The window (including shadows) is rendered into the top left corner * NOTICE: do NOT call setXRenderOffscreen(true) in addition! * NOTICE: do not forget to xRenderPopTarget once you're done to continue the normal render process - **/ + */ KWINXRENDERUTILS_EXPORT void xRenderPushTarget(XRenderPicture *pic); KWINXRENDERUTILS_EXPORT void xRenderPopTarget(); /** * Whether windows are currently rendered into an offscreen target buffer - **/ + */ KWINXRENDERUTILS_EXPORT bool xRenderOffscreen(); /** * The offscreen buffer as set by the renderer because of setXRenderWindowOffscreen(true) - **/ + */ KWINXRENDERUTILS_EXPORT xcb_render_picture_t xRenderOffscreenTarget(); /** * NOTICE: HANDS OFF!!! * scene_setXRenderWindowOffscreenTarget() is ONLY to be used by the renderer - DO NOT TOUCH! - **/ + */ KWINXRENDERUTILS_EXPORT void scene_setXRenderOffscreenTarget(xcb_render_picture_t pix); /** * scene_xRenderWindowOffscreenTarget() is used by the scene to figure the target set by an effect - **/ + */ KWINXRENDERUTILS_EXPORT XRenderPicture *scene_xRenderOffscreenTarget(); namespace XRenderUtils { /** * @internal - **/ + */ KWINXRENDERUTILS_EXPORT void init(xcb_connection_t *connection, xcb_window_t rootWindow); /** * Returns the Xrender format that corresponds to the given visual ID. - **/ + */ KWINXRENDERUTILS_EXPORT xcb_render_pictformat_t findPictFormat(xcb_visualid_t visual); /** * Returns the xcb_render_directformat_t for the given Xrender format. - **/ + */ KWINXRENDERUTILS_EXPORT const xcb_render_directformat_t *findPictFormatInfo(xcb_render_pictformat_t format); /** * @internal - **/ + */ KWINXRENDERUTILS_EXPORT void cleanup(); } // namespace XRenderUtils } // namespace KWin /** @} */ #endif diff --git a/logind.h b/logind.h index c5ff17274..165d1f614 100644 --- a/logind.h +++ b/logind.h @@ -1,112 +1,112 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 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_LOGIND_H #define KWIN_LOGIND_H #include #include #include class QDBusServiceWatcher; namespace KWin { class KWIN_EXPORT LogindIntegration : public QObject { Q_OBJECT public: ~LogindIntegration() override; bool isConnected() const { return m_connected; } bool hasSessionControl() const { return m_sessionControl; } bool isActiveSession() const { return m_sessionActive; } int vt() const { return m_vt; } void switchVirtualTerminal(quint32 vtNr); void takeControl(); void releaseControl(); int takeDevice(const char *path); void releaseDevice(int fd); const QString seat() const { return m_seatName; } Q_SIGNALS: void connectedChanged(); void hasSessionControlChanged(bool); void sessionActiveChanged(bool); void virtualTerminalChanged(int); private Q_SLOTS: void getSessionActive(); void getVirtualTerminal(); void pauseDevice(uint major, uint minor, const QString &type); private: friend class LogindTest; /** * The DBusConnection argument is needed for the unit test. Logind uses the system bus * on which the unit test's fake logind cannot register to. Thus the unit test need to * be able to do everything over the session bus. This ctor allows the LogindTest to * create a LogindIntegration which listens on the session bus. - **/ + */ explicit LogindIntegration(const QDBusConnection &connection, QObject *parent = nullptr); void logindServiceRegistered(); void connectSessionPropertiesChanged(); enum SessionController { SessionControllerLogind, SessionControllerConsoleKit, }; void setupSessionController(SessionController controller); void getSeat(); QDBusConnection m_bus; QDBusServiceWatcher *m_logindServiceWatcher; bool m_connected; QString m_sessionPath; bool m_sessionControl; bool m_sessionActive; int m_vt = -1; QString m_seatName = QStringLiteral("seat0"); QString m_seatPath; QString m_sessionControllerName; QString m_sessionControllerService; QString m_sessionControllerPath; QString m_sessionControllerManagerInterface; QString m_sessionControllerSeatInterface; QString m_sessionControllerSessionInterface; QString m_sessionControllerActiveProperty; KWIN_SINGLETON(LogindIntegration) }; } #endif diff --git a/main.h b/main.h index 36a5acde9..1585c4d68 100644 --- a/main.h +++ b/main.h @@ -1,292 +1,292 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 MAIN_H #define MAIN_H #include #include #include // Qt #include #include #include class KPluginMetaData; class QCommandLineParser; namespace KWin { class Platform; class XcbEventFilter : public QAbstractNativeEventFilter { public: bool nativeEventFilter(const QByteArray &eventType, void *message, long int *result) override; }; class KWIN_EXPORT Application : public QApplication { Q_OBJECT Q_PROPERTY(quint32 x11Time READ x11Time WRITE setX11Time) Q_PROPERTY(quint32 x11RootWindow READ x11RootWindow CONSTANT) Q_PROPERTY(void *x11Connection READ x11Connection NOTIFY x11ConnectionChanged) Q_PROPERTY(int x11ScreenNumber READ x11ScreenNumber CONSTANT) Q_PROPERTY(KSharedConfigPtr config READ config WRITE setConfig) Q_PROPERTY(KSharedConfigPtr kxkbConfig READ kxkbConfig WRITE setKxkbConfig) Q_PROPERTY(KSharedConfigPtr inputConfig READ inputConfig WRITE setInputConfig) public: /** * @brief This enum provides the various operation modes of KWin depending on the available * Windowing Systems at startup. For example whether KWin only talks to X11 or also to a Wayland * Compositor. * - **/ + */ enum OperationMode { /** * @brief KWin uses only X11 for managing windows and compositing - **/ + */ OperationModeX11, /** * @brief KWin uses only Wayland - **/ + */ OperationModeWaylandOnly, /** * @brief KWin uses Wayland and controls a nested Xwayland server. - **/ + */ OperationModeXwayland }; ~Application() override; void setConfigLock(bool lock); KSharedConfigPtr config() const { return m_config; } void setConfig(KSharedConfigPtr config) { m_config = config; } KSharedConfigPtr kxkbConfig() const { return m_kxkbConfig; } void setKxkbConfig(KSharedConfigPtr config) { m_kxkbConfig = config; } KSharedConfigPtr inputConfig() const { return m_inputConfig; } void setInputConfig(KSharedConfigPtr config) { m_inputConfig = config; } void start(); /** * @brief The operation mode used by KWin. * * @return OperationMode - **/ + */ OperationMode operationMode() const; void setOperationMode(OperationMode mode); bool shouldUseWaylandForCompositing() const; void setupTranslator(); void setupCommandLine(QCommandLineParser *parser); void processCommandLine(QCommandLineParser *parser); xcb_timestamp_t x11Time() const { return m_x11Time; } enum class TimestampUpdate { OnlyIfLarger, Always }; void setX11Time(xcb_timestamp_t timestamp, TimestampUpdate force = TimestampUpdate::OnlyIfLarger) { if ((timestamp > m_x11Time || force == TimestampUpdate::Always) && timestamp != 0) { m_x11Time = timestamp; } } void updateX11Time(xcb_generic_event_t *event); void createScreens(); static void setCrashCount(int count); static bool wasCrash(); /** * Creates the KAboutData object for the KWin instance and registers it as * KAboutData::setApplicationData. - **/ + */ static void createAboutData(); /** * @returns the X11 Screen number. If not applicable it's set to @c -1. - **/ + */ static int x11ScreenNumber(); /** * Sets the X11 screen number of this KWin instance to @p screenNumber. - **/ + */ static void setX11ScreenNumber(int screenNumber); /** * @returns whether this is a multi head setup on X11. - **/ + */ static bool isX11MultiHead(); /** * Sets whether this is a multi head setup on X11. - **/ + */ static void setX11MultiHead(bool multiHead); /** * @returns the X11 root window. - **/ + */ xcb_window_t x11RootWindow() const { return m_rootWindow; } /** * @returns the X11 xcb connection - **/ + */ xcb_connection_t *x11Connection() const { return m_connection; } #ifdef KWIN_BUILD_ACTIVITIES bool usesKActivities() const { return m_useKActivities; } void setUseKActivities(bool use) { m_useKActivities = use; } #endif virtual QProcessEnvironment processStartupEnvironment() const; void initPlatform(const KPluginMetaData &plugin); Platform *platform() const { return m_platform; } bool isTerminating() const { return m_terminating; } static void setupMalloc(); static void setupLocalizedString(); static bool usesLibinput(); static void setUseLibinput(bool use); Q_SIGNALS: void x11ConnectionChanged(); void x11ConnectionAboutToBeDestroyed(); void workspaceCreated(); void screensCreated(); void virtualTerminalCreated(); protected: Application(OperationMode mode, int &argc, char **argv); virtual void performStartup() = 0; void notifyKSplash(); void createInput(); void createWorkspace(); void createAtoms(); void createOptions(); void createCompositor(); void setupEventFilters(); void destroyWorkspace(); void destroyCompositor(); /** * Inheriting classes should use this method to set the X11 root window * before accessing any X11 specific code pathes. - **/ + */ void setX11RootWindow(xcb_window_t root) { m_rootWindow = root; } /** * Inheriting classes should use this method to set the xcb connection * before accessing any X11 specific code pathes. - **/ + */ void setX11Connection(xcb_connection_t *c) { m_connection = c; emit x11ConnectionChanged(); } void destroyAtoms(); void setTerminating() { m_terminating = true; } protected: QString m_originalSessionKey; static int crashes; private Q_SLOTS: void resetCrashesCount(); private: QScopedPointer m_eventFilter; bool m_configLock; KSharedConfigPtr m_config; KSharedConfigPtr m_kxkbConfig; KSharedConfigPtr m_inputConfig; OperationMode m_operationMode; xcb_timestamp_t m_x11Time = XCB_TIME_CURRENT_TIME; xcb_window_t m_rootWindow = XCB_WINDOW_NONE; xcb_connection_t *m_connection = nullptr; #ifdef KWIN_BUILD_ACTIVITIES bool m_useKActivities = true; #endif Platform *m_platform = nullptr; bool m_terminating = false; }; inline static Application *kwinApp() { return static_cast(QCoreApplication::instance()); } namespace Xwl { class Xwayland; } class KWIN_EXPORT ApplicationWaylandAbstract : public Application { Q_OBJECT public: ~ApplicationWaylandAbstract() override = 0; protected: friend class Xwl::Xwayland; ApplicationWaylandAbstract(OperationMode mode, int &argc, char **argv); virtual void setProcessStartupEnvironment(const QProcessEnvironment &environment) { Q_UNUSED(environment); } virtual void startSession() {} }; } // namespace #endif diff --git a/netinfo.h b/netinfo.h index 835b908cf..a6ee95083 100644 --- a/netinfo.h +++ b/netinfo.h @@ -1,100 +1,100 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 Lucas Murray 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_NETINFO_H #define KWIN_NETINFO_H #include #include #include namespace KWin { class AbstractClient; class Client; class RootInfoFilter; /** * NET WM Protocol handler class - **/ + */ class RootInfo : public NETRootInfo { private: typedef KWin::Client Client; // Because of NET::Client public: static RootInfo *create(); static void destroy(); void setActiveClient(AbstractClient *client); protected: void changeNumberOfDesktops(int n) override; void changeCurrentDesktop(int d) override; void changeActiveWindow(xcb_window_t w, NET::RequestSource src, xcb_timestamp_t timestamp, xcb_window_t active_window) override; void closeWindow(xcb_window_t w) override; void moveResize(xcb_window_t w, int x_root, int y_root, unsigned long direction) override; void moveResizeWindow(xcb_window_t w, int flags, int x, int y, int width, int height) override; void gotPing(xcb_window_t w, xcb_timestamp_t timestamp) override; void restackWindow(xcb_window_t w, RequestSource source, xcb_window_t above, int detail, xcb_timestamp_t timestamp) override; void changeShowingDesktop(bool showing) override; private: RootInfo(xcb_window_t w, const char* name, NET::Properties properties, NET::WindowTypes types, NET::States states, NET::Properties2 properties2, NET::Actions actions, int scr = -1); static RootInfo *s_self; friend RootInfo *rootInfo(); xcb_window_t m_activeWindow; std::unique_ptr m_eventFilter; }; inline RootInfo *rootInfo() { return RootInfo::s_self; } /** * NET WM Protocol handler class - **/ + */ class WinInfo : public NETWinInfo { private: typedef KWin::Client Client; // Because of NET::Client public: WinInfo(Client* c, xcb_window_t window, xcb_window_t rwin, NET::Properties properties, NET::Properties2 properties2); void changeDesktop(int desktop) override; void changeFullscreenMonitors(NETFullscreenMonitors topology) override; void changeState(NET::States state, NET::States mask) override; void disable(); private: Client * m_client; }; } // KWin #endif diff --git a/options.h b/options.h index 14b7d7ef6..cb0a8894c 100644 --- a/options.h +++ b/options.h @@ -1,935 +1,935 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak 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_OPTIONS_H #define KWIN_OPTIONS_H #include "main.h" #include "placement.h" namespace KWin { // Whether to keep all windows mapped when compositing (i.e. whether to have // actively updated window pixmaps). enum HiddenPreviews { // The normal mode with regard to mapped windows. Hidden (minimized, etc.) // and windows on inactive virtual desktops are not mapped, their pixmaps // are only their icons. HiddenPreviewsNever, // Like normal mode, but shown windows (i.e. on inactive virtual desktops) // are kept mapped, only hidden windows are unmapped. HiddenPreviewsShown, // All windows are kept mapped regardless of their state. HiddenPreviewsAlways }; class Settings; class KWIN_EXPORT Options : public QObject { Q_OBJECT Q_ENUMS(FocusPolicy) Q_ENUMS(GlSwapStrategy) Q_ENUMS(MouseCommand) Q_ENUMS(MouseWheelCommand) Q_ENUMS(WindowOperation) Q_PROPERTY(FocusPolicy focusPolicy READ focusPolicy WRITE setFocusPolicy NOTIFY focusPolicyChanged) Q_PROPERTY(bool nextFocusPrefersMouse READ isNextFocusPrefersMouse WRITE setNextFocusPrefersMouse NOTIFY nextFocusPrefersMouseChanged) /** * Whether clicking on a window raises it in FocusFollowsMouse * mode or not. - **/ + */ Q_PROPERTY(bool clickRaise READ isClickRaise WRITE setClickRaise NOTIFY clickRaiseChanged) /** * Whether autoraise is enabled FocusFollowsMouse mode or not. - **/ + */ Q_PROPERTY(bool autoRaise READ isAutoRaise WRITE setAutoRaise NOTIFY autoRaiseChanged) /** * Autoraise interval. - **/ + */ Q_PROPERTY(int autoRaiseInterval READ autoRaiseInterval WRITE setAutoRaiseInterval NOTIFY autoRaiseIntervalChanged) /** * Delayed focus interval. - **/ + */ Q_PROPERTY(int delayFocusInterval READ delayFocusInterval WRITE setDelayFocusInterval NOTIFY delayFocusIntervalChanged) /** * Whether shade hover is enabled or not. - **/ + */ Q_PROPERTY(bool shadeHover READ isShadeHover WRITE setShadeHover NOTIFY shadeHoverChanged) /** * Shade hover interval. - **/ + */ Q_PROPERTY(int shadeHoverInterval READ shadeHoverInterval WRITE setShadeHoverInterval NOTIFY shadeHoverIntervalChanged) /** * Whether to see Xinerama screens separately for focus (in Alt+Tab, when activating next client) - **/ + */ Q_PROPERTY(bool separateScreenFocus READ isSeparateScreenFocus WRITE setSeparateScreenFocus NOTIFY separateScreenFocusChanged) Q_PROPERTY(int placement READ placement WRITE setPlacement NOTIFY placementChanged) Q_PROPERTY(bool focusPolicyIsReasonable READ focusPolicyIsReasonable NOTIFY focusPolicyIsResonableChanged) /** * The size of the zone that triggers snapping on desktop borders. - **/ + */ Q_PROPERTY(int borderSnapZone READ borderSnapZone WRITE setBorderSnapZone NOTIFY borderSnapZoneChanged) /** * The size of the zone that triggers snapping with other windows. - **/ + */ Q_PROPERTY(int windowSnapZone READ windowSnapZone WRITE setWindowSnapZone NOTIFY windowSnapZoneChanged) /** * The size of the zone that triggers snapping on the screen center. - **/ + */ Q_PROPERTY(int centerSnapZone READ centerSnapZone WRITE setCenterSnapZone NOTIFY centerSnapZoneChanged) /** * Snap only when windows will overlap. - **/ + */ Q_PROPERTY(bool snapOnlyWhenOverlapping READ isSnapOnlyWhenOverlapping WRITE setSnapOnlyWhenOverlapping NOTIFY snapOnlyWhenOverlappingChanged) /** * Whether or not we roll over to the other edge when switching desktops past the edge. - **/ + */ Q_PROPERTY(bool rollOverDesktops READ isRollOverDesktops WRITE setRollOverDesktops NOTIFY rollOverDesktopsChanged) /** * 0 - 4 , see Workspace::allowClientActivation() - **/ + */ Q_PROPERTY(int focusStealingPreventionLevel READ focusStealingPreventionLevel WRITE setFocusStealingPreventionLevel NOTIFY focusStealingPreventionLevelChanged) Q_PROPERTY(KWin::Options::WindowOperation operationTitlebarDblClick READ operationTitlebarDblClick WRITE setOperationTitlebarDblClick NOTIFY operationTitlebarDblClickChanged) Q_PROPERTY(KWin::Options::WindowOperation operationMaxButtonLeftClick READ operationMaxButtonLeftClick WRITE setOperationMaxButtonLeftClick NOTIFY operationMaxButtonLeftClickChanged) Q_PROPERTY(KWin::Options::WindowOperation operationMaxButtonMiddleClick READ operationMaxButtonMiddleClick WRITE setOperationMaxButtonMiddleClick NOTIFY operationMaxButtonMiddleClickChanged) Q_PROPERTY(KWin::Options::WindowOperation operationMaxButtonRightClick READ operationMaxButtonRightClick WRITE setOperationMaxButtonRightClick NOTIFY operationMaxButtonRightClickChanged) Q_PROPERTY(MouseCommand commandActiveTitlebar1 READ commandActiveTitlebar1 WRITE setCommandActiveTitlebar1 NOTIFY commandActiveTitlebar1Changed) Q_PROPERTY(MouseCommand commandActiveTitlebar2 READ commandActiveTitlebar2 WRITE setCommandActiveTitlebar2 NOTIFY commandActiveTitlebar2Changed) Q_PROPERTY(MouseCommand commandActiveTitlebar3 READ commandActiveTitlebar3 WRITE setCommandActiveTitlebar3 NOTIFY commandActiveTitlebar3Changed) Q_PROPERTY(MouseCommand commandInactiveTitlebar1 READ commandInactiveTitlebar1 WRITE setCommandInactiveTitlebar1 NOTIFY commandInactiveTitlebar1Changed) Q_PROPERTY(MouseCommand commandInactiveTitlebar2 READ commandInactiveTitlebar2 WRITE setCommandInactiveTitlebar2 NOTIFY commandInactiveTitlebar2Changed) Q_PROPERTY(MouseCommand commandInactiveTitlebar3 READ commandInactiveTitlebar3 WRITE setCommandInactiveTitlebar3 NOTIFY commandInactiveTitlebar3Changed) Q_PROPERTY(MouseCommand commandWindow1 READ commandWindow1 WRITE setCommandWindow1 NOTIFY commandWindow1Changed) Q_PROPERTY(MouseCommand commandWindow2 READ commandWindow2 WRITE setCommandWindow2 NOTIFY commandWindow2Changed) Q_PROPERTY(MouseCommand commandWindow3 READ commandWindow3 WRITE setCommandWindow3 NOTIFY commandWindow3Changed) Q_PROPERTY(MouseCommand commandWindowWheel READ commandWindowWheel WRITE setCommandWindowWheel NOTIFY commandWindowWheelChanged) Q_PROPERTY(MouseCommand commandAll1 READ commandAll1 WRITE setCommandAll1 NOTIFY commandAll1Changed) Q_PROPERTY(MouseCommand commandAll2 READ commandAll2 WRITE setCommandAll2 NOTIFY commandAll2Changed) Q_PROPERTY(MouseCommand commandAll3 READ commandAll3 WRITE setCommandAll3 NOTIFY commandAll3Changed) Q_PROPERTY(uint keyCmdAllModKey READ keyCmdAllModKey WRITE setKeyCmdAllModKey NOTIFY keyCmdAllModKeyChanged) /** * Whether the Geometry Tip should be shown during a window move/resize. - **/ + */ Q_PROPERTY(bool showGeometryTip READ showGeometryTip WRITE setShowGeometryTip NOTIFY showGeometryTipChanged) /** * Whether the visible name should be condensed. - **/ + */ Q_PROPERTY(bool condensedTitle READ condensedTitle WRITE setCondensedTitle NOTIFY condensedTitleChanged) /** * Whether a window gets maximized when it reaches top screen edge while being moved. - **/ + */ Q_PROPERTY(bool electricBorderMaximize READ electricBorderMaximize WRITE setElectricBorderMaximize NOTIFY electricBorderMaximizeChanged) /** * Whether a window is tiled to half screen when reaching left or right screen edge while been moved. - **/ + */ Q_PROPERTY(bool electricBorderTiling READ electricBorderTiling WRITE setElectricBorderTiling NOTIFY electricBorderTilingChanged) /** * Whether a window is tiled to half screen when reaching left or right screen edge while been moved. - **/ + */ Q_PROPERTY(float electricBorderCornerRatio READ electricBorderCornerRatio WRITE setElectricBorderCornerRatio NOTIFY electricBorderCornerRatioChanged) Q_PROPERTY(bool borderlessMaximizedWindows READ borderlessMaximizedWindows WRITE setBorderlessMaximizedWindows NOTIFY borderlessMaximizedWindowsChanged) /** * timeout before non-responding application will be killed after attempt to close. - **/ + */ Q_PROPERTY(int killPingTimeout READ killPingTimeout WRITE setKillPingTimeout NOTIFY killPingTimeoutChanged) /** * Whether to hide utility windows for inactive applications. - **/ + */ Q_PROPERTY(bool hideUtilityWindowsForInactive READ isHideUtilityWindowsForInactive WRITE setHideUtilityWindowsForInactive NOTIFY hideUtilityWindowsForInactiveChanged) Q_PROPERTY(bool inactiveTabsSkipTaskbar READ isInactiveTabsSkipTaskbar WRITE setInactiveTabsSkipTaskbar NOTIFY inactiveTabsSkipTaskbarChanged) Q_PROPERTY(bool autogroupSimilarWindows READ isAutogroupSimilarWindows WRITE setAutogroupSimilarWindows NOTIFY autogroupSimilarWindowsChanged) Q_PROPERTY(bool autogroupInForeground READ isAutogroupInForeground WRITE setAutogroupInForeground NOTIFY autogroupInForegroundChanged) Q_PROPERTY(int compositingMode READ compositingMode WRITE setCompositingMode NOTIFY compositingModeChanged) Q_PROPERTY(bool useCompositing READ isUseCompositing WRITE setUseCompositing NOTIFY useCompositingChanged) Q_PROPERTY(int hiddenPreviews READ hiddenPreviews WRITE setHiddenPreviews NOTIFY hiddenPreviewsChanged) /** * 0 = no, 1 = yes when transformed, * 2 = try trilinear when transformed; else 1, * -1 = auto - **/ + */ Q_PROPERTY(int glSmoothScale READ glSmoothScale WRITE setGlSmoothScale NOTIFY glSmoothScaleChanged) Q_PROPERTY(bool xrenderSmoothScale READ isXrenderSmoothScale WRITE setXrenderSmoothScale NOTIFY xrenderSmoothScaleChanged) Q_PROPERTY(qint64 maxFpsInterval READ maxFpsInterval WRITE setMaxFpsInterval NOTIFY maxFpsIntervalChanged) Q_PROPERTY(uint refreshRate READ refreshRate WRITE setRefreshRate NOTIFY refreshRateChanged) Q_PROPERTY(qint64 vBlankTime READ vBlankTime WRITE setVBlankTime NOTIFY vBlankTimeChanged) Q_PROPERTY(bool glStrictBinding READ isGlStrictBinding WRITE setGlStrictBinding NOTIFY glStrictBindingChanged) /** * Whether strict binding follows the driver or has been overwritten by a user defined config value. * If @c true glStrictBinding is set by the OpenGL Scene during initialization. * If @c false glStrictBinding is set from a config value and not updated during scene initialization. - **/ + */ Q_PROPERTY(bool glStrictBindingFollowsDriver READ isGlStrictBindingFollowsDriver WRITE setGlStrictBindingFollowsDriver NOTIFY glStrictBindingFollowsDriverChanged) Q_PROPERTY(bool glCoreProfile READ glCoreProfile WRITE setGLCoreProfile NOTIFY glCoreProfileChanged) Q_PROPERTY(GlSwapStrategy glPreferBufferSwap READ glPreferBufferSwap WRITE setGlPreferBufferSwap NOTIFY glPreferBufferSwapChanged) Q_PROPERTY(KWin::OpenGLPlatformInterface glPlatformInterface READ glPlatformInterface WRITE setGlPlatformInterface NOTIFY glPlatformInterfaceChanged) Q_PROPERTY(bool windowsBlockCompositing READ windowsBlockCompositing WRITE setWindowsBlockCompositing NOTIFY windowsBlockCompositingChanged) public: explicit Options(QObject *parent = NULL); ~Options() override; void updateSettings(); /** * This enum type is used to specify the focus policy. * * Note that FocusUnderMouse and FocusStrictlyUnderMouse are not * particulary useful. They are only provided for old-fashined * die-hard UNIX people ;-) - **/ + */ enum FocusPolicy { /** * Clicking into a window activates it. This is also the default. - **/ + */ ClickToFocus, /** * Moving the mouse pointer actively onto a normal window activates it. * For convenience, the desktop and windows on the dock are excluded. * They require clicking. - **/ + */ FocusFollowsMouse, /** * The window that happens to be under the mouse pointer becomes active. * The invariant is: no window can have focus that is not under the mouse. * This also means that Alt-Tab won't work properly and popup dialogs are * usually unsable with the keyboard. Note that the desktop and windows on * the dock are excluded for convenience. They get focus only when clicking * on it. - **/ + */ FocusUnderMouse, /** * This is even worse than FocusUnderMouse. Only the window under the mouse * pointer is active. If the mouse points nowhere, nothing has the focus. If * the mouse points onto the desktop, the desktop has focus. The same holds * for windows on the dock. - **/ + */ FocusStrictlyUnderMouse }; FocusPolicy focusPolicy() const { return m_focusPolicy; } bool isNextFocusPrefersMouse() const { return m_nextFocusPrefersMouse; } /** * Whether clicking on a window raises it in FocusFollowsMouse * mode or not. - **/ + */ bool isClickRaise() const { return m_clickRaise; } /** * Whether autoraise is enabled FocusFollowsMouse mode or not. - **/ + */ bool isAutoRaise() const { return m_autoRaise; } /** * Autoraise interval - **/ + */ int autoRaiseInterval() const { return m_autoRaiseInterval; } /** * Delayed focus interval. - **/ + */ int delayFocusInterval() const { return m_delayFocusInterval; } /** * Whether shade hover is enabled or not. - **/ + */ bool isShadeHover() const { return m_shadeHover; } /** * Shade hover interval. - **/ + */ int shadeHoverInterval() { return m_shadeHoverInterval; } /** * Whether to see Xinerama screens separately for focus (in Alt+Tab, when activating next client) - **/ + */ bool isSeparateScreenFocus() const { return m_separateScreenFocus; } Placement::Policy placement() const { return m_placement; } bool focusPolicyIsReasonable() { return m_focusPolicy == ClickToFocus || m_focusPolicy == FocusFollowsMouse; } /** * The size of the zone that triggers snapping on desktop borders. - **/ + */ int borderSnapZone() const { return m_borderSnapZone; } /** * The size of the zone that triggers snapping with other windows. - **/ + */ int windowSnapZone() const { return m_windowSnapZone; } /** * The size of the zone that triggers snapping on the screen center. - **/ + */ int centerSnapZone() const { return m_centerSnapZone; } /** * Snap only when windows will overlap. - **/ + */ bool isSnapOnlyWhenOverlapping() const { return m_snapOnlyWhenOverlapping; } /** * Whether or not we roll over to the other edge when switching desktops past the edge. - **/ + */ bool isRollOverDesktops() const { return m_rollOverDesktops; } /** * Returns the focus stealing prevention level. * * @see allowClientActivation - **/ + */ int focusStealingPreventionLevel() const { return m_focusStealingPreventionLevel; } enum WindowOperation { MaximizeOp = 5000, RestoreOp, MinimizeOp, MoveOp, UnrestrictedMoveOp, ResizeOp, UnrestrictedResizeOp, CloseOp, OnAllDesktopsOp, ShadeOp, KeepAboveOp, KeepBelowOp, OperationsOp, WindowRulesOp, ToggleStoreSettingsOp = WindowRulesOp, ///< @obsolete HMaximizeOp, VMaximizeOp, LowerOp, FullScreenOp, NoBorderOp, NoOp, SetupWindowShortcutOp, ApplicationRulesOp, RemoveTabFromGroupOp, // Remove from group CloseTabGroupOp, // Close the group ActivateNextTabOp, // Move left in the group ActivatePreviousTabOp, // Move right in the group TabDragOp, }; WindowOperation operationTitlebarDblClick() const { return OpTitlebarDblClick; } WindowOperation operationMaxButtonLeftClick() const { return opMaxButtonLeftClick; } WindowOperation operationMaxButtonRightClick() const { return opMaxButtonRightClick; } WindowOperation operationMaxButtonMiddleClick() const { return opMaxButtonMiddleClick; } WindowOperation operationMaxButtonClick(Qt::MouseButtons button) const; enum MouseCommand { MouseRaise, MouseLower, MouseOperationsMenu, MouseToggleRaiseAndLower, MouseActivateAndRaise, MouseActivateAndLower, MouseActivate, MouseActivateRaiseAndPassClick, MouseActivateAndPassClick, MouseMove, MouseUnrestrictedMove, MouseActivateRaiseAndMove, MouseActivateRaiseAndUnrestrictedMove, MouseResize, MouseUnrestrictedResize, MouseShade, MouseSetShade, MouseUnsetShade, MouseMaximize, MouseRestore, MouseMinimize, MouseNextDesktop, MousePreviousDesktop, MouseAbove, MouseBelow, MouseOpacityMore, MouseOpacityLess, MouseClose, MousePreviousTab, MouseNextTab, MouseDragTab, MouseNothing }; enum MouseWheelCommand { MouseWheelRaiseLower, MouseWheelShadeUnshade, MouseWheelMaximizeRestore, MouseWheelAboveBelow, MouseWheelPreviousNextDesktop, MouseWheelChangeOpacity, MouseWheelChangeCurrentTab, MouseWheelNothing }; MouseCommand operationTitlebarMouseWheel(int delta) const { return wheelToMouseCommand(CmdTitlebarWheel, delta); } MouseCommand operationWindowMouseWheel(int delta) const { return wheelToMouseCommand(CmdAllWheel, delta); } MouseCommand commandActiveTitlebar1() const { return CmdActiveTitlebar1; } MouseCommand commandActiveTitlebar2() const { return CmdActiveTitlebar2; } MouseCommand commandActiveTitlebar3() const { return CmdActiveTitlebar3; } MouseCommand commandInactiveTitlebar1() const { return CmdInactiveTitlebar1; } MouseCommand commandInactiveTitlebar2() const { return CmdInactiveTitlebar2; } MouseCommand commandInactiveTitlebar3() const { return CmdInactiveTitlebar3; } MouseCommand commandWindow1() const { return CmdWindow1; } MouseCommand commandWindow2() const { return CmdWindow2; } MouseCommand commandWindow3() const { return CmdWindow3; } MouseCommand commandWindowWheel() const { return CmdWindowWheel; } MouseCommand commandAll1() const { return CmdAll1; } MouseCommand commandAll2() const { return CmdAll2; } MouseCommand commandAll3() const { return CmdAll3; } uint keyCmdAllModKey() const { return CmdAllModKey; } Qt::KeyboardModifier commandAllModifier() const { switch (CmdAllModKey) { case Qt::Key_Alt: return Qt::AltModifier; case Qt::Key_Meta: return Qt::MetaModifier; default: Q_UNREACHABLE(); } } static WindowOperation windowOperation(const QString &name, bool restricted); static MouseCommand mouseCommand(const QString &name, bool restricted); static MouseWheelCommand mouseWheelCommand(const QString &name); /** * @returns true if the Geometry Tip should be shown during a window move/resize. - **/ + */ bool showGeometryTip() const; /** * Returns whether the user prefers his caption clean. - **/ + */ bool condensedTitle() const; /** * @returns true if a window gets maximized when it reaches top screen edge * while being moved. - **/ + */ bool electricBorderMaximize() const { return electric_border_maximize; } /** * @returns true if window is tiled to half screen when reaching left or * right screen edge while been moved. - **/ + */ bool electricBorderTiling() const { return electric_border_tiling; } /** * @returns the factor that determines the corner part of the edge (ie. 0.1 means tiny corner) - **/ + */ float electricBorderCornerRatio() const { return electric_border_corner_ratio; } bool borderlessMaximizedWindows() const { return borderless_maximized_windows; } /** * Timeout before non-responding application will be killed after attempt to close. - **/ + */ int killPingTimeout() const { return m_killPingTimeout; } /** * Whether to hide utility windows for inactive applications. - **/ + */ bool isHideUtilityWindowsForInactive() const { return m_hideUtilityWindowsForInactive; } bool isInactiveTabsSkipTaskbar() const { return m_inactiveTabsSkipTaskbar; } bool isAutogroupSimilarWindows() const { return m_autogroupSimilarWindows; } bool isAutogroupInForeground() const { return m_autogroupInForeground; } /** * Returns the animation time factor for desktop effects. - **/ + */ double animationTimeFactor() const; //---------------------- // Compositing settings void reloadCompositingSettings(bool force = false); CompositingType compositingMode() const { return m_compositingMode; } void setCompositingMode(CompositingType mode) { m_compositingMode = mode; } // Separate to mode so the user can toggle bool isUseCompositing() const; // General preferences HiddenPreviews hiddenPreviews() const { return m_hiddenPreviews; } // OpenGL // 0 = no, 1 = yes when transformed, // 2 = try trilinear when transformed; else 1, // -1 = auto int glSmoothScale() const { return m_glSmoothScale; } // XRender bool isXrenderSmoothScale() const { return m_xrenderSmoothScale; } qint64 maxFpsInterval() const { return m_maxFpsInterval; } // Settings that should be auto-detected uint refreshRate() const { return m_refreshRate; } qint64 vBlankTime() const { return m_vBlankTime; } bool isGlStrictBinding() const { return m_glStrictBinding; } bool isGlStrictBindingFollowsDriver() const { return m_glStrictBindingFollowsDriver; } bool glCoreProfile() const { return m_glCoreProfile; } OpenGLPlatformInterface glPlatformInterface() const { return m_glPlatformInterface; } enum GlSwapStrategy { NoSwapEncourage = 0, CopyFrontBuffer = 'c', PaintFullScreen = 'p', ExtendDamage = 'e', AutoSwapStrategy = 'a' }; GlSwapStrategy glPreferBufferSwap() const { return m_glPreferBufferSwap; } bool windowsBlockCompositing() const { return m_windowsBlockCompositing; } QStringList modifierOnlyDBusShortcut(Qt::KeyboardModifier mod) const; // setters void setFocusPolicy(FocusPolicy focusPolicy); void setNextFocusPrefersMouse(bool nextFocusPrefersMouse); void setClickRaise(bool clickRaise); void setAutoRaise(bool autoRaise); void setAutoRaiseInterval(int autoRaiseInterval); void setDelayFocusInterval(int delayFocusInterval); void setShadeHover(bool shadeHover); void setShadeHoverInterval(int shadeHoverInterval); void setSeparateScreenFocus(bool separateScreenFocus); void setPlacement(int placement); void setBorderSnapZone(int borderSnapZone); void setWindowSnapZone(int windowSnapZone); void setCenterSnapZone(int centerSnapZone); void setSnapOnlyWhenOverlapping(bool snapOnlyWhenOverlapping); void setRollOverDesktops(bool rollOverDesktops); void setFocusStealingPreventionLevel(int focusStealingPreventionLevel); void setOperationTitlebarDblClick(WindowOperation operationTitlebarDblClick); void setOperationMaxButtonLeftClick(WindowOperation op); void setOperationMaxButtonRightClick(WindowOperation op); void setOperationMaxButtonMiddleClick(WindowOperation op); void setCommandActiveTitlebar1(MouseCommand commandActiveTitlebar1); void setCommandActiveTitlebar2(MouseCommand commandActiveTitlebar2); void setCommandActiveTitlebar3(MouseCommand commandActiveTitlebar3); void setCommandInactiveTitlebar1(MouseCommand commandInactiveTitlebar1); void setCommandInactiveTitlebar2(MouseCommand commandInactiveTitlebar2); void setCommandInactiveTitlebar3(MouseCommand commandInactiveTitlebar3); void setCommandWindow1(MouseCommand commandWindow1); void setCommandWindow2(MouseCommand commandWindow2); void setCommandWindow3(MouseCommand commandWindow3); void setCommandWindowWheel(MouseCommand commandWindowWheel); void setCommandAll1(MouseCommand commandAll1); void setCommandAll2(MouseCommand commandAll2); void setCommandAll3(MouseCommand commandAll3); void setKeyCmdAllModKey(uint keyCmdAllModKey); void setShowGeometryTip(bool showGeometryTip); void setCondensedTitle(bool condensedTitle); void setElectricBorderMaximize(bool electricBorderMaximize); void setElectricBorderTiling(bool electricBorderTiling); void setElectricBorderCornerRatio(float electricBorderCornerRatio); void setBorderlessMaximizedWindows(bool borderlessMaximizedWindows); void setKillPingTimeout(int killPingTimeout); void setHideUtilityWindowsForInactive(bool hideUtilityWindowsForInactive); void setInactiveTabsSkipTaskbar(bool inactiveTabsSkipTaskbar); void setAutogroupSimilarWindows(bool autogroupSimilarWindows); void setAutogroupInForeground(bool autogroupInForeground); void setCompositingMode(int compositingMode); void setUseCompositing(bool useCompositing); void setHiddenPreviews(int hiddenPreviews); void setGlSmoothScale(int glSmoothScale); void setXrenderSmoothScale(bool xrenderSmoothScale); void setMaxFpsInterval(qint64 maxFpsInterval); void setRefreshRate(uint refreshRate); void setVBlankTime(qint64 vBlankTime); void setGlStrictBinding(bool glStrictBinding); void setGlStrictBindingFollowsDriver(bool glStrictBindingFollowsDriver); void setGLCoreProfile(bool glCoreProfile); void setGlPreferBufferSwap(char glPreferBufferSwap); void setGlPlatformInterface(OpenGLPlatformInterface interface); void setWindowsBlockCompositing(bool set); // default values static WindowOperation defaultOperationTitlebarDblClick() { return MaximizeOp; } static WindowOperation defaultOperationMaxButtonLeftClick() { return MaximizeOp; } static WindowOperation defaultOperationMaxButtonRightClick() { return HMaximizeOp; } static WindowOperation defaultOperationMaxButtonMiddleClick() { return VMaximizeOp; } static MouseCommand defaultCommandActiveTitlebar1() { return MouseRaise; } static MouseCommand defaultCommandActiveTitlebar2() { return MouseDragTab; } static MouseCommand defaultCommandActiveTitlebar3() { return MouseOperationsMenu; } static MouseCommand defaultCommandInactiveTitlebar1() { return MouseActivateAndRaise; } static MouseCommand defaultCommandInactiveTitlebar2() { return MouseDragTab; } static MouseCommand defaultCommandInactiveTitlebar3() { return MouseOperationsMenu; } static MouseCommand defaultCommandWindow1() { return MouseActivateRaiseAndPassClick; } static MouseCommand defaultCommandWindow2() { return MouseActivateAndPassClick; } static MouseCommand defaultCommandWindow3() { return MouseActivateAndPassClick; } static MouseCommand defaultCommandWindowWheel() { return MouseNothing; } static MouseCommand defaultCommandAll1() { return MouseUnrestrictedMove; } static MouseCommand defaultCommandAll2() { return MouseToggleRaiseAndLower; } static MouseCommand defaultCommandAll3() { return MouseUnrestrictedResize; } static MouseWheelCommand defaultCommandTitlebarWheel() { return MouseWheelChangeCurrentTab; } static MouseWheelCommand defaultCommandAllWheel() { return MouseWheelNothing; } static uint defaultKeyCmdAllModKey() { return Qt::Key_Alt; } static bool defaultAutogroupInForeground() { return true; } static CompositingType defaultCompositingMode() { return OpenGLCompositing; } static bool defaultUseCompositing() { return true; } static HiddenPreviews defaultHiddenPreviews() { return HiddenPreviewsShown; } static int defaultGlSmoothScale() { return 2; } static bool defaultXrenderSmoothScale() { return false; } static qint64 defaultMaxFpsInterval() { return (1 * 1000 * 1000 * 1000) /60.0; // nanoseconds / Hz } static int defaultMaxFps() { return 60; } static uint defaultRefreshRate() { return 0; } static uint defaultVBlankTime() { return 6000; // 6ms } static bool defaultGlStrictBinding() { return true; } static bool defaultGlStrictBindingFollowsDriver() { return true; } static bool defaultGLCoreProfile() { return false; } static GlSwapStrategy defaultGlPreferBufferSwap() { return AutoSwapStrategy; } static OpenGLPlatformInterface defaultGlPlatformInterface() { return kwinApp()->shouldUseWaylandForCompositing() ? EglPlatformInterface : GlxPlatformInterface; }; static int defaultAnimationSpeed() { return 3; } /** * Performs loading all settings except compositing related. - **/ + */ void loadConfig(); /** * Performs loading of compositing settings which do not depend on OpenGL. - **/ + */ bool loadCompositingConfig(bool force); void reparseConfiguration(); static int currentRefreshRate(); //---------------------- Q_SIGNALS: // for properties void focusPolicyChanged(); void focusPolicyIsResonableChanged(); void nextFocusPrefersMouseChanged(); void clickRaiseChanged(); void autoRaiseChanged(); void autoRaiseIntervalChanged(); void delayFocusIntervalChanged(); void shadeHoverChanged(); void shadeHoverIntervalChanged(); void separateScreenFocusChanged(bool); void placementChanged(); void borderSnapZoneChanged(); void windowSnapZoneChanged(); void centerSnapZoneChanged(); void snapOnlyWhenOverlappingChanged(); void rollOverDesktopsChanged(bool enabled); void focusStealingPreventionLevelChanged(); void operationTitlebarDblClickChanged(); void operationMaxButtonLeftClickChanged(); void operationMaxButtonRightClickChanged(); void operationMaxButtonMiddleClickChanged(); void commandActiveTitlebar1Changed(); void commandActiveTitlebar2Changed(); void commandActiveTitlebar3Changed(); void commandInactiveTitlebar1Changed(); void commandInactiveTitlebar2Changed(); void commandInactiveTitlebar3Changed(); void commandWindow1Changed(); void commandWindow2Changed(); void commandWindow3Changed(); void commandWindowWheelChanged(); void commandAll1Changed(); void commandAll2Changed(); void commandAll3Changed(); void keyCmdAllModKeyChanged(); void showGeometryTipChanged(); void condensedTitleChanged(); void electricBorderMaximizeChanged(); void electricBorderTilingChanged(); void electricBorderCornerRatioChanged(); void borderlessMaximizedWindowsChanged(); void killPingTimeoutChanged(); void hideUtilityWindowsForInactiveChanged(); void inactiveTabsSkipTaskbarChanged(); void autogroupSimilarWindowsChanged(); void autogroupInForegroundChanged(); void compositingModeChanged(); void useCompositingChanged(); void hiddenPreviewsChanged(); void glSmoothScaleChanged(); void xrenderSmoothScaleChanged(); void maxFpsIntervalChanged(); void refreshRateChanged(); void vBlankTimeChanged(); void glStrictBindingChanged(); void glStrictBindingFollowsDriverChanged(); void glCoreProfileChanged(); void glPreferBufferSwapChanged(); void glPlatformInterfaceChanged(); void windowsBlockCompositingChanged(); void configChanged(); private: void setElectricBorders(int borders); void syncFromKcfgc(); QScopedPointer m_settings; FocusPolicy m_focusPolicy; bool m_nextFocusPrefersMouse; bool m_clickRaise; bool m_autoRaise; int m_autoRaiseInterval; int m_delayFocusInterval; bool m_shadeHover; int m_shadeHoverInterval; bool m_separateScreenFocus; Placement::Policy m_placement; int m_borderSnapZone; int m_windowSnapZone; int m_centerSnapZone; bool m_snapOnlyWhenOverlapping; bool m_rollOverDesktops; int m_focusStealingPreventionLevel; int m_killPingTimeout; bool m_hideUtilityWindowsForInactive; bool m_inactiveTabsSkipTaskbar; bool m_autogroupSimilarWindows; bool m_autogroupInForeground; CompositingType m_compositingMode; bool m_useCompositing; HiddenPreviews m_hiddenPreviews; int m_glSmoothScale; bool m_xrenderSmoothScale; qint64 m_maxFpsInterval; // Settings that should be auto-detected uint m_refreshRate; qint64 m_vBlankTime; bool m_glStrictBinding; bool m_glStrictBindingFollowsDriver; bool m_glCoreProfile; GlSwapStrategy m_glPreferBufferSwap; OpenGLPlatformInterface m_glPlatformInterface; bool m_windowsBlockCompositing; WindowOperation OpTitlebarDblClick; WindowOperation opMaxButtonRightClick = defaultOperationMaxButtonRightClick(); WindowOperation opMaxButtonMiddleClick = defaultOperationMaxButtonMiddleClick(); WindowOperation opMaxButtonLeftClick = defaultOperationMaxButtonRightClick(); // mouse bindings MouseCommand CmdActiveTitlebar1; MouseCommand CmdActiveTitlebar2; MouseCommand CmdActiveTitlebar3; MouseCommand CmdInactiveTitlebar1; MouseCommand CmdInactiveTitlebar2; MouseCommand CmdInactiveTitlebar3; MouseWheelCommand CmdTitlebarWheel; MouseCommand CmdWindow1; MouseCommand CmdWindow2; MouseCommand CmdWindow3; MouseCommand CmdWindowWheel; MouseCommand CmdAll1; MouseCommand CmdAll2; MouseCommand CmdAll3; MouseWheelCommand CmdAllWheel; uint CmdAllModKey; bool electric_border_maximize; bool electric_border_tiling; float electric_border_corner_ratio; bool borderless_maximized_windows; bool show_geometry_tip; bool condensed_title; int animationSpeed; // 0 - instant, 5 - very slow QHash m_modifierOnlyShortcuts; MouseCommand wheelToMouseCommand(MouseWheelCommand com, int delta) const; }; extern KWIN_EXPORT Options* options; } // namespace Q_DECLARE_METATYPE(KWin::Options::WindowOperation) Q_DECLARE_METATYPE(KWin::OpenGLPlatformInterface) #endif diff --git a/orientation_sensor.h b/orientation_sensor.h index 7f287694a..a560571ba 100644 --- a/orientation_sensor.h +++ b/orientation_sensor.h @@ -1,95 +1,95 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 Martin Flöser 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 . *********************************************************************/ #pragma once #include #include #include class QOrientationSensor; class OrientationSensorAdaptor; class KStatusNotifierItem; namespace KWin { class KWIN_EXPORT OrientationSensor : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.OrientationSensor") Q_PROPERTY(bool userEnabled READ isUserEnabled WRITE setUserEnabled NOTIFY userEnabledChanged) public: explicit OrientationSensor(QObject *parent = nullptr); ~OrientationSensor() override; void setEnabled(bool enabled); /** * Just like QOrientationReading::Orientation, * copied to not leak the QSensors API into internal API. - **/ + */ enum class Orientation { Undefined, TopUp, TopDown, LeftUp, RightUp, FaceUp, FaceDown }; Q_ENUM(Orientation) Orientation orientation() const { return m_orientation; } void setConfig(KSharedConfig::Ptr config) { m_config = config; } bool isUserEnabled() const { return m_userEnabled; } void setUserEnabled(bool enabled); Q_SIGNALS: void orientationChanged(); void userEnabledChanged(bool); private: void startStopSensor(); void loadConfig(); void refresh(); void activate(); void updateState(); QOrientationSensor *m_sensor; bool m_enabled = false; bool m_userEnabled = true; Orientation m_orientation = Orientation::Undefined; KStatusNotifierItem *m_sni = nullptr; KSharedConfig::Ptr m_config; OrientationSensorAdaptor *m_adaptor = nullptr; }; } diff --git a/outline.h b/outline.h index e4ba94f72..c1e402b48 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() override; /** * Set the outline geometry. * 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 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 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 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); ~CompositedOutlineVisual() override; void show() override; void hide() override; 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/outputscreens.h b/outputscreens.h index 90fd071ca..3bc8ba26b 100644 --- a/outputscreens.h +++ b/outputscreens.h @@ -1,61 +1,61 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 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_OUTPUTSCREENS_H #define KWIN_OUTPUTSCREENS_H #include "screens.h" namespace KWin { class AbstractOutput; /** * @brief Implementation for backends with Outputs - **/ + */ class KWIN_EXPORT OutputScreens : public Screens { Q_OBJECT public: OutputScreens(Platform *platform, QObject *parent = nullptr); ~OutputScreens() override; void init() override; QString name(int screen) const override; bool isInternal(int screen) const override; QSizeF physicalSize(int screen) const override; QRect geometry(int screen) const override; QSize size(int screen) const override; qreal scale(int screen) const override; float refreshRate(int screen) const override; Qt::ScreenOrientation orientation(int screen) const override; void updateCount() override; int number(const QPoint &pos) const override; protected: Platform *m_platform; private: AbstractOutput *findOutput(int screen) const; }; } #endif // KWIN_OUTPUTSCREENS_H diff --git a/placement.cpp b/placement.cpp index 220f5aae3..193f26540 100644 --- a/placement.cpp +++ b/placement.cpp @@ -1,957 +1,957 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 1997 to 2002 Cristian Tibirna Copyright (C) 2003 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 . *********************************************************************/ #include "placement.h" #ifndef KCMRULES #include "workspace.h" #include "client.h" #include "cursor.h" #include "options.h" #include "rules.h" #include "screens.h" #endif #include #include #include namespace KWin { #ifndef KCMRULES KWIN_SINGLETON_FACTORY(Placement) Placement::Placement(QObject*) { reinitCascading(0); } Placement::~Placement() { s_self = NULL; } /** * Places the client \a c according to the workspace's layout policy - **/ + */ void Placement::place(AbstractClient* c, QRect& area) { Policy policy = c->rules()->checkPlacement(Default); if (policy != Default) { place(c, area, policy); return; } if (c->isUtility()) placeUtility(c, area, options->placement()); else if (c->isDialog()) placeDialog(c, area, options->placement()); else if (c->isSplash()) placeOnMainWindow(c, area); // on mainwindow, if any, otherwise centered else if (c->isOnScreenDisplay() || c->isNotification() || c->isCriticalNotification()) placeOnScreenDisplay(c, area); else if (c->isTransient() && c->hasTransientPlacementHint()) placeTransient(c); else if (c->isTransient() && c->surface()) placeDialog(c, area, options->placement()); else place(c, area, options->placement()); } void Placement::place(AbstractClient* c, QRect& area, Policy policy, Policy nextPlacement) { if (policy == Unknown) policy = Default; if (policy == Default) policy = options->placement(); if (policy == NoPlacement) return; else if (policy == Random) placeAtRandom(c, area, nextPlacement); else if (policy == Cascade) placeCascaded(c, area, nextPlacement); else if (policy == Centered) placeCentered(c, area, nextPlacement); else if (policy == ZeroCornered) placeZeroCornered(c, area, nextPlacement); else if (policy == UnderMouse) placeUnderMouse(c, area, nextPlacement); else if (policy == OnMainWindow) placeOnMainWindow(c, area, nextPlacement); else if (policy == Maximizing) placeMaximizing(c, area, nextPlacement); else placeSmart(c, area, nextPlacement); if (options->borderSnapZone()) { // snap to titlebar / snap to window borders on inner screen edges const QRect geo(c->geometry()); QPoint corner = geo.topLeft(); const QPoint cp = c->clientPos(); const QSize cs = geo.size() - c->clientSize(); AbstractClient::Position titlePos = c->titlebarPosition(); const QRect fullRect = workspace()->clientArea(FullArea, c); if (!(c->maximizeMode() & MaximizeHorizontal)) { if (titlePos != AbstractClient::PositionRight && geo.right() == fullRect.right()) corner.rx() += cs.width() - cp.x(); if (titlePos != AbstractClient::PositionLeft && geo.x() == fullRect.x()) corner.rx() -= cp.x(); } if (!(c->maximizeMode() & MaximizeVertical)) { if (titlePos != AbstractClient::PositionBottom && geo.bottom() == fullRect.bottom()) corner.ry() += cs.height() - cp.y(); if (titlePos != AbstractClient::PositionTop && geo.y() == fullRect.y()) corner.ry() -= cp.y(); } c->move(corner); } } /** * Place the client \a c according to a simply "random" placement algorithm. - **/ + */ void Placement::placeAtRandom(AbstractClient* c, const QRect& area, Policy /*next*/) { const int step = 24; static int px = step; static int py = 2 * step; int tx, ty; const QRect maxRect = checkArea(c, area); if (px < maxRect.x()) px = maxRect.x(); if (py < maxRect.y()) py = maxRect.y(); px += step; py += 2 * step; if (px > maxRect.width() / 2) px = maxRect.x() + step; if (py > maxRect.height() / 2) py = maxRect.y() + step; tx = px; ty = py; if (tx + c->width() > maxRect.right()) { tx = maxRect.right() - c->width(); if (tx < 0) tx = 0; px = maxRect.x(); } if (ty + c->height() > maxRect.bottom()) { ty = maxRect.bottom() - c->height(); if (ty < 0) ty = 0; py = maxRect.y(); } c->move(tx, ty); } // TODO: one day, there'll be C++11 ... static inline bool isIrrelevant(const AbstractClient *client, const AbstractClient *regarding, int desktop) { if (!client) return true; if (client == regarding) return true; if (!client->isCurrentTab()) return true; if (!client->isShown(false)) return true; if (!client->isOnDesktop(desktop)) return true; if (!client->isOnCurrentActivity()) return true; if (client->isDesktop()) return true; return false; } /** * Place the client \a c according to a really smart placement algorithm :-) - **/ + */ void Placement::placeSmart(AbstractClient* c, const QRect& area, Policy /*next*/) { /* * SmartPlacement by Cristian Tibirna (tibirna@kde.org) * adapted for kwm (16-19jan98) and for kwin (16Nov1999) using (with * permission) ideas from fvwm, authored by * Anthony Martin (amartin@engr.csulb.edu). * Xinerama supported added by Balaji Ramani (balaji@yablibli.com) * with ideas from xfce. */ if (!c->size().isValid()) { return; } const int none = 0, h_wrong = -1, w_wrong = -2; // overlap types long int overlap, min_overlap = 0; int x_optimal, y_optimal; int possible; int desktop = c->desktop() == 0 || c->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : c->desktop(); int cxl, cxr, cyt, cyb; //temp coords int xl, xr, yt, yb; //temp coords int basket; //temp holder // get the maximum allowed windows space const QRect maxRect = checkArea(c, area); int x = maxRect.left(), y = maxRect.top(); x_optimal = x; y_optimal = y; //client gabarit int ch = c->height() - 1; int cw = c->width() - 1; bool first_pass = true; //CT lame flag. Don't like it. What else would do? //loop over possible positions do { //test if enough room in x and y directions if (y + ch > maxRect.bottom() && ch < maxRect.height()) overlap = h_wrong; // this throws the algorithm to an exit else if (x + cw > maxRect.right()) overlap = w_wrong; else { overlap = none; //initialize cxl = x; cxr = x + cw; cyt = y; cyb = y + ch; ToplevelList::ConstIterator l; for (l = workspace()->stackingOrder().constBegin(); l != workspace()->stackingOrder().constEnd() ; ++l) { AbstractClient *client = qobject_cast(*l); if (isIrrelevant(client, c, desktop)) { continue; } xl = client->x(); yt = client->y(); xr = xl + client->width(); yb = yt + client->height(); //if windows overlap, calc the overall overlapping if ((cxl < xr) && (cxr > xl) && (cyt < yb) && (cyb > yt)) { xl = qMax(cxl, xl); xr = qMin(cxr, xr); yt = qMax(cyt, yt); yb = qMin(cyb, yb); if (client->keepAbove()) overlap += 16 * (xr - xl) * (yb - yt); else if (client->keepBelow() && !client->isDock()) // ignore KeepBelow windows overlap += 0; // for placement (see Client::belongsToLayer() for Dock) else overlap += (xr - xl) * (yb - yt); } } } //CT first time we get no overlap we stop. if (overlap == none) { x_optimal = x; y_optimal = y; break; } if (first_pass) { first_pass = false; min_overlap = overlap; } //CT save the best position and the minimum overlap up to now else if (overlap >= none && overlap < min_overlap) { min_overlap = overlap; x_optimal = x; y_optimal = y; } // really need to loop? test if there's any overlap if (overlap > none) { possible = maxRect.right(); if (possible - cw > x) possible -= cw; // compare to the position of each client on the same desk ToplevelList::ConstIterator l; for (l = workspace()->stackingOrder().constBegin(); l != workspace()->stackingOrder().constEnd() ; ++l) { AbstractClient *client = qobject_cast(*l); if (isIrrelevant(client, c, desktop)) { continue; } xl = client->x(); yt = client->y(); xr = xl + client->width(); yb = yt + client->height(); // if not enough room above or under the current tested client // determine the first non-overlapped x position if ((y < yb) && (yt < ch + y)) { if ((xr > x) && (possible > xr)) possible = xr; basket = xl - cw; if ((basket > x) && (possible > basket)) possible = basket; } } x = possible; } // ... else ==> not enough x dimension (overlap was wrong on horizontal) else if (overlap == w_wrong) { x = maxRect.left(); possible = maxRect.bottom(); if (possible - ch > y) possible -= ch; //test the position of each window on the desk ToplevelList::ConstIterator l; for (l = workspace()->stackingOrder().constBegin(); l != workspace()->stackingOrder().constEnd() ; ++l) { AbstractClient *client = qobject_cast(*l); if (isIrrelevant(client, c, desktop)) { continue; } xl = client->x(); yt = client->y(); xr = xl + client->width(); yb = yt + client->height(); // if not enough room to the left or right of the current tested client // determine the first non-overlapped y position if ((yb > y) && (possible > yb)) possible = yb; basket = yt - ch; if ((basket > y) && (possible > basket)) possible = basket; } y = possible; } } while ((overlap != none) && (overlap != h_wrong) && (y < maxRect.bottom())); if (ch >= maxRect.height()) y_optimal = maxRect.top(); // place the window c->move(x_optimal, y_optimal); } void Placement::reinitCascading(int desktop) { // desktop == 0 - reinit all if (desktop == 0) { cci.clear(); for (uint i = 0; i < VirtualDesktopManager::self()->count(); ++i) { DesktopCascadingInfo inf; inf.pos = QPoint(-1, -1); inf.col = 0; inf.row = 0; cci.append(inf); } } else { cci[desktop - 1].pos = QPoint(-1, -1); cci[desktop - 1].col = cci[desktop - 1].row = 0; } } QPoint Workspace::cascadeOffset(const AbstractClient *c) const { QRect area = clientArea(PlacementArea, c->geometry().center(), c->desktop()); return QPoint(area.width()/48, area.height()/48); } /** * Place windows in a cascading order, remembering positions for each desktop - **/ + */ void Placement::placeCascaded(AbstractClient* c, QRect& area, Policy nextPlacement) { if (!c->size().isValid()) { return; } /* cascadePlacement by Cristian Tibirna (tibirna@kde.org) (30Jan98) */ // work coords int xp, yp; //CT how do I get from the 'Client' class the size that NW squarish "handle" const QPoint delta = workspace()->cascadeOffset(c); const int dn = c->desktop() == 0 || c->isOnAllDesktops() ? (VirtualDesktopManager::self()->current() - 1) : (c->desktop() - 1); // get the maximum allowed windows space and desk's origin QRect maxRect = checkArea(c, area); // initialize often used vars: width and height of c; we gain speed const int ch = c->height(); const int cw = c->width(); const int X = maxRect.left(); const int Y = maxRect.top(); const int H = maxRect.height(); const int W = maxRect.width(); if (nextPlacement == Unknown) nextPlacement = Smart; //initialize if needed if (cci[dn].pos.x() < 0 || cci[dn].pos.x() < X || cci[dn].pos.y() < Y) { cci[dn].pos = QPoint(X, Y); cci[dn].col = cci[dn].row = 0; } xp = cci[dn].pos.x(); yp = cci[dn].pos.y(); //here to touch in case people vote for resize on placement if ((yp + ch) > H) yp = Y; if ((xp + cw) > W) { if (!yp) { place(c, area, nextPlacement); return; } else xp = X; } //if this isn't the first window if (cci[dn].pos.x() != X && cci[dn].pos.y() != Y) { /* The following statements cause an internal compiler error with * egcs-2.91.66 on SuSE Linux 6.3. The equivalent forms compile fine. * 22-Dec-1999 CS * * if (xp != X && yp == Y) xp = delta.x() * (++(cci[dn].col)); * if (yp != Y && xp == X) yp = delta.y() * (++(cci[dn].row)); */ if (xp != X && yp == Y) { ++(cci[dn].col); xp = delta.x() * cci[dn].col; } if (yp != Y && xp == X) { ++(cci[dn].row); yp = delta.y() * cci[dn].row; } // last resort: if still doesn't fit, smart place it if (((xp + cw) > W - X) || ((yp + ch) > H - Y)) { place(c, area, nextPlacement); return; } } // place the window c->move(QPoint(xp, yp)); // new position cci[dn].pos = QPoint(xp + delta.x(), yp + delta.y()); } /** * Place windows centered, on top of all others - **/ + */ void Placement::placeCentered(AbstractClient* c, const QRect& area, Policy /*next*/) { // get the maximum allowed windows space and desk's origin const QRect maxRect = checkArea(c, area); const int xp = maxRect.left() + (maxRect.width() - c->width()) / 2; const int yp = maxRect.top() + (maxRect.height() - c->height()) / 2; // place the window c->move(QPoint(xp, yp)); } /** * Place windows in the (0,0) corner, on top of all others - **/ + */ void Placement::placeZeroCornered(AbstractClient* c, const QRect& area, Policy /*next*/) { // get the maximum allowed windows space and desk's origin c->move(checkArea(c, area).topLeft()); } void Placement::placeUtility(AbstractClient* c, QRect& area, Policy /*next*/) { // TODO kwin should try to place utility windows next to their mainwindow, // preferably at the right edge, and going down if there are more of them // if there's not enough place outside the mainwindow, it should prefer // top-right corner // use the default placement for now place(c, area, Default); } void Placement::placeOnScreenDisplay(AbstractClient* c, QRect& area) { // place at lower 1/3 of the screen const int x = area.left() + (area.width() - c->width()) / 2; const int y = area.top() + 2 * (area.height() - c->height()) / 3; c->move(QPoint(x, y)); } void Placement::placeTransient(AbstractClient *c) { const auto parent = c->transientFor(); const QRect screen = Workspace::self()->clientArea(parent->isFullScreen() ? FullScreenArea : PlacementArea, parent); const QRect popupGeometry = c->transientPlacement(screen); c->setGeometry(popupGeometry); // Potentially a client could set no constraint adjustments // and we'll be offscreen. // The spec implies we should place window the offscreen. However, // practically Qt doesn't set any constraint adjustments yet so we can't. // Also kwin generally doesn't let clients do what they want if (!screen.contains(c->geometry())) { c->keepInArea(screen); } } void Placement::placeDialog(AbstractClient* c, QRect& area, Policy nextPlacement) { placeOnMainWindow(c, area, nextPlacement); } void Placement::placeUnderMouse(AbstractClient* c, QRect& area, Policy /*next*/) { area = checkArea(c, area); QRect geom = c->geometry(); geom.moveCenter(Cursor::pos()); c->move(geom.topLeft()); c->keepInArea(area); // make sure it's kept inside workarea } void Placement::placeOnMainWindow(AbstractClient* c, QRect& area, Policy nextPlacement) { if (nextPlacement == Unknown) nextPlacement = Centered; if (nextPlacement == Maximizing) // maximize if needed placeMaximizing(c, area, NoPlacement); area = checkArea(c, area); auto mainwindows = c->mainClients(); AbstractClient* place_on = nullptr; AbstractClient* place_on2 = nullptr; int mains_count = 0; for (auto it = mainwindows.constBegin(); it != mainwindows.constEnd(); ++it) { if (mainwindows.count() > 1 && (*it)->isSpecialWindow()) continue; // don't consider toolbars etc when placing ++mains_count; place_on2 = *it; if ((*it)->isOnCurrentDesktop()) { if (place_on == NULL) place_on = *it; else { // two or more on current desktop -> center // That's the default at least. However, with maximizing placement // policy as the default, the dialog should be either maximized or // made as large as its maximum size and then placed centered. // So the nextPlacement argument allows chaining. In this case, nextPlacement // is Maximizing and it will call placeCentered(). place(c, area, Centered); return; } } } if (place_on == NULL) { // 'mains_count' is used because it doesn't include ignored mainwindows if (mains_count != 1) { place(c, area, Centered); return; } place_on = place_on2; // use the only window filtered together with 'mains_count' } if (place_on->isDesktop()) { place(c, area, Centered); return; } QRect geom = c->geometry(); geom.moveCenter(place_on->geometry().center()); c->move(geom.topLeft()); // get area again, because the mainwindow may be on different xinerama screen area = checkArea(c, QRect()); c->keepInArea(area); // make sure it's kept inside workarea } void Placement::placeMaximizing(AbstractClient* c, QRect& area, Policy nextPlacement) { if (nextPlacement == Unknown) nextPlacement = Smart; if (c->isMaximizable() && c->maxSize().width() >= area.width() && c->maxSize().height() >= area.height()) { if (workspace()->clientArea(MaximizeArea, c) == area) c->maximize(MaximizeFull); else { // if the geometry doesn't match default maximize area (xinerama case?), // it's probably better to use the given area c->setGeometry(area); } } else { c->resizeWithChecks(c->maxSize().boundedTo(area.size())); place(c, area, nextPlacement); } } void Placement::cascadeDesktop() { // TODO XINERAMA this probably is not right for xinerama Workspace *ws = Workspace::self(); const int desktop = VirtualDesktopManager::self()->current(); reinitCascading(desktop); // TODO: make area const once placeFoo methods are fixed to take a const QRect& QRect area = ws->clientArea(PlacementArea, QPoint(0, 0), desktop); foreach (Toplevel *toplevel, ws->stackingOrder()) { auto client = qobject_cast(toplevel); if (!client || (!client->isOnCurrentDesktop()) || (client->isMinimized()) || (client->isOnAllDesktops()) || (!client->isMovable())) continue; placeCascaded(client, area); } } void Placement::unclutterDesktop() { const auto &clients = Workspace::self()->allClientList(); for (int i = clients.size() - 1; i >= 0; i--) { auto client = clients.at(i); if ((!client->isOnCurrentDesktop()) || (client->isMinimized()) || (client->isOnAllDesktops()) || (!client->isMovable())) continue; placeSmart(client, QRect()); } } QRect Placement::checkArea(const AbstractClient* c, const QRect& area) { if (area.isNull()) return workspace()->clientArea(PlacementArea, c->geometry().center(), c->desktop()); return area; } #endif Placement::Policy Placement::policyFromString(const QString& policy, bool no_special) { if (policy == QStringLiteral("NoPlacement")) return NoPlacement; else if (policy == QStringLiteral("Default") && !no_special) return Default; else if (policy == QStringLiteral("Random")) return Random; else if (policy == QStringLiteral("Cascade")) return Cascade; else if (policy == QStringLiteral("Centered")) return Centered; else if (policy == QStringLiteral("ZeroCornered")) return ZeroCornered; else if (policy == QStringLiteral("UnderMouse")) return UnderMouse; else if (policy == QStringLiteral("OnMainWindow") && !no_special) return OnMainWindow; else if (policy == QStringLiteral("Maximizing")) return Maximizing; else return Smart; } const char* Placement::policyToString(Policy policy) { const char* const policies[] = { "NoPlacement", "Default", "XXX should never see", "Random", "Smart", "Cascade", "Centered", "ZeroCornered", "UnderMouse", "OnMainWindow", "Maximizing" }; assert(policy < int(sizeof(policies) / sizeof(policies[ 0 ]))); return policies[ policy ]; } #ifndef KCMRULES // ******************** // Workspace // ******************** void AbstractClient::packTo(int left, int top) { workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event; const int oldScreen = screen(); move(left, top); if (screen() != oldScreen) { workspace()->sendClientToScreen(this, screen()); // checks rule validity if (maximizeMode() != MaximizeRestore) checkWorkspacePosition(); } } /** * Moves active window left until in bumps into another window or workarea edge. - **/ + */ void Workspace::slotWindowPackLeft() { if (active_client && active_client->isMovable()) active_client->packTo(packPositionLeft(active_client, active_client->geometry().left(), true), active_client->y()); } void Workspace::slotWindowPackRight() { if (active_client && active_client->isMovable()) active_client->packTo(packPositionRight(active_client, active_client->geometry().right(), true) - active_client->width() + 1, active_client->y()); } void Workspace::slotWindowPackUp() { if (active_client && active_client->isMovable()) active_client->packTo(active_client->x(), packPositionUp(active_client, active_client->geometry().top(), true)); } void Workspace::slotWindowPackDown() { if (active_client && active_client->isMovable()) active_client->packTo(active_client->x(), packPositionDown(active_client, active_client->geometry().bottom(), true) - active_client->height() + 1); } void Workspace::slotWindowGrowHorizontal() { if (active_client) active_client->growHorizontal(); } void AbstractClient::growHorizontal() { if (!isResizable() || isShade()) return; QRect geom = geometry(); geom.setRight(workspace()->packPositionRight(this, geom.right(), true)); QSize adjsize = adjustedSize(geom.size(), SizemodeFixedW); if (geometry().size() == adjsize && geom.size() != adjsize && resizeIncrements().width() > 1) { // take care of size increments int newright = workspace()->packPositionRight(this, geom.right() + resizeIncrements().width() - 1, true); // check that it hasn't grown outside of the area, due to size increments // TODO this may be wrong? if (workspace()->clientArea(MovementArea, QPoint((x() + newright) / 2, geometry().center().y()), desktop()).right() >= newright) geom.setRight(newright); } geom.setSize(adjustedSize(geom.size(), SizemodeFixedW)); geom.setSize(adjustedSize(geom.size(), SizemodeFixedH)); workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event; setGeometry(geom); } void Workspace::slotWindowShrinkHorizontal() { if (active_client) active_client->shrinkHorizontal(); } void AbstractClient::shrinkHorizontal() { if (!isResizable() || isShade()) return; QRect geom = geometry(); geom.setRight(workspace()->packPositionLeft(this, geom.right(), false)); if (geom.width() <= 1) return; geom.setSize(adjustedSize(geom.size(), SizemodeFixedW)); if (geom.width() > 20) { workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event; setGeometry(geom); } } void Workspace::slotWindowGrowVertical() { if (active_client) active_client->growVertical(); } void AbstractClient::growVertical() { if (!isResizable() || isShade()) return; QRect geom = geometry(); geom.setBottom(workspace()->packPositionDown(this, geom.bottom(), true)); QSize adjsize = adjustedSize(geom.size(), SizemodeFixedH); if (geometry().size() == adjsize && geom.size() != adjsize && resizeIncrements().height() > 1) { // take care of size increments int newbottom = workspace()->packPositionDown(this, geom.bottom() + resizeIncrements().height() - 1, true); // check that it hasn't grown outside of the area, due to size increments if (workspace()->clientArea(MovementArea, QPoint(geometry().center().x(), (y() + newbottom) / 2), desktop()).bottom() >= newbottom) geom.setBottom(newbottom); } geom.setSize(adjustedSize(geom.size(), SizemodeFixedH)); workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event; setGeometry(geom); } void Workspace::slotWindowShrinkVertical() { if (active_client) active_client->shrinkVertical(); } void AbstractClient::shrinkVertical() { if (!isResizable() || isShade()) return; QRect geom = geometry(); geom.setBottom(workspace()->packPositionUp(this, geom.bottom(), false)); if (geom.height() <= 1) return; geom.setSize(adjustedSize(geom.size(), SizemodeFixedH)); if (geom.height() > 20) { workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event; setGeometry(geom); } } void Workspace::quickTileWindow(QuickTileMode mode) { if (!active_client) { return; } active_client->setQuickTileMode(mode, true); } int Workspace::packPositionLeft(const AbstractClient* cl, int oldx, bool left_edge) const { int newx = clientArea(MaximizeArea, cl).left(); if (oldx <= newx) // try another Xinerama screen newx = clientArea(MaximizeArea, QPoint(cl->geometry().left() - 1, cl->geometry().center().y()), cl->desktop()).left(); if (cl->titlebarPosition() != AbstractClient::PositionLeft) { QRect geo = cl->geometry(); int rgt = newx - cl->clientPos().x(); geo.moveRight(rgt); if (screens()->intersecting(geo) < 2) newx = rgt; } if (oldx <= newx) return oldx; const int desktop = cl->desktop() == 0 || cl->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : cl->desktop(); for (auto it = m_allClients.constBegin(), end = m_allClients.constEnd(); it != end; ++it) { if (isIrrelevant(*it, cl, desktop)) continue; int x = left_edge ? (*it)->geometry().right() + 1 : (*it)->geometry().left() - 1; if (x > newx && x < oldx && !(cl->geometry().top() > (*it)->geometry().bottom() // they overlap in Y direction || cl->geometry().bottom() < (*it)->geometry().top())) newx = x; } return newx; } int Workspace::packPositionRight(const AbstractClient* cl, int oldx, bool right_edge) const { int newx = clientArea(MaximizeArea, cl).right(); if (oldx >= newx) // try another Xinerama screen newx = clientArea(MaximizeArea, QPoint(cl->geometry().right() + 1, cl->geometry().center().y()), cl->desktop()).right(); if (cl->titlebarPosition() != AbstractClient::PositionRight) { QRect geo = cl->geometry(); int rgt = newx + cl->width() - (cl->clientSize().width() + cl->clientPos().x()); geo.moveRight(rgt); if (screens()->intersecting(geo) < 2) newx = rgt; } if (oldx >= newx) return oldx; const int desktop = cl->desktop() == 0 || cl->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : cl->desktop(); for (auto it = m_allClients.constBegin(), end = m_allClients.constEnd(); it != end; ++it) { if (isIrrelevant(*it, cl, desktop)) continue; int x = right_edge ? (*it)->geometry().left() - 1 : (*it)->geometry().right() + 1; if (x < newx && x > oldx && !(cl->geometry().top() > (*it)->geometry().bottom() || cl->geometry().bottom() < (*it)->geometry().top())) newx = x; } return newx; } int Workspace::packPositionUp(const AbstractClient* cl, int oldy, bool top_edge) const { int newy = clientArea(MaximizeArea, cl).top(); if (oldy <= newy) // try another Xinerama screen newy = clientArea(MaximizeArea, QPoint(cl->geometry().center().x(), cl->geometry().top() - 1), cl->desktop()).top(); if (cl->titlebarPosition() != AbstractClient::PositionTop) { QRect geo = cl->geometry(); int top = newy - cl->clientPos().y(); geo.moveTop(top); if (screens()->intersecting(geo) < 2) newy = top; } if (oldy <= newy) return oldy; const int desktop = cl->desktop() == 0 || cl->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : cl->desktop(); for (auto it = m_allClients.constBegin(), end = m_allClients.constEnd(); it != end; ++it) { if (isIrrelevant(*it, cl, desktop)) continue; int y = top_edge ? (*it)->geometry().bottom() + 1 : (*it)->geometry().top() - 1; if (y > newy && y < oldy && !(cl->geometry().left() > (*it)->geometry().right() // they overlap in X direction || cl->geometry().right() < (*it)->geometry().left())) newy = y; } return newy; } int Workspace::packPositionDown(const AbstractClient* cl, int oldy, bool bottom_edge) const { int newy = clientArea(MaximizeArea, cl).bottom(); if (oldy >= newy) // try another Xinerama screen newy = clientArea(MaximizeArea, QPoint(cl->geometry().center().x(), cl->geometry().bottom() + 1), cl->desktop()).bottom(); if (cl->titlebarPosition() != AbstractClient::PositionBottom) { QRect geo = cl->geometry(); int btm = newy + cl->height() - (cl->clientSize().height() + cl->clientPos().y()); geo.moveBottom(btm); if (screens()->intersecting(geo) < 2) newy = btm; } if (oldy >= newy) return oldy; const int desktop = cl->desktop() == 0 || cl->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : cl->desktop(); for (auto it = m_allClients.constBegin(), end = m_allClients.constEnd(); it != end; ++it) { if (isIrrelevant(*it, cl, desktop)) continue; int y = bottom_edge ? (*it)->geometry().top() - 1 : (*it)->geometry().bottom() + 1; if (y < newy && y > oldy && !(cl->geometry().left() > (*it)->geometry().right() || cl->geometry().right() < (*it)->geometry().left())) newy = y; } return newy; } #endif } // namespace diff --git a/placement.h b/placement.h index b60450bdc..91b1cf15c 100644 --- a/placement.h +++ b/placement.h @@ -1,112 +1,112 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 1997 to 2002 Cristian Tibirna Copyright (C) 2003 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_PLACEMENT_H #define KWIN_PLACEMENT_H // KWin #include // Qt #include #include #include class QObject; namespace KWin { class AbstractClient; class Client; class KWIN_EXPORT Placement { public: virtual ~Placement(); /** * Placement policies. How workspace decides the way windows get positioned * on the screen. The better the policy, the heavier the resource use. * Normally you don't have to worry. What the WM adds to the startup time * is nil compared to the creation of the window itself in the memory - **/ + */ enum Policy { NoPlacement, // not really a placement Default, // special, means to use the global default Unknown, // special, means the function should use its default Random, Smart, Cascade, Centered, ZeroCornered, UnderMouse, // special OnMainWindow, // special Maximizing }; void place(AbstractClient* c, QRect& area); void placeAtRandom(AbstractClient* c, const QRect& area, Policy next = Unknown); void placeCascaded(AbstractClient* c, QRect& area, Policy next = Unknown); void placeSmart(AbstractClient* c, const QRect& area, Policy next = Unknown); void placeMaximizing(AbstractClient* c, QRect& area, Policy next = Unknown); void placeCentered(AbstractClient* c, const QRect& area, Policy next = Unknown); void placeZeroCornered(AbstractClient* c, const QRect& area, Policy next = Unknown); void placeDialog(AbstractClient* c, QRect& area, Policy next = Unknown); void placeUtility(AbstractClient* c, QRect& area, Policy next = Unknown); void placeOnScreenDisplay(AbstractClient* c, QRect& area); void reinitCascading(int desktop); /** * Cascades all clients on the current desktop - **/ + */ void cascadeDesktop(); /** * Unclutters the current desktop by smart-placing all clients again. - **/ + */ void unclutterDesktop(); static Policy policyFromString(const QString& policy, bool no_special); static const char* policyToString(Policy policy); private: void place(AbstractClient* c, QRect& area, Policy policy, Policy nextPlacement = Unknown); void placeUnderMouse(AbstractClient* c, QRect& area, Policy next = Unknown); void placeOnMainWindow(AbstractClient* c, QRect& area, Policy next = Unknown); void placeTransient(AbstractClient *c); QRect checkArea(const AbstractClient*c, const QRect& area); //CT needed for cascading+ struct DesktopCascadingInfo { QPoint pos; int col; int row; }; QList cci; KWIN_SINGLETON(Placement) }; } // namespace #endif diff --git a/platform.h b/platform.h index 113d21793..1488aeccd 100644 --- a/platform.h +++ b/platform.h @@ -1,563 +1,563 @@ /******************************************************************** 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_PLATFORM_H #define KWIN_PLATFORM_H #include #include #include #include #include "fixqopengl.h" #include "input.h" #include #include #include class QAction; namespace KWayland { namespace Server { class OutputConfigurationInterface; } } namespace KWin { namespace ColorCorrect { class Manager; } class AbstractOutput; class Edge; class Compositor; class OverlayWindow; class OpenGLBackend; class Outline; class OutlineVisual; class QPainterBackend; class Scene; class Screens; class ScreenEdges; class Toplevel; class WaylandCursorTheme; namespace Decoration { class Renderer; class DecoratedClientImpl; } class KWIN_EXPORT Outputs : public QVector { public: Outputs(){}; template Outputs(const QVector &other) { resize(other.size()); std::copy(other.constBegin(), other.constEnd(), begin()); } }; class KWIN_EXPORT Platform : public QObject { Q_OBJECT public: ~Platform() override; virtual void init() = 0; virtual Screens *createScreens(QObject *parent = nullptr); virtual OpenGLBackend *createOpenGLBackend(); virtual QPainterBackend *createQPainterBackend(); /** * Allows the platform to create a platform specific screen edge. * The default implementation creates a Edge. - **/ + */ virtual Edge *createScreenEdge(ScreenEdges *parent); /** * Allows the platform to create a platform specific Cursor. * The default implementation creates an InputRedirectionCursor. - **/ + */ virtual void createPlatformCursor(QObject *parent = nullptr); virtual void warpPointer(const QPointF &globalPos); /** * Whether our Compositing EGL display allows a surface less context * so that a sharing context could be created. - **/ + */ virtual bool supportsQpaContext() const; /** * The EGLDisplay used by the compositing scene. - **/ + */ EGLDisplay sceneEglDisplay() const; void setSceneEglDisplay(EGLDisplay display); /** * The EGLContext used by the compositing scene. - **/ + */ virtual EGLContext sceneEglContext() const { return m_context; } /** * Sets the @p context used by the compositing scene. - **/ + */ void setSceneEglContext(EGLContext context) { m_context = context; } /** * The first (in case of multiple) EGLSurface used by the compositing scene. - **/ + */ EGLSurface sceneEglSurface() const { return m_surface; } /** * Sets the first @p surface used by the compositing scene. * @see sceneEglSurface - **/ + */ void setSceneEglSurface(EGLSurface surface) { m_surface = surface; } /** * The EglConfig used by the compositing scene. - **/ + */ EGLConfig sceneEglConfig() const { return m_eglConfig; } /** * Sets the @p config used by the compositing scene. * @see sceneEglConfig - **/ + */ void setSceneEglConfig(EGLConfig config) { m_eglConfig = config; } /** * Implementing subclasses should provide a size in case the backend represents * a basic screen and uses the BasicScreens. * * Base implementation returns an invalid size. - **/ + */ virtual QSize screenSize() const; /** * Implementing subclasses should provide all geometries in case the backend represents * a basic screen and uses the BasicScreens. * * Base implementation returns one QRect positioned at 0/0 with screenSize() as size. - **/ + */ virtual QVector screenGeometries() const; /** * Implementing subclasses should provide all geometries in case the backend represents * a basic screen and uses the BasicScreens. * * Base implementation returns a screen with a scale of 1. - **/ + */ virtual QVector screenScales() const; /** * Implement this method to receive configuration change requests through KWayland's * OutputManagement interface. * * Base implementation warns that the current backend does not implement this * functionality. - **/ + */ virtual void configurationChangeRequested(KWayland::Server::OutputConfigurationInterface *config); /** * Whether the Platform requires compositing for rendering. * Default implementation returns @c true. If the implementing Platform allows to be used * without compositing (e.g. rendering is done by the windowing system), re-implement this method. - **/ + */ virtual bool requiresCompositing() const; /** * Whether Compositing is possible in the Platform. * Returning @c false in this method makes only sense if requiresCompositing returns @c false. * * The default implementation returns @c true. * @see requiresCompositing - **/ + */ virtual bool compositingPossible() const; /** * Returns a user facing text explaining why compositing is not possible in case * compositingPossible returns @c false. * * The default implementation returns an empty string. * @see compositingPossible - **/ + */ virtual QString compositingNotPossibleReason() const; /** * Whether OpenGL compositing is broken. * The Platform can implement this method if it is able to detect whether OpenGL compositing * broke (e.g. triggered a crash in a previous run). * * Default implementation returns @c false. * @see createOpenGLSafePoint - **/ + */ virtual bool openGLCompositingIsBroken() const; enum class OpenGLSafePoint { PreInit, PostInit, PreFrame, PostFrame, PostLastGuardedFrame }; /** * This method is invoked before and after creating the OpenGL rendering Scene. * An implementing Platform can use it to detect crashes triggered by the OpenGL implementation. * This can be used for openGLCompositingIsBroken. * * The default implementation does nothing. * @see openGLCompositingIsBroken. - **/ + */ virtual void createOpenGLSafePoint(OpenGLSafePoint safePoint); /** * Starts an interactive window selection process. * * Once the user selected a window the @p callback is invoked with the selected Toplevel 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 unless * @p cursorName is provided. The argument @p cursorName is a QByteArray instead of Qt::CursorShape * to support the "pirate" cursor for kill window which is not wrapped by Qt::CursorShape. * * The default implementation forwards to InputRedirection. * * @param callback The function to invoke once the interactive window selection ends * @param cursorName The optional name of the cursor shape to use, default is crosshair - **/ + */ virtual void startInteractiveWindowSelection(std::function callback, const QByteArray &cursorName = QByteArray()); /** * 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. * * The default implementation forwards to InputRedirection. * * @param callback The function to invoke once the interactive position selection ends - **/ + */ virtual void startInteractivePositionSelection(std::function callback); /** * Platform specific preparation for an @p action which is used for KGlobalAccel. * * A platform might need to do preparation for an @p action before * it can be used with KGlobalAccel. * * Code using KGlobalAccel should invoke this method for the @p action * prior to setting up any shortcuts and connections. * * The default implementation does nothing. * * @param action The action which will be used with KGlobalAccel. * @since 5.10 - **/ + */ virtual void setupActionForGlobalAccel(QAction *action); bool usesSoftwareCursor() const { return m_softWareCursor; } QImage softwareCursor() const; QPoint softwareCursorHotspot() const; void markCursorAsRendered(); /** * Returns a PlatformCursorImage. By default this is created by softwareCursor and * softwareCursorHotspot. An implementing subclass can use this to provide a better * suited PlatformCursorImage. * * @see softwareCursor * @see softwareCursorHotspot * @since 5.9 - **/ + */ virtual PlatformCursorImage cursorImage() const; /** * The Platform cursor image should be hidden. * @see showCursor * @see doHideCursor * @see isCursorHidden * @since 5.9 - **/ + */ void hideCursor(); /** * The Platform cursor image should be shown again. * @see hideCursor * @see doShowCursor * @see isCursorHidden * @since 5.9 - **/ + */ void showCursor(); /** * Whether the cursor is currently hidden. * @see showCursor * @see hideCursor * @since 5.9 - **/ + */ bool isCursorHidden() const { return m_hideCursorCounter > 0; } bool handlesOutputs() const { return m_handlesOutputs; } bool isReady() const { return m_ready; } void setInitialWindowSize(const QSize &size) { m_initialWindowSize = size; } void setDeviceIdentifier(const QByteArray &identifier) { m_deviceIdentifier = identifier; } bool supportsPointerWarping() const { return m_pointerWarping; } bool areOutputsEnabled() const { return m_outputsEnabled; } void setOutputsEnabled(bool enabled) { m_outputsEnabled = enabled; } int initialOutputCount() const { return m_initialOutputCount; } void setInitialOutputCount(int count) { m_initialOutputCount = count; } qreal initialOutputScale() const { return m_initialOutputScale; } void setInitialOutputScale(qreal scale) { m_initialOutputScale = scale; } /** * Creates the OverlayWindow required for X11 based compositors. * Default implementation returns @c nullptr. - **/ + */ virtual OverlayWindow *createOverlayWindow(); /** * Allows a platform to update the X11 timestamp. * Mostly for the X11 standalone platform to interact with QX11Info. * * Default implementation does nothing. This means code relying on the X timestamp being up to date, * might not be working. E.g. synced X11 window resizing - **/ + */ virtual void updateXTime(); /** * Creates the OutlineVisual for the given @p outline. * Default implementation creates an OutlineVisual suited for composited usage. - **/ + */ virtual OutlineVisual *createOutline(Outline *outline); /** * Creates the Decoration::Renderer for the given @p client. * * The default implementation creates a Renderer suited for the Compositor, @c nullptr if there is no Compositor. - **/ + */ virtual Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *client); /** * Platform specific way to invert the screen. * Default implementation invokes the invert effect - **/ + */ virtual void invertScreen(); /** * Default implementation creates an EffectsHandlerImp; - **/ + */ virtual void createEffectsHandler(Compositor *compositor, Scene *scene); /** * The CompositingTypes supported by the Platform. * The first item should be the most preferred one. * @since 5.11 - **/ + */ virtual QVector supportedCompositors() const = 0; /** * Whether gamma control is supported by the backend. * @since 5.12 - **/ + */ bool supportsGammaControl() const { return m_supportsGammaControl; } ColorCorrect::Manager *colorCorrectManager() { return m_colorCorrect; } // outputs with connections (org_kde_kwin_outputdevice) virtual Outputs outputs() const { return Outputs(); } // actively compositing outputs (wl_output) virtual Outputs enabledOutputs() const { return Outputs(); } /** * A string of information to include in kwin debug output * It should not be translated. * * The base implementation prints the name. * @since 5.12 - **/ + */ virtual QString supportInformation() const; /** * The compositor plugin which got selected from @link{supportedCompositors}. * Prior to selecting a compositor this returns @c NoCompositing. * * This method allows the platforms to limit the offerings in @link{supportedCompositors} * in case they do not support runtime compositor switching - **/ + */ CompositingType selectedCompositor() const { return m_selectedCompositor; } /** * Used by Compositor to set the used compositor. - **/ + */ void setSelectedCompositor(CompositingType type) { m_selectedCompositor = type; } public Q_SLOTS: void pointerMotion(const QPointF &position, quint32 time); void pointerButtonPressed(quint32 button, quint32 time); void pointerButtonReleased(quint32 button, quint32 time); void pointerAxisHorizontal(qreal delta, quint32 time, qint32 discreteDelta = 0, InputRedirection::PointerAxisSource source = InputRedirection::PointerAxisSourceUnknown); void pointerAxisVertical(qreal delta, quint32 time, qint32 discreteDelta = 0, InputRedirection::PointerAxisSource source = InputRedirection::PointerAxisSourceUnknown); void keyboardKeyPressed(quint32 key, quint32 time); void keyboardKeyReleased(quint32 key, quint32 time); void keyboardModifiers(uint32_t modsDepressed, uint32_t modsLatched, uint32_t modsLocked, uint32_t group); void keymapChange(int fd, uint32_t size); void touchDown(qint32 id, const QPointF &pos, quint32 time); void touchUp(qint32 id, quint32 time); void touchMotion(qint32 id, const QPointF &pos, quint32 time); void touchCancel(); void touchFrame(); void processSwipeGestureBegin(int fingerCount, quint32 time); void processSwipeGestureUpdate(const QSizeF &delta, quint32 time); void processSwipeGestureEnd(quint32 time); void processSwipeGestureCancelled(quint32 time); void processPinchGestureBegin(int fingerCount, quint32 time); void processPinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time); void processPinchGestureEnd(quint32 time); void processPinchGestureCancelled(quint32 time); Q_SIGNALS: void screensQueried(); void initFailed(); void cursorChanged(); void readyChanged(bool); /** * Emitted by backends using a one screen (nested window) approach and when the size of that changes. - **/ + */ void screenSizeChanged(); protected: explicit Platform(QObject *parent = nullptr); void setSoftWareCursor(bool set); void handleOutputs() { m_handlesOutputs = true; } void repaint(const QRect &rect); void setReady(bool ready); QSize initialWindowSize() const { return m_initialWindowSize; } QByteArray deviceIdentifier() const { return m_deviceIdentifier; } void setSupportsPointerWarping(bool set) { m_pointerWarping = set; } void setSupportsGammaControl(bool set) { m_supportsGammaControl = set; } /** * Actual platform specific way to hide the cursor. * Sub-classes need to implement if they support hiding the cursor. * * This method is invoked by hideCursor if the cursor needs to be hidden. * The default implementation does nothing. * * @see doShowCursor * @see hideCursor * @see showCursor - **/ + */ virtual void doHideCursor(); /** * Actual platform specific way to show the cursor. * Sub-classes need to implement if they support showing the cursor. * * This method is invoked by showCursor if the cursor needs to be shown again. * * @see doShowCursor * @see hideCursor * @see showCursor - **/ + */ virtual void doShowCursor(); private: void triggerCursorRepaint(); bool m_softWareCursor = false; struct { QRect lastRenderedGeometry; } m_cursor; bool m_handlesOutputs = false; bool m_ready = false; QSize m_initialWindowSize; QByteArray m_deviceIdentifier; bool m_pointerWarping = false; bool m_outputsEnabled = true; int m_initialOutputCount = 1; qreal m_initialOutputScale = 1; EGLDisplay m_eglDisplay; EGLConfig m_eglConfig = nullptr; EGLContext m_context = EGL_NO_CONTEXT; EGLSurface m_surface = EGL_NO_SURFACE; int m_hideCursorCounter = 0; ColorCorrect::Manager *m_colorCorrect = nullptr; bool m_supportsGammaControl = false; CompositingType m_selectedCompositor = NoCompositing; }; } Q_DECLARE_INTERFACE(KWin::Platform, "org.kde.kwin.Platform") #endif diff --git a/platformsupport/scenes/opengl/backend.h b/platformsupport/scenes/opengl/backend.h index f4fa9269d..b2a7bc15e 100644 --- a/platformsupport/scenes/opengl/backend.h +++ b/platformsupport/scenes/opengl/backend.h @@ -1,325 +1,325 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 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_SCENE_OPENGL_BACKEND_H #define KWIN_SCENE_OPENGL_BACKEND_H #include #include #include namespace KWin { class OpenGLBackend; class OverlayWindow; class SceneOpenGL; class SceneOpenGLTexture; class SceneOpenGLTexturePrivate; class WindowPixmap; /** * @brief The OpenGLBackend creates and holds the OpenGL context and is responsible for Texture from Pixmap. * * The OpenGLBackend is an abstract base class used by the SceneOpenGL to abstract away the differences * between various OpenGL windowing systems such as GLX and EGL. * * A concrete implementation has to create and release the OpenGL context in a way so that the * SceneOpenGL does not have to care about it. * * In addition a major task for this class is to generate the SceneOpenGLTexturePrivate which is * able to perform the texture from pixmap operation in the given backend. * * @author Martin Gräßlin - **/ + */ class KWIN_EXPORT OpenGLBackend { public: OpenGLBackend(); virtual ~OpenGLBackend(); virtual void init() = 0; /** * @return Time passes since start of rendering current frame. * @see startRenderTimer - **/ + */ qint64 renderTime() { return m_renderTimer.nsecsElapsed(); } virtual void screenGeometryChanged(const QSize &size) = 0; virtual SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) = 0; /** * @brief Backend specific code to prepare the rendering of a frame including flushing the * previously rendered frame to the screen if the backend works this way. * * @return A region that if not empty will be repainted in addition to the damaged region - **/ + */ virtual QRegion prepareRenderingFrame() = 0; /** * @brief Backend specific code to handle the end of rendering a frame. * * @param renderedRegion The possibly larger region that has been rendered * @param damagedRegion The damaged region that should be posted - **/ + */ virtual void endRenderingFrame(const QRegion &damage, const QRegion &damagedRegion) = 0; virtual void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion); virtual bool makeCurrent() = 0; virtual void doneCurrent() = 0; virtual bool usesOverlayWindow() const = 0; /** * Whether the rendering needs to be split per screen. * Default implementation returns @c false. - **/ + */ virtual bool perScreenRendering() const; virtual QRegion prepareRenderingForScreen(int screenId); /** * @brief Compositor is going into idle mode, flushes any pending paints. - **/ + */ void idle(); /** * @return bool Whether the scene needs to flush a frame. - **/ + */ bool hasPendingFlush() const { return !m_lastDamage.isEmpty(); } /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* - **/ + */ virtual OverlayWindow *overlayWindow(); /** * @brief Whether the creation of the Backend failed. * * The SceneOpenGL should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneOpenGL should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. - **/ + */ bool isFailed() const { return m_failed; } /** * @brief Whether the Backend provides VSync. * * Currently only the GLX backend can provide VSync. * * @return bool @c true if VSync support is available, @c false otherwise - **/ + */ bool syncsToVBlank() const { return m_syncsToVBlank; } /** * @brief Whether VSync blocks execution until the screen is in the retrace * * Case for waitVideoSync and non triple buffering buffer swaps * - **/ + */ bool blocksForRetrace() const { return m_blocksForRetrace; } /** * @brief Whether the backend uses direct rendering. * * Some OpenGLScene modes require direct rendering. E.g. the OpenGL 2 should not be used * if direct rendering is not supported by the Scene. * * @return bool @c true if the GL context is direct, @c false if indirect - **/ + */ bool isDirectRendering() const { return m_directRendering; } bool supportsBufferAge() const { return m_haveBufferAge; } /** * @returns whether the context is surfaceless - **/ + */ bool isSurfaceLessContext() const { return m_surfaceLessContext; } /** * Returns the damage that has accumulated since a buffer of the given age was presented. - **/ + */ QRegion accumulatedDamageHistory(int bufferAge) const; /** * Saves the given region to damage history. - **/ + */ void addToDamageHistory(const QRegion ®ion); /** * The backend specific extensions (e.g. EGL/GLX extensions). * * Not the OpenGL (ES) extension! - **/ + */ QList extensions() const { return m_extensions; } /** * @returns whether the backend specific extensions contains @p extension. - **/ + */ bool hasExtension(const QByteArray &extension) const { return m_extensions.contains(extension); } /** * Copy a region of pixels from the current read to the current draw buffer - **/ + */ void copyPixels(const QRegion ®ion); protected: /** * @brief Backend specific flushing of frame to screen. - **/ + */ virtual void present() = 0; /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. - **/ + */ void setFailed(const QString &reason); /** * @brief Sets whether the backend provides VSync. * * Should be called by the concrete subclass once it is determined whether VSync is supported. * If the subclass does not call this method, the backend defaults to @c false. * @param enabled @c true if VSync support available, @c false otherwise. - **/ + */ void setSyncsToVBlank(bool enabled) { m_syncsToVBlank = enabled; } /** * @brief Sets whether the VSync iplementation blocks * * Should be called by the concrete subclass once it is determined how VSync works. * If the subclass does not call this method, the backend defaults to @c false. * @param enabled @c true if VSync blocks, @c false otherwise. - **/ + */ void setBlocksForRetrace(bool enabled) { m_blocksForRetrace = enabled; } /** * @brief Sets whether the OpenGL context is direct. * * Should be called by the concrete subclass once it is determined whether the OpenGL context is * direct or indirect. * If the subclass does not call this method, the backend defaults to @c false. * * @param direct @c true if the OpenGL context is direct, @c false if indirect - **/ + */ void setIsDirectRendering(bool direct) { m_directRendering = direct; } void setSupportsBufferAge(bool value) { m_haveBufferAge = value; } /** * @return const QRegion& Damage of previously rendered frame - **/ + */ const QRegion &lastDamage() const { return m_lastDamage; } void setLastDamage(const QRegion &damage) { m_lastDamage = damage; } /** * @brief Starts the timer for how long it takes to render the frame. * * @see renderTime - **/ + */ void startRenderTimer() { m_renderTimer.start(); } /** * @param set whether the context is surface less - **/ + */ void setSurfaceLessContext(bool set) { m_surfaceLessContext = set; } /** * Sets the platform-specific @p extensions. * * These are the EGL/GLX extensions, not the OpenGL extensions - **/ + */ void setExtensions(const QList &extensions) { m_extensions = extensions; } private: /** * @brief Whether VSync is available and used, defaults to @c false. - **/ + */ bool m_syncsToVBlank; /** * @brief Whether present() will block execution until the next vertical retrace @c false. - **/ + */ bool m_blocksForRetrace; /** * @brief Whether direct rendering is used, defaults to @c false. - **/ + */ bool m_directRendering; /** * @brief Whether the backend supports GLX_EXT_buffer_age / EGL_EXT_buffer_age. - **/ + */ bool m_haveBufferAge; /** * @brief Whether the initialization failed, of course default to @c false. - **/ + */ bool m_failed; /** * @brief Damaged region of previously rendered frame. - **/ + */ QRegion m_lastDamage; /** * @brief The damage history for the past 10 frames. - **/ + */ QList m_damageHistory; /** * @brief Timer to measure how long a frame renders. - **/ + */ QElapsedTimer m_renderTimer; bool m_surfaceLessContext = false; QList m_extensions; }; } #endif diff --git a/platformsupport/scenes/opengl/swap_profiler.h b/platformsupport/scenes/opengl/swap_profiler.h index 8415b0a8d..cbc4d1636 100644 --- a/platformsupport/scenes/opengl/swap_profiler.h +++ b/platformsupport/scenes/opengl/swap_profiler.h @@ -1,53 +1,53 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 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_SCENE_OPENGL_SWAP_PROFILER_H #define KWIN_SCENE_OPENGL_SWAP_PROFILER_H #include #include namespace KWin { /** * @short Profiler to detect whether we have triple buffering * The strategy is to start setBlocksForRetrace(false) but assume blocking and have the system prove that assumption wrong - **/ + */ class KWIN_EXPORT SwapProfiler { public: SwapProfiler(); void init(); void begin(); /** * @return char being 'd' for double, 't' for triple (or more - but non-blocking) buffering and * 0 (NOT '0') otherwise, so you can act on "if (char result = SwapProfiler::end()) { fooBar(); } - **/ + */ char end(); private: QElapsedTimer m_timer; qint64 m_time; int m_counter; }; } #endif diff --git a/platformsupport/scenes/qpainter/backend.h b/platformsupport/scenes/qpainter/backend.h index 54ab4a753..819721170 100644 --- a/platformsupport/scenes/qpainter/backend.h +++ b/platformsupport/scenes/qpainter/backend.h @@ -1,108 +1,108 @@ /******************************************************************** 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_SCENE_QPAINTER_BACKEND_H #define KWIN_SCENE_QPAINTER_BACKEND_H class QImage; class QRegion; class QSize; class QString; namespace KWin { class OverlayWindow; class QPainterBackend { public: virtual ~QPainterBackend(); virtual void present(int mask, const QRegion &damage) = 0; /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* - **/ + */ virtual OverlayWindow *overlayWindow(); virtual bool usesOverlayWindow() const = 0; virtual void prepareRenderingFrame() = 0; /** * @brief Shows the Overlay Window * * Default implementation does nothing. - **/ + */ virtual void showOverlay(); /** * @brief React on screen geometry changes. * * Default implementation does nothing. Override if specific functionality is required. * * @param size The new screen size - **/ + */ virtual void screenGeometryChanged(const QSize &size); /** * @brief Whether the creation of the Backend failed. * * The SceneQPainter should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneQPainter should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. - **/ + */ bool isFailed() const { return m_failed; } virtual QImage *buffer() = 0; /** * Overload for the case that there is a different buffer per screen. * Default implementation just calls buffer. * @param screenId The id of the screen as used in Screens * @todo Get a better identifier for screen then a counter variable - **/ + */ virtual QImage *bufferForScreen(int screenId); virtual bool needsFullRepaint() const = 0; /** * Whether the rendering needs to be split per screen. * Default implementation returns @c false. - **/ + */ virtual bool perScreenRendering() const; protected: QPainterBackend(); /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. - **/ + */ void setFailed(const QString &reason); private: bool m_failed; }; } // KWin #endif diff --git a/plugins/kdecorations/aurorae/src/aurorae.cpp b/plugins/kdecorations/aurorae/src/aurorae.cpp index 5abe48268..9407d64e4 100644 --- a/plugins/kdecorations/aurorae/src/aurorae.cpp +++ b/plugins/kdecorations/aurorae/src/aurorae.cpp @@ -1,799 +1,799 @@ /******************************************************************** Copyright (C) 2009, 2010, 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 . *********************************************************************/ #include "aurorae.h" #include "auroraetheme.h" #include "config-kwin.h" // qml imports #include "decorationoptions.h" // KDecoration2 #include #include #include // KDE #include #include #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(AuroraeDecoFactory, "aurorae.json", registerPlugin(); registerPlugin(QStringLiteral("themes")); registerPlugin(QStringLiteral("kcmodule")); ) namespace Aurorae { class Helper { public: void ref(); void unref(); QQmlComponent *component(const QString &theme); QQmlContext *rootContext(); QQmlComponent *svgComponent() { return m_svgComponent.data(); } static Helper &instance(); private: Helper() = default; void init(); QQmlComponent *loadComponent(const QString &themeName); int m_refCount = 0; QScopedPointer m_engine; QHash m_components; QScopedPointer m_svgComponent; }; Helper &Helper::instance() { static Helper s_helper; return s_helper; } void Helper::ref() { m_refCount++; if (m_refCount == 1) { m_engine.reset(new QQmlEngine); init(); } } void Helper::unref() { m_refCount--; if (m_refCount == 0) { // cleanup m_svgComponent.reset(); m_engine.reset(); m_components.clear(); } } static const QString s_defaultTheme = QStringLiteral("kwin4_decoration_qml_plastik"); static const QString s_qmlPackageFolder = QStringLiteral(KWIN_NAME "/decorations/"); /* * KDecoration2::BorderSize doesn't map to the indices used for the Aurorae SVG Button Sizes. * BorderSize defines None and NoSideBorder as index 0 and 1. These do not make sense for Button * Size, thus we need to perform a mapping between the enum value and the config value. - **/ + */ static const int s_indexMapper = 2; QQmlComponent *Helper::component(const QString &themeName) { // maybe it's an SVG theme? if (themeName.startsWith(QLatin1Literal("__aurorae__svg__"))) { if (m_svgComponent.isNull()) { /* use logic from KDeclarative::setupBindings(): "addImportPath adds the path at the beginning, so to honour user's paths we need to traverse the list in reverse order" */ QStringListIterator paths(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("module/imports"), QStandardPaths::LocateDirectory)); paths.toBack(); while (paths.hasPrevious()) { m_engine->addImportPath(paths.previous()); } m_svgComponent.reset(new QQmlComponent(m_engine.data())); m_svgComponent->loadUrl(QUrl(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kwin/aurorae/aurorae.qml")))); } // verify that the theme exists if (!QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("aurorae/themes/%1/%1rc").arg(themeName.mid(16))).isEmpty()) { return m_svgComponent.data(); } } // try finding the QML package auto it = m_components.constFind(themeName); if (it != m_components.constEnd()) { return it.value(); } auto component = loadComponent(themeName); if (component) { m_components.insert(themeName, component); return component; } // try loading default component if (themeName != s_defaultTheme) { return loadComponent(s_defaultTheme); } return nullptr; } QQmlComponent *Helper::loadComponent(const QString &themeName) { qCDebug(AURORAE) << "Trying to load QML Decoration " << themeName; const QString internalname = themeName.toLower(); const auto offers = KPackage::PackageLoader::self()->findPackages(QStringLiteral("KWin/Decoration"), s_qmlPackageFolder, [internalname] (const KPluginMetaData &data) { return data.pluginId().compare(internalname, Qt::CaseInsensitive) == 0; } ); if (offers.isEmpty()) { qCCritical(AURORAE) << "Couldn't find QML Decoration " << themeName; // TODO: what to do in error case? return nullptr; } const KPluginMetaData &service = offers.first(); const QString pluginName = service.pluginId(); const QString scriptName = service.value(QStringLiteral("X-Plasma-MainScript")); const QString file = QStandardPaths::locate(QStandardPaths::GenericDataLocation, s_qmlPackageFolder + pluginName + QLatin1String("/contents/") + scriptName); if (file.isNull()) { qCDebug(AURORAE) << "Could not find script file for " << pluginName; // TODO: what to do in error case? return nullptr; } // setup the QML engine /* use logic from KDeclarative::setupBindings(): "addImportPath adds the path at the beginning, so to honour user's paths we need to traverse the list in reverse order" */ QStringListIterator paths(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("module/imports"), QStandardPaths::LocateDirectory)); paths.toBack(); while (paths.hasPrevious()) { m_engine->addImportPath(paths.previous()); } QQmlComponent *component = new QQmlComponent(m_engine.data(), m_engine.data()); component->loadUrl(QUrl::fromLocalFile(file)); return component; } QQmlContext *Helper::rootContext() { return m_engine->rootContext(); } void Helper::init() { // we need to first load our decoration plugin // once it's loaded we can provide the Borders and access them from C++ side // so let's try to locate our plugin: QString pluginPath; for (const QString &path : m_engine->importPathList()) { QDirIterator it(path, QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo fileInfo = it.fileInfo(); if (!fileInfo.isFile()) { continue; } if (!fileInfo.path().endsWith(QLatin1String("/org/kde/kwin/decoration"))) { continue; } if (fileInfo.fileName() == QLatin1String("libdecorationplugin.so")) { pluginPath = fileInfo.absoluteFilePath(); break; } } if (!pluginPath.isEmpty()) { break; } } m_engine->importPlugin(pluginPath, "org.kde.kwin.decoration", nullptr); qmlRegisterType("org.kde.kwin.decoration", 0, 1, "Borders"); qmlRegisterType(); qmlRegisterType(); qRegisterMetaType(); } static QString findTheme(const QVariantList &args) { if (args.isEmpty()) { return QString(); } const auto map = args.first().toMap(); auto it = map.constFind(QStringLiteral("theme")); if (it == map.constEnd()) { return QString(); } return it.value().toString(); } Decoration::Decoration(QObject *parent, const QVariantList &args) : KDecoration2::Decoration(parent, args) , m_item(nullptr) , m_borders(nullptr) , m_maximizedBorders(nullptr) , m_extendedBorders(nullptr) , m_padding(nullptr) , m_themeName(s_defaultTheme) { m_themeName = findTheme(args); Helper::instance().ref(); } Decoration::~Decoration() { Helper::instance().unref(); if (m_context) { m_context->makeCurrent(m_offscreenSurface.data()); delete m_renderControl; delete m_view.data(); m_fbo.reset(); delete m_item; m_context->doneCurrent(); } } void Decoration::init() { KDecoration2::Decoration::init(); auto s = settings(); connect(s.data(), &KDecoration2::DecorationSettings::reconfigured, this, &Decoration::configChanged); QQmlContext *context = new QQmlContext(Helper::instance().rootContext(), this); context->setContextProperty(QStringLiteral("decoration"), this); context->setContextProperty(QStringLiteral("decorationSettings"), s.data()); auto component = Helper::instance().component(m_themeName); if (!component) { return; } if (component == Helper::instance().svgComponent()) { // load SVG theme const QString themeName = m_themeName.mid(16); KConfig config(QLatin1String("aurorae/themes/") + themeName + QLatin1Char('/') + themeName + QLatin1String("rc"), KConfig::FullConfig, QStandardPaths::GenericDataLocation); AuroraeTheme *theme = new AuroraeTheme(this); theme->loadTheme(themeName, config); theme->setBorderSize(s->borderSize()); connect(s.data(), &KDecoration2::DecorationSettings::borderSizeChanged, theme, &AuroraeTheme::setBorderSize); auto readButtonSize = [this, theme] { const KSharedConfigPtr conf = KSharedConfig::openConfig(QStringLiteral("auroraerc")); const KConfigGroup themeGroup(conf, m_themeName.mid(16)); theme->setButtonSize((KDecoration2::BorderSize)(themeGroup.readEntry("ButtonSize", int(KDecoration2::BorderSize::Normal) - s_indexMapper) + s_indexMapper)); }; connect(this, &Decoration::configChanged, theme, readButtonSize); readButtonSize(); // m_theme->setTabDragMimeType(tabDragMimeType()); context->setContextProperty(QStringLiteral("auroraeTheme"), theme); } m_item = qobject_cast< QQuickItem* >(component->create(context)); if (!m_item) { if (component->isError()) { const auto errors = component->errors(); for (const auto &error: errors) { qCWarning(AURORAE) << error; } } return; } m_item->setParent(this); QVariant visualParent = property("visualParent"); if (visualParent.isValid()) { m_item->setParentItem(visualParent.value()); visualParent.value()->setProperty("drawBackground", false); } else { m_renderControl = new QQuickRenderControl(this); m_view = new QQuickWindow(m_renderControl); bool usingGL = m_view->rendererInterface()->graphicsApi() == QSGRendererInterface::OpenGL; m_view->setColor(Qt::transparent); m_view->setFlags(Qt::FramelessWindowHint); if (usingGL) { // first create the context QSurfaceFormat format; format.setDepthBufferSize(16); format.setStencilBufferSize(8); m_context.reset(new QOpenGLContext); m_context->setFormat(format); m_context->create(); // and the offscreen surface m_offscreenSurface.reset(new QOffscreenSurface); m_offscreenSurface->setFormat(m_context->format()); m_offscreenSurface->create(); } // delay rendering a little bit for better performance m_updateTimer.reset(new QTimer); m_updateTimer->setSingleShot(true); m_updateTimer->setInterval(5); connect(m_updateTimer.data(), &QTimer::timeout, this, [this, usingGL] { if (usingGL) { if (!m_context->makeCurrent(m_offscreenSurface.data())) { return; } if (m_fbo.isNull() || m_fbo->size() != m_view->size()) { m_fbo.reset(new QOpenGLFramebufferObject(m_view->size(), QOpenGLFramebufferObject::CombinedDepthStencil)); if (!m_fbo->isValid()) { qCWarning(AURORAE) << "Creating FBO as render target failed"; m_fbo.reset(); return; } } m_view->setRenderTarget(m_fbo.data()); m_view->resetOpenGLState(); } m_buffer = m_renderControl->grab(); m_contentRect = QRect(QPoint(0, 0), m_buffer.size()); if (m_padding && (m_padding->left() > 0 || m_padding->top() > 0 || m_padding->right() > 0 || m_padding->bottom() > 0) && !client().data()->isMaximized()) { m_contentRect = m_contentRect.adjusted(m_padding->left(), m_padding->top(), -m_padding->right(), -m_padding->bottom()); } updateShadow(); QOpenGLFramebufferObject::bindDefault(); update(); } ); auto requestUpdate = [this] { if (m_updateTimer->isActive()) { return; } m_updateTimer->start(); }; connect(m_renderControl, &QQuickRenderControl::renderRequested, this, requestUpdate); connect(m_renderControl, &QQuickRenderControl::sceneChanged, this, requestUpdate); m_item->setParentItem(m_view->contentItem()); if (usingGL) { m_context->makeCurrent(m_offscreenSurface.data()); m_renderControl->initialize(m_context.data()); m_context->doneCurrent(); } } setupBorders(m_item); // TODO: Is there a more efficient way to react to border changes? auto trackBorders = [this](KWin::Borders *borders) { if (!borders) { return; } connect(borders, &KWin::Borders::leftChanged, this, &Decoration::updateBorders); connect(borders, &KWin::Borders::rightChanged, this, &Decoration::updateBorders); connect(borders, &KWin::Borders::topChanged, this, &Decoration::updateBorders); connect(borders, &KWin::Borders::bottomChanged, this, &Decoration::updateBorders); }; trackBorders(m_borders); trackBorders(m_maximizedBorders); if (m_extendedBorders) { auto updateExtendedBorders = [this] { setResizeOnlyBorders(*m_extendedBorders); }; updateExtendedBorders(); connect(m_extendedBorders, &KWin::Borders::leftChanged, this, updateExtendedBorders); connect(m_extendedBorders, &KWin::Borders::rightChanged, this, updateExtendedBorders); connect(m_extendedBorders, &KWin::Borders::topChanged, this, updateExtendedBorders); connect(m_extendedBorders, &KWin::Borders::bottomChanged, this, updateExtendedBorders); } connect(client().data(), &KDecoration2::DecoratedClient::maximizedChanged, this, &Decoration::updateBorders, Qt::QueuedConnection); connect(client().data(), &KDecoration2::DecoratedClient::shadedChanged, this, &Decoration::updateBorders); updateBorders(); if (!m_view.isNull()) { auto resizeWindow = [this] { QRect rect(QPoint(0, 0), size()); if (m_padding && !client().data()->isMaximized()) { rect = rect.adjusted(-m_padding->left(), -m_padding->top(), m_padding->right(), m_padding->bottom()); } m_view->setGeometry(rect); }; connect(this, &Decoration::bordersChanged, this, resizeWindow); connect(client().data(), &KDecoration2::DecoratedClient::widthChanged, this, resizeWindow); connect(client().data(), &KDecoration2::DecoratedClient::heightChanged, this, resizeWindow); connect(client().data(), &KDecoration2::DecoratedClient::maximizedChanged, this, resizeWindow); connect(client().data(), &KDecoration2::DecoratedClient::shadedChanged, this, resizeWindow); resizeWindow(); } else { // create a dummy shadow for the configuration interface if (m_padding) { auto s = QSharedPointer::create(); s->setPadding(*m_padding); s->setInnerShadowRect(QRect(m_padding->left(), m_padding->top(), 1, 1)); setShadow(s); } } } QVariant Decoration::readConfig(const QString &key, const QVariant &defaultValue) { KSharedConfigPtr config = KSharedConfig::openConfig(QStringLiteral("auroraerc")); return config->group(m_themeName).readEntry(key, defaultValue); } void Decoration::setupBorders(QQuickItem *item) { m_borders = item->findChild(QStringLiteral("borders")); m_maximizedBorders = item->findChild(QStringLiteral("maximizedBorders")); m_extendedBorders = item->findChild(QStringLiteral("extendedBorders")); m_padding = item->findChild(QStringLiteral("padding")); } void Decoration::updateBorders() { KWin::Borders *b = m_borders; if (client().data()->isMaximized() && m_maximizedBorders) { b = m_maximizedBorders; } if (!b) { return; } setBorders(*b); } void Decoration::paint(QPainter *painter, const QRect &repaintRegion) { Q_UNUSED(repaintRegion) painter->fillRect(rect(), Qt::transparent); painter->drawImage(rect(), m_buffer, m_contentRect); } void Decoration::updateShadow() { bool updateShadow = false; const auto oldShadow = shadow(); if (m_padding && (m_padding->left() > 0 || m_padding->top() > 0 || m_padding->right() > 0 || m_padding->bottom() > 0) && !client().data()->isMaximized()) { if (oldShadow.isNull()) { updateShadow = true; } else { // compare padding if (oldShadow->padding() != *m_padding) { updateShadow = true; } } QImage img(m_buffer.size(), QImage::Format_ARGB32_Premultiplied); img.fill(Qt::transparent); QPainter p(&img); // top p.drawImage(0, 0, m_buffer, 0, 0, img.width(), m_padding->top()); // left p.drawImage(0, m_padding->top(), m_buffer, 0, m_padding->top(), m_padding->left(), m_buffer.height() - m_padding->top()); // bottom p.drawImage(m_padding->left(), m_buffer.height() - m_padding->bottom(), m_buffer, m_padding->left(), m_buffer.height() - m_padding->bottom(), m_buffer.width() - m_padding->left(), m_padding->bottom()); // right p.drawImage(m_buffer.width() - m_padding->right(), m_padding->top(), m_buffer, m_buffer.width() - m_padding->right(), m_padding->top(), m_padding->right(), m_buffer.height() - m_padding->top() - m_padding->bottom()); if (!updateShadow) { updateShadow = (oldShadow->shadow() != img); } if (updateShadow) { auto s = QSharedPointer::create(); s->setShadow(img); s->setPadding(*m_padding); s->setInnerShadowRect(QRect(m_padding->left(), m_padding->top(), m_buffer.width() - m_padding->left() - m_padding->right(), m_buffer.height() - m_padding->top() - m_padding->bottom())); setShadow(s); } } else { if (!oldShadow.isNull()) { setShadow(QSharedPointer()); } } } QMouseEvent Decoration::translatedMouseEvent(QMouseEvent *orig) { if (!m_padding || client().data()->isMaximized()) { orig->setAccepted(false); return *orig; } QMouseEvent event(orig->type(), orig->localPos() + QPointF(m_padding->left(), m_padding->top()), orig->button(), orig->buttons(), orig->modifiers()); event.setAccepted(false); return event; } void Decoration::hoverEnterEvent(QHoverEvent *event) { if (m_view) { event->setAccepted(false); QCoreApplication::sendEvent(m_view.data(), event); } KDecoration2::Decoration::hoverEnterEvent(event); } void Decoration::hoverLeaveEvent(QHoverEvent *event) { if (m_view) { event->setAccepted(false); QCoreApplication::sendEvent(m_view.data(), event); } KDecoration2::Decoration::hoverLeaveEvent(event); } void Decoration::hoverMoveEvent(QHoverEvent *event) { if (m_view) { QMouseEvent mouseEvent(QEvent::MouseMove, event->posF(), Qt::NoButton, Qt::NoButton, Qt::NoModifier); QMouseEvent ev = translatedMouseEvent(&mouseEvent); QCoreApplication::sendEvent(m_view.data(), &ev); event->setAccepted(ev.isAccepted()); } KDecoration2::Decoration::hoverMoveEvent(event); } void Decoration::mouseMoveEvent(QMouseEvent *event) { if (m_view) { QMouseEvent ev = translatedMouseEvent(event); QCoreApplication::sendEvent(m_view.data(), &ev); event->setAccepted(ev.isAccepted()); } KDecoration2::Decoration::mouseMoveEvent(event); } void Decoration::mousePressEvent(QMouseEvent *event) { if (m_view) { QMouseEvent ev = translatedMouseEvent(event); QCoreApplication::sendEvent(m_view.data(), &ev); if (ev.button() == Qt::LeftButton) { if (!m_doubleClickTimer.hasExpired(QGuiApplication::styleHints()->mouseDoubleClickInterval())) { QMouseEvent dc(QEvent::MouseButtonDblClick, ev.localPos(), ev.windowPos(), ev.screenPos(), ev.button(), ev.buttons(), ev.modifiers()); QCoreApplication::sendEvent(m_view.data(), &dc); } } m_doubleClickTimer.invalidate(); event->setAccepted(ev.isAccepted()); } KDecoration2::Decoration::mousePressEvent(event); } void Decoration::mouseReleaseEvent(QMouseEvent *event) { if (m_view) { QMouseEvent ev = translatedMouseEvent(event); QCoreApplication::sendEvent(m_view.data(), &ev); event->setAccepted(ev.isAccepted()); if (ev.isAccepted() && ev.button() == Qt::LeftButton) { m_doubleClickTimer.start(); } } KDecoration2::Decoration::mouseReleaseEvent(event); } void Decoration::installTitleItem(QQuickItem *item) { auto update = [this, item] { QRect rect = item->mapRectToScene(item->childrenRect()).toRect(); if (rect.isNull()) { rect = item->parentItem()->mapRectToScene(QRectF(item->x(), item->y(), item->width(), item->height())).toRect(); } setTitleBar(rect); }; update(); connect(item, &QQuickItem::widthChanged, this, update); connect(item, &QQuickItem::heightChanged, this, update); connect(item, &QQuickItem::xChanged, this, update); connect(item, &QQuickItem::yChanged, this, update); } KDecoration2::DecoratedClient *Decoration::clientPointer() const { return client().data(); } ThemeFinder::ThemeFinder(QObject *parent, const QVariantList &args) : QObject(parent) { Q_UNUSED(args) init(); } void ThemeFinder::init() { findAllQmlThemes(); findAllSvgThemes(); } void ThemeFinder::findAllQmlThemes() { const auto offers = KPackage::PackageLoader::self()->findPackages(QStringLiteral("KWin/Decoration"), s_qmlPackageFolder); for (const auto &offer : offers) { m_themes.insert(offer.name(), offer.pluginId()); } } void ThemeFinder::findAllSvgThemes() { QStringList themes; const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("aurorae/themes/"), QStandardPaths::LocateDirectory); QStringList themeDirectories; for (const QString &dir : dirs) { QDir directory = QDir(dir); for (const QString &themeDir : directory.entryList(QDir::AllDirs | QDir::NoDotAndDotDot)) { themeDirectories << dir + themeDir; } } for (const QString &dir : themeDirectories) { for (const QString & file : QDir(dir).entryList(QStringList() << QStringLiteral("metadata.desktop"))) { themes.append(dir + '/' + file); } } for (const QString & theme : themes) { int themeSepIndex = theme.lastIndexOf('/', -1); QString themeRoot = theme.left(themeSepIndex); int themeNameSepIndex = themeRoot.lastIndexOf('/', -1); QString packageName = themeRoot.right(themeRoot.length() - themeNameSepIndex - 1); KDesktopFile df(theme); QString name = df.readName(); if (name.isEmpty()) { name = packageName; } m_themes.insert(name, QString(QLatin1String("__aurorae__svg__") + packageName)); } } static const QString s_configUiPath = QStringLiteral("kwin/decorations/%1/contents/ui/config.ui"); static const QString s_configXmlPath = QStringLiteral("kwin/decorations/%1/contents/config/main.xml"); bool ThemeFinder::hasConfiguration(const QString &theme) const { if (theme.startsWith(QLatin1String("__aurorae__svg__"))) { return true; } const QString ui = QStandardPaths::locate(QStandardPaths::GenericDataLocation, s_configUiPath.arg(theme)); const QString xml = QStandardPaths::locate(QStandardPaths::GenericDataLocation, s_configXmlPath.arg(theme)); return !(ui.isEmpty() || xml.isEmpty()); } ConfigurationModule::ConfigurationModule(QWidget *parent, const QVariantList &args) : KCModule(parent, args) , m_theme(findTheme(args)) , m_buttonSize(int(KDecoration2::BorderSize::Normal) - s_indexMapper) { setLayout(new QVBoxLayout(this)); init(); } void ConfigurationModule::init() { if (m_theme.startsWith(QLatin1String("__aurorae__svg__"))) { // load the generic setting module initSvg(); } else { initQml(); } } void ConfigurationModule::initSvg() { QWidget *form = new QWidget(this); form->setLayout(new QHBoxLayout(form)); QComboBox *sizes = new QComboBox(form); sizes->addItem(i18nc("@item:inlistbox Button size:", "Tiny")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Normal")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Large")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Very Large")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Huge")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Very Huge")); sizes->addItem(i18nc("@item:inlistbox Button size:", "Oversized")); sizes->setObjectName(QStringLiteral("kcfg_ButtonSize")); QLabel *label = new QLabel(i18n("Button size:"), form); label->setBuddy(sizes); form->layout()->addWidget(label); form->layout()->addWidget(sizes); layout()->addWidget(form); KCoreConfigSkeleton *skel = new KCoreConfigSkeleton(KSharedConfig::openConfig(QStringLiteral("auroraerc")), this); skel->setCurrentGroup(m_theme.mid(16)); skel->addItemInt(QStringLiteral("ButtonSize"), m_buttonSize, int(KDecoration2::BorderSize::Normal) - s_indexMapper, QStringLiteral("ButtonSize")); addConfig(skel, form); } void ConfigurationModule::initQml() { const QString ui = QStandardPaths::locate(QStandardPaths::GenericDataLocation, s_configUiPath.arg(m_theme)); const QString xml = QStandardPaths::locate(QStandardPaths::GenericDataLocation, s_configXmlPath.arg(m_theme)); if (ui.isEmpty() || xml.isEmpty()) { return; } KLocalizedTranslator *translator = new KLocalizedTranslator(this); QCoreApplication::instance()->installTranslator(translator); const KDesktopFile metaData(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kwin/decorations/%1/metadata.desktop").arg(m_theme))); const QString translationDomain = metaData.desktopGroup().readEntry("X-KWin-Config-TranslationDomain", QString()); if (!translationDomain.isEmpty()) { translator->setTranslationDomain(translationDomain); } // load the KConfigSkeleton QFile configFile(xml); KSharedConfigPtr auroraeConfig = KSharedConfig::openConfig("auroraerc"); KConfigGroup configGroup = auroraeConfig->group(m_theme); m_skeleton = new KConfigLoader(configGroup, &configFile, this); // load the ui file QUiLoader *loader = new QUiLoader(this); loader->setLanguageChangeEnabled(true); QFile uiFile(ui); uiFile.open(QFile::ReadOnly); QWidget *customConfigForm = loader->load(&uiFile, this); translator->addContextToMonitor(customConfigForm->objectName()); uiFile.close(); layout()->addWidget(customConfigForm); // connect the ui file with the skeleton addConfig(m_skeleton, customConfigForm); // send a custom event to the translator to retranslate using our translator QEvent le(QEvent::LanguageChange); QCoreApplication::sendEvent(customConfigForm, &le); } } #include "aurorae.moc" diff --git a/plugins/kdecorations/aurorae/src/colorhelper.h b/plugins/kdecorations/aurorae/src/colorhelper.h index 91f889d96..cb02b7d03 100644 --- a/plugins/kdecorations/aurorae/src/colorhelper.h +++ b/plugins/kdecorations/aurorae/src/colorhelper.h @@ -1,241 +1,241 @@ /******************************************************************** 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 COLOR_HELPER_H #define COLOR_HELPER_H #include #include /** * @short Helper to manipulate colors. * * Exports a few functions from KColorScheme. - **/ + */ class ColorHelper : public QObject { Q_OBJECT Q_ENUMS(ShadeRole) Q_ENUMS(ForegroundRole) Q_ENUMS(BackgroundRole) /** * Same as KGlobalSettings::contrastF. - **/ + */ Q_PROPERTY(qreal contrast READ contrast CONSTANT) public: explicit ColorHelper(QObject *parent = nullptr); ~ColorHelper() override; /** * This enumeration describes the color shade being selected from the given * set. * * Color shades are used to draw "3d" elements, such as frames and bevels. * They are neither foreground nor background colors. Text should not be * painted over a shade, and shades should not be used to draw text. - **/ + */ enum ShadeRole { /** * The light color is lighter than dark() or shadow() and contrasts * with the base color. - **/ + */ LightShade, /** * The midlight color is in between base() and light(). - **/ + */ MidlightShade, /** * The mid color is in between base() and dark(). - **/ + */ MidShade, /** * The dark color is in between mid() and shadow(). - **/ + */ DarkShade, /** * The shadow color is darker than light() or midlight() and contrasts * the base color. - **/ + */ ShadowShade }; /** * This enumeration describes the background color being selected from the * given set. * * Background colors are suitable for drawing under text, and should never * be used to draw text. In combination with one of the overloads of * KColorScheme::shade, they may be used to generate colors for drawing * frames, bevels, and similar decorations. - **/ + */ enum BackgroundRole { /** * Normal background. - **/ + */ NormalBackground = 0, /** * Alternate background; for example, for use in lists. * * This color may be the same as BackgroundNormal, especially in sets * other than View and Window. - **/ + */ AlternateBackground = 1, /** * Third color; for example, items which are new, active, requesting * attention, etc. * * Alerting the user that a certain field must be filled out would be a * good usage (although NegativeBackground could be used to the same * effect, depending on what you are trying to achieve). Unlike * ActiveText, this should not be used for mouseover effects. - **/ + */ ActiveBackground = 2, /** * Fourth color; corresponds to (unvisited) links. * * Exactly what this might be used for is somewhat harder to qualify; * it might be used for bookmarks, as a 'you can click here' indicator, * or to highlight recent content (i.e. in a most-recently-accessed * list). - **/ + */ LinkBackground = 3, /** * Fifth color; corresponds to visited links. * * This can also be used to indicate "not recent" content, especially * when a color is needed to denote content which is "old" or * "archival". - **/ + */ VisitedBackground = 4, /** * Sixth color; for example, errors, untrusted content, etc. - **/ + */ NegativeBackground = 5, /** * Seventh color; for example, warnings, secure/encrypted content. - **/ + */ NeutralBackground = 6, /** * Eigth color; for example, success messages, trusted content. - **/ + */ PositiveBackground = 7 }; /** * This enumeration describes the foreground color being selected from the * given set. * * Foreground colors are suitable for drawing text or glyphs (such as the * symbols on window decoration buttons, assuming a suitable background * brush is used), and should never be used to draw backgrounds. * * For window decorations, the following is suggested, but not set in * stone: * @li Maximize - PositiveText * @li Minimize - NeutralText * @li Close - NegativeText * @li WhatsThis - LinkText * @li Sticky - ActiveText - **/ + */ enum ForegroundRole { /** * Normal foreground. - **/ + */ NormalText = 0, /** * Second color; for example, comments, items which are old, inactive * or disabled. Generally used for things that are meant to be "less * important". InactiveText is not the same role as NormalText in the * inactive state. - **/ + */ InactiveText = 1, /** * Third color; for example items which are new, active, requesting * attention, etc. May be used as a hover color for clickable items. - **/ + */ ActiveText = 2, /** * Fourth color; use for (unvisited) links. May also be used for other * clickable items or content that indicates relationships, items that * indicate somewhere the user can visit, etc. - **/ + */ LinkText = 3, /** * Fifth color; used for (visited) links. As with LinkText, may be used * for items that have already been "visited" or accessed. May also be * used to indicate "historical" (i.e. "old") items or information, * especially if InactiveText is being used in the same context to * express something different. - **/ + */ VisitedText = 4, /** * Sixth color; for example, errors, untrusted content, deletions, * etc. - **/ + */ NegativeText = 5, /** * Seventh color; for example, warnings, secure/encrypted content. - **/ + */ NeutralText = 6, /** * Eigth color; for example, additions, success messages, trusted * content. - **/ + */ PositiveText = 7 }; /** * Retrieve the requested shade color, using the specified color as the * base color and the system contrast setting. * * @note Shades are chosen such that all shades would contrast with the * base color. This means that if base is very dark, the 'dark' shades will * be lighter than the base color, with midlight() == shadow(). * Conversely, if the base color is very light, the 'light' shades will be * darker than the base color, with light() == mid(). - **/ + */ Q_INVOKABLE QColor shade(const QColor& color, ShadeRole role); Q_INVOKABLE QColor shade(const QColor& color, ShadeRole role, qreal contrast); /** * Retrieve the requested shade color, using the specified color as the * base color and the specified contrast. * * @param contrast Amount roughly specifying the contrast by which to * adjust the base color, between -1.0 and 1.0 (values between 0.0 and 1.0 * correspond to the value from KGlobalSettings::contrastF) * * @note Shades are chosen such that all shades would contrast with the * base color. This means that if base is very dark, the 'dark' shades will * be lighter than the base color, with midlight() == shadow(). * Conversely, if the base color is very light, the 'light' shades will be * darker than the base color, with light() == mid(). * * @see KColorUtils::shade - **/ + */ Q_INVOKABLE QColor multiplyAlpha(const QColor& color, qreal alpha); /** * Retrieve the requested background brush's color for the @p active button. * @param active Whether the active or inactive palette should be used. - **/ + */ Q_INVOKABLE QColor background(bool active, BackgroundRole role = NormalBackground) const; /** * Retrieve the requested foreground brush's color for the @p active button. * @param active Whether the active or inactive palette should be used. - **/ + */ Q_INVOKABLE QColor foreground(bool active, ForegroundRole role = NormalText) const; qreal contrast() const; }; #endif diff --git a/plugins/kdecorations/aurorae/src/decorationoptions.h b/plugins/kdecorations/aurorae/src/decorationoptions.h index d38e2ca72..58b3bf766 100644 --- a/plugins/kdecorations/aurorae/src/decorationoptions.h +++ b/plugins/kdecorations/aurorae/src/decorationoptions.h @@ -1,318 +1,318 @@ /******************************************************************** 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_DECORATION_OPTIONS_H #define KWIN_DECORATION_OPTIONS_H #include #include #include #include #include namespace KWin { // TODO: move to deco API class ColorSettings { public: ColorSettings(const QPalette &pal); void update(const QPalette &pal); const QColor &titleBarColor(bool active) const { return active ? m_activeTitleBarColor : m_inactiveTitleBarColor; } const QColor &activeTitleBarColor() const { return m_activeTitleBarColor; } const QColor &inactiveTitleBarColor() const { return m_inactiveTitleBarColor; } const QColor &activeTitleBarBlendColor() const { return m_activeTitleBarBlendColor; } const QColor &inactiveTitleBarBlendColor() const { return m_inactiveTitleBarBlendColor; } const QColor &frame(bool active) const { return active ? m_activeFrameColor : m_inactiveFrameColor; } const QColor &activeFrame() const { return m_activeFrameColor; } const QColor &inactiveFrame() const { return m_inactiveFrameColor; } const QColor &font(bool active) const { return active ? m_activeFontColor : m_inactiveFontColor; } const QColor &activeFont() const { return m_activeFontColor; } const QColor &inactiveFont() const { return m_inactiveFontColor; } const QColor &activeButtonColor() const { return m_activeButtonColor; } const QColor &inactiveButtonColor() const { return m_inactiveButtonColor; } const QColor &activeHandle() const { return m_activeHandle; } const QColor &inactiveHandle() const { return m_inactiveHandle; } const QPalette &palette() const { return m_palette; } private: void init(const QPalette &pal); QColor m_activeTitleBarColor; QColor m_inactiveTitleBarColor; QColor m_activeTitleBarBlendColor; QColor m_inactiveTitleBarBlendColor; QColor m_activeFrameColor; QColor m_inactiveFrameColor; QColor m_activeFontColor; QColor m_inactiveFontColor; QColor m_activeButtonColor; QColor m_inactiveButtonColor; QColor m_activeHandle; QColor m_inactiveHandle; QPalette m_palette; }; /** * @short Common Window Decoration Options. * * This Class provides common window decoration options which can be used, but do not have to * be used by a window decoration. The class provides properties for global settings such as * color, font and decoration button position. * * If a window decoration wants to follow the global color scheme it should honor the values * provided by the properties. * * In any case it makes sense to respect the font settings for the decoration as this is also * an accessibility feature. * * In order to use the options in a QML based window decoration an instance of this object needs * to be created and the as a context property available "decoration" needs to be passed to the * DecorationOptions instance: * * @code * DecorationOptions { * id: options * deco: decoration * } * @endcode - **/ + */ class DecorationOptions : public QObject { Q_OBJECT Q_ENUMS(BorderSize) Q_ENUMS(DecorationButton) /** * The decoration Object for which this set of options should be used. The decoration is * required to get the correct colors and fonts depending on whether the decoration represents * an active or inactive window. * * Best pass the decoration object available as a context property to this property. - **/ + */ Q_PROPERTY(KDecoration2::Decoration *deco READ decoration WRITE setDecoration NOTIFY decorationChanged) /** * The color for the titlebar depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor titleBarColor READ titleBarColor NOTIFY colorsChanged) /** * The blend color for the titlebar depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor titleBarBlendColor READ titleBarBlendColor NOTIFY colorsChanged) /** * The titlebar text color depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor fontColor READ fontColor NOTIFY colorsChanged) /** * The color to use for titlebar buttons depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor buttonColor READ buttonColor NOTIFY colorsChanged) /** * The color for the window frame (border) depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor borderColor READ borderColor NOTIFY colorsChanged) /** * The color for the resize handle depending on the decoration's active state. - **/ + */ Q_PROPERTY(QColor resizeHandleColor READ resizeHandleColor NOTIFY colorsChanged) /** * The font to be used for the decoration caption depending on the decoration's active state. - **/ + */ Q_PROPERTY(QFont titleFont READ titleFont NOTIFY fontChanged) /** * The buttons to be positioned on the left side of the titlebar from left to right. - **/ + */ Q_PROPERTY(QList titleButtonsLeft READ titleButtonsLeft NOTIFY titleButtonsChanged) /** * The buttons to be positioned on the right side of the titlebar from left to right. - **/ + */ Q_PROPERTY(QList titleButtonsRight READ titleButtonsRight NOTIFY titleButtonsChanged) Q_PROPERTY(int mousePressAndHoldInterval READ mousePressAndHoldInterval CONSTANT) public: enum BorderSize { BorderNone, ///< No borders except title BorderNoSides, ///< No borders on sides BorderTiny, ///< Minimal borders BorderNormal, ///< Standard size borders, the default setting BorderLarge, ///< Larger borders BorderVeryLarge, ///< Very large borders BorderHuge, ///< Huge borders BorderVeryHuge, ///< Very huge borders BorderOversized ///< Oversized borders }; /** * Enum values to identify the decorations buttons which should be used * by the decoration. * - **/ + */ enum DecorationButton { /** * Invalid button value. A decoration should not create a button for * this type. - **/ + */ DecorationButtonNone, DecorationButtonMenu, DecorationButtonApplicationMenu, DecorationButtonOnAllDesktops, DecorationButtonQuickHelp, DecorationButtonMinimize, DecorationButtonMaximizeRestore, DecorationButtonClose, DecorationButtonKeepAbove, DecorationButtonKeepBelow, DecorationButtonShade, DecorationButtonResize, /** * The decoration should create an empty spacer instead of a button for * this type. - **/ + */ DecorationButtonExplicitSpacer }; explicit DecorationOptions(QObject *parent = nullptr); ~DecorationOptions() override; QColor titleBarColor() const; QColor titleBarBlendColor() const; QColor fontColor() const; QColor buttonColor() const; QColor borderColor() const; QColor resizeHandleColor() const; QFont titleFont() const; QList titleButtonsLeft() const; QList titleButtonsRight() const; KDecoration2::Decoration *decoration() const; void setDecoration(KDecoration2::Decoration *decoration); int mousePressAndHoldInterval() const; Q_SIGNALS: void colorsChanged(); void fontChanged(); void decorationChanged(); void titleButtonsChanged(); private Q_SLOTS: void slotActiveChanged(); private: bool m_active; KDecoration2::Decoration *m_decoration; ColorSettings m_colors; QMetaObject::Connection m_paletteConnection; }; class Borders : public QObject { Q_OBJECT Q_PROPERTY(int left READ left WRITE setLeft NOTIFY leftChanged) Q_PROPERTY(int right READ right WRITE setRight NOTIFY rightChanged) Q_PROPERTY(int top READ top WRITE setTop NOTIFY topChanged) Q_PROPERTY(int bottom READ bottom WRITE setBottom NOTIFY bottomChanged) public: Borders(QObject *parent = nullptr); ~Borders() override; int left() const; int right() const; int top() const; int bottom() const; void setLeft(int left); void setRight(int right); void setTop(int top); void setBottom(int bottom); operator QMargins() const; public Q_SLOTS: /** * Sets all four borders to @p value. - **/ + */ void setAllBorders(int value); /** * Sets all borders except the title border to @p value. - **/ + */ void setBorders(int value); /** * Sets the side borders (e.g. if title is on top, the left and right borders) * to @p value. - **/ + */ void setSideBorders(int value); /** * Sets the title border to @p value. - **/ + */ void setTitle(int value); Q_SIGNALS: void leftChanged(); void rightChanged(); void topChanged(); void bottomChanged(); private: int m_left; int m_right; int m_top; int m_bottom; }; #define GETTER( name ) \ inline int Borders::name() const \ { \ return m_##name;\ }\ GETTER(left) GETTER(right) GETTER(top) GETTER(bottom) #undef GETTER } // namespace #endif // KWIN_DECORATION_OPTIONS_H diff --git a/plugins/kdecorations/aurorae/src/lib/auroraetheme.h b/plugins/kdecorations/aurorae/src/lib/auroraetheme.h index d45f1941c..aa7fa755c 100644 --- a/plugins/kdecorations/aurorae/src/lib/auroraetheme.h +++ b/plugins/kdecorations/aurorae/src/lib/auroraetheme.h @@ -1,229 +1,229 @@ /* Library for Aurorae window decoration themes. Copyright (C) 2009, 2010, 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef AURORAETHEME_H #define AURORAETHEME_H // #include "libaurorae_export.h" #include #include #include Q_DECLARE_LOGGING_CATEGORY(AURORAE) class KConfig; namespace Aurorae { class AuroraeThemePrivate; class ThemeConfig; enum AuroraeButtonType { MinimizeButton = 0, MaximizeButton, RestoreButton, CloseButton, AllDesktopsButton, KeepAboveButton, KeepBelowButton, ShadeButton, HelpButton, MenuButton, AppMenuButton }; enum DecorationPosition { DecorationTop = 0, DecorationLeft, DecorationRight, DecorationBottom }; class /*LIBAURORAE_EXPORT*/ AuroraeTheme : public QObject { Q_OBJECT Q_PROPERTY(int borderLeft READ leftBorder NOTIFY borderSizesChanged) Q_PROPERTY(int borderRight READ rightBorder NOTIFY borderSizesChanged) Q_PROPERTY(int borderTop READ topBorder NOTIFY borderSizesChanged) Q_PROPERTY(int borderBottom READ bottomBorder NOTIFY borderSizesChanged) Q_PROPERTY(int borderLeftMaximized READ leftBorderMaximized NOTIFY borderSizesChanged) Q_PROPERTY(int borderRightMaximized READ rightBorderMaximized NOTIFY borderSizesChanged) Q_PROPERTY(int borderTopMaximized READ topBorderMaximized NOTIFY borderSizesChanged) Q_PROPERTY(int borderBottomMaximized READ bottomBorderMaximized NOTIFY borderSizesChanged) Q_PROPERTY(int paddingLeft READ paddingLeft NOTIFY themeChanged) Q_PROPERTY(int paddingRight READ paddingRight NOTIFY themeChanged) Q_PROPERTY(int paddingTop READ paddingTop NOTIFY themeChanged) Q_PROPERTY(int paddingBottom READ paddingBottom NOTIFY themeChanged) Q_PROPERTY(QString themeName READ themeName NOTIFY themeChanged) Q_PROPERTY(int buttonHeight READ buttonHeight NOTIFY themeChanged) Q_PROPERTY(int buttonWidth READ buttonWidth NOTIFY themeChanged) Q_PROPERTY(int buttonWidthMinimize READ buttonWidthMinimize NOTIFY themeChanged) Q_PROPERTY(int buttonWidthMaximizeRestore READ buttonWidthMaximizeRestore NOTIFY themeChanged) Q_PROPERTY(int buttonWidthClose READ buttonWidthClose NOTIFY themeChanged) Q_PROPERTY(int buttonWidthAllDesktops READ buttonWidthAllDesktops NOTIFY themeChanged) Q_PROPERTY(int buttonWidthKeepAbove READ buttonWidthKeepAbove NOTIFY themeChanged) Q_PROPERTY(int buttonWidthKeepBelow READ buttonWidthKeepBelow NOTIFY themeChanged) Q_PROPERTY(int buttonWidthShade READ buttonWidthShade NOTIFY themeChanged) Q_PROPERTY(int buttonWidthHelp READ buttonWidthHelp NOTIFY themeChanged) Q_PROPERTY(int buttonWidthMenu READ buttonWidthMenu NOTIFY themeChanged) Q_PROPERTY(int buttonWidthAppMenu READ buttonWidthAppMenu NOTIFY themeChanged) Q_PROPERTY(int buttonSpacing READ buttonSpacing NOTIFY themeChanged) Q_PROPERTY(int buttonMarginTop READ buttonMarginTop NOTIFY themeChanged) Q_PROPERTY(int explicitButtonSpacer READ explicitButtonSpacer NOTIFY themeChanged) Q_PROPERTY(qreal buttonSizeFactor READ buttonSizeFactor NOTIFY buttonSizesChanged) Q_PROPERTY(int animationTime READ animationTime NOTIFY themeChanged) Q_PROPERTY(int titleEdgeLeft READ titleEdgeLeft NOTIFY themeChanged) Q_PROPERTY(int titleEdgeRight READ titleEdgeRight NOTIFY themeChanged) Q_PROPERTY(int titleEdgeTop READ titleEdgeTop NOTIFY themeChanged) Q_PROPERTY(int titleEdgeLeftMaximized READ titleEdgeLeftMaximized NOTIFY themeChanged) Q_PROPERTY(int titleEdgeRightMaximized READ titleEdgeRightMaximized NOTIFY themeChanged) Q_PROPERTY(int titleEdgeTopMaximized READ titleEdgeTopMaximized NOTIFY themeChanged) Q_PROPERTY(int titleBorderRight READ titleBorderRight NOTIFY themeChanged) Q_PROPERTY(int titleBorderLeft READ titleBorderLeft NOTIFY themeChanged) Q_PROPERTY(int titleHeight READ titleHeight NOTIFY themeChanged) Q_PROPERTY(QString decorationPath READ decorationPath NOTIFY themeChanged) Q_PROPERTY(QString minimizeButtonPath READ minimizeButtonPath NOTIFY themeChanged) Q_PROPERTY(QString maximizeButtonPath READ maximizeButtonPath NOTIFY themeChanged) Q_PROPERTY(QString restoreButtonPath READ restoreButtonPath NOTIFY themeChanged) Q_PROPERTY(QString closeButtonPath READ closeButtonPath NOTIFY themeChanged) Q_PROPERTY(QString allDesktopsButtonPath READ allDesktopsButtonPath NOTIFY themeChanged) Q_PROPERTY(QString keepAboveButtonPath READ keepAboveButtonPath NOTIFY themeChanged) Q_PROPERTY(QString keepBelowButtonPath READ keepBelowButtonPath NOTIFY themeChanged) Q_PROPERTY(QString shadeButtonPath READ shadeButtonPath NOTIFY themeChanged) Q_PROPERTY(QString helpButtonPath READ helpButtonPath NOTIFY themeChanged) Q_PROPERTY(QColor activeTextColor READ activeTextColor NOTIFY themeChanged) Q_PROPERTY(QColor inactiveTextColor READ inactiveTextColor NOTIFY themeChanged) Q_PROPERTY(Qt::Alignment horizontalAlignment READ alignment NOTIFY themeChanged) Q_PROPERTY(Qt::Alignment verticalAlignment READ verticalAlignment NOTIFY themeChanged) public: explicit AuroraeTheme(QObject* parent = nullptr); ~AuroraeTheme() override; // TODO: KSharedConfigPtr void loadTheme(const QString &name, const KConfig &config); bool isValid() const; const QString &themeName() const; int leftBorder() const; int rightBorder() const; int topBorder() const; int bottomBorder() const; int leftBorderMaximized() const; int rightBorderMaximized() const; int topBorderMaximized() const; int bottomBorderMaximized() const; int paddingLeft() const; int paddingRight() const; int paddingTop() const; int paddingBottom() const; int buttonWidth() const; int buttonWidthMinimize() const; int buttonWidthMaximizeRestore() const; int buttonWidthClose() const; int buttonWidthAllDesktops() const; int buttonWidthKeepAbove() const; int buttonWidthKeepBelow() const; int buttonWidthShade() const; int buttonWidthHelp() const; int buttonWidthMenu() const; int buttonWidthAppMenu() const; int buttonHeight() const; int buttonSpacing() const; int buttonMarginTop() const; int explicitButtonSpacer() const; int animationTime() const; int titleEdgeLeft() const; int titleEdgeRight() const; int titleEdgeTop() const; int titleEdgeLeftMaximized() const; int titleEdgeRightMaximized() const; int titleEdgeTopMaximized() const; int titleBorderLeft() const; int titleBorderRight() const; int titleHeight() const; QString decorationPath() const; QString minimizeButtonPath() const; QString maximizeButtonPath() const; QString restoreButtonPath() const; QString closeButtonPath() const; QString allDesktopsButtonPath() const; QString keepAboveButtonPath() const; QString keepBelowButtonPath() const; QString shadeButtonPath() const; QString helpButtonPath() const; QColor activeTextColor() const; QColor inactiveTextColor() const; Qt::Alignment alignment() const; Qt::Alignment verticalAlignment() const; /** * Sets the title edges according to maximized state. * Title edges are global to all windows. - **/ + */ void titleEdges(int &left, int &top, int &right, int &bottom, bool maximized) const; void setCompositingActive(bool active); bool isCompositingActive() const; /** * @returns true if the theme contains a FrameSvg for specified button. - **/ + */ bool hasButton(AuroraeButtonType button) const; void setBorderSize(KDecoration2::BorderSize size); /** * Sets the size of the buttons. * The available sizes are identical to border sizes, therefore BorderSize is used. * @param size The buttons size - **/ + */ void setButtonSize(KDecoration2::BorderSize size); qreal buttonSizeFactor() const; DecorationPosition decorationPosition() const; void setTabDragMimeType(const QString &mime); const QString &tabDragMimeType() const; // TODO: move to namespace static QLatin1String mapButtonToName(AuroraeButtonType type); public Q_SLOTS: void loadTheme(const QString &name); Q_SIGNALS: void themeChanged(); void buttonSizesChanged(); void borderSizesChanged(); private: /** * Sets the borders according to maximized state. * Borders are global to all windows. - **/ + */ void borders(int &left, int &top, int &right, int &bottom, bool maximized) const; /** * Sets the padding according. * Padding is global to all windows. - **/ + */ void padding(int &left, int &top, int &right, int &bottom) const; AuroraeThemePrivate* const d; }; } // namespace #endif // AURORAETHEME_H diff --git a/plugins/kdecorations/aurorae/themes/plastik/code/plastikbutton.h b/plugins/kdecorations/aurorae/themes/plastik/code/plastikbutton.h index 7a3553c8f..02c94b464 100644 --- a/plugins/kdecorations/aurorae/themes/plastik/code/plastikbutton.h +++ b/plugins/kdecorations/aurorae/themes/plastik/code/plastikbutton.h @@ -1,84 +1,84 @@ /******************************************************************** 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_PLASTIK_BUTTON_H #define KWIN_PLASTIK_BUTTON_H #include namespace KWin { class PlastikButtonProvider : public QQuickImageProvider { public: explicit PlastikButtonProvider(); QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override; private: enum ButtonIcon { CloseIcon = 0, MaxIcon, MaxRestoreIcon, MinIcon, HelpIcon, OnAllDesktopsIcon, NotOnAllDesktopsIcon, KeepAboveIcon, NoKeepAboveIcon, KeepBelowIcon, NoKeepBelowIcon, ShadeIcon, UnShadeIcon, AppMenuIcon, NumButtonIcons }; enum Object { HorizontalLine, VerticalLine, DiagonalLine, CrossDiagonalLine }; enum DecorationButton { /** * Invalid button value. A decoration should not create a button for * this type. - **/ + */ DecorationButtonNone, DecorationButtonMenu, DecorationButtonApplicationMenu, DecorationButtonOnAllDesktops, DecorationButtonQuickHelp, DecorationButtonMinimize, DecorationButtonMaximizeRestore, DecorationButtonClose, DecorationButtonKeepAbove, DecorationButtonKeepBelow, DecorationButtonShade, DecorationButtonResize, /** * The decoration should create an empty spacer instead of a button for * this type. - **/ + */ DecorationButtonExplicitSpacer }; QPixmap icon(ButtonIcon icon, int size, bool active, bool shadow); void drawObject(QPainter &p, Object object, int x, int y, int length, int lineWidth); }; } // namespace #endif // KWIN_PLASTIK_BUTTON_H diff --git a/plugins/platforms/drm/drm_backend.h b/plugins/platforms/drm/drm_backend.h index 8e029231b..3bdb4fda7 100644 --- a/plugins/platforms/drm/drm_backend.h +++ b/plugins/platforms/drm/drm_backend.h @@ -1,212 +1,212 @@ /******************************************************************** 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_DRM_BACKEND_H #define KWIN_DRM_BACKEND_H #include "platform.h" #include "input.h" #include "drm_buffer.h" #if HAVE_GBM #include "drm_buffer_gbm.h" #endif #include "drm_inputeventfilter.h" #include "drm_pointer.h" #include #include #include #include #include #include #include struct gbm_bo; struct gbm_device; struct gbm_surface; namespace KWayland { namespace Server { class OutputInterface; class OutputDeviceInterface; class OutputChangeSet; class OutputManagementInterface; } } namespace KWin { class Udev; class UdevMonitor; class DrmOutput; class DrmPlane; class DrmCrtc; class DrmConnector; class GbmSurface; class KWIN_EXPORT DrmBackend : public Platform { Q_OBJECT Q_INTERFACES(KWin::Platform) Q_PLUGIN_METADATA(IID "org.kde.kwin.Platform" FILE "drm.json") public: explicit DrmBackend(QObject *parent = nullptr); ~DrmBackend() override; void configurationChangeRequested(KWayland::Server::OutputConfigurationInterface *config) override; Screens *createScreens(QObject *parent = nullptr) override; QPainterBackend *createQPainterBackend() override; OpenGLBackend* createOpenGLBackend() override; void init() override; DrmDumbBuffer *createBuffer(const QSize &size); #if HAVE_GBM DrmSurfaceBuffer *createBuffer(const std::shared_ptr &surface); #endif bool present(DrmBuffer *buffer, DrmOutput *output); int fd() const { return m_fd; } Outputs outputs() const override; Outputs enabledOutputs() const override; QVector drmOutputs() const { return m_outputs; } QVector drmEnabledOutputs() const { return m_enabledOutputs; } QVector planes() const { return m_planes; } QVector overlayPlanes() const { return m_overlayPlanes; } void outputWentOff(); void checkOutputsAreOn(); // QPainter reuses buffers bool deleteBufferAfterPageFlip() const { return m_deleteBufferAfterPageFlip; } // returns use of AMS, default is not/legacy bool atomicModeSetting() const { return m_atomicModeSetting; } void setGbmDevice(gbm_device *device) { m_gbmDevice = device; } gbm_device *gbmDevice() const { return m_gbmDevice; } QByteArray devNode() const { return m_devNode; } #if HAVE_EGL_STREAMS bool useEglStreams() const { return m_useEglStreams; } #endif QVector supportedCompositors() const override; QString supportInformation() const override; public Q_SLOTS: void turnOutputsOn(); Q_SIGNALS: /** * Emitted whenever an output is removed/disabled - **/ + */ void outputRemoved(KWin::DrmOutput *output); /** * Emitted whenever an output is added/enabled - **/ + */ void outputAdded(KWin::DrmOutput *output); protected: void doHideCursor() override; void doShowCursor() override; private: static void pageFlipHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data); void openDrm(); void activate(bool active); void reactivate(); void deactivate(); void updateOutputs(); void setCursor(); void updateCursor(); void moveCursor(); void initCursor(); void outputDpmsChanged(); void readOutputsConfiguration(); void writeOutputsConfiguration(); QByteArray generateOutputConfigurationUuid() const; DrmOutput *findOutput(quint32 connector); DrmOutput *findOutput(const QByteArray &uuid); QScopedPointer m_udev; QScopedPointer m_udevMonitor; int m_fd = -1; int m_drmId = 0; // all crtcs QVector m_crtcs; // all connectors QVector m_connectors; // active output pipelines (planes + crtc + encoder + connector) QVector m_outputs; // active and enabled pipelines (above + wl_output) QVector m_enabledOutputs; bool m_deleteBufferAfterPageFlip; bool m_atomicModeSetting = false; bool m_cursorEnabled = false; QSize m_cursorSize; int m_pageFlipsPending = 0; bool m_active = false; QByteArray m_devNode; #if HAVE_EGL_STREAMS bool m_useEglStreams = false; #endif // all available planes: primarys, cursors and overlays QVector m_planes; QVector m_overlayPlanes; QScopedPointer m_dpmsFilter; KWayland::Server::OutputManagementInterface *m_outputManagement = nullptr; gbm_device *m_gbmDevice = nullptr; }; } #endif diff --git a/plugins/platforms/drm/edid.h b/plugins/platforms/drm/edid.h index fe19eff79..bd9952f90 100644 --- a/plugins/platforms/drm/edid.h +++ b/plugins/platforms/drm/edid.h @@ -1,73 +1,73 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2019 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 . *********************************************************************/ #pragma once #include #include namespace KWin { /** * Helper class that can be used for parsing EDID blobs. * * http://read.pudn.com/downloads110/ebook/456020/E-EDID%20Standard.pdf - **/ + */ class Edid { public: Edid(); Edid(const void *data, uint32_t size); /** * Whether this instance of EDID is valid. - **/ + */ bool isValid() const; /** * Returns physical dimensions of the monitor, in millimeters. - **/ + */ QSize physicalSize() const; /** * Returns EISA ID of the manufacturer of the monitor. - **/ + */ QByteArray eisaId() const; /** * Returns the product name of the monitor. - **/ + */ QByteArray monitorName() const; /** * Returns the serial number of the monitor. - **/ + */ QByteArray serialNumber() const; private: QSize m_physicalSize; QByteArray m_eisaId; QByteArray m_monitorName; QByteArray m_serialNumber; bool m_isValid = false; }; } // namespace KWin diff --git a/plugins/platforms/drm/egl_gbm_backend.h b/plugins/platforms/drm/egl_gbm_backend.h index 2b1af6a66..f87e32743 100644 --- a/plugins/platforms/drm/egl_gbm_backend.h +++ b/plugins/platforms/drm/egl_gbm_backend.h @@ -1,101 +1,101 @@ /******************************************************************** 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_EGL_GBM_BACKEND_H #define KWIN_EGL_GBM_BACKEND_H #include "abstract_egl_backend.h" #include "remoteaccess_manager.h" #include struct gbm_surface; namespace KWin { class DrmBackend; class DrmBuffer; class DrmOutput; class GbmSurface; /** * @brief OpenGL Backend using Egl on a GBM surface. - **/ + */ class EglGbmBackend : public AbstractEglBackend { Q_OBJECT public: EglGbmBackend(DrmBackend *b); ~EglGbmBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &renderedRegion, const QRegion &damagedRegion) override; void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion) override; bool usesOverlayWindow() const override; bool perScreenRendering() const override; QRegion prepareRenderingForScreen(int screenId) override; void init() override; protected: void present() override; void cleanupSurfaces() override; private: bool initializeEgl(); bool initBufferConfigs(); bool initRenderingContext(); void initRemotePresent(); struct Output { DrmOutput *output = nullptr; DrmBuffer *buffer = nullptr; std::shared_ptr gbmSurface; EGLSurface eglSurface = EGL_NO_SURFACE; int bufferAge = 0; /** * @brief The damage history for the past 10 frames. - **/ + */ QList damageHistory; }; bool resetOutput(Output &output, DrmOutput *drmOutput); bool makeContextCurrent(const Output &output); void presentOnOutput(Output &output); void cleanupOutput(const Output &output); void createOutput(DrmOutput *output); DrmBackend *m_backend; QVector m_outputs; QScopedPointer m_remoteaccessManager; friend class EglGbmTexture; }; /** * @brief Texture using an EGLImageKHR. - **/ + */ class EglGbmTexture : public AbstractEglTexture { public: ~EglGbmTexture() override; private: friend class EglGbmBackend; EglGbmTexture(SceneOpenGLTexture *texture, EglGbmBackend *backend); }; } // namespace #endif diff --git a/plugins/platforms/drm/egl_stream_backend.h b/plugins/platforms/drm/egl_stream_backend.h index 1c5a5b80d..9ea9613e6 100644 --- a/plugins/platforms/drm/egl_stream_backend.h +++ b/plugins/platforms/drm/egl_stream_backend.h @@ -1,116 +1,116 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2019 NVIDIA Inc. 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_EGL_STREAM_BACKEND_H #define KWIN_EGL_STREAM_BACKEND_H #include "abstract_egl_backend.h" #include #include #include namespace KWin { class DrmBackend; class DrmOutput; class DrmBuffer; class ShellClient; /** * @brief OpenGL Backend using Egl with an EGLDevice. - **/ + */ class EglStreamBackend : public AbstractEglBackend { Q_OBJECT public: EglStreamBackend(DrmBackend *b); ~EglStreamBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &renderedRegion, const QRegion &damagedRegion) override; void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion) override; bool usesOverlayWindow() const override; bool perScreenRendering() const override; QRegion prepareRenderingForScreen(int screenId) override; void init() override; protected: void present() override; void cleanupSurfaces() override; private: bool initializeEgl(); bool initBufferConfigs(); bool initRenderingContext(); struct StreamTexture { EGLStreamKHR stream; GLuint texture; }; StreamTexture *lookupStreamTexture(KWayland::Server::SurfaceInterface *surface); void attachStreamConsumer(KWayland::Server::SurfaceInterface *surface, void *eglStream, wl_array *attribs); struct Output { DrmOutput *output = nullptr; DrmBuffer *buffer = nullptr; EGLSurface eglSurface = EGL_NO_SURFACE; EGLStreamKHR eglStream = EGL_NO_STREAM_KHR; }; bool resetOutput(Output &output, DrmOutput *drmOutput); bool makeContextCurrent(const Output &output); void presentOnOutput(Output &output); void cleanupOutput(const Output &output); void createOutput(DrmOutput *output); DrmBackend *m_backend; QVector m_outputs; KWayland::Server::EglStreamControllerInterface *m_eglStreamControllerInterface; QHash m_streamTextures; friend class EglStreamTexture; }; /** * @brief External texture bound to an EGLStreamKHR. - **/ + */ class EglStreamTexture : public AbstractEglTexture { public: ~EglStreamTexture() override; bool loadTexture(WindowPixmap *pixmap) override; void updateTexture(WindowPixmap *pixmap) override; private: EglStreamTexture(SceneOpenGLTexture *texture, EglStreamBackend *backend); bool acquireStreamFrame(EGLStreamKHR stream); void createFbo(); void copyExternalTexture(GLuint tex); bool attachBuffer(KWayland::Server::BufferInterface *buffer); EglStreamBackend *m_backend; GLuint m_fbo, m_rbo; GLenum m_format; friend class EglStreamBackend; }; } // namespace #endif diff --git a/plugins/platforms/fbdev/fb_backend.h b/plugins/platforms/fbdev/fb_backend.h index b044abb13..09bf37ff2 100644 --- a/plugins/platforms/fbdev/fb_backend.h +++ b/plugins/platforms/fbdev/fb_backend.h @@ -1,131 +1,131 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2015 Martin Gräßlin Copyright 2019 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_FB_BACKEND_H #define KWIN_FB_BACKEND_H #include "abstract_wayland_output.h" #include "platform.h" #include #include namespace KWin { class FramebufferOutput : public AbstractWaylandOutput { Q_OBJECT public: FramebufferOutput(QObject *parent = nullptr) : AbstractWaylandOutput(parent) {} ~FramebufferOutput() override = default; QSize pixelSize() const override { return m_pixelSize; } void setPixelSize(const QSize &set) { m_pixelSize = set; } void setRawPhysicalSize(const QSize &set) { AbstractWaylandOutput::setRawPhysicalSize(set); } private: QSize m_pixelSize; }; class KWIN_EXPORT FramebufferBackend : public Platform { Q_OBJECT Q_INTERFACES(KWin::Platform) Q_PLUGIN_METADATA(IID "org.kde.kwin.Platform" FILE "fbdev.json") public: explicit FramebufferBackend(QObject *parent = nullptr); ~FramebufferBackend() override; Screens *createScreens(QObject *parent = nullptr) override; QPainterBackend *createQPainterBackend() override; QSize screenSize() const override; void init() override; bool isValid() const { return m_fd >= 0; } void map(); void unmap(); void *mappedMemory() const { return m_memory; } int bytesPerLine() const { return m_bytesPerLine; } int bufferSize() const { return m_bufferLength; } quint32 bitsPerPixel() const { return m_bitsPerPixel; } QImage::Format imageFormat() const; /** * @returns whether the imageFormat is BGR instead of RGB. - **/ + */ bool isBGR() const { return m_bgr; } Outputs outputs() const override; Outputs enabledOutputs() const override; QVector supportedCompositors() const override { return QVector{QPainterCompositing}; } private: void openFrameBuffer(); bool handleScreenInfo(); void initImageFormat(); QVector m_outputs; QByteArray m_id; struct Color { quint32 offset; quint32 length; }; Color m_red; Color m_green; Color m_blue; Color m_alpha; quint32 m_bitsPerPixel = 0; int m_fd = -1; quint32 m_bufferLength = 0; int m_bytesPerLine = 0; void *m_memory = nullptr; QImage::Format m_imageFormat = QImage::Format_Invalid; bool m_bgr = false; }; } #endif diff --git a/plugins/platforms/virtual/egl_gbm_backend.h b/plugins/platforms/virtual/egl_gbm_backend.h index 128244af7..7b44623a6 100644 --- a/plugins/platforms/virtual/egl_gbm_backend.h +++ b/plugins/platforms/virtual/egl_gbm_backend.h @@ -1,74 +1,74 @@ /******************************************************************** 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_EGL_GBM_BACKEND_H #define KWIN_EGL_GBM_BACKEND_H #include "abstract_egl_backend.h" namespace KWin { class VirtualBackend; class GLTexture; class GLRenderTarget; /** * @brief OpenGL Backend using Egl on a GBM surface. - **/ + */ class EglGbmBackend : public AbstractEglBackend { public: EglGbmBackend(VirtualBackend *b); ~EglGbmBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &renderedRegion, const QRegion &damagedRegion) override; bool usesOverlayWindow() const override; void init() override; protected: void present() override; private: bool initializeEgl(); bool initBufferConfigs(); bool initRenderingContext(); VirtualBackend *m_backend; GLTexture *m_backBuffer = nullptr; GLRenderTarget *m_fbo = nullptr; int m_frameCounter = 0; friend class EglGbmTexture; }; /** * @brief Texture using an EGLImageKHR. - **/ + */ class EglGbmTexture : public AbstractEglTexture { public: ~EglGbmTexture() override; private: friend class EglGbmBackend; EglGbmTexture(SceneOpenGLTexture *texture, EglGbmBackend *backend); }; } // namespace #endif diff --git a/plugins/platforms/wayland/egl_wayland_backend.h b/plugins/platforms/wayland/egl_wayland_backend.h index b0957d0ec..7bd339216 100644 --- a/plugins/platforms/wayland/egl_wayland_backend.h +++ b/plugins/platforms/wayland/egl_wayland_backend.h @@ -1,132 +1,132 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2013 Martin Gräßlin Copyright 2019 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_EGL_WAYLAND_BACKEND_H #define KWIN_EGL_WAYLAND_BACKEND_H #include "abstract_egl_backend.h" // wayland #include class QTemporaryFile; struct wl_buffer; struct wl_shm; namespace KWin { namespace Wayland { class WaylandBackend; class WaylandOutput; class EglWaylandBackend; class EglWaylandOutput : public QObject { Q_OBJECT public: EglWaylandOutput(WaylandOutput *output, QObject *parent = nullptr); ~EglWaylandOutput() override = default; bool init(EglWaylandBackend *backend); void updateSize(const QSize &size); private: WaylandOutput *m_waylandOutput; wl_egl_window *m_overlay = nullptr; EGLSurface m_eglSurface = EGL_NO_SURFACE; int m_bufferAge = 0; /** * @brief The damage history for the past 10 frames. */ QVector m_damageHistory; friend class EglWaylandBackend; }; /** * @brief OpenGL Backend using Egl on a Wayland surface. * * This Backend is the basis for a session compositor running on top of a Wayland system compositor. * It creates a Surface as large as the screen and maps it as a fullscreen shell surface on the * system compositor. The OpenGL context is created on the Wayland surface, so for rendering X11 is * not involved. * * Also in repainting the backend is currently still rather limited. Only supported mode is fullscreen * repaints, which is obviously not optimal. Best solution is probably to go for buffer_age extension * and make it the only available solution next to fullscreen repaints. - **/ + */ class EglWaylandBackend : public AbstractEglBackend { Q_OBJECT public: EglWaylandBackend(WaylandBackend *b); ~EglWaylandBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; QRegion prepareRenderingForScreen(int screenId) override; void endRenderingFrame(const QRegion &renderedRegion, const QRegion &damagedRegion) override; void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion) override; bool usesOverlayWindow() const override; bool perScreenRendering() const override; void init() override; bool havePlatformBase() const { return m_havePlatformBase; } private: bool initializeEgl(); bool initBufferConfigs(); bool initRenderingContext(); bool createEglWaylandOutput(WaylandOutput *output); void cleanupSurfaces() override; void cleanupOutput(EglWaylandOutput *output); bool makeContextCurrent(EglWaylandOutput *output); void present() override; void presentOnSurface(EglWaylandOutput *output); WaylandBackend *m_backend; QVector m_outputs; bool m_havePlatformBase; bool m_swapping = false; friend class EglWaylandTexture; }; /** * @brief Texture using an EGLImageKHR. - **/ + */ class EglWaylandTexture : public AbstractEglTexture { public: ~EglWaylandTexture() override; private: friend class EglWaylandBackend; EglWaylandTexture(SceneOpenGLTexture *texture, EglWaylandBackend *backend); }; } } #endif diff --git a/plugins/platforms/x11/common/eglonxbackend.h b/plugins/platforms/x11/common/eglonxbackend.h index ea253d91d..20c94dca8 100644 --- a/plugins/platforms/x11/common/eglonxbackend.h +++ b/plugins/platforms/x11/common/eglonxbackend.h @@ -1,108 +1,108 @@ /******************************************************************** 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_EGL_ON_X_BACKEND_H #define KWIN_EGL_ON_X_BACKEND_H #include "abstract_egl_backend.h" #include "swap_profiler.h" #include namespace KWin { /** * @brief OpenGL Backend using Egl windowing system over an X overlay window. - **/ + */ class KWIN_EXPORT EglOnXBackend : public AbstractEglBackend { public: EglOnXBackend(Display *display); explicit EglOnXBackend(xcb_connection_t *connection, Display *display, xcb_window_t rootWindow, int screenNumber, xcb_window_t renderingWindow); ~EglOnXBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &damage, const QRegion &damagedRegion) override; OverlayWindow* overlayWindow() override; bool usesOverlayWindow() const override; void init() override; bool isX11TextureFromPixmapSupported() const { return m_x11TextureFromPixmapSupported; } protected: void present() override; void presentSurface(EGLSurface surface, const QRegion &damage, const QRect &screenGeometry); virtual bool createSurfaces(); EGLSurface createSurface(xcb_window_t window); void setHavePlatformBase(bool have) { m_havePlatformBase = have; } bool havePlatformBase() const { return m_havePlatformBase; } bool makeContextCurrent(const EGLSurface &surface); void setX11TextureFromPixmapSupported(bool set) { m_x11TextureFromPixmapSupported = set; } private: bool initBufferConfigs(); bool initRenderingContext(); /** * @brief The OverlayWindow used by this Backend. - **/ + */ OverlayWindow *m_overlayWindow; int surfaceHasSubPost; int m_bufferAge; bool m_usesOverlayWindow; xcb_connection_t *m_connection; Display *m_x11Display; xcb_window_t m_rootWindow; int m_x11ScreenNumber; xcb_window_t m_renderingWindow = XCB_WINDOW_NONE; bool m_havePlatformBase = false; bool m_x11TextureFromPixmapSupported = true; SwapProfiler m_swapProfiler; friend class EglTexture; }; /** * @brief Texture using an EGLImageKHR. - **/ + */ class EglTexture : public AbstractEglTexture { public: ~EglTexture() override; void onDamage() override; bool loadTexture(WindowPixmap *pixmap) override; private: bool loadTexture(xcb_pixmap_t pix, const QSize &size); friend class EglOnXBackend; EglTexture(SceneOpenGLTexture *texture, EglOnXBackend *backend); EglOnXBackend *m_backend; }; } // namespace #endif // KWIN_EGL_ON_X_BACKEND_H diff --git a/plugins/platforms/x11/standalone/edge.h b/plugins/platforms/x11/standalone/edge.h index f913c2a64..0867efde3 100644 --- a/plugins/platforms/x11/standalone/edge.h +++ b/plugins/platforms/x11/standalone/edge.h @@ -1,79 +1,79 @@ /******************************************************************** 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_EDGE_H #define KWIN_EDGE_H #include "screenedge.h" #include "xcbutils.h" namespace KWin { class WindowBasedEdge : public Edge { Q_OBJECT public: explicit WindowBasedEdge(ScreenEdges *parent); ~WindowBasedEdge() override; quint32 window() const override; /** * The approach window is a special window to notice when get close to the screen border but * not yet triggering the border. - **/ + */ quint32 approachWindow() const override; protected: void doGeometryUpdate() override; void doActivate() override; void doDeactivate() override; void doStartApproaching() override; void doStopApproaching() override; void doUpdateBlocking() override; private: void createWindow(); void createApproachWindow(); Xcb::Window m_window; Xcb::Window m_approachWindow; QMetaObject::Connection m_cursorPollingConnection; }; inline quint32 WindowBasedEdge::window() const { return m_window; } inline quint32 WindowBasedEdge::approachWindow() const { return m_approachWindow; } } #endif diff --git a/plugins/platforms/x11/standalone/glxbackend.h b/plugins/platforms/x11/standalone/glxbackend.h index 97017d7d0..2d62e997e 100644 --- a/plugins/platforms/x11/standalone/glxbackend.h +++ b/plugins/platforms/x11/standalone/glxbackend.h @@ -1,150 +1,150 @@ /******************************************************************** 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_GLX_BACKEND_H #define KWIN_GLX_BACKEND_H #include "backend.h" #include "texture.h" #include "swap_profiler.h" #include "x11eventfilter.h" #include #include #include #include namespace KWin { // GLX_MESA_swap_interval using glXSwapIntervalMESA_func = int (*)(unsigned int interval); extern glXSwapIntervalMESA_func glXSwapIntervalMESA; class FBConfigInfo { public: GLXFBConfig fbconfig; int bind_texture_format; int texture_targets; int y_inverted; int mipmap; }; // ------------------------------------------------------------------ class SwapEventFilter : public X11EventFilter { public: SwapEventFilter(xcb_drawable_t drawable, xcb_glx_drawable_t glxDrawable); bool event(xcb_generic_event_t *event) override; private: xcb_drawable_t m_drawable; xcb_glx_drawable_t m_glxDrawable; }; /** * @brief OpenGL Backend using GLX over an X overlay window. - **/ + */ class GlxBackend : public OpenGLBackend { public: GlxBackend(Display *display); ~GlxBackend() override; void screenGeometryChanged(const QSize &size) override; SceneOpenGLTexturePrivate *createBackendTexture(SceneOpenGLTexture *texture) override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &damage, const QRegion &damagedRegion) override; bool makeCurrent() override; void doneCurrent() override; OverlayWindow* overlayWindow() override; bool usesOverlayWindow() const override; void init() override; protected: void present() override; private: bool initBuffer(); bool checkVersion(); void initExtensions(); void waitSync(); bool initRenderingContext(); bool initFbConfig(); void initVisualDepthHashTable(); void setSwapInterval(int interval); Display *display() const { return m_x11Display; } int visualDepth(xcb_visualid_t visual) const; FBConfigInfo *infoForVisual(xcb_visualid_t visual); /** * @brief The OverlayWindow used by this Backend. - **/ + */ OverlayWindow *m_overlayWindow; Window window; GLXFBConfig fbconfig; GLXWindow glxWindow; GLXContext ctx; QHash m_fbconfigHash; QHash m_visualDepthHash; std::unique_ptr m_swapEventFilter; int m_bufferAge; bool m_haveMESACopySubBuffer = false; bool m_haveMESASwapControl = false; bool m_haveEXTSwapControl = false; bool m_haveSGISwapControl = false; bool m_haveINTELSwapEvent = false; bool haveSwapInterval = false; bool haveWaitSync = false; Display *m_x11Display; SwapProfiler m_swapProfiler; friend class GlxTexture; }; /** * @brief Texture using an GLXPixmap. - **/ + */ class GlxTexture : public SceneOpenGLTexturePrivate { public: ~GlxTexture() override; void onDamage() override; bool loadTexture(WindowPixmap *pixmap) override; OpenGLBackend *backend() override; private: friend class GlxBackend; GlxTexture(SceneOpenGLTexture *texture, GlxBackend *backend); bool loadTexture(xcb_pixmap_t pix, const QSize &size, xcb_visualid_t visual); Display *display() const { return m_backend->m_x11Display; } SceneOpenGLTexture *q; GlxBackend *m_backend; GLXPixmap m_glxpixmap; // the glx pixmap the texture is bound to }; } // namespace #endif // KWIN_GLX_BACKEND_H diff --git a/plugins/platforms/x11/standalone/x11_output.h b/plugins/platforms/x11/standalone/x11_output.h index 71240041c..bb6ac6fbe 100644 --- a/plugins/platforms/x11/standalone/x11_output.h +++ b/plugins/platforms/x11/standalone/x11_output.h @@ -1,80 +1,80 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_X11_OUTPUT_H #define KWIN_X11_OUTPUT_H #include "abstract_output.h" #include #include #include #include namespace KWin { /** * X11 output representation - **/ + */ class KWIN_EXPORT X11Output : public AbstractOutput { Q_OBJECT public: explicit X11Output(QObject *parent = nullptr); ~X11Output() override = default; QString name() const override; void setName(QString set); /** * The geometry of this output in global compositor co-ordinates (i.e scaled) - **/ + */ QRect geometry() const override; void setGeometry(QRect set); /** * Current refresh rate in 1/ms. - **/ + */ int refreshRate() const override; void setRefreshRate(int set); /** * The size of gamma lookup table. - **/ + */ int gammaRampSize() const override; bool setGammaRamp(const GammaRamp &gamma) override; private: void setCrtc(xcb_randr_crtc_t crtc); void setGammaRampSize(int size); xcb_randr_crtc_t m_crtc = XCB_NONE; QString m_name; QRect m_geometry; int m_gammaRampSize; int m_refreshRate; friend class X11StandalonePlatform; }; } #endif diff --git a/plugins/platforms/x11/standalone/x11_platform.h b/plugins/platforms/x11/standalone/x11_platform.h index 56b4fcb58..ac6fff0ac 100644 --- a/plugins/platforms/x11/standalone/x11_platform.h +++ b/plugins/platforms/x11/standalone/x11_platform.h @@ -1,113 +1,113 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2016 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_X11_PLATFORM_H #define KWIN_X11_PLATFORM_H #include "platform.h" #include #include #include namespace KWin { class SyncFilter; class XInputIntegration; class WindowSelector; class X11EventFilter; class X11Output; class KWIN_EXPORT X11StandalonePlatform : public Platform { Q_OBJECT Q_INTERFACES(KWin::Platform) Q_PLUGIN_METADATA(IID "org.kde.kwin.Platform" FILE "x11.json") public: X11StandalonePlatform(QObject *parent = nullptr); ~X11StandalonePlatform() override; void init() override; Screens *createScreens(QObject *parent = nullptr) override; OpenGLBackend *createOpenGLBackend() override; Edge *createScreenEdge(ScreenEdges *parent) override; void createPlatformCursor(QObject *parent = nullptr) override; bool requiresCompositing() const override; bool compositingPossible() const override; QString compositingNotPossibleReason() const override; bool openGLCompositingIsBroken() const override; void createOpenGLSafePoint(OpenGLSafePoint safePoint) override; void startInteractiveWindowSelection(std::function callback, const QByteArray &cursorName = QByteArray()) override; void startInteractivePositionSelection(std::function callback) override; PlatformCursorImage cursorImage() const override; void setupActionForGlobalAccel(QAction *action) override; OverlayWindow *createOverlayWindow() override; void updateXTime() override; OutlineVisual *createOutline(Outline *outline) override; Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *client) override; void invertScreen() override; void createEffectsHandler(Compositor *compositor, Scene *scene) override; QVector supportedCompositors() const override; void initOutputs(); void updateOutputs(); Outputs outputs() const override; Outputs enabledOutputs() const override; protected: void doHideCursor() override; void doShowCursor() override; private: /** * Tests whether GLX is supported and returns @c true * in case KWin is compiled with OpenGL support and GLX * is available. * * If KWin is compiled with OpenGL ES or without OpenGL at * all, @c false is returned. * @returns @c true if GLX is available, @c false otherwise and if not build with OpenGL support. - **/ + */ static bool hasGlx(); template void doUpdateOutputs(); XInputIntegration *m_xinputIntegration = nullptr; QThread *m_openGLFreezeProtectionThread = nullptr; QTimer *m_openGLFreezeProtection = nullptr; Display *m_x11Display; QScopedPointer m_windowSelector; QScopedPointer m_screenEdgesFilter; std::unique_ptr m_syncFilter; QVector m_outputs; }; } #endif diff --git a/plugins/platforms/x11/standalone/x11cursor.h b/plugins/platforms/x11/standalone/x11cursor.h index 7aabc264a..6ed5cfae3 100644 --- a/plugins/platforms/x11/standalone/x11cursor.h +++ b/plugins/platforms/x11/standalone/x11cursor.h @@ -1,85 +1,85 @@ /******************************************************************** 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_X11CURSOR_H #define KWIN_X11CURSOR_H #include "cursor.h" #include namespace KWin { class XFixesCursorEventFilter; class KWIN_EXPORT X11Cursor : public Cursor { Q_OBJECT public: X11Cursor(QObject *parent, bool xInputSupport = false); ~X11Cursor() override; void schedulePoll() { m_needsPoll = true; } /** * @internal * * Called from X11 event handler. - **/ + */ void notifyCursorChanged(); protected: xcb_cursor_t getX11Cursor(CursorShape shape) override; xcb_cursor_t getX11Cursor(const QByteArray &name) override; void doSetPos() override; void doGetPos() override; void doStartMousePolling() override; void doStopMousePolling() override; void doStartCursorTracking() override; void doStopCursorTracking() override; private Q_SLOTS: /** * Because of QTimer's and the impossibility to get events for all mouse * movements (at least I haven't figured out how) the position needs * to be also refetched after each return to the event loop. - **/ + */ void resetTimeStamp(); void mousePolled(); void aboutToBlock(); private: xcb_cursor_t createCursor(const QByteArray &name); QHash m_cursors; xcb_timestamp_t m_timeStamp; uint16_t m_buttonMask; QTimer *m_resetTimeStampTimer; QTimer *m_mousePollingTimer; bool m_hasXInput; bool m_needsPoll; std::unique_ptr m_xfixesFilter; friend class Cursor; }; } #endif diff --git a/plugins/platforms/x11/windowed/egl_x11_backend.h b/plugins/platforms/x11/windowed/egl_x11_backend.h index e9d18f39d..dc31bdadd 100644 --- a/plugins/platforms/x11/windowed/egl_x11_backend.h +++ b/plugins/platforms/x11/windowed/egl_x11_backend.h @@ -1,57 +1,57 @@ /******************************************************************** 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_EGL_X11_BACKEND_H #define KWIN_EGL_X11_BACKEND_H #include "eglonxbackend.h" namespace KWin { class X11WindowedBackend; /** * @brief OpenGL Backend using Egl windowing system over an X overlay window. - **/ + */ class EglX11Backend : public EglOnXBackend { public: explicit EglX11Backend(X11WindowedBackend *backend); ~EglX11Backend() override; QRegion prepareRenderingFrame() override; void endRenderingFrame(const QRegion &damage, const QRegion &damagedRegion) override; bool usesOverlayWindow() const override; bool perScreenRendering() const override; QRegion prepareRenderingForScreen(int screenId) override; void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion) override; protected: void present() override; void cleanupSurfaces() override; bool createSurfaces() override; private: void setupViewport(int screenId); QVector m_surfaces; X11WindowedBackend *m_backend; }; } // namespace #endif diff --git a/plugins/platforms/x11/windowed/x11windowed_output.h b/plugins/platforms/x11/windowed/x11windowed_output.h index 893b1882d..65ca9b7e9 100644 --- a/plugins/platforms/x11/windowed/x11windowed_output.h +++ b/plugins/platforms/x11/windowed/x11windowed_output.h @@ -1,85 +1,85 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_X11WINDOWED_OUTPUT_H #define KWIN_X11WINDOWED_OUTPUT_H #include "abstract_wayland_output.h" #include #include #include #include #include class NETWinInfo; namespace KWin { class X11WindowedBackend; /** * Wayland outputs in a nested X11 setup - **/ + */ class KWIN_EXPORT X11WindowedOutput : public AbstractWaylandOutput { Q_OBJECT public: explicit X11WindowedOutput(X11WindowedBackend *backend); ~X11WindowedOutput() override; void init(); xcb_window_t window() const { return m_window; } QPoint internalPosition() const; QPoint hostPosition() const { return m_hostPosition; } void setHostPosition(const QPoint &pos); void setWindowTitle(const QString &title); QSize pixelSize() const override; /** * @brief defines the geometry of the output * @param logicalPosition top left position of the output in compositor space * @param pixelSize output size as seen from the outside */ void setGeometry(const QPoint &logicalPosition, const QSize &pixelSize); private: void initXInputForWindow(); xcb_window_t m_window = XCB_WINDOW_NONE; NETWinInfo *m_winInfo = nullptr; QPoint m_hostPosition; QSize m_pixelSize; X11WindowedBackend *m_backend; }; } #endif diff --git a/plugins/scenes/opengl/scene_opengl.cpp b/plugins/scenes/opengl/scene_opengl.cpp index 967fb1749..83087e0a2 100644 --- a/plugins/scenes/opengl/scene_opengl.cpp +++ b/plugins/scenes/opengl/scene_opengl.cpp @@ -1,2574 +1,2574 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 2010, 2011 Martin Gräßlin Based on glcompmgr code by Felix Bellaby. Using code from Compiz and Beryl. Explicit command stream synchronization based on the sample implementation by James Jones , Copyright © 2011 NVIDIA Corporation 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 . *********************************************************************/ #include "scene_opengl.h" #include "platform.h" #include "wayland_server.h" #include "platformsupport/scenes/opengl/texture.h" #include #include "utils.h" #include "client.h" #include "composite.h" #include "deleted.h" #include "effects.h" #include "lanczosfilter.h" #include "main.h" #include "overlaywindow.h" #include "screens.h" #include "cursor.h" #include "decorations/decoratedclient.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // HACK: workaround for libepoxy < 1.3 #ifndef GL_GUILTY_CONTEXT_RESET #define GL_GUILTY_CONTEXT_RESET 0x8253 #endif #ifndef GL_INNOCENT_CONTEXT_RESET #define GL_INNOCENT_CONTEXT_RESET 0x8254 #endif #ifndef GL_UNKNOWN_CONTEXT_RESET #define GL_UNKNOWN_CONTEXT_RESET 0x8255 #endif namespace KWin { extern int currentRefreshRate(); /** * SyncObject represents a fence used to synchronize operations in * the kwin command stream with operations in the X command stream. - **/ + */ class SyncObject { public: enum State { Ready, TriggerSent, Waiting, Done, Resetting }; SyncObject(); ~SyncObject(); State state() const { return m_state; } void trigger(); void wait(); bool finish(); void reset(); void finishResetting(); private: State m_state; GLsync m_sync; xcb_sync_fence_t m_fence; xcb_get_input_focus_cookie_t m_reset_cookie; }; SyncObject::SyncObject() { m_state = Ready; xcb_connection_t * const c = connection(); m_fence = xcb_generate_id(c); xcb_sync_create_fence(c, rootWindow(), m_fence, false); xcb_flush(c); m_sync = glImportSyncEXT(GL_SYNC_X11_FENCE_EXT, m_fence, 0); } SyncObject::~SyncObject() { // If glDeleteSync is called before the xcb fence is signalled // the nvidia driver (the only one to implement GL_SYNC_X11_FENCE_EXT) // deadlocks waiting for the fence to be signalled. // To avoid this, make sure the fence is signalled before // deleting the sync. if (m_state == Resetting || m_state == Ready){ trigger(); // The flush is necessary! // The trigger command needs to be sent to the X server. xcb_flush(connection()); } xcb_sync_destroy_fence(connection(), m_fence); glDeleteSync(m_sync); if (m_state == Resetting) xcb_discard_reply(connection(), m_reset_cookie.sequence); } void SyncObject::trigger() { assert(m_state == Ready || m_state == Resetting); // Finish resetting the fence if necessary if (m_state == Resetting) finishResetting(); xcb_sync_trigger_fence(connection(), m_fence); m_state = TriggerSent; } void SyncObject::wait() { if (m_state != TriggerSent) return; glWaitSync(m_sync, 0, GL_TIMEOUT_IGNORED); m_state = Waiting; } bool SyncObject::finish() { if (m_state == Done) return true; // Note: It is possible that we never inserted a wait for the fence. // This can happen if we ended up not rendering the damaged // window because it is fully occluded. assert(m_state == TriggerSent || m_state == Waiting); // Check if the fence is signaled GLint value; glGetSynciv(m_sync, GL_SYNC_STATUS, 1, nullptr, &value); if (value != GL_SIGNALED) { qCDebug(KWIN_OPENGL) << "Waiting for X fence to finish"; // Wait for the fence to become signaled with a one second timeout const GLenum result = glClientWaitSync(m_sync, 0, 1000000000); switch (result) { case GL_TIMEOUT_EXPIRED: qCWarning(KWIN_OPENGL) << "Timeout while waiting for X fence"; return false; case GL_WAIT_FAILED: qCWarning(KWIN_OPENGL) << "glClientWaitSync() failed"; return false; } } m_state = Done; return true; } void SyncObject::reset() { assert(m_state == Done); xcb_connection_t * const c = connection(); // Send the reset request along with a sync request. // We use the cookie to ensure that the server has processed the reset // request before we trigger the fence and call glWaitSync(). // Otherwise there is a race condition between the reset finishing and // the glWaitSync() call. xcb_sync_reset_fence(c, m_fence); m_reset_cookie = xcb_get_input_focus(c); xcb_flush(c); m_state = Resetting; } void SyncObject::finishResetting() { assert(m_state == Resetting); free(xcb_get_input_focus_reply(connection(), m_reset_cookie, nullptr)); m_state = Ready; } // ----------------------------------------------------------------------- /** * SyncManager manages a set of fences used for explicit synchronization * with the X command stream. - **/ + */ class SyncManager { public: enum { MaxFences = 4 }; SyncManager(); ~SyncManager(); SyncObject *nextFence(); bool updateFences(); private: std::array m_fences; int m_next; }; SyncManager::SyncManager() : m_next(0) { } SyncManager::~SyncManager() { } SyncObject *SyncManager::nextFence() { SyncObject *fence = &m_fences[m_next]; m_next = (m_next + 1) % MaxFences; return fence; } bool SyncManager::updateFences() { for (int i = 0; i < qMin(2, MaxFences - 1); i++) { const int index = (m_next + i) % MaxFences; SyncObject &fence = m_fences[index]; switch (fence.state()) { case SyncObject::Ready: break; case SyncObject::TriggerSent: case SyncObject::Waiting: if (!fence.finish()) return false; fence.reset(); break; // Should not happen in practice since we always reset the fence // after finishing it case SyncObject::Done: fence.reset(); break; case SyncObject::Resetting: fence.finishResetting(); break; } } return true; } // ----------------------------------------------------------------------- /************************************************ * SceneOpenGL ***********************************************/ SceneOpenGL::SceneOpenGL(OpenGLBackend *backend, QObject *parent) : Scene(parent) , init_ok(true) , m_backend(backend) , m_syncManager(nullptr) , m_currentFence(nullptr) { if (m_backend->isFailed()) { init_ok = false; return; } if (!viewportLimitsMatched(screens()->size())) return; // perform Scene specific checks GLPlatform *glPlatform = GLPlatform::instance(); if (!glPlatform->isGLES() && !hasGLExtension(QByteArrayLiteral("GL_ARB_texture_non_power_of_two")) && !hasGLExtension(QByteArrayLiteral("GL_ARB_texture_rectangle"))) { qCCritical(KWIN_OPENGL) << "GL_ARB_texture_non_power_of_two and GL_ARB_texture_rectangle missing"; init_ok = false; return; // error } if (glPlatform->isMesaDriver() && glPlatform->mesaVersion() < kVersionNumber(10, 0)) { qCCritical(KWIN_OPENGL) << "KWin requires at least Mesa 10.0 for OpenGL compositing."; init_ok = false; return; } if (!glPlatform->isGLES() && !m_backend->isSurfaceLessContext()) { glDrawBuffer(GL_BACK); } m_debug = qstrcmp(qgetenv("KWIN_GL_DEBUG"), "1") == 0; initDebugOutput(); // set strict binding if (options->isGlStrictBindingFollowsDriver()) { options->setGlStrictBinding(!glPlatform->supports(LooseBinding)); } bool haveSyncObjects = glPlatform->isGLES() ? hasGLVersion(3, 0) : hasGLVersion(3, 2) || hasGLExtension("GL_ARB_sync"); if (hasGLExtension("GL_EXT_x11_sync_object") && haveSyncObjects && kwinApp()->operationMode() == Application::OperationModeX11) { const QByteArray useExplicitSync = qgetenv("KWIN_EXPLICIT_SYNC"); if (useExplicitSync != "0") { qCDebug(KWIN_OPENGL) << "Initializing fences for synchronization with the X command stream"; m_syncManager = new SyncManager; } else { qCDebug(KWIN_OPENGL) << "Explicit synchronization with the X command stream disabled by environment variable"; } } } static SceneOpenGL *gs_debuggedScene = nullptr; SceneOpenGL::~SceneOpenGL() { // do cleanup after initBuffer() gs_debuggedScene = nullptr; if (init_ok) { makeOpenGLContextCurrent(); } SceneOpenGL::EffectFrame::cleanup(); delete m_syncManager; // backend might be still needed for a different scene delete m_backend; } static void scheduleVboReInit() { if (!gs_debuggedScene) return; static QPointer timer; if (!timer) { delete timer; timer = new QTimer(gs_debuggedScene); timer->setSingleShot(true); QObject::connect(timer.data(), &QTimer::timeout, gs_debuggedScene, []() { GLVertexBuffer::cleanup(); GLVertexBuffer::initStatic(); }); } timer->start(250); } void SceneOpenGL::initDebugOutput() { const bool have_KHR_debug = hasGLExtension(QByteArrayLiteral("GL_KHR_debug")); const bool have_ARB_debug = hasGLExtension(QByteArrayLiteral("GL_ARB_debug_output")); if (!have_KHR_debug && !have_ARB_debug) return; if (!have_ARB_debug) { // if we don't have ARB debug, but only KHR debug we need to verify whether the context is a debug context // it should work without as well, but empirical tests show: no it doesn't if (GLPlatform::instance()->isGLES()) { if (!hasGLVersion(3, 2)) { // empirical data shows extension doesn't work return; } } else if (!hasGLVersion(3, 0)) { return; } // can only be queried with either OpenGL >= 3.0 or OpenGL ES of at least 3.1 GLint value = 0; glGetIntegerv(GL_CONTEXT_FLAGS, &value); if (!(value & GL_CONTEXT_FLAG_DEBUG_BIT)) { return; } } gs_debuggedScene = this; // Set the callback function auto callback = [](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *userParam) { Q_UNUSED(source) Q_UNUSED(severity) Q_UNUSED(userParam) while (message[length] == '\n' || message[length] == '\r') --length; switch (type) { case GL_DEBUG_TYPE_ERROR: case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: qCWarning(KWIN_OPENGL, "%#x: %.*s", id, length, message); break; case GL_DEBUG_TYPE_OTHER: // at least the nvidia driver seems prone to end up with invalid VBOs after // transferring them between system heap and VRAM // so we re-init them whenever this happens (typically when switching VT, resuming // from STR and XRandR events - #344326 if (strstr(message, "Buffer detailed info:") && strstr(message, "has been updated")) scheduleVboReInit(); // fall through! for general message printing Q_FALLTHROUGH(); case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: case GL_DEBUG_TYPE_PORTABILITY: case GL_DEBUG_TYPE_PERFORMANCE: default: qCDebug(KWIN_OPENGL, "%#x: %.*s", id, length, message); break; } }; glDebugMessageCallback(callback, nullptr); // This state exists only in GL_KHR_debug if (have_KHR_debug) glEnable(GL_DEBUG_OUTPUT); #ifndef NDEBUG // Enable all debug messages glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); #else // Enable error messages glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE); glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE); #endif // Insert a test message const QByteArray message = QByteArrayLiteral("OpenGL debug output initialized"); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0, GL_DEBUG_SEVERITY_LOW, message.length(), message.constData()); } SceneOpenGL *SceneOpenGL::createScene(QObject *parent) { OpenGLBackend *backend = kwinApp()->platform()->createOpenGLBackend(); if (!backend) { return nullptr; } if (!backend->isFailed()) { backend->init(); } if (backend->isFailed()) { delete backend; return NULL; } SceneOpenGL *scene = NULL; // first let's try an OpenGL 2 scene if (SceneOpenGL2::supported(backend)) { scene = new SceneOpenGL2(backend, parent); if (scene->initFailed()) { delete scene; scene = NULL; } else { return scene; } } if (!scene) { if (GLPlatform::instance()->recommendedCompositor() == XRenderCompositing) { qCCritical(KWIN_OPENGL) << "OpenGL driver recommends XRender based compositing. Falling back to XRender."; qCCritical(KWIN_OPENGL) << "To overwrite the detection use the environment variable KWIN_COMPOSE"; qCCritical(KWIN_OPENGL) << "For more information see https://community.kde.org/KWin/Environment_Variables#KWIN_COMPOSE"; } delete backend; } return scene; } OverlayWindow *SceneOpenGL::overlayWindow() { return m_backend->overlayWindow(); } bool SceneOpenGL::syncsToVBlank() const { return m_backend->syncsToVBlank(); } bool SceneOpenGL::blocksForRetrace() const { return m_backend->blocksForRetrace(); } void SceneOpenGL::idle() { m_backend->idle(); Scene::idle(); } bool SceneOpenGL::initFailed() const { return !init_ok; } void SceneOpenGL::handleGraphicsReset(GLenum status) { switch (status) { case GL_GUILTY_CONTEXT_RESET: qCDebug(KWIN_OPENGL) << "A graphics reset attributable to the current GL context occurred."; break; case GL_INNOCENT_CONTEXT_RESET: qCDebug(KWIN_OPENGL) << "A graphics reset not attributable to the current GL context occurred."; break; case GL_UNKNOWN_CONTEXT_RESET: qCDebug(KWIN_OPENGL) << "A graphics reset of an unknown cause occurred."; break; default: break; } QElapsedTimer timer; timer.start(); // Wait until the reset is completed or max 10 seconds while (timer.elapsed() < 10000 && glGetGraphicsResetStatus() != GL_NO_ERROR) usleep(50); qCDebug(KWIN_OPENGL) << "Attempting to reset compositing."; QMetaObject::invokeMethod(this, "resetCompositing", Qt::QueuedConnection); KNotification::event(QStringLiteral("graphicsreset"), i18n("Desktop effects were restarted due to a graphics reset")); } void SceneOpenGL::triggerFence() { if (m_syncManager) { m_currentFence = m_syncManager->nextFence(); m_currentFence->trigger(); } } void SceneOpenGL::insertWait() { if (m_currentFence && m_currentFence->state() != SyncObject::Waiting) { m_currentFence->wait(); } } /** * Render cursor texture in case hardware cursor is disabled. * Useful for screen recording apps or backends that can't do planes. - **/ + */ void SceneOpenGL2::paintCursor() { // don't paint if we use hardware cursor or the cursor is hidden if (!kwinApp()->platform()->usesSoftwareCursor() || kwinApp()->platform()->isCursorHidden() || kwinApp()->platform()->softwareCursor().isNull()) { return; } // lazy init texture cursor only in case we need software rendering if (!m_cursorTexture) { auto updateCursorTexture = [this] { // don't paint if no image for cursor is set const QImage img = kwinApp()->platform()->softwareCursor(); if (img.isNull()) { return; } m_cursorTexture.reset(new GLTexture(img)); }; // init now updateCursorTexture(); // handle shape update on case cursor image changed connect(kwinApp()->platform(), &Platform::cursorChanged, this, updateCursorTexture); } // get cursor position in projection coordinates const QPoint cursorPos = Cursor::pos() - kwinApp()->platform()->softwareCursorHotspot(); const QRect cursorRect(0, 0, m_cursorTexture->width(), m_cursorTexture->height()); QMatrix4x4 mvp = m_projectionMatrix; mvp.translate(cursorPos.x(), cursorPos.y()); // handle transparence glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // paint texture in cursor offset m_cursorTexture->bind(); ShaderBinder binder(ShaderTrait::MapTexture); binder.shader()->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_cursorTexture->render(QRegion(cursorRect), cursorRect); m_cursorTexture->unbind(); kwinApp()->platform()->markCursorAsRendered(); glDisable(GL_BLEND); } qint64 SceneOpenGL::paint(QRegion damage, ToplevelList toplevels) { // actually paint the frame, flushed with the NEXT frame createStackingOrder(toplevels); // After this call, updateRegion will contain the damaged region in the // back buffer. This is the region that needs to be posted to repair // the front buffer. It doesn't include the additional damage returned // by prepareRenderingFrame(). validRegion is the region that has been // repainted, and may be larger than updateRegion. QRegion updateRegion, validRegion; if (m_backend->perScreenRendering()) { // trigger start render timer m_backend->prepareRenderingFrame(); for (int i = 0; i < screens()->count(); ++i) { const QRect &geo = screens()->geometry(i); QRegion update; QRegion valid; // prepare rendering makes context current on the output QRegion repaint = m_backend->prepareRenderingForScreen(i); GLVertexBuffer::setVirtualScreenGeometry(geo); GLRenderTarget::setVirtualScreenGeometry(geo); GLVertexBuffer::setVirtualScreenScale(screens()->scale(i)); GLRenderTarget::setVirtualScreenScale(screens()->scale(i)); const GLenum status = glGetGraphicsResetStatus(); if (status != GL_NO_ERROR) { handleGraphicsReset(status); return 0; } int mask = 0; updateProjectionMatrix(); paintScreen(&mask, damage.intersected(geo), repaint, &update, &valid, projectionMatrix(), geo); // call generic implementation paintCursor(); GLVertexBuffer::streamingBuffer()->endOfFrame(); m_backend->endRenderingFrameForScreen(i, valid, update); GLVertexBuffer::streamingBuffer()->framePosted(); } } else { m_backend->makeCurrent(); QRegion repaint = m_backend->prepareRenderingFrame(); const GLenum status = glGetGraphicsResetStatus(); if (status != GL_NO_ERROR) { handleGraphicsReset(status); return 0; } GLVertexBuffer::setVirtualScreenGeometry(screens()->geometry()); GLRenderTarget::setVirtualScreenGeometry(screens()->geometry()); GLVertexBuffer::setVirtualScreenScale(1); GLRenderTarget::setVirtualScreenScale(1); int mask = 0; updateProjectionMatrix(); paintScreen(&mask, damage, repaint, &updateRegion, &validRegion, projectionMatrix()); // call generic implementation if (!GLPlatform::instance()->isGLES()) { const QSize &screenSize = screens()->size(); const QRegion displayRegion(0, 0, screenSize.width(), screenSize.height()); // copy dirty parts from front to backbuffer if (!m_backend->supportsBufferAge() && options->glPreferBufferSwap() == Options::CopyFrontBuffer && validRegion != displayRegion) { glReadBuffer(GL_FRONT); m_backend->copyPixels(displayRegion - validRegion); glReadBuffer(GL_BACK); validRegion = displayRegion; } } GLVertexBuffer::streamingBuffer()->endOfFrame(); m_backend->endRenderingFrame(validRegion, updateRegion); GLVertexBuffer::streamingBuffer()->framePosted(); } if (m_currentFence) { if (!m_syncManager->updateFences()) { qCDebug(KWIN_OPENGL) << "Aborting explicit synchronization with the X command stream."; qCDebug(KWIN_OPENGL) << "Future frames will be rendered unsynchronized."; delete m_syncManager; m_syncManager = nullptr; } m_currentFence = nullptr; } // do cleanup clearStackingOrder(); return m_backend->renderTime(); } QMatrix4x4 SceneOpenGL::transformation(int mask, const ScreenPaintData &data) const { QMatrix4x4 matrix; if (!(mask & PAINT_SCREEN_TRANSFORMED)) return matrix; matrix.translate(data.translation()); data.scale().applyTo(&matrix); if (data.rotationAngle() == 0.0) return matrix; // Apply the rotation // cannot use data.rotation->applyTo(&matrix) as QGraphicsRotation uses projectedRotate to map back to 2D matrix.translate(data.rotationOrigin()); const QVector3D axis = data.rotationAxis(); matrix.rotate(data.rotationAngle(), axis.x(), axis.y(), axis.z()); matrix.translate(-data.rotationOrigin()); return matrix; } void SceneOpenGL::paintBackground(QRegion region) { PaintClipper pc(region); if (!PaintClipper::clip()) { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); return; } if (pc.clip() && pc.paintArea().isEmpty()) return; // no background to paint QVector verts; for (PaintClipper::Iterator iterator; !iterator.isDone(); iterator.next()) { QRect r = iterator.boundingRect(); verts << r.x() + r.width() << r.y(); verts << r.x() << r.y(); verts << r.x() << r.y() + r.height(); verts << r.x() << r.y() + r.height(); verts << r.x() + r.width() << r.y() + r.height(); verts << r.x() + r.width() << r.y(); } doPaintBackground(verts); } void SceneOpenGL::extendPaintRegion(QRegion ®ion, bool opaqueFullscreen) { if (m_backend->supportsBufferAge()) return; const QSize &screenSize = screens()->size(); if (options->glPreferBufferSwap() == Options::ExtendDamage) { // only Extend "large" repaints const QRegion displayRegion(0, 0, screenSize.width(), screenSize.height()); uint damagedPixels = 0; const uint fullRepaintLimit = (opaqueFullscreen?0.49f:0.748f)*screenSize.width()*screenSize.height(); // 16:9 is 75% of 4:3 and 2.55:1 is 49.01% of 5:4 // (5:4 is the most square format and 2.55:1 is Cinemascope55 - the widest ever shot // movie aspect - two times ;-) It's a Fox format, though, so maybe we want to restrict // to 2.20:1 - Panavision - which has actually been used for interesting movies ...) // would be 57% of 5/4 for (const QRect &r : region) { // damagedPixels += r.width() * r.height(); // combined window damage test damagedPixels = r.width() * r.height(); // experimental single window damage testing if (damagedPixels > fullRepaintLimit) { region = displayRegion; return; } } } else if (options->glPreferBufferSwap() == Options::PaintFullScreen) { // forced full rePaint region = QRegion(0, 0, screenSize.width(), screenSize.height()); } } SceneOpenGLTexture *SceneOpenGL::createTexture() { return new SceneOpenGLTexture(m_backend); } bool SceneOpenGL::viewportLimitsMatched(const QSize &size) const { GLint limit[2]; glGetIntegerv(GL_MAX_VIEWPORT_DIMS, limit); if (limit[0] < size.width() || limit[1] < size.height()) { QMetaObject::invokeMethod(Compositor::self(), "suspend", Qt::QueuedConnection, Q_ARG(Compositor::SuspendReason, Compositor::AllReasonSuspend)); return false; } return true; } void SceneOpenGL::screenGeometryChanged(const QSize &size) { if (!viewportLimitsMatched(size)) return; Scene::screenGeometryChanged(size); glViewport(0,0, size.width(), size.height()); m_backend->screenGeometryChanged(size); GLRenderTarget::setVirtualScreenSize(size); } void SceneOpenGL::paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data) { const QRect r = region.boundingRect(); glEnable(GL_SCISSOR_TEST); glScissor(r.x(), screens()->size().height() - r.y() - r.height(), r.width(), r.height()); KWin::Scene::paintDesktop(desktop, mask, region, data); glDisable(GL_SCISSOR_TEST); } bool SceneOpenGL::makeOpenGLContextCurrent() { return m_backend->makeCurrent(); } void SceneOpenGL::doneOpenGLContextCurrent() { m_backend->doneCurrent(); } Scene::EffectFrame *SceneOpenGL::createEffectFrame(EffectFrameImpl *frame) { return new SceneOpenGL::EffectFrame(frame, this); } Shadow *SceneOpenGL::createShadow(Toplevel *toplevel) { return new SceneOpenGLShadow(toplevel); } Decoration::Renderer *SceneOpenGL::createDecorationRenderer(Decoration::DecoratedClientImpl *impl) { return new SceneOpenGLDecorationRenderer(impl); } bool SceneOpenGL::animationsSupported() const { return !GLPlatform::instance()->isSoftwareEmulation(); } QVector SceneOpenGL::openGLPlatformInterfaceExtensions() const { return m_backend->extensions().toVector(); } //**************************************** // SceneOpenGL2 //**************************************** bool SceneOpenGL2::supported(OpenGLBackend *backend) { const QByteArray forceEnv = qgetenv("KWIN_COMPOSE"); if (!forceEnv.isEmpty()) { if (qstrcmp(forceEnv, "O2") == 0 || qstrcmp(forceEnv, "O2ES") == 0) { qCDebug(KWIN_OPENGL) << "OpenGL 2 compositing enforced by environment variable"; return true; } else { // OpenGL 2 disabled by environment variable return false; } } if (!backend->isDirectRendering()) { return false; } if (GLPlatform::instance()->recommendedCompositor() < OpenGL2Compositing) { qCDebug(KWIN_OPENGL) << "Driver does not recommend OpenGL 2 compositing"; return false; } return true; } SceneOpenGL2::SceneOpenGL2(OpenGLBackend *backend, QObject *parent) : SceneOpenGL(backend, parent) , m_lanczosFilter(NULL) { if (!init_ok) { // base ctor already failed return; } // We only support the OpenGL 2+ shader API, not GL_ARB_shader_objects if (!hasGLVersion(2, 0)) { qCDebug(KWIN_OPENGL) << "OpenGL 2.0 is not supported"; init_ok = false; return; } const QSize &s = screens()->size(); GLRenderTarget::setVirtualScreenSize(s); GLRenderTarget::setVirtualScreenGeometry(screens()->geometry()); // push one shader on the stack so that one is always bound ShaderManager::instance()->pushShader(ShaderTrait::MapTexture); if (checkGLError("Init")) { qCCritical(KWIN_OPENGL) << "OpenGL 2 compositing setup failed"; init_ok = false; return; // error } // It is not legal to not have a vertex array object bound in a core context if (!GLPlatform::instance()->isGLES() && hasGLExtension(QByteArrayLiteral("GL_ARB_vertex_array_object"))) { glGenVertexArrays(1, &vao); glBindVertexArray(vao); } if (!ShaderManager::instance()->selfTest()) { qCCritical(KWIN_OPENGL) << "ShaderManager self test failed"; init_ok = false; return; } qCDebug(KWIN_OPENGL) << "OpenGL 2 compositing successfully initialized"; init_ok = true; } SceneOpenGL2::~SceneOpenGL2() { if (m_lanczosFilter) { makeOpenGLContextCurrent(); delete m_lanczosFilter; m_lanczosFilter = nullptr; } } QMatrix4x4 SceneOpenGL2::createProjectionMatrix() const { // Create a perspective projection with a 60° field-of-view, // and an aspect ratio of 1.0. const float fovY = 60.0f; const float aspect = 1.0f; const float zNear = 0.1f; const float zFar = 100.0f; const float yMax = zNear * std::tan(fovY * M_PI / 360.0f); const float yMin = -yMax; const float xMin = yMin * aspect; const float xMax = yMax * aspect; QMatrix4x4 projection; projection.frustum(xMin, xMax, yMin, yMax, zNear, zFar); // Create a second matrix that transforms screen coordinates // to world coordinates. const float scaleFactor = 1.1 * std::tan(fovY * M_PI / 360.0f) / yMax; const QSize size = screens()->size(); QMatrix4x4 matrix; matrix.translate(xMin * scaleFactor, yMax * scaleFactor, -1.1); matrix.scale( (xMax - xMin) * scaleFactor / size.width(), -(yMax - yMin) * scaleFactor / size.height(), 0.001); // Combine the matrices return projection * matrix; } void SceneOpenGL2::updateProjectionMatrix() { m_projectionMatrix = createProjectionMatrix(); } void SceneOpenGL2::paintSimpleScreen(int mask, QRegion region) { m_screenProjectionMatrix = m_projectionMatrix; Scene::paintSimpleScreen(mask, region); } void SceneOpenGL2::paintGenericScreen(int mask, ScreenPaintData data) { const QMatrix4x4 screenMatrix = transformation(mask, data); m_screenProjectionMatrix = m_projectionMatrix * screenMatrix; Scene::paintGenericScreen(mask, data); } void SceneOpenGL2::doPaintBackground(const QVector< float >& vertices) { GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setUseColor(true); vbo->setData(vertices.count() / 2, 2, vertices.data(), NULL); ShaderBinder binder(ShaderTrait::UniformColor); binder.shader()->setUniform(GLShader::ModelViewProjectionMatrix, m_projectionMatrix); vbo->render(GL_TRIANGLES); } Scene::Window *SceneOpenGL2::createWindow(Toplevel *t) { SceneOpenGL2Window *w = new SceneOpenGL2Window(t); w->setScene(this); return w; } void SceneOpenGL2::finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { if (waylandServer() && waylandServer()->isScreenLocked() && !w->window()->isLockScreen() && !w->window()->isInputMethod()) { return; } performPaintWindow(w, mask, region, data); } void SceneOpenGL2::performPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { if (mask & PAINT_WINDOW_LANCZOS) { if (!m_lanczosFilter) { m_lanczosFilter = new LanczosFilter(this); // reset the lanczos filter when the screen gets resized // it will get created next paint connect(screens(), &Screens::changed, this, [this]() { makeOpenGLContextCurrent(); delete m_lanczosFilter; m_lanczosFilter = NULL; }); } m_lanczosFilter->performPaint(w, mask, region, data); } else w->sceneWindow()->performPaint(mask, region, data); } //**************************************** // SceneOpenGL::Window //**************************************** SceneOpenGL::Window::Window(Toplevel* c) : Scene::Window(c) , m_scene(NULL) { } SceneOpenGL::Window::~Window() { } static SceneOpenGLTexture *s_frameTexture = NULL; // Bind the window pixmap to an OpenGL texture. bool SceneOpenGL::Window::bindTexture() { s_frameTexture = NULL; OpenGLWindowPixmap *pixmap = windowPixmap(); if (!pixmap) { return false; } s_frameTexture = pixmap->texture(); if (pixmap->isDiscarded()) { return !pixmap->texture()->isNull(); } if (!window()->damage().isEmpty()) m_scene->insertWait(); return pixmap->bind(); } QMatrix4x4 SceneOpenGL::Window::transformation(int mask, const WindowPaintData &data) const { QMatrix4x4 matrix; matrix.translate(x(), y()); if (!(mask & PAINT_WINDOW_TRANSFORMED)) return matrix; matrix.translate(data.translation()); data.scale().applyTo(&matrix); if (data.rotationAngle() == 0.0) return matrix; // Apply the rotation // cannot use data.rotation.applyTo(&matrix) as QGraphicsRotation uses projectedRotate to map back to 2D matrix.translate(data.rotationOrigin()); const QVector3D axis = data.rotationAxis(); matrix.rotate(data.rotationAngle(), axis.x(), axis.y(), axis.z()); matrix.translate(-data.rotationOrigin()); return matrix; } bool SceneOpenGL::Window::beginRenderWindow(int mask, const QRegion ®ion, WindowPaintData &data) { if (region.isEmpty()) return false; m_hardwareClipping = region != infiniteRegion() && (mask & PAINT_WINDOW_TRANSFORMED) && !(mask & PAINT_SCREEN_TRANSFORMED); if (region != infiniteRegion() && !m_hardwareClipping) { WindowQuadList quads; quads.reserve(data.quads.count()); const QRegion filterRegion = region.translated(-x(), -y()); // split all quads in bounding rect with the actual rects in the region foreach (const WindowQuad &quad, data.quads) { for (const QRect &r : filterRegion) { const QRectF rf(r); const QRectF quadRect(QPointF(quad.left(), quad.top()), QPointF(quad.right(), quad.bottom())); const QRectF &intersected = rf.intersected(quadRect); if (intersected.isValid()) { if (quadRect == intersected) { // case 1: completely contains, include and do not check other rects quads << quad; break; } // case 2: intersection quads << quad.makeSubQuad(intersected.left(), intersected.top(), intersected.right(), intersected.bottom()); } } } data.quads = quads; } if (data.quads.isEmpty()) return false; if (!bindTexture() || !s_frameTexture) { return false; } if (m_hardwareClipping) { glEnable(GL_SCISSOR_TEST); } // Update the texture filter if (options->glSmoothScale() != 0 && (mask & (PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_TRANSFORMED))) filter = ImageFilterGood; else filter = ImageFilterFast; s_frameTexture->setFilter(filter == ImageFilterGood ? GL_LINEAR : GL_NEAREST); const GLVertexAttrib attribs[] = { { VA_Position, 2, GL_FLOAT, offsetof(GLVertex2D, position) }, { VA_TexCoord, 2, GL_FLOAT, offsetof(GLVertex2D, texcoord) }, }; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setAttribLayout(attribs, 2, sizeof(GLVertex2D)); return true; } void SceneOpenGL::Window::endRenderWindow() { if (m_hardwareClipping) { glDisable(GL_SCISSOR_TEST); } } GLTexture *SceneOpenGL::Window::getDecorationTexture() const { if (AbstractClient *client = dynamic_cast(toplevel)) { if (client->noBorder()) { return nullptr; } if (!client->isDecorated()) { return nullptr; } if (SceneOpenGLDecorationRenderer *renderer = static_cast(client->decoratedClient()->renderer())) { renderer->render(); return renderer->texture(); } } else if (toplevel->isDeleted()) { Deleted *deleted = static_cast(toplevel); if (!deleted->wasClient() || deleted->noBorder()) { return nullptr; } if (const SceneOpenGLDecorationRenderer *renderer = static_cast(deleted->decorationRenderer())) { return renderer->texture(); } } return nullptr; } WindowPixmap* SceneOpenGL::Window::createWindowPixmap() { return new OpenGLWindowPixmap(this, m_scene); } //*************************************** // SceneOpenGL2Window //*************************************** SceneOpenGL2Window::SceneOpenGL2Window(Toplevel *c) : SceneOpenGL::Window(c) , m_blendingEnabled(false) { } SceneOpenGL2Window::~SceneOpenGL2Window() { } QVector4D SceneOpenGL2Window::modulate(float opacity, float brightness) const { const float a = opacity; const float rgb = opacity * brightness; return QVector4D(rgb, rgb, rgb, a); } void SceneOpenGL2Window::setBlendEnabled(bool enabled) { if (enabled && !m_blendingEnabled) glEnable(GL_BLEND); else if (!enabled && m_blendingEnabled) glDisable(GL_BLEND); m_blendingEnabled = enabled; } void SceneOpenGL2Window::setupLeafNodes(LeafNode *nodes, const WindowQuadList *quads, const WindowPaintData &data) { if (!quads[ShadowLeaf].isEmpty()) { nodes[ShadowLeaf].texture = static_cast(m_shadow)->shadowTexture(); nodes[ShadowLeaf].opacity = data.opacity(); nodes[ShadowLeaf].hasAlpha = true; nodes[ShadowLeaf].coordinateType = NormalizedCoordinates; } if (!quads[DecorationLeaf].isEmpty()) { nodes[DecorationLeaf].texture = getDecorationTexture(); nodes[DecorationLeaf].opacity = data.opacity(); nodes[DecorationLeaf].hasAlpha = true; nodes[DecorationLeaf].coordinateType = UnnormalizedCoordinates; } nodes[ContentLeaf].texture = s_frameTexture; nodes[ContentLeaf].hasAlpha = !isOpaque(); // TODO: ARGB crsoofading is atm. a hack, playing on opacities for two dumb SrcOver operations // Should be a shader if (data.crossFadeProgress() != 1.0 && (data.opacity() < 0.95 || toplevel->hasAlpha())) { const float opacity = 1.0 - data.crossFadeProgress(); nodes[ContentLeaf].opacity = data.opacity() * (1 - pow(opacity, 1.0f + 2.0f * data.opacity())); } else { nodes[ContentLeaf].opacity = data.opacity(); } nodes[ContentLeaf].coordinateType = UnnormalizedCoordinates; if (data.crossFadeProgress() != 1.0) { OpenGLWindowPixmap *previous = previousWindowPixmap(); nodes[PreviousContentLeaf].texture = previous ? previous->texture() : NULL; nodes[PreviousContentLeaf].hasAlpha = !isOpaque(); nodes[PreviousContentLeaf].opacity = data.opacity() * (1.0 - data.crossFadeProgress()); nodes[PreviousContentLeaf].coordinateType = NormalizedCoordinates; } } QMatrix4x4 SceneOpenGL2Window::modelViewProjectionMatrix(int mask, const WindowPaintData &data) const { SceneOpenGL2 *scene = static_cast(m_scene); const QMatrix4x4 pMatrix = data.projectionMatrix(); const QMatrix4x4 mvMatrix = data.modelViewMatrix(); // An effect may want to override the default projection matrix in some cases, // such as when it is rendering a window on a render target that doesn't have // the same dimensions as the default framebuffer. // // Note that the screen transformation is not applied here. if (!pMatrix.isIdentity()) return pMatrix * mvMatrix; // If an effect has specified a model-view matrix, we multiply that matrix // with the default projection matrix. If the effect hasn't specified a // model-view matrix, mvMatrix will be the identity matrix. if (mask & Scene::PAINT_SCREEN_TRANSFORMED) return scene->screenProjectionMatrix() * mvMatrix; return scene->projectionMatrix() * mvMatrix; } void SceneOpenGL2Window::renderSubSurface(GLShader *shader, const QMatrix4x4 &mvp, const QMatrix4x4 &windowMatrix, OpenGLWindowPixmap *pixmap, const QRegion ®ion, bool hardwareClipping) { QMatrix4x4 newWindowMatrix = windowMatrix; newWindowMatrix.translate(pixmap->subSurface()->position().x(), pixmap->subSurface()->position().y()); qreal scale = 1.0; if (pixmap->surface()) { scale = pixmap->surface()->scale(); } if (!pixmap->texture()->isNull()) { setBlendEnabled(pixmap->buffer() && pixmap->buffer()->hasAlphaChannel()); // render this texture shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp * newWindowMatrix); auto texture = pixmap->texture(); texture->bind(); texture->render(region, QRect(0, 0, texture->width() / scale, texture->height() / scale), hardwareClipping); texture->unbind(); } const auto &children = pixmap->children(); for (auto pixmap : children) { if (pixmap->subSurface().isNull() || pixmap->subSurface()->surface().isNull() || !pixmap->subSurface()->surface()->isMapped()) { continue; } renderSubSurface(shader, mvp, newWindowMatrix, static_cast(pixmap), region, hardwareClipping); } } void SceneOpenGL2Window::performPaint(int mask, QRegion region, WindowPaintData data) { if (!beginRenderWindow(mask, region, data)) return; QMatrix4x4 windowMatrix = transformation(mask, data); const QMatrix4x4 modelViewProjection = modelViewProjectionMatrix(mask, data); const QMatrix4x4 mvpMatrix = modelViewProjection * windowMatrix; GLShader *shader = data.shader; if (!shader) { ShaderTraits traits = ShaderTrait::MapTexture; if (data.opacity() != 1.0 || data.brightness() != 1.0 || data.crossFadeProgress() != 1.0) traits |= ShaderTrait::Modulate; if (data.saturation() != 1.0) traits |= ShaderTrait::AdjustSaturation; shader = ShaderManager::instance()->pushShader(traits); } shader->setUniform(GLShader::ModelViewProjectionMatrix, mvpMatrix); shader->setUniform(GLShader::Saturation, data.saturation()); const GLenum filter = (mask & (Effect::PAINT_WINDOW_TRANSFORMED | Effect::PAINT_SCREEN_TRANSFORMED)) && options->glSmoothScale() != 0 ? GL_LINEAR : GL_NEAREST; WindowQuadList quads[LeafCount]; // Split the quads into separate lists for each type foreach (const WindowQuad &quad, data.quads) { switch (quad.type()) { case WindowQuadDecoration: quads[DecorationLeaf].append(quad); continue; case WindowQuadContents: quads[ContentLeaf].append(quad); continue; case WindowQuadShadow: quads[ShadowLeaf].append(quad); continue; default: continue; } } if (data.crossFadeProgress() != 1.0) { OpenGLWindowPixmap *previous = previousWindowPixmap(); if (previous) { const QRect &oldGeometry = previous->contentsRect(); for (const WindowQuad &quad : quads[ContentLeaf]) { // we need to create new window quads with normalize texture coordinates // normal quads divide the x/y position by width/height. This would not work as the texture // is larger than the visible content in case of a decorated Client resulting in garbage being shown. // So we calculate the normalized texture coordinate in the Client's new content space and map it to // the previous Client's content space. WindowQuad newQuad(WindowQuadContents); for (int i = 0; i < 4; ++i) { const qreal xFactor = qreal(quad[i].textureX() - toplevel->clientPos().x())/qreal(toplevel->clientSize().width()); const qreal yFactor = qreal(quad[i].textureY() - toplevel->clientPos().y())/qreal(toplevel->clientSize().height()); WindowVertex vertex(quad[i].x(), quad[i].y(), (xFactor * oldGeometry.width() + oldGeometry.x())/qreal(previous->size().width()), (yFactor * oldGeometry.height() + oldGeometry.y())/qreal(previous->size().height())); newQuad[i] = vertex; } quads[PreviousContentLeaf].append(newQuad); } } } const bool indexedQuads = GLVertexBuffer::supportsIndexedQuads(); const GLenum primitiveType = indexedQuads ? GL_QUADS : GL_TRIANGLES; const int verticesPerQuad = indexedQuads ? 4 : 6; const size_t size = verticesPerQuad * (quads[0].count() + quads[1].count() + quads[2].count() + quads[3].count()) * sizeof(GLVertex2D); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); GLVertex2D *map = (GLVertex2D *) vbo->map(size); LeafNode nodes[LeafCount]; setupLeafNodes(nodes, quads, data); for (int i = 0, v = 0; i < LeafCount; i++) { if (quads[i].isEmpty() || !nodes[i].texture) continue; nodes[i].firstVertex = v; nodes[i].vertexCount = quads[i].count() * verticesPerQuad; const QMatrix4x4 matrix = nodes[i].texture->matrix(nodes[i].coordinateType); quads[i].makeInterleavedArrays(primitiveType, &map[v], matrix); v += quads[i].count() * verticesPerQuad; } vbo->unmap(); vbo->bindArrays(); // Make sure the blend function is set up correctly in case we will be doing blending glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); float opacity = -1.0; for (int i = 0; i < LeafCount; i++) { if (nodes[i].vertexCount == 0) continue; setBlendEnabled(nodes[i].hasAlpha || nodes[i].opacity < 1.0); if (opacity != nodes[i].opacity) { shader->setUniform(GLShader::ModulationConstant, modulate(nodes[i].opacity, data.brightness())); opacity = nodes[i].opacity; } nodes[i].texture->setFilter(filter); nodes[i].texture->setWrapMode(GL_CLAMP_TO_EDGE); nodes[i].texture->bind(); vbo->draw(region, primitiveType, nodes[i].firstVertex, nodes[i].vertexCount, m_hardwareClipping); } vbo->unbindArrays(); // render sub-surfaces auto wp = windowPixmap(); const auto &children = wp ? wp->children() : QVector(); windowMatrix.translate(toplevel->clientPos().x(), toplevel->clientPos().y()); for (auto pixmap : children) { if (pixmap->subSurface().isNull() || pixmap->subSurface()->surface().isNull() || !pixmap->subSurface()->surface()->isMapped()) { continue; } renderSubSurface(shader, modelViewProjection, windowMatrix, static_cast(pixmap), region, m_hardwareClipping); } setBlendEnabled(false); if (!data.shader) ShaderManager::instance()->popShader(); endRenderWindow(); } //**************************************** // OpenGLWindowPixmap //**************************************** OpenGLWindowPixmap::OpenGLWindowPixmap(Scene::Window *window, SceneOpenGL* scene) : WindowPixmap(window) , m_texture(scene->createTexture()) , m_scene(scene) { } OpenGLWindowPixmap::OpenGLWindowPixmap(const QPointer &subSurface, WindowPixmap *parent, SceneOpenGL *scene) : WindowPixmap(subSurface, parent) , m_texture(scene->createTexture()) , m_scene(scene) { } OpenGLWindowPixmap::~OpenGLWindowPixmap() { } bool OpenGLWindowPixmap::bind() { if (!m_texture->isNull()) { // always call updateBuffer to get the sub-surface tree updated if (subSurface().isNull() && !toplevel()->damage().isEmpty()) { updateBuffer(); } auto s = surface(); if (s && !s->trackedDamage().isEmpty()) { m_texture->updateFromPixmap(this); // mipmaps need to be updated m_texture->setDirty(); } if (subSurface().isNull()) { toplevel()->resetDamage(); } // also bind all children for (auto it = children().constBegin(); it != children().constEnd(); ++it) { static_cast(*it)->bind(); } return true; } // also bind all children, needs to be done before checking isValid // as there might be valid children to render, see https://bugreports.qt.io/browse/QTBUG-52192 if (subSurface().isNull()) { updateBuffer(); } for (auto it = children().constBegin(); it != children().constEnd(); ++it) { static_cast(*it)->bind(); } if (!isValid()) { return false; } bool success = m_texture->load(this); if (success) { if (subSurface().isNull()) { toplevel()->resetDamage(); } } else qCDebug(KWIN_OPENGL) << "Failed to bind window"; return success; } WindowPixmap *OpenGLWindowPixmap::createChild(const QPointer &subSurface) { return new OpenGLWindowPixmap(subSurface, this, m_scene); } bool OpenGLWindowPixmap::isValid() const { if (!m_texture->isNull()) { return true; } return WindowPixmap::isValid(); } //**************************************** // SceneOpenGL::EffectFrame //**************************************** GLTexture* SceneOpenGL::EffectFrame::m_unstyledTexture = NULL; QPixmap* SceneOpenGL::EffectFrame::m_unstyledPixmap = NULL; SceneOpenGL::EffectFrame::EffectFrame(EffectFrameImpl* frame, SceneOpenGL *scene) : Scene::EffectFrame(frame) , m_texture(NULL) , m_textTexture(NULL) , m_oldTextTexture(NULL) , m_textPixmap(NULL) , m_iconTexture(NULL) , m_oldIconTexture(NULL) , m_selectionTexture(NULL) , m_unstyledVBO(NULL) , m_scene(scene) { if (m_effectFrame->style() == EffectFrameUnstyled && !m_unstyledTexture) { updateUnstyledTexture(); } } SceneOpenGL::EffectFrame::~EffectFrame() { delete m_texture; delete m_textTexture; delete m_textPixmap; delete m_oldTextTexture; delete m_iconTexture; delete m_oldIconTexture; delete m_selectionTexture; delete m_unstyledVBO; } void SceneOpenGL::EffectFrame::free() { glFlush(); delete m_texture; m_texture = NULL; delete m_textTexture; m_textTexture = NULL; delete m_textPixmap; m_textPixmap = NULL; delete m_iconTexture; m_iconTexture = NULL; delete m_selectionTexture; m_selectionTexture = NULL; delete m_unstyledVBO; m_unstyledVBO = NULL; delete m_oldIconTexture; m_oldIconTexture = NULL; delete m_oldTextTexture; m_oldTextTexture = NULL; } void SceneOpenGL::EffectFrame::freeIconFrame() { delete m_iconTexture; m_iconTexture = NULL; } void SceneOpenGL::EffectFrame::freeTextFrame() { delete m_textTexture; m_textTexture = NULL; delete m_textPixmap; m_textPixmap = NULL; } void SceneOpenGL::EffectFrame::freeSelection() { delete m_selectionTexture; m_selectionTexture = NULL; } void SceneOpenGL::EffectFrame::crossFadeIcon() { delete m_oldIconTexture; m_oldIconTexture = m_iconTexture; m_iconTexture = NULL; } void SceneOpenGL::EffectFrame::crossFadeText() { delete m_oldTextTexture; m_oldTextTexture = m_textTexture; m_textTexture = NULL; } void SceneOpenGL::EffectFrame::render(QRegion region, double opacity, double frameOpacity) { if (m_effectFrame->geometry().isEmpty()) return; // Nothing to display region = infiniteRegion(); // TODO: Old region doesn't seem to work with OpenGL GLShader* shader = m_effectFrame->shader(); if (!shader) { shader = ShaderManager::instance()->pushShader(ShaderTrait::MapTexture | ShaderTrait::Modulate); } else if (shader) { ShaderManager::instance()->pushShader(shader); } if (shader) { shader->setUniform(GLShader::ModulationConstant, QVector4D(1.0, 1.0, 1.0, 1.0)); shader->setUniform(GLShader::Saturation, 1.0f); } const QMatrix4x4 projection = m_scene->projectionMatrix(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Render the actual frame if (m_effectFrame->style() == EffectFrameUnstyled) { if (!m_unstyledVBO) { m_unstyledVBO = new GLVertexBuffer(GLVertexBuffer::Static); QRect area = m_effectFrame->geometry(); area.moveTo(0, 0); area.adjust(-5, -5, 5, 5); const int roundness = 5; QVector verts, texCoords; verts.reserve(84); texCoords.reserve(84); // top left verts << area.left() << area.top(); texCoords << 0.0f << 0.0f; verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; // top verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; // top right verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() << area.top(); texCoords << 1.0f << 0.0f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; verts << area.right() << area.top(); texCoords << 1.0f << 0.0f; // bottom left verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.left() << area.bottom(); texCoords << 0.0f << 1.0f; verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.left() << area.bottom(); texCoords << 0.0f << 1.0f; verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; // bottom verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; // bottom right verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() << area.bottom(); texCoords << 1.0f << 1.0f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; // center verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; m_unstyledVBO->setData(verts.count() / 2, 2, verts.data(), texCoords.data()); } if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_unstyledTexture->bind(); const QPoint pt = m_effectFrame->geometry().topLeft(); QMatrix4x4 mvp(projection); mvp.translate(pt.x(), pt.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_unstyledVBO->render(region, GL_TRIANGLES); m_unstyledTexture->unbind(); } else if (m_effectFrame->style() == EffectFrameStyled) { if (!m_texture) // Lazy creation updateTexture(); if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_texture->bind(); qreal left, top, right, bottom; m_effectFrame->frame().getMargins(left, top, right, bottom); // m_geometry is the inner geometry const QRect rect = m_effectFrame->geometry().adjusted(-left, -top, right, bottom); QMatrix4x4 mvp(projection); mvp.translate(rect.x(), rect.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_texture->render(region, rect); m_texture->unbind(); } if (!m_effectFrame->selection().isNull()) { if (!m_selectionTexture) { // Lazy creation QPixmap pixmap = m_effectFrame->selectionFrame().framePixmap(); if (!pixmap.isNull()) m_selectionTexture = new GLTexture(pixmap); } if (m_selectionTexture) { if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } QMatrix4x4 mvp(projection); mvp.translate(m_effectFrame->selection().x(), m_effectFrame->selection().y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); m_selectionTexture->bind(); m_selectionTexture->render(region, m_effectFrame->selection()); m_selectionTexture->unbind(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } // Render icon if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) { QPoint topLeft(m_effectFrame->geometry().x(), m_effectFrame->geometry().center().y() - m_effectFrame->iconSize().height() / 2); QMatrix4x4 mvp(projection); mvp.translate(topLeft.x(), topLeft.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); if (m_effectFrame->isCrossFade() && m_oldIconTexture) { if (shader) { const float a = opacity * (1.0 - m_effectFrame->crossFadeProgress()); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_oldIconTexture->bind(); m_oldIconTexture->render(region, QRect(topLeft, m_effectFrame->iconSize())); m_oldIconTexture->unbind(); if (shader) { const float a = opacity * m_effectFrame->crossFadeProgress(); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } } else { if (shader) { const QVector4D constant(opacity, opacity, opacity, opacity); shader->setUniform(GLShader::ModulationConstant, constant); } } if (!m_iconTexture) { // lazy creation m_iconTexture = new GLTexture(m_effectFrame->icon().pixmap(m_effectFrame->iconSize())); } m_iconTexture->bind(); m_iconTexture->render(region, QRect(topLeft, m_effectFrame->iconSize())); m_iconTexture->unbind(); } // Render text if (!m_effectFrame->text().isEmpty()) { QMatrix4x4 mvp(projection); mvp.translate(m_effectFrame->geometry().x(), m_effectFrame->geometry().y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); if (m_effectFrame->isCrossFade() && m_oldTextTexture) { if (shader) { const float a = opacity * (1.0 - m_effectFrame->crossFadeProgress()); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_oldTextTexture->bind(); m_oldTextTexture->render(region, m_effectFrame->geometry()); m_oldTextTexture->unbind(); if (shader) { const float a = opacity * m_effectFrame->crossFadeProgress(); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } } else { if (shader) { const QVector4D constant(opacity, opacity, opacity, opacity); shader->setUniform(GLShader::ModulationConstant, constant); } } if (!m_textTexture) // Lazy creation updateTextTexture(); if (m_textTexture) { m_textTexture->bind(); m_textTexture->render(region, m_effectFrame->geometry()); m_textTexture->unbind(); } } if (shader) { ShaderManager::instance()->popShader(); } glDisable(GL_BLEND); } void SceneOpenGL::EffectFrame::updateTexture() { delete m_texture; m_texture = 0L; if (m_effectFrame->style() == EffectFrameStyled) { QPixmap pixmap = m_effectFrame->frame().framePixmap(); m_texture = new GLTexture(pixmap); } } void SceneOpenGL::EffectFrame::updateTextTexture() { delete m_textTexture; m_textTexture = 0L; delete m_textPixmap; m_textPixmap = 0L; if (m_effectFrame->text().isEmpty()) return; // Determine position on texture to paint text QRect rect(QPoint(0, 0), m_effectFrame->geometry().size()); if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) rect.setLeft(m_effectFrame->iconSize().width()); // If static size elide text as required QString text = m_effectFrame->text(); if (m_effectFrame->isStatic()) { QFontMetrics metrics(m_effectFrame->font()); text = metrics.elidedText(text, Qt::ElideRight, rect.width()); } m_textPixmap = new QPixmap(m_effectFrame->geometry().size()); m_textPixmap->fill(Qt::transparent); QPainter p(m_textPixmap); p.setFont(m_effectFrame->font()); if (m_effectFrame->style() == EffectFrameStyled) p.setPen(m_effectFrame->styledTextColor()); else // TODO: What about no frame? Custom color setting required p.setPen(Qt::white); p.drawText(rect, m_effectFrame->alignment(), text); p.end(); m_textTexture = new GLTexture(*m_textPixmap); } void SceneOpenGL::EffectFrame::updateUnstyledTexture() { delete m_unstyledTexture; m_unstyledTexture = 0L; delete m_unstyledPixmap; m_unstyledPixmap = 0L; // Based off circle() from kwinxrenderutils.cpp #define CS 8 m_unstyledPixmap = new QPixmap(2 * CS, 2 * CS); m_unstyledPixmap->fill(Qt::transparent); QPainter p(m_unstyledPixmap); p.setRenderHint(QPainter::Antialiasing); p.setPen(Qt::NoPen); p.setBrush(Qt::black); p.drawEllipse(m_unstyledPixmap->rect()); p.end(); #undef CS m_unstyledTexture = new GLTexture(*m_unstyledPixmap); } void SceneOpenGL::EffectFrame::cleanup() { delete m_unstyledTexture; m_unstyledTexture = NULL; delete m_unstyledPixmap; m_unstyledPixmap = NULL; } //**************************************** // SceneOpenGL::Shadow //**************************************** class DecorationShadowTextureCache { public: ~DecorationShadowTextureCache(); DecorationShadowTextureCache(const DecorationShadowTextureCache&) = delete; static DecorationShadowTextureCache &instance(); void unregister(SceneOpenGLShadow *shadow); QSharedPointer getTexture(SceneOpenGLShadow *shadow); private: DecorationShadowTextureCache() = default; struct Data { QSharedPointer texture; QVector shadows; }; QHash m_cache; }; DecorationShadowTextureCache &DecorationShadowTextureCache::instance() { static DecorationShadowTextureCache s_instance; return s_instance; } DecorationShadowTextureCache::~DecorationShadowTextureCache() { Q_ASSERT(m_cache.isEmpty()); } void DecorationShadowTextureCache::unregister(SceneOpenGLShadow *shadow) { auto it = m_cache.begin(); while (it != m_cache.end()) { auto &d = it.value(); // check whether the Vector of Shadows contains our shadow and remove all of them auto glIt = d.shadows.begin(); while (glIt != d.shadows.end()) { if (*glIt == shadow) { glIt = d.shadows.erase(glIt); } else { glIt++; } } // if there are no shadows any more we can erase the cache entry if (d.shadows.isEmpty()) { it = m_cache.erase(it); } else { it++; } } } QSharedPointer DecorationShadowTextureCache::getTexture(SceneOpenGLShadow *shadow) { Q_ASSERT(shadow->hasDecorationShadow()); unregister(shadow); const auto &decoShadow = shadow->decorationShadow(); Q_ASSERT(!decoShadow.isNull()); auto it = m_cache.find(decoShadow.data()); if (it != m_cache.end()) { Q_ASSERT(!it.value().shadows.contains(shadow)); it.value().shadows << shadow; return it.value().texture; } Data d; d.shadows << shadow; d.texture = QSharedPointer::create(shadow->decorationShadowImage()); m_cache.insert(decoShadow.data(), d); return d.texture; } SceneOpenGLShadow::SceneOpenGLShadow(Toplevel *toplevel) : Shadow(toplevel) { } SceneOpenGLShadow::~SceneOpenGLShadow() { Scene *scene = Compositor::self()->scene(); if (scene) { scene->makeOpenGLContextCurrent(); DecorationShadowTextureCache::instance().unregister(this); m_texture.reset(); } } static inline void distributeHorizontally(QRectF &leftRect, QRectF &rightRect) { if (leftRect.right() > rightRect.left()) { const qreal boundedRight = qMin(leftRect.right(), rightRect.right()); const qreal boundedLeft = qMax(leftRect.left(), rightRect.left()); const qreal halfOverlap = (boundedRight - boundedLeft) / 2.0; leftRect.setRight(boundedRight - halfOverlap); rightRect.setLeft(boundedLeft + halfOverlap); } } static inline void distributeVertically(QRectF &topRect, QRectF &bottomRect) { if (topRect.bottom() > bottomRect.top()) { const qreal boundedBottom = qMin(topRect.bottom(), bottomRect.bottom()); const qreal boundedTop = qMax(topRect.top(), bottomRect.top()); const qreal halfOverlap = (boundedBottom - boundedTop) / 2.0; topRect.setBottom(boundedBottom - halfOverlap); bottomRect.setTop(boundedTop + halfOverlap); } } void SceneOpenGLShadow::buildQuads() { // Do not draw shadows if window width or window height is less than // 5 px. 5 is an arbitrary choice. if (topLevel()->width() < 5 || topLevel()->height() < 5) { m_shadowQuads.clear(); setShadowRegion(QRegion()); return; } const QSizeF top(elementSize(ShadowElementTop)); const QSizeF topRight(elementSize(ShadowElementTopRight)); const QSizeF right(elementSize(ShadowElementRight)); const QSizeF bottomRight(elementSize(ShadowElementBottomRight)); const QSizeF bottom(elementSize(ShadowElementBottom)); const QSizeF bottomLeft(elementSize(ShadowElementBottomLeft)); const QSizeF left(elementSize(ShadowElementLeft)); const QSizeF topLeft(elementSize(ShadowElementTopLeft)); const QMarginsF shadowMargins( std::max({topLeft.width(), left.width(), bottomLeft.width()}), std::max({topLeft.height(), top.height(), topRight.height()}), std::max({topRight.width(), right.width(), bottomRight.width()}), std::max({bottomRight.height(), bottom.height(), bottomLeft.height()})); const QRectF outerRect(QPointF(-leftOffset(), -topOffset()), QPointF(topLevel()->width() + rightOffset(), topLevel()->height() + bottomOffset())); const int width = shadowMargins.left() + std::max(top.width(), bottom.width()) + shadowMargins.right(); const int height = shadowMargins.top() + std::max(left.height(), right.height()) + shadowMargins.bottom(); QRectF topLeftRect; if (!topLeft.isEmpty()) { topLeftRect = QRectF(outerRect.topLeft(), topLeft); } else { topLeftRect = QRectF( outerRect.left() + shadowMargins.left(), outerRect.top() + shadowMargins.top(), 0, 0); } QRectF topRightRect; if (!topRight.isEmpty()) { topRightRect = QRectF( outerRect.right() - topRight.width(), outerRect.top(), topRight.width(), topRight.height()); } else { topRightRect = QRectF( outerRect.right() - shadowMargins.right(), outerRect.top() + shadowMargins.top(), 0, 0); } QRectF bottomRightRect; if (!bottomRight.isEmpty()) { bottomRightRect = QRectF( outerRect.right() - bottomRight.width(), outerRect.bottom() - bottomRight.height(), bottomRight.width(), bottomRight.height()); } else { bottomRightRect = QRectF( outerRect.right() - shadowMargins.right(), outerRect.bottom() - shadowMargins.bottom(), 0, 0); } QRectF bottomLeftRect; if (!bottomLeft.isEmpty()) { bottomLeftRect = QRectF( outerRect.left(), outerRect.bottom() - bottomLeft.height(), bottomLeft.width(), bottomLeft.height()); } else { bottomLeftRect = QRectF( outerRect.left() + shadowMargins.left(), outerRect.bottom() - shadowMargins.bottom(), 0, 0); } // Re-distribute the corner tiles so no one of them is overlapping with others. // By doing this, we assume that shadow's corner tiles are symmetric // and it is OK to not draw top/right/bottom/left tile between corners. // For example, let's say top-left and top-right tiles are overlapping. // In that case, the right side of the top-left tile will be shifted to left, // the left side of the top-right tile will shifted to right, and the top // tile won't be rendered. distributeHorizontally(topLeftRect, topRightRect); distributeHorizontally(bottomLeftRect, bottomRightRect); distributeVertically(topLeftRect, bottomLeftRect); distributeVertically(topRightRect, bottomRightRect); qreal tx1 = 0.0, tx2 = 0.0, ty1 = 0.0, ty2 = 0.0; m_shadowQuads.clear(); if (topLeftRect.isValid()) { tx1 = 0.0; ty1 = 0.0; tx2 = topLeftRect.width() / width; ty2 = topLeftRect.height() / height; WindowQuad topLeftQuad(WindowQuadShadow); topLeftQuad[0] = WindowVertex(topLeftRect.left(), topLeftRect.top(), tx1, ty1); topLeftQuad[1] = WindowVertex(topLeftRect.right(), topLeftRect.top(), tx2, ty1); topLeftQuad[2] = WindowVertex(topLeftRect.right(), topLeftRect.bottom(), tx2, ty2); topLeftQuad[3] = WindowVertex(topLeftRect.left(), topLeftRect.bottom(), tx1, ty2); m_shadowQuads.append(topLeftQuad); } if (topRightRect.isValid()) { tx1 = 1.0 - topRightRect.width() / width; ty1 = 0.0; tx2 = 1.0; ty2 = topRightRect.height() / height; WindowQuad topRightQuad(WindowQuadShadow); topRightQuad[0] = WindowVertex(topRightRect.left(), topRightRect.top(), tx1, ty1); topRightQuad[1] = WindowVertex(topRightRect.right(), topRightRect.top(), tx2, ty1); topRightQuad[2] = WindowVertex(topRightRect.right(), topRightRect.bottom(), tx2, ty2); topRightQuad[3] = WindowVertex(topRightRect.left(), topRightRect.bottom(), tx1, ty2); m_shadowQuads.append(topRightQuad); } if (bottomRightRect.isValid()) { tx1 = 1.0 - bottomRightRect.width() / width; tx2 = 1.0; ty1 = 1.0 - bottomRightRect.height() / height; ty2 = 1.0; WindowQuad bottomRightQuad(WindowQuadShadow); bottomRightQuad[0] = WindowVertex(bottomRightRect.left(), bottomRightRect.top(), tx1, ty1); bottomRightQuad[1] = WindowVertex(bottomRightRect.right(), bottomRightRect.top(), tx2, ty1); bottomRightQuad[2] = WindowVertex(bottomRightRect.right(), bottomRightRect.bottom(), tx2, ty2); bottomRightQuad[3] = WindowVertex(bottomRightRect.left(), bottomRightRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomRightQuad); } if (bottomLeftRect.isValid()) { tx1 = 0.0; tx2 = bottomLeftRect.width() / width; ty1 = 1.0 - bottomLeftRect.height() / height; ty2 = 1.0; WindowQuad bottomLeftQuad(WindowQuadShadow); bottomLeftQuad[0] = WindowVertex(bottomLeftRect.left(), bottomLeftRect.top(), tx1, ty1); bottomLeftQuad[1] = WindowVertex(bottomLeftRect.right(), bottomLeftRect.top(), tx2, ty1); bottomLeftQuad[2] = WindowVertex(bottomLeftRect.right(), bottomLeftRect.bottom(), tx2, ty2); bottomLeftQuad[3] = WindowVertex(bottomLeftRect.left(), bottomLeftRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomLeftQuad); } QRectF topRect( QPointF(topLeftRect.right(), outerRect.top()), QPointF(topRightRect.left(), outerRect.top() + top.height())); QRectF rightRect( QPointF(outerRect.right() - right.width(), topRightRect.bottom()), QPointF(outerRect.right(), bottomRightRect.top())); QRectF bottomRect( QPointF(bottomLeftRect.right(), outerRect.bottom() - bottom.height()), QPointF(bottomRightRect.left(), outerRect.bottom())); QRectF leftRect( QPointF(outerRect.left(), topLeftRect.bottom()), QPointF(outerRect.left() + left.width(), bottomLeftRect.top())); // Re-distribute left/right and top/bottom shadow tiles so they don't // overlap when the window is too small. Please notice that we don't // fix overlaps between left/top(left/bottom, right/top, and so on) // corner tiles because corresponding counter parts won't be valid when // the window is too small, which means they won't be rendered. distributeHorizontally(leftRect, rightRect); distributeVertically(topRect, bottomRect); if (topRect.isValid()) { tx1 = shadowMargins.left() / width; ty1 = 0.0; tx2 = tx1 + top.width() / width; ty2 = topRect.height() / height; WindowQuad topQuad(WindowQuadShadow); topQuad[0] = WindowVertex(topRect.left(), topRect.top(), tx1, ty1); topQuad[1] = WindowVertex(topRect.right(), topRect.top(), tx2, ty1); topQuad[2] = WindowVertex(topRect.right(), topRect.bottom(), tx2, ty2); topQuad[3] = WindowVertex(topRect.left(), topRect.bottom(), tx1, ty2); m_shadowQuads.append(topQuad); } if (rightRect.isValid()) { tx1 = 1.0 - rightRect.width() / width; ty1 = shadowMargins.top() / height; tx2 = 1.0; ty2 = ty1 + right.height() / height; WindowQuad rightQuad(WindowQuadShadow); rightQuad[0] = WindowVertex(rightRect.left(), rightRect.top(), tx1, ty1); rightQuad[1] = WindowVertex(rightRect.right(), rightRect.top(), tx2, ty1); rightQuad[2] = WindowVertex(rightRect.right(), rightRect.bottom(), tx2, ty2); rightQuad[3] = WindowVertex(rightRect.left(), rightRect.bottom(), tx1, ty2); m_shadowQuads.append(rightQuad); } if (bottomRect.isValid()) { tx1 = shadowMargins.left() / width; ty1 = 1.0 - bottomRect.height() / height; tx2 = tx1 + bottom.width() / width; ty2 = 1.0; WindowQuad bottomQuad(WindowQuadShadow); bottomQuad[0] = WindowVertex(bottomRect.left(), bottomRect.top(), tx1, ty1); bottomQuad[1] = WindowVertex(bottomRect.right(), bottomRect.top(), tx2, ty1); bottomQuad[2] = WindowVertex(bottomRect.right(), bottomRect.bottom(), tx2, ty2); bottomQuad[3] = WindowVertex(bottomRect.left(), bottomRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomQuad); } if (leftRect.isValid()) { tx1 = 0.0; ty1 = shadowMargins.top() / height; tx2 = leftRect.width() / width; ty2 = ty1 + left.height() / height; WindowQuad leftQuad(WindowQuadShadow); leftQuad[0] = WindowVertex(leftRect.left(), leftRect.top(), tx1, ty1); leftQuad[1] = WindowVertex(leftRect.right(), leftRect.top(), tx2, ty1); leftQuad[2] = WindowVertex(leftRect.right(), leftRect.bottom(), tx2, ty2); leftQuad[3] = WindowVertex(leftRect.left(), leftRect.bottom(), tx1, ty2); m_shadowQuads.append(leftQuad); } } bool SceneOpenGLShadow::prepareBackend() { if (hasDecorationShadow()) { // simplifies a lot by going directly to Scene *scene = Compositor::self()->scene(); scene->makeOpenGLContextCurrent(); m_texture = DecorationShadowTextureCache::instance().getTexture(this); return true; } const QSize top(shadowPixmap(ShadowElementTop).size()); const QSize topRight(shadowPixmap(ShadowElementTopRight).size()); const QSize right(shadowPixmap(ShadowElementRight).size()); const QSize bottom(shadowPixmap(ShadowElementBottom).size()); const QSize bottomLeft(shadowPixmap(ShadowElementBottomLeft).size()); const QSize left(shadowPixmap(ShadowElementLeft).size()); const QSize topLeft(shadowPixmap(ShadowElementTopLeft).size()); const QSize bottomRight(shadowPixmap(ShadowElementBottomRight).size()); const int width = std::max({topLeft.width(), left.width(), bottomLeft.width()}) + std::max(top.width(), bottom.width()) + std::max({topRight.width(), right.width(), bottomRight.width()}); const int height = std::max({topLeft.height(), top.height(), topRight.height()}) + std::max(left.height(), right.height()) + std::max({bottomLeft.height(), bottom.height(), bottomRight.height()}); if (width == 0 || height == 0) { return false; } QImage image(width, height, QImage::Format_ARGB32); image.fill(Qt::transparent); const int innerRectTop = std::max({topLeft.height(), top.height(), topRight.height()}); const int innerRectLeft = std::max({topLeft.width(), left.width(), bottomLeft.width()}); QPainter p; p.begin(&image); p.drawPixmap(0, 0, shadowPixmap(ShadowElementTopLeft)); p.drawPixmap(innerRectLeft, 0, shadowPixmap(ShadowElementTop)); p.drawPixmap(width - topRight.width(), 0, shadowPixmap(ShadowElementTopRight)); p.drawPixmap(0, innerRectTop, shadowPixmap(ShadowElementLeft)); p.drawPixmap(width - right.width(), innerRectTop, shadowPixmap(ShadowElementRight)); p.drawPixmap(0, height - bottomLeft.height(), shadowPixmap(ShadowElementBottomLeft)); p.drawPixmap(innerRectLeft, height - bottom.height(), shadowPixmap(ShadowElementBottom)); p.drawPixmap(width - bottomRight.width(), height - bottomRight.height(), shadowPixmap(ShadowElementBottomRight)); p.end(); // Check if the image is alpha-only in practice, and if so convert it to an 8-bpp format if (!GLPlatform::instance()->isGLES() && GLTexture::supportsSwizzle() && GLTexture::supportsFormatRG()) { QImage alphaImage(image.size(), QImage::Format_Indexed8); // Change to Format_Alpha8 w/ Qt 5.5 bool alphaOnly = true; for (ptrdiff_t y = 0; alphaOnly && y < image.height(); y++) { const uint32_t * const src = reinterpret_cast(image.scanLine(y)); uint8_t * const dst = reinterpret_cast(alphaImage.scanLine(y)); for (ptrdiff_t x = 0; x < image.width(); x++) { if (src[x] & 0x00ffffff) alphaOnly = false; dst[x] = qAlpha(src[x]); } } if (alphaOnly) { image = alphaImage; } } Scene *scene = Compositor::self()->scene(); scene->makeOpenGLContextCurrent(); m_texture = QSharedPointer::create(image); if (m_texture->internalFormat() == GL_R8) { // Swizzle red to alpha and all other channels to zero m_texture->bind(); m_texture->setSwizzle(GL_ZERO, GL_ZERO, GL_ZERO, GL_RED); } return true; } SceneOpenGLDecorationRenderer::SceneOpenGLDecorationRenderer(Decoration::DecoratedClientImpl *client) : Renderer(client) , m_texture() { connect(this, &Renderer::renderScheduled, client->client(), static_cast(&AbstractClient::addRepaint)); } SceneOpenGLDecorationRenderer::~SceneOpenGLDecorationRenderer() { if (Scene *scene = Compositor::self()->scene()) { scene->makeOpenGLContextCurrent(); } } // Rotates the given source rect 90° counter-clockwise, // and flips it vertically static QImage rotate(const QImage &srcImage, const QRect &srcRect) { auto dpr = srcImage.devicePixelRatio(); QImage image(srcRect.height() * dpr, srcRect.width() * dpr, srcImage.format()); image.setDevicePixelRatio(dpr); const QPoint srcPoint(srcRect.x() * dpr, srcRect.y() * dpr); const uint32_t *src = reinterpret_cast(srcImage.bits()); uint32_t *dst = reinterpret_cast(image.bits()); for (int x = 0; x < image.width(); x++) { const uint32_t *s = src + (srcPoint.y() + x) * srcImage.width() + srcPoint.x(); uint32_t *d = dst + x; for (int y = 0; y < image.height(); y++) { *d = s[y]; d += image.width(); } } return image; } void SceneOpenGLDecorationRenderer::render() { const QRegion scheduled = getScheduled(); const bool dirty = areImageSizesDirty(); if (scheduled.isEmpty() && !dirty) { return; } if (dirty) { resizeTexture(); resetImageSizesDirty(); } if (!m_texture) { // for invalid sizes we get no texture, see BUG 361551 return; } QRect left, top, right, bottom; client()->client()->layoutDecorationRects(left, top, right, bottom); const QRect geometry = dirty ? QRect(QPoint(0, 0), client()->client()->geometry().size()) : scheduled.boundingRect(); auto renderPart = [this](const QRect &geo, const QRect &partRect, const QPoint &offset, bool rotated = false) { if (!geo.isValid()) { return; } QImage image = renderToImage(geo); if (rotated) { // TODO: get this done directly when rendering to the image image = rotate(image, QRect(geo.topLeft() - partRect.topLeft(), geo.size())); } m_texture->update(image, (geo.topLeft() - partRect.topLeft() + offset) * image.devicePixelRatio()); }; renderPart(left.intersected(geometry), left, QPoint(0, top.height() + bottom.height() + 2), true); renderPart(top.intersected(geometry), top, QPoint(0, 0)); renderPart(right.intersected(geometry), right, QPoint(0, top.height() + bottom.height() + left.width() + 3), true); renderPart(bottom.intersected(geometry), bottom, QPoint(0, top.height() + 1)); } static int align(int value, int align) { return (value + align - 1) & ~(align - 1); } void SceneOpenGLDecorationRenderer::resizeTexture() { QRect left, top, right, bottom; client()->client()->layoutDecorationRects(left, top, right, bottom); QSize size; size.rwidth() = qMax(qMax(top.width(), bottom.width()), qMax(left.height(), right.height())); size.rheight() = top.height() + bottom.height() + left.width() + right.width() + 3; size.rwidth() = align(size.width(), 128); size *= client()->client()->screenScale(); if (m_texture && m_texture->size() == size) return; if (!size.isEmpty()) { m_texture.reset(new GLTexture(GL_RGBA8, size.width(), size.height())); m_texture->setYInverted(true); m_texture->setWrapMode(GL_CLAMP_TO_EDGE); m_texture->clear(); } else { m_texture.reset(); } } void SceneOpenGLDecorationRenderer::reparent(Deleted *deleted) { render(); Renderer::reparent(deleted); } OpenGLFactory::OpenGLFactory(QObject *parent) : SceneFactory(parent) { } OpenGLFactory::~OpenGLFactory() = default; Scene *OpenGLFactory::create(QObject *parent) const { qCDebug(KWIN_OPENGL) << "Initializing OpenGL compositing"; // Some broken drivers crash on glXQuery() so to prevent constant KWin crashes: if (kwinApp()->platform()->openGLCompositingIsBroken()) { qCWarning(KWIN_OPENGL) << "KWin has detected that your OpenGL library is unsafe to use"; return nullptr; } kwinApp()->platform()->createOpenGLSafePoint(Platform::OpenGLSafePoint::PreInit); auto s = SceneOpenGL::createScene(parent); kwinApp()->platform()->createOpenGLSafePoint(Platform::OpenGLSafePoint::PostInit); if (s && s->initFailed()) { delete s; return nullptr; } return s; } } // namespace diff --git a/plugins/scenes/opengl/scene_opengl.h b/plugins/scenes/opengl/scene_opengl.h index e2cc16709..80a5f2d14 100644 --- a/plugins/scenes/opengl/scene_opengl.h +++ b/plugins/scenes/opengl/scene_opengl.h @@ -1,357 +1,357 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 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_SCENE_OPENGL_H #define KWIN_SCENE_OPENGL_H #include "scene.h" #include "shadow.h" #include "kwinglutils.h" #include "decorations/decorationrenderer.h" #include "platformsupport/scenes/opengl/backend.h" namespace KWin { class LanczosFilter; class OpenGLBackend; class SyncManager; class SyncObject; class KWIN_EXPORT SceneOpenGL : public Scene { Q_OBJECT public: class EffectFrame; class Window; ~SceneOpenGL() override; bool initFailed() const override; bool hasPendingFlush() const override; qint64 paint(QRegion damage, ToplevelList windows) override; Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame) override; Shadow *createShadow(Toplevel *toplevel) override; void screenGeometryChanged(const QSize &size) override; OverlayWindow *overlayWindow() override; bool usesOverlayWindow() const override; bool blocksForRetrace() const override; bool syncsToVBlank() const override; bool makeOpenGLContextCurrent() override; void doneOpenGLContextCurrent() override; Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *impl) override; void triggerFence() override; virtual QMatrix4x4 projectionMatrix() const = 0; bool animationsSupported() const override; void insertWait(); void idle() override; bool debug() const { return m_debug; } void initDebugOutput(); /** * @brief Factory method to create a backend specific texture. * * @return :SceneOpenGL::Texture* - **/ + */ SceneOpenGLTexture *createTexture(); OpenGLBackend *backend() const { return m_backend; } QVector openGLPlatformInterfaceExtensions() const override; static SceneOpenGL *createScene(QObject *parent); protected: SceneOpenGL(OpenGLBackend *backend, QObject *parent = nullptr); void paintBackground(QRegion region) override; void extendPaintRegion(QRegion ®ion, bool opaqueFullscreen) override; QMatrix4x4 transformation(int mask, const ScreenPaintData &data) const; void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data) override; void handleGraphicsReset(GLenum status); virtual void doPaintBackground(const QVector &vertices) = 0; virtual void updateProjectionMatrix() = 0; protected: bool init_ok; private: bool viewportLimitsMatched(const QSize &size) const; private: bool m_debug; OpenGLBackend *m_backend; SyncManager *m_syncManager; SyncObject *m_currentFence; }; class SceneOpenGL2 : public SceneOpenGL { Q_OBJECT public: explicit SceneOpenGL2(OpenGLBackend *backend, QObject *parent = nullptr); ~SceneOpenGL2() override; CompositingType compositingType() const override { return OpenGL2Compositing; } static bool supported(OpenGLBackend *backend); QMatrix4x4 projectionMatrix() const override { return m_projectionMatrix; } QMatrix4x4 screenProjectionMatrix() const override { return m_screenProjectionMatrix; } protected: void paintSimpleScreen(int mask, QRegion region) override; void paintGenericScreen(int mask, ScreenPaintData data) override; void doPaintBackground(const QVector< float >& vertices) override; Scene::Window *createWindow(Toplevel *t) override; void finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) override; void updateProjectionMatrix() override; void paintCursor() override; private: void performPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); QMatrix4x4 createProjectionMatrix() const; private: LanczosFilter *m_lanczosFilter; QScopedPointer m_cursorTexture; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_screenProjectionMatrix; GLuint vao; }; class SceneOpenGL::Window : public Scene::Window { public: ~Window() override; bool beginRenderWindow(int mask, const QRegion ®ion, WindowPaintData &data); void performPaint(int mask, QRegion region, WindowPaintData data) override = 0; void endRenderWindow(); bool bindTexture(); void setScene(SceneOpenGL *scene) { m_scene = scene; } protected: WindowPixmap* createWindowPixmap() override; Window(Toplevel* c); enum TextureType { Content, Decoration, Shadow }; QMatrix4x4 transformation(int mask, const WindowPaintData &data) const; GLTexture *getDecorationTexture() const; protected: SceneOpenGL *m_scene; bool m_hardwareClipping; }; class OpenGLWindowPixmap; class SceneOpenGL2Window : public SceneOpenGL::Window { public: enum Leaf { ShadowLeaf = 0, DecorationLeaf, ContentLeaf, PreviousContentLeaf, LeafCount }; struct LeafNode { LeafNode() : texture(0), firstVertex(0), vertexCount(0), opacity(1.0), hasAlpha(false), coordinateType(UnnormalizedCoordinates) { } GLTexture *texture; int firstVertex; int vertexCount; float opacity; bool hasAlpha; TextureCoordinateType coordinateType; }; explicit SceneOpenGL2Window(Toplevel *c); ~SceneOpenGL2Window() override; protected: QMatrix4x4 modelViewProjectionMatrix(int mask, const WindowPaintData &data) const; QVector4D modulate(float opacity, float brightness) const; void setBlendEnabled(bool enabled); void setupLeafNodes(LeafNode *nodes, const WindowQuadList *quads, const WindowPaintData &data); void performPaint(int mask, QRegion region, WindowPaintData data) override; private: void renderSubSurface(GLShader *shader, const QMatrix4x4 &mvp, const QMatrix4x4 &windowMatrix, OpenGLWindowPixmap *pixmap, const QRegion ®ion, bool hardwareClipping); /** * Whether prepareStates enabled blending and restore states should disable again. - **/ + */ bool m_blendingEnabled; }; class OpenGLWindowPixmap : public WindowPixmap { public: explicit OpenGLWindowPixmap(Scene::Window *window, SceneOpenGL *scene); ~OpenGLWindowPixmap() override; SceneOpenGLTexture *texture() const; bool bind(); bool isValid() const override; protected: WindowPixmap *createChild(const QPointer &subSurface) override; private: explicit OpenGLWindowPixmap(const QPointer &subSurface, WindowPixmap *parent, SceneOpenGL *scene); QScopedPointer m_texture; SceneOpenGL *m_scene; }; class SceneOpenGL::EffectFrame : public Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame, SceneOpenGL *scene); ~EffectFrame() override; void free() override; void freeIconFrame() override; void freeTextFrame() override; void freeSelection() override; void render(QRegion region, double opacity, double frameOpacity) override; void crossFadeIcon() override; void crossFadeText() override; static void cleanup(); private: void updateTexture(); void updateTextTexture(); GLTexture *m_texture; GLTexture *m_textTexture; GLTexture *m_oldTextTexture; QPixmap *m_textPixmap; // need to keep the pixmap around to workaround some driver problems GLTexture *m_iconTexture; GLTexture *m_oldIconTexture; GLTexture *m_selectionTexture; GLVertexBuffer *m_unstyledVBO; SceneOpenGL *m_scene; static GLTexture* m_unstyledTexture; static QPixmap* m_unstyledPixmap; // need to keep the pixmap around to workaround some driver problems static void updateUnstyledTexture(); // Update OpenGL unstyled frame texture }; /** * @short OpenGL implementation of Shadow. * * This class extends Shadow by the Elements required for OpenGL rendering. * @author Martin Gräßlin - **/ + */ class SceneOpenGLShadow : public Shadow { public: explicit SceneOpenGLShadow(Toplevel *toplevel); ~SceneOpenGLShadow() override; GLTexture *shadowTexture() { return m_texture.data(); } protected: void buildQuads() override; bool prepareBackend() override; private: QSharedPointer m_texture; }; class SceneOpenGLDecorationRenderer : public Decoration::Renderer { Q_OBJECT public: enum class DecorationPart : int { Left, Top, Right, Bottom, Count }; explicit SceneOpenGLDecorationRenderer(Decoration::DecoratedClientImpl *client); ~SceneOpenGLDecorationRenderer() override; void render() override; void reparent(Deleted *deleted) override; GLTexture *texture() { return m_texture.data(); } GLTexture *texture() const { return m_texture.data(); } private: void resizeTexture(); QScopedPointer m_texture; }; inline bool SceneOpenGL::hasPendingFlush() const { return m_backend->hasPendingFlush(); } inline bool SceneOpenGL::usesOverlayWindow() const { return m_backend->usesOverlayWindow(); } inline SceneOpenGLTexture* OpenGLWindowPixmap::texture() const { return m_texture.data(); } class KWIN_EXPORT OpenGLFactory : public SceneFactory { Q_OBJECT Q_INTERFACES(KWin::SceneFactory) Q_PLUGIN_METADATA(IID "org.kde.kwin.Scene" FILE "opengl.json") public: explicit OpenGLFactory(QObject *parent = nullptr); ~OpenGLFactory() override; Scene *create(QObject *parent = nullptr) const override; }; } // namespace #endif diff --git a/plugins/scenes/xrender/scene_xrender.h b/plugins/scenes/xrender/scene_xrender.h index e727206d3..35846b3e6 100644 --- a/plugins/scenes/xrender/scene_xrender.h +++ b/plugins/scenes/xrender/scene_xrender.h @@ -1,358 +1,358 @@ /******************************************************************** 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_XRENDER_H #define KWIN_SCENE_XRENDER_H #include "scene.h" #include "shadow.h" #include "decorations/decorationrenderer.h" #ifdef KWIN_HAVE_XRENDER_COMPOSITING namespace KWin { namespace Xcb { class Shm; } /** * @brief Backend for the SceneXRender to hold the compositing buffer and take care of buffer * swapping. * * This class is intended as a small abstraction to support multiple compositing backends in the * SceneXRender. - **/ + */ class XRenderBackend { public: virtual ~XRenderBackend(); virtual void present(int mask, const QRegion &damage) = 0; /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* - **/ + */ virtual OverlayWindow *overlayWindow(); virtual bool usesOverlayWindow() const = 0; /** * @brief Shows the Overlay Window * * Default implementation does nothing. - **/ + */ virtual void showOverlay(); /** * @brief React on screen geometry changes. * * Default implementation does nothing. Override if specific functionality is required. * * @param size The new screen size - **/ + */ virtual void screenGeometryChanged(const QSize &size); /** * @brief The compositing buffer hold by this backend. * * The Scene composites the new frame into this buffer. * * @return xcb_render_picture_t - **/ + */ xcb_render_picture_t buffer() const { return m_buffer; } /** * @brief Whether the creation of the Backend failed. * * The SceneXRender should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneXRender should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. - **/ + */ bool isFailed() const { return m_failed; } protected: XRenderBackend(); /** * @brief A subclass needs to call this method once it created the compositing back buffer. * * @param buffer The buffer to use for compositing * @return void - **/ + */ void setBuffer(xcb_render_picture_t buffer); /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. - **/ + */ void setFailed(const QString &reason); private: // Create the compositing buffer. The root window is not double-buffered, // so it is done manually using this buffer, xcb_render_picture_t m_buffer; bool m_failed; }; /** * @brief XRenderBackend using an X11 Overlay Window as compositing target. - **/ + */ class X11XRenderBackend : public XRenderBackend { public: X11XRenderBackend(); ~X11XRenderBackend() override; void present(int mask, const QRegion &damage) override; OverlayWindow* overlayWindow() override; void showOverlay() override; void screenGeometryChanged(const QSize &size) override; bool usesOverlayWindow() const override; private: void init(bool createOverlay); void createBuffer(); QScopedPointer m_overlayWindow; xcb_render_picture_t m_front; xcb_render_pictformat_t m_format; }; class SceneXrender : public Scene { Q_OBJECT public: class EffectFrame; ~SceneXrender() override; bool initFailed() const override; CompositingType compositingType() const override { return XRenderCompositing; } qint64 paint(QRegion damage, ToplevelList windows) override; Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame) override; Shadow *createShadow(Toplevel *toplevel) override; void screenGeometryChanged(const QSize &size) override; xcb_render_picture_t xrenderBufferPicture() const override; OverlayWindow *overlayWindow() override { return m_backend->overlayWindow(); } bool usesOverlayWindow() const override { return m_backend->usesOverlayWindow(); } Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *client) override; bool animationsSupported() const override { return true; } static SceneXrender *createScene(QObject *parent); protected: Scene::Window *createWindow(Toplevel *toplevel) override; void paintBackground(QRegion region) override; void paintGenericScreen(int mask, ScreenPaintData data) override; void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data) override; void paintCursor() override; private: explicit SceneXrender(XRenderBackend *backend, QObject *parent = nullptr); static ScreenPaintData screen_paint; class Window; QScopedPointer m_backend; }; class SceneXrender::Window : public Scene::Window { public: Window(Toplevel* c, SceneXrender *scene); ~Window() override; void performPaint(int mask, QRegion region, WindowPaintData data) override; QRegion transformedShape() const; void setTransformedShape(const QRegion& shape); static void cleanup(); protected: WindowPixmap* createWindowPixmap() override; private: QRect mapToScreen(int mask, const WindowPaintData &data, const QRect &rect) const; QPoint mapToScreen(int mask, const WindowPaintData &data, const QPoint &point) const; void prepareTempPixmap(); void setPictureFilter(xcb_render_picture_t pic, ImageFilterType filter); SceneXrender *m_scene; xcb_render_pictformat_t format; QRegion transformed_shape; static QRect temp_visibleRect; static XRenderPicture *s_tempPicture; static XRenderPicture *s_fadeAlphaPicture; }; class XRenderWindowPixmap : public WindowPixmap { public: explicit XRenderWindowPixmap(Scene::Window *window, xcb_render_pictformat_t format); ~XRenderWindowPixmap() override; xcb_render_picture_t picture() const; void create() override; private: xcb_render_picture_t m_picture; xcb_render_pictformat_t m_format; }; class SceneXrender::EffectFrame : public Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame); ~EffectFrame() override; void free() override; void freeIconFrame() override; void freeTextFrame() override; void freeSelection() override; void crossFadeIcon() override; void crossFadeText() override; void render(QRegion region, double opacity, double frameOpacity) override; static void cleanup(); private: void updatePicture(); void updateTextPicture(); void renderUnstyled(xcb_render_picture_t pict, const QRect &rect, qreal opacity); XRenderPicture* m_picture; XRenderPicture* m_textPicture; XRenderPicture* m_iconPicture; XRenderPicture* m_selectionPicture; static XRenderPicture* s_effectFrameCircle; }; inline xcb_render_picture_t SceneXrender::xrenderBufferPicture() const { return m_backend->buffer(); } inline QRegion SceneXrender::Window::transformedShape() const { return transformed_shape; } inline void SceneXrender::Window::setTransformedShape(const QRegion& shape) { transformed_shape = shape; } inline xcb_render_picture_t XRenderWindowPixmap::picture() const { return m_picture; } /** * @short XRender implementation of Shadow. * * This class extends Shadow by the elements required for XRender rendering. * @author Jacopo De Simoi - **/ + */ class SceneXRenderShadow : public Shadow { public: explicit SceneXRenderShadow(Toplevel *toplevel); using Shadow::ShadowElements; using Shadow::ShadowElementTop; using Shadow::ShadowElementTopRight; using Shadow::ShadowElementRight; using Shadow::ShadowElementBottomRight; using Shadow::ShadowElementBottom; using Shadow::ShadowElementBottomLeft; using Shadow::ShadowElementLeft; using Shadow::ShadowElementTopLeft; using Shadow::ShadowElementsCount; using Shadow::shadowPixmap; ~SceneXRenderShadow() override; void layoutShadowRects(QRect& top, QRect& topRight, QRect& right, QRect& bottomRight, QRect& bottom, QRect& bottomLeft, QRect& Left, QRect& topLeft); xcb_render_picture_t picture(ShadowElements element) const; protected: void buildQuads() override; bool prepareBackend() override; private: XRenderPicture* m_pictures[ShadowElementsCount]; }; class SceneXRenderDecorationRenderer : public Decoration::Renderer { Q_OBJECT public: enum class DecorationPart : int { Left, Top, Right, Bottom, Count }; explicit SceneXRenderDecorationRenderer(Decoration::DecoratedClientImpl *client); ~SceneXRenderDecorationRenderer() override; void render() override; void reparent(Deleted *deleted) override; xcb_render_picture_t picture(DecorationPart part) const; private: void resizePixmaps(); QSize m_sizes[int(DecorationPart::Count)]; xcb_pixmap_t m_pixmaps[int(DecorationPart::Count)]; xcb_gcontext_t m_gc; XRenderPicture* m_pictures[int(DecorationPart::Count)]; }; class KWIN_EXPORT XRenderFactory : public SceneFactory { Q_OBJECT Q_INTERFACES(KWin::SceneFactory) Q_PLUGIN_METADATA(IID "org.kde.kwin.Scene" FILE "xrender.json") public: explicit XRenderFactory(QObject *parent = nullptr); ~XRenderFactory() override; Scene *create(QObject *parent = nullptr) const override; }; } // namespace #endif #endif diff --git a/pointer_input.h b/pointer_input.h index 2e41e16bd..31cf04fb7 100644 --- a/pointer_input.h +++ b/pointer_input.h @@ -1,259 +1,259 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013, 2016 Martin Gräßlin Copyright (C) 2018 Roman Gilg Copyright (C) 2019 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 KWIN_POINTER_INPUT_H #define KWIN_POINTER_INPUT_H #include "input.h" #include #include #include #include class QWindow; namespace KWayland { namespace Server { class SurfaceInterface; } } namespace KWin { class CursorImage; class InputRedirection; class Toplevel; class WaylandCursorTheme; class CursorShape; namespace Decoration { class DecoratedClientImpl; } namespace LibInput { class Device; } class KWIN_EXPORT PointerInputRedirection : public InputDeviceHandler { Q_OBJECT public: explicit PointerInputRedirection(InputRedirection *parent); ~PointerInputRedirection() override; void init() override; void updateAfterScreenChange(); bool supportsWarping() const; void warp(const QPointF &pos); QPointF pos() const { return m_pos; } Qt::MouseButtons buttons() const { return m_qtButtons; } bool areButtonsPressed() const; QImage cursorImage() const; QPoint cursorHotSpot() const; void markCursorAsRendered(); void setEffectsOverrideCursor(Qt::CursorShape shape); void removeEffectsOverrideCursor(); void setWindowSelectionCursor(const QByteArray &shape); void removeWindowSelectionCursor(); void updatePointerConstraints(); void setEnableConstraints(bool set); bool isConstrained() const { return m_confined || m_locked; } bool focusUpdatesBlocked() override; /** * @internal - **/ + */ void processMotion(const QPointF &pos, uint32_t time, LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processMotion(const QPointF &pos, const QSizeF &delta, const QSizeF &deltaNonAccelerated, uint32_t time, quint64 timeUsec, LibInput::Device *device); /** * @internal - **/ + */ void processButton(uint32_t button, InputRedirection::PointerButtonState state, uint32_t time, LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processAxis(InputRedirection::PointerAxis axis, qreal delta, qint32 discreteDelta, InputRedirection::PointerAxisSource source, uint32_t time, LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processSwipeGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processSwipeGestureUpdate(const QSizeF &delta, quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processSwipeGestureEnd(quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processSwipeGestureCancelled(quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processPinchGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processPinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processPinchGestureEnd(quint32 time, KWin::LibInput::Device *device = nullptr); /** * @internal - **/ + */ void processPinchGestureCancelled(quint32 time, KWin::LibInput::Device *device = nullptr); private: void cleanupInternalWindow(QWindow *old, QWindow *now) override; void cleanupDecoration(Decoration::DecoratedClientImpl *old, Decoration::DecoratedClientImpl *now) override; void focusUpdate(Toplevel *focusOld, Toplevel *focusNow) override; QPointF position() const override; void updateOnStartMoveResize(); void updateToReset(); void updatePosition(const QPointF &pos); void updateButton(uint32_t button, InputRedirection::PointerButtonState state); void warpXcbOnSurfaceLeft(KWayland::Server::SurfaceInterface *surface); QPointF applyPointerConfinement(const QPointF &pos) const; void disconnectConfinedPointerRegionConnection(); void disconnectLockedPointerAboutToBeUnboundConnection(); void disconnectPointerConstraintsConnection(); void breakPointerConstraints(KWayland::Server::SurfaceInterface *surface); CursorImage *m_cursor; bool m_supportsWarping; QPointF m_pos; QHash m_buttons; Qt::MouseButtons m_qtButtons; QMetaObject::Connection m_focusGeometryConnection; QMetaObject::Connection m_internalWindowConnection; QMetaObject::Connection m_constraintsConnection; QMetaObject::Connection m_constraintsActivatedConnection; QMetaObject::Connection m_confinedPointerRegionConnection; QMetaObject::Connection m_lockedPointerAboutToBeUnboundConnection; QMetaObject::Connection m_decorationGeometryConnection; bool m_confined = false; bool m_locked = false; bool m_enableConstraints = true; }; class CursorImage : public QObject { Q_OBJECT public: explicit CursorImage(PointerInputRedirection *parent = nullptr); ~CursorImage() override; void setEffectsOverrideCursor(Qt::CursorShape shape); void removeEffectsOverrideCursor(); void setWindowSelectionCursor(const QByteArray &shape); void removeWindowSelectionCursor(); QImage image() const; QPoint hotSpot() const; void markAsRendered(); Q_SIGNALS: void changed(); private: void reevaluteSource(); void update(); void updateServerCursor(); void updateDecoration(); void updateDecorationCursor(); void updateMoveResize(); void updateDrag(); void updateDragCursor(); void loadTheme(); struct Image { QImage image; QPoint hotSpot; }; void loadThemeCursor(CursorShape shape, Image *image); void loadThemeCursor(const QByteArray &shape, Image *image); template void loadThemeCursor(const T &shape, QHash &cursors, Image *image); enum class CursorSource { LockScreen, EffectsOverride, MoveResize, PointerSurface, Decoration, DragAndDrop, Fallback, WindowSelector }; void setSource(CursorSource source); PointerInputRedirection *m_pointer; CursorSource m_currentSource = CursorSource::Fallback; WaylandCursorTheme *m_cursorTheme = nullptr; struct { QMetaObject::Connection connection; QImage image; QPoint hotSpot; } m_serverCursor; Image m_effectsCursor; Image m_decorationCursor; QMetaObject::Connection m_decorationConnection; Image m_fallbackCursor; Image m_moveResizeCursor; Image m_windowSelectionCursor; QHash m_cursors; QHash m_cursorsByName; QElapsedTimer m_surfaceRenderedTimer; struct { Image cursor; QMetaObject::Connection connection; } m_drag; }; } #endif diff --git a/scene.h b/scene.h index b426f2c01..29256ccf5 100644 --- a/scene.h +++ b/scene.h @@ -1,689 +1,689 @@ /******************************************************************** 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); ~Scene() override = 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; /** * Adds the Toplevel to the Scene. * * If the toplevel gets deleted, then the scene will try automatically * to re-bind an underlying scene window to the corresponding Deleted. * * @param toplevel The window to be added. * @note You can add a toplevel to scene only once. - **/ + */ void addToplevel(Toplevel *toplevel); /** * Removes the Toplevel from the Scene. * * @param toplevel The window to be removed. * @note You can remove a toplevel from the scene only once. - **/ + */ void removeToplevel(Toplevel *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: // 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 { Window *window = nullptr; QRegion region; QRegion clip; int mask = 0; 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: ~SceneFactory() override; /** * @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 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 * 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 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 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 isValid will return @c false. The pixmap mapping to the window can be established * through @ref create. If it succeeds 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 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, 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 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 fd8f83368..a7159f79c 100644 --- a/screenedge.h +++ b/screenedge.h @@ -1,591 +1,591 @@ /******************************************************************** 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); ~Edge() override; 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. 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 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: ~ScreenEdges() override; /** * @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 * @param o Qt orientations - **/ + */ 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/screens.h b/screens.h index a92d96f4b..13c1414e2 100644 --- a/screens.h +++ b/screens.h @@ -1,255 +1,255 @@ /******************************************************************** 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_SCREENS_H #define KWIN_SCREENS_H // KWin includes #include // KDE includes #include #include // Qt includes #include #include #include #include namespace KWin { class AbstractClient; class Platform; class OrientationSensor; class KWIN_EXPORT Screens : public QObject { Q_OBJECT Q_PROPERTY(int count READ count WRITE setCount NOTIFY countChanged) Q_PROPERTY(int current READ current WRITE setCurrent NOTIFY currentChanged) Q_PROPERTY(bool currentFollowsMouse READ isCurrentFollowsMouse WRITE setCurrentFollowsMouse) public: ~Screens() override; /** * @internal - **/ + */ void setConfig(KSharedConfig::Ptr config); int count() const; int current() const; void setCurrent(int current); /** * Called e.g. when a user clicks on a window, set current screen to be the screen * where the click occurred - **/ + */ void setCurrent(const QPoint &pos); /** * Check whether a client moved completely out of what's considered the current screen, * if yes, set a new active screen. - **/ + */ void setCurrent(const AbstractClient *c); bool isCurrentFollowsMouse() const; void setCurrentFollowsMouse(bool follows); virtual QRect geometry(int screen) const = 0; /** * The bounding geometry of all screens combined. Overlapping areas * are not counted multiple times. * @see geometryChanged() - **/ + */ QRect geometry() const; /** * The output name of the screen (usually eg. LVDS-1, VGA-0 or DVI-I-1 etc.) - **/ + */ virtual QString name(int screen) const; /** * @returns current refreshrate of the @p screen. - **/ + */ virtual float refreshRate(int screen) const; /** * @returns size of the @p screen. * * To get the size of all screens combined use size(). * @see size() - **/ + */ virtual QSize size(int screen) const = 0; /** * The highest scale() of all connected screens * for use when deciding what scale to load global assets at * Similar to QGuiApplication::scale * @see scale - **/ + */ qreal maxScale() const; /** * The output scale for this display, for use by high DPI displays - **/ + */ virtual qreal scale(int screen) const; /** * The bounding size of all screens combined. Overlapping areas * are not counted multiple times. * * @see geometry() * @see sizeChanged() - **/ + */ QSize size() const; virtual int number(const QPoint &pos) const = 0; inline bool isChanging() { return m_changedTimer->isActive(); } int intersecting(const QRect &r) const; /** * The virtual bounding size of all screens combined. * The default implementation returns the same as @ref size and that is the * method which should be preferred. * * This method is only for cases where the platform specific implementation needs * to support different virtual sizes like on X11 with XRandR panning. * * @see size - **/ + */ virtual QSize displaySize() const; /** * The physical size of @p screen in mm. * Default implementation returns a size derived from 96 DPI. - **/ + */ virtual QSizeF physicalSize(int screen) const; /** * @returns @c true if the @p screen is connected through an internal display (e.g. LVDS). * Default implementation returns @c false. - **/ + */ virtual bool isInternal(int screen) const; /** * @returns @c true if the @p screen can be rotated. * Default implementation returns @c false - **/ + */ virtual bool supportsTransformations(int screen) const; virtual Qt::ScreenOrientation orientation(int screen) const; /** * Provides access to the OrientationSensor. The OrientationSensor is controlled by the * base implementation. The implementing subclass can use this to get notifications about * changes of the orientation and current orientation. There is no need to enable/disable it, * that is done by the base implementation - **/ + */ OrientationSensor *orientationSensor() const { return m_orientationSensor; } public Q_SLOTS: void reconfigure(); Q_SIGNALS: void countChanged(int previousCount, int newCount); /** * Emitted whenever the screens are changed either count or geometry. - **/ + */ void changed(); void currentChanged(); /** * Emitted when the geometry of all screens combined changes. * Not emitted when the geometry of an individual screen changes. * @see geometry() - **/ + */ void geometryChanged(); /** * Emitted when the size of all screens combined changes. * Not emitted when the size of an individual screen changes. * @see size() - **/ + */ void sizeChanged(); /** * Emitted when the maximum scale of all attached screens changes * @see maxScale - **/ + */ void maxScaleChanged(); protected Q_SLOTS: void setCount(int count); void startChangedTimer(); virtual void updateCount() = 0; protected: /** * Called once the singleton instance has been created. * Any initialization code should go into this method. Overriding classes have to call * the base implementation first. - **/ + */ virtual void init(); private Q_SLOTS: void updateSize(); private: int m_count; int m_current; bool m_currentFollowsMouse; QTimer *m_changedTimer; KSharedConfig::Ptr m_config; QSize m_boundingSize; OrientationSensor *m_orientationSensor; qreal m_maxScale; KWIN_SINGLETON(Screens) }; inline int Screens::count() const { return m_count; } inline bool Screens::isCurrentFollowsMouse() const { return m_currentFollowsMouse; } inline void Screens::startChangedTimer() { m_changedTimer->start(); } inline QSize Screens::size() const { return m_boundingSize; } inline QRect Screens::geometry() const { return QRect(QPoint(0,0), size()); } inline Screens *screens() { return Screens::self(); } } #endif // KWIN_SCREENS_H diff --git a/scripting/dbuscall.h b/scripting/dbuscall.h index 9d3a4a0af..7b9391251 100644 --- a/scripting/dbuscall.h +++ b/scripting/dbuscall.h @@ -1,147 +1,147 @@ /******************************************************************** 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_DBUSCALL_H #define KWIN_DBUSCALL_H #include #include namespace KWin { /** * @brief Qml export for providing a wrapper for sending a message over the DBus * session bus. * * Allows to setup the connection arguments just like in QDBusMessage and supports * adding arguments to the call. To invoke the message use the slot @ref call. * * If the call succeeds the signal @ref finished is emitted, if the call fails * the signal @ref failed is emitted. * * Note: the DBusCall always uses the session bus and performs an async call. * * Example on how to use in Qml: * @code * DBusCall { * id: dbus * service: "org.kde.KWin" * path: "/KWin" * method: "nextDesktop" * Component.onCompleted: dbus.call() * } * @endcode * * Example with arguments: * @code * DBusCall { * id: dbus * service: "org.kde.KWin" * path: "/KWin" * method: "setCurrentDesktop" * arguments: [1] * Component.onCompleted: dbus.call() * } * @endcode * * Example with a callback: * @code * DBusCall { * id: dbus * service: "org.kde.KWin" * path: "/KWin" * method: "currentDesktop" * onFinished: console.log(returnValue[0]) * } * @endcode - **/ + */ class DBusCall : public QObject { Q_OBJECT Q_PROPERTY(QString service READ service WRITE setService NOTIFY serviceChanged) Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged) Q_PROPERTY(QString dbusInterface READ interface WRITE setInterface NOTIFY interfaceChanged) Q_PROPERTY(QString method READ method WRITE setMethod NOTIFY methodChanged) Q_PROPERTY(QVariantList arguments READ arguments WRITE setArguments NOTIFY argumentsChanged) public: explicit DBusCall(QObject* parent = 0); ~DBusCall() override; const QString &service() const; const QString &path() const; const QString &interface() const; const QString &method() const; const QVariantList &arguments() const; public Q_SLOTS: void call(); void setService(const QString &service); void setPath(const QString &path); void setInterface(const QString &interface); void setMethod(const QString &method); void setArguments(const QVariantList &arguments); Q_SIGNALS: void finished(QVariantList returnValue); void failed(); void serviceChanged(); void pathChanged(); void interfaceChanged(); void methodChanged(); void argumentsChanged(); private: QString m_service; QString m_path; QString m_interface; QString m_method; QVariantList m_arguments; }; #define GENERIC_WRAPPER(type, name, upperName) \ inline type DBusCall::name() const \ { \ return m_##name; \ }\ inline void DBusCall::set##upperName(type name) \ {\ if (m_##name == name) { \ return; \ } \ m_##name = name; \ emit name##Changed(); \ } #define WRAPPER(name, upperName) \ GENERIC_WRAPPER(const QString&, name, upperName) WRAPPER(interface, Interface) WRAPPER(method, Method) WRAPPER(path, Path) WRAPPER(service, Service) GENERIC_WRAPPER(const QVariantList &, arguments, Arguments) #undef WRAPPER #undef GENERIC_WRAPPER } // KWin #endif // KWIN_SCRIPTING_DBUSCALL_H diff --git a/scripting/meta.cpp b/scripting/meta.cpp index 406bdc1eb..14064e5ba 100644 --- a/scripting/meta.cpp +++ b/scripting/meta.cpp @@ -1,241 +1,241 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 Rohan Prabhu 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 . *********************************************************************/ #include "meta.h" #include "client.h" #include using namespace KWin::MetaScripting; // Meta for QPoint object QScriptValue Point::toScriptValue(QScriptEngine* eng, const QPoint& point) { QScriptValue temp = eng->newObject(); temp.setProperty(QStringLiteral("x"), point.x()); temp.setProperty(QStringLiteral("y"), point.y()); return temp; } void Point::fromScriptValue(const QScriptValue& obj, QPoint& point) { QScriptValue x = obj.property(QStringLiteral("x"), QScriptValue::ResolveLocal); QScriptValue y = obj.property(QStringLiteral("y"), QScriptValue::ResolveLocal); if (!x.isUndefined() && !y.isUndefined()) { point.setX(x.toInt32()); point.setY(y.toInt32()); } } // End of meta for QPoint object // Meta for QSize object QScriptValue Size::toScriptValue(QScriptEngine* eng, const QSize& size) { QScriptValue temp = eng->newObject(); temp.setProperty(QStringLiteral("w"), size.width()); temp.setProperty(QStringLiteral("h"), size.height()); return temp; } void Size::fromScriptValue(const QScriptValue& obj, QSize& size) { QScriptValue w = obj.property(QStringLiteral("w"), QScriptValue::ResolveLocal); QScriptValue h = obj.property(QStringLiteral("h"), QScriptValue::ResolveLocal); if (!w.isUndefined() && !h.isUndefined()) { size.setWidth(w.toInt32()); size.setHeight(h.toInt32()); } } // End of meta for QSize object // Meta for QRect object. Just a temporary measure, hope to // add a much better wrapping of the QRect object soon QScriptValue Rect::toScriptValue(QScriptEngine* eng, const QRect& rect) { QScriptValue temp = eng->newObject(); temp.setProperty(QStringLiteral("x"), rect.x()); temp.setProperty(QStringLiteral("y"), rect.y()); temp.setProperty(QStringLiteral("width"), rect.width()); temp.setProperty(QStringLiteral("height"), rect.height()); return temp; } void Rect::fromScriptValue(const QScriptValue& obj, QRect &rect) { QScriptValue w = obj.property(QStringLiteral("width"), QScriptValue::ResolveLocal); QScriptValue h = obj.property(QStringLiteral("height"), QScriptValue::ResolveLocal); QScriptValue x = obj.property(QStringLiteral("x"), QScriptValue::ResolveLocal); QScriptValue y = obj.property(QStringLiteral("y"), QScriptValue::ResolveLocal); if (!w.isUndefined() && !h.isUndefined() && !x.isUndefined() && !y.isUndefined()) { rect.setX(x.toInt32()); rect.setY(y.toInt32()); rect.setWidth(w.toInt32()); rect.setHeight(h.toInt32()); } } // End of meta for QRect object QScriptValue Client::toScriptValue(QScriptEngine *eng, const KClientRef &client) { return eng->newQObject(client, QScriptEngine::QtOwnership, QScriptEngine::ExcludeChildObjects | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject | QScriptEngine::AutoCreateDynamicProperties); } void Client::fromScriptValue(const QScriptValue &value, KWin::Client* &client) { client = qobject_cast(value.toQObject()); } QScriptValue Toplevel::toScriptValue(QScriptEngine *eng, const KToplevelRef &client) { return eng->newQObject(client, QScriptEngine::QtOwnership, QScriptEngine::ExcludeChildObjects | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject | QScriptEngine::AutoCreateDynamicProperties); } void Toplevel::fromScriptValue(const QScriptValue &value, KToplevelRef &client) { client = qobject_cast(value.toQObject()); } // Other helper functions void KWin::MetaScripting::registration(QScriptEngine* eng) { qScriptRegisterMetaType(eng, Point::toScriptValue, Point::fromScriptValue); qScriptRegisterMetaType(eng, Size::toScriptValue, Size::fromScriptValue); qScriptRegisterMetaType(eng, Rect::toScriptValue, Rect::fromScriptValue); qScriptRegisterMetaType(eng, Client::toScriptValue, Client::fromScriptValue); qScriptRegisterMetaType(eng, Toplevel::toScriptValue, Toplevel::fromScriptValue); qScriptRegisterSequenceMetaType(eng); qScriptRegisterSequenceMetaType< QList >(eng); qScriptRegisterSequenceMetaType< QList >(eng); } QScriptValue KWin::MetaScripting::configExists(QScriptContext* ctx, QScriptEngine* eng) { QHash scriptConfig = (((ctx->thisObject()).data()).toVariant()).toHash(); QVariant val = scriptConfig.value((ctx->argument(0)).toString(), QVariant()); return eng->toScriptValue(val.isValid()); } QScriptValue KWin::MetaScripting::getConfigValue(QScriptContext* ctx, QScriptEngine* eng) { int num = ctx->argumentCount(); QHash scriptConfig = (((ctx->thisObject()).data()).toVariant()).toHash(); /* * Handle config.get() separately. Compute and return immediately. - **/ + */ if (num == 0) { QHash::const_iterator i; QScriptValue ret = eng->newArray(); for (i = scriptConfig.constBegin(); i != scriptConfig.constEnd(); ++i) { ret.setProperty(i.key(), eng->newVariant(i.value())); } return ret; } if ((num == 1) && !((ctx->argument(0)).isArray())) { QVariant val = scriptConfig.value((ctx->argument(0)).toString(), QVariant()); if (val.isValid()) { return eng->newVariant(val); } else { return QScriptValue(); } } else { QScriptValue ret = eng->newArray(); int j = 0; if ((ctx->argument(0)).isArray()) { bool simple = (num == 1) ? 0 : (ctx->argument(1)).toBool(); QScriptValue array = (ctx->argument(0)); int len = (array.property(QStringLiteral("length")).isValid()) ? array.property(QStringLiteral("length")).toNumber() : 0; for (int i = 0; i < len; i++) { QVariant val = scriptConfig.value(array.property(i).toString(), QVariant()); if (val.isValid()) { if (simple) { ret.setProperty(j, eng->newVariant(val)); } else { ret.setProperty(array.property(i).toString(), eng->newVariant(val)); } j++; } } } else { for (int i = 0; i < num; i++) { QVariant val = scriptConfig.value((ctx->argument(i)).toString(), QVariant()); if (val.isValid()) { ret.setProperty((ctx->argument(i)).toString(), eng->newVariant(val)); j = 1; } } } if (j == 0) { return QScriptValue(); } else { return ret; } } } void KWin::MetaScripting::supplyConfig(QScriptEngine* eng, const QVariant& scriptConfig) { QScriptValue configObject = eng->newObject(); configObject.setData(eng->newVariant(scriptConfig)); configObject.setProperty(QStringLiteral("get"), eng->newFunction(getConfigValue, 0), QScriptValue::Undeletable); configObject.setProperty(QStringLiteral("exists"), eng->newFunction(configExists, 0), QScriptValue::Undeletable); configObject.setProperty(QStringLiteral("loaded"), ((scriptConfig.toHash().empty()) ? eng->newVariant((bool)0) : eng->newVariant((bool)1)), QScriptValue::Undeletable); (eng->globalObject()).setProperty(QStringLiteral("config"), configObject); } void KWin::MetaScripting::supplyConfig(QScriptEngine* eng) { KWin::MetaScripting::supplyConfig(eng, QVariant(QHash())); } void KWin::MetaScripting::valueMerge(QScriptValue& first, QScriptValue second) { QScriptValueIterator value_it(second); while (value_it.hasNext()) { value_it.next(); first.setProperty(value_it.name(), value_it.value()); } } diff --git a/scripting/meta.h b/scripting/meta.h index e086b182f..2626f3a4d 100644 --- a/scripting/meta.h +++ b/scripting/meta.h @@ -1,127 +1,127 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 Rohan Prabhu 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_SCRIPTING_META_H #define KWIN_SCRIPTING_META_H #include // forward declarations class QPoint; class QRect; class QScriptContext; class QSize; namespace KWin { class Client; class Toplevel; } typedef KWin::Client* KClientRef; typedef KWin::Toplevel* KToplevelRef; namespace KWin { namespace MetaScripting { /** * The toScriptValue and fromScriptValue functions used in qScriptRegisterMetaType. * Conversion functions for QPoint - **/ + */ namespace Point { QScriptValue toScriptValue(QScriptEngine*, const QPoint&); void fromScriptValue(const QScriptValue&, QPoint&); } /** * The toScriptValue and fromScriptValue functions used in qScriptRegisterMetaType. * Conversion functions for QSize - **/ + */ namespace Size { QScriptValue toScriptValue(QScriptEngine*, const QSize&); void fromScriptValue(const QScriptValue&, QSize&); } /** * The toScriptValue and fromScriptValue functions used in qScriptRegisterMetaType. * Conversion functions for QRect * TODO: QRect conversions have to be linked from plasma as they provide a lot more * features. As for QSize and QPoint, I don't really plan any such thing. - **/ + */ namespace Rect { QScriptValue toScriptValue(QScriptEngine*, const QRect&); void fromScriptValue(const QScriptValue&, QRect&); } namespace Client { QScriptValue toScriptValue(QScriptEngine *eng, const KClientRef &client); void fromScriptValue(const QScriptValue &value, KClientRef& client); } namespace Toplevel { QScriptValue toScriptValue(QScriptEngine *eng, const KToplevelRef &client); void fromScriptValue(const QScriptValue &value, KToplevelRef& client); } /** * Merges the second QScriptValue in the first one. - **/ + */ void valueMerge(QScriptValue&, QScriptValue); /** * Registers all the meta conversion to the provided QScriptEngine - **/ + */ void registration(QScriptEngine* eng); /** * Functions for the JS function objects, config.exists and config.get. * Read scripting/IMPLIST for details on how they work - **/ + */ QScriptValue configExists(QScriptContext*, QScriptEngine*); QScriptValue getConfigValue(QScriptContext*, QScriptEngine*); /** * Provide a config object to the given QScriptEngine depending * on the keys provided in the QVariant. The provided QVariant * MUST returns (true) on isHash() - **/ + */ void supplyConfig(QScriptEngine*, const QVariant&); /** * For engines whose scripts have no associated configuration. - **/ + */ void supplyConfig(QScriptEngine*); } } /** * Code linked from plasma for QTimer. - **/ + */ QScriptValue constructTimerClass(QScriptEngine *eng); #endif diff --git a/scripting/screenedgeitem.h b/scripting/screenedgeitem.h index 324223af8..c5e10e85b 100644 --- a/scripting/screenedgeitem.h +++ b/scripting/screenedgeitem.h @@ -1,126 +1,126 @@ /******************************************************************** 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_SCREENEDGEITEM_H #define KWIN_SCREENEDGEITEM_H #include #include class QAction; namespace KWin { /** * @brief Qml export for reserving a Screen Edge. * * The edge is controlled by the @c enabled property and the @c edge * property. If the edge is enabled and gets triggered the @ref activated() * signal gets emitted. * * Example usage: * @code * ScreenEdgeItem { * edge: ScreenEdgeItem.LeftEdge * onActivated: doSomething() * } * @endcode - **/ + */ class ScreenEdgeItem : public QObject { Q_OBJECT Q_ENUMS(Edge) Q_ENUMS(Mode) /** * @brief Whether the edge is currently enabled, that is reserved. Default value is @c true. - **/ + */ Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged) /** * @brief Which of the screen edges is to be reserved. Default value is @c NoEdge. - **/ + */ Q_PROPERTY(Edge edge READ edge WRITE setEdge NOTIFY edgeChanged) /** * @brief The operation mode for this edge. Default value is @c Mode::Pointer - **/ + */ Q_PROPERTY(Mode mode READ mode WRITE setMode NOTIFY modeChanged) public: enum Edge { TopEdge, TopRightEdge, RightEdge, BottomRightEdge, BottomEdge, BottomLeftEdge, LeftEdge, TopLeftEdge, EDGE_COUNT, NoEdge }; /** * Enum describing the operation modes of the edge. - **/ + */ enum class Mode { Pointer, Touch }; explicit ScreenEdgeItem(QObject *parent = 0); ~ScreenEdgeItem() override; bool isEnabled() const; Edge edge() const; Mode mode() const { return m_mode; } public Q_SLOTS: void setEnabled(bool enabled); void setEdge(Edge edge); void setMode(Mode mode); Q_SIGNALS: void enabledChanged(); void edgeChanged(); void modeChanged(); void activated(); private Q_SLOTS: bool borderActivated(ElectricBorder edge); private: void enableEdge(); void disableEdge(); bool m_enabled; Edge m_edge; Mode m_mode = Mode::Pointer; QAction *m_action; }; inline bool ScreenEdgeItem::isEnabled() const { return m_enabled; } inline ScreenEdgeItem::Edge ScreenEdgeItem::edge() const { return m_edge; } } // namespace KWin #endif // KWIN_SCREENEDGEITEM_H diff --git a/scripting/scriptedeffect.h b/scripting/scriptedeffect.h index a98050d4b..6f1cb57c4 100644 --- a/scripting/scriptedeffect.h +++ b/scripting/scriptedeffect.h @@ -1,167 +1,167 @@ /******************************************************************** 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_SCRIPTEDEFFECT_H #define KWIN_SCRIPTEDEFFECT_H #include class KConfigLoader; class KPluginMetaData; class QScriptEngine; class QScriptValue; namespace KWin { class KWIN_EXPORT ScriptedEffect : public KWin::AnimationEffect { Q_OBJECT Q_ENUMS(DataRole) Q_ENUMS(Qt::Axis) Q_ENUMS(Anchor) Q_ENUMS(MetaType) Q_ENUMS(EasingCurve) /** * True if we are the active fullscreen effect - **/ + */ Q_PROPERTY(bool isActiveFullScreenEffect READ isActiveFullScreenEffect NOTIFY isActiveFullScreenEffectChanged) public: // copied from kwineffects.h 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 }; enum EasingCurve { GaussianCurve = 128 }; const QString &scriptFile() const { return m_scriptFile; } void reconfigure(ReconfigureFlags flags) override; int requestedEffectChainPosition() const override { return m_chainPosition; } QString activeConfig() const; void setActiveConfig(const QString &name); static ScriptedEffect *create(const QString &effectName, const QString &pathToScript, int chainPosition); static ScriptedEffect *create(const KPluginMetaData &effect); static bool supported(); ~ScriptedEffect() override; /** * Whether another effect has grabbed the @p w with the given @p grabRole. * @param w The window to check * @param grabRole The grab role to check * @returns @c true if another window has grabbed the effect, @c false otherwise - **/ + */ Q_SCRIPTABLE bool isGrabbed(KWin::EffectWindow *w, DataRole grabRole); /** * Grabs the window with the specified role. * * @param w The window. * @param grabRole The grab role. * @param force By default, if the window is already grabbed by another effect, * then that window won't be grabbed by effect that called this method. If you * would like to grab a window even if it's grabbed by another effect, then * pass @c true. * @returns @c true if the window was grabbed successfully, otherwise @c false. - **/ + */ Q_SCRIPTABLE bool grab(KWin::EffectWindow *w, DataRole grabRole, bool force = false); /** * Ungrabs the window with the specified role. * * @param w The window. * @param grabRole The grab role. * @returns @c true if the window was ungrabbed successfully, otherwise @c false. - **/ + */ Q_SCRIPTABLE bool ungrab(KWin::EffectWindow *w, DataRole grabRole); /** * Reads the value from the configuration data for the given key. * @param key The key to search for * @param defaultValue The value to return if the key is not found * @returns The config value if present - **/ + */ Q_SCRIPTABLE QVariant readConfig(const QString &key, const QVariant defaultValue = QVariant()); void registerShortcut(QAction *a, QScriptValue callback); const QHash &shortcutCallbacks() const { return m_shortcutCallbacks; } QHash > &screenEdgeCallbacks() { return m_screenEdgeCallbacks; } bool isActiveFullScreenEffect() const; bool registerTouchScreenCallback(int edge, QScriptValue callback); bool unregisterTouchScreenCallback(int edge); public Q_SLOTS: //curve should be of type QEasingCurve::type or ScriptedEffect::EasingCurve quint64 animate(KWin::EffectWindow *w, Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from = KWin::FPx2(), uint metaData = 0, int curve = QEasingCurve::Linear, int delay = 0, bool fullScreen = false, bool keepAlive = true); quint64 set(KWin::EffectWindow *w, Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from = KWin::FPx2(), uint metaData = 0, int curve = QEasingCurve::Linear, int delay = 0, bool fullScreen = false, bool keepAlive = true); bool retarget(quint64 animationId, KWin::FPx2 newTarget, int newRemainingTime = -1); bool redirect(quint64 animationId, Direction direction, TerminationFlags terminationFlags = TerminateAtSource); bool complete(quint64 animationId); bool cancel(quint64 animationId) { return AnimationEffect::cancel(animationId); } bool borderActivated(ElectricBorder border) override; Q_SIGNALS: /** * Signal emitted whenever the effect's config changed. - **/ + */ void configChanged(); void animationEnded(KWin::EffectWindow *w, quint64 animationId); void isActiveFullScreenEffectChanged(); protected: ScriptedEffect(); QScriptEngine *engine() const; bool init(const QString &effectName, const QString &pathToScript); void animationEnded(KWin::EffectWindow *w, Attribute a, uint meta) override; private Q_SLOTS: void signalHandlerException(const QScriptValue &value); void globalShortcutTriggered(); private: QScriptEngine *m_engine; QString m_effectName; QString m_scriptFile; QHash m_shortcutCallbacks; QHash > m_screenEdgeCallbacks; KConfigLoader *m_config; int m_chainPosition; QHash m_touchScreenEdgeCallbacks; Effect *m_activeFullScreenEffect = nullptr; }; } #endif // KWIN_SCRIPTEDEFFECT_H diff --git a/scripting/scripting.h b/scripting/scripting.h index 7f467af14..d8bfed400 100644 --- a/scripting/scripting.h +++ b/scripting/scripting.h @@ -1,432 +1,432 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 Rohan Prabhu Copyright (C) 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_SCRIPTING_H #define KWIN_SCRIPTING_H #include #include #include #include #include #include #include #include class QQmlComponent; class QQmlContext; class QQmlEngine; class QAction; class QDBusPendingCallWatcher; class QGraphicsScene; class QMenu; class QMutex; class QScriptEngine; class QScriptValue; class QQuickWindow; class KConfigGroup; /// @c true == javascript, @c false == qml typedef QList< QPair > > LoadScriptList; namespace KWin { class AbstractClient; class Client; class ScriptUnloaderAgent; class QtScriptWorkspaceWrapper; class KWIN_EXPORT AbstractScript : public QObject { Q_OBJECT public: AbstractScript(int id, QString scriptName, QString pluginName, QObject *parent = nullptr); ~AbstractScript() override; QString fileName() const { return m_fileName; } const QString &pluginName() { return m_pluginName; } void printMessage(const QString &message); void registerShortcut(QAction *a, QScriptValue callback); /** * @brief Registers the given @p callback to be invoked whenever the UserActionsMenu is about * to be showed. In the callback the script can create a further sub menu or menu entry to be * added to the UserActionsMenu. * * @param callback Script method to execute when the UserActionsMenu is about to be shown. * @return void * @see actionsForUserActionMenu - **/ + */ void registerUseractionsMenuCallback(QScriptValue callback); /** * @brief Creates actions for the UserActionsMenu by invoking the registered callbacks. * * This method invokes all the callbacks previously registered with registerUseractionsMenuCallback. * The Client @p c is passed in as an argument to the invoked method. * * The invoked method is supposed to return a JavaScript object containing either the menu or * menu entry to be added. In case the callback returns a null or undefined or any other invalid * value, it is not considered for adding to the menu. * * The JavaScript object structure for a menu entry looks like the following: * @code * { * title: "My Menu Entry", * checkable: true, * checked: false, * triggered: function (action) { * // callback when the menu entry is triggered with the QAction as argument * } * } * @endcode * * To construct a complete Menu the JavaScript object looks like the following: * @code * { * title: "My Menu Title", * items: [{...}, {...}, ...] // list of menu entries as described above * } * @endcode * * The returned JavaScript object is introspected and for a menu entry a QAction is created, * while for a menu a QMenu is created and QActions for the individual entries. Of course it * is allowed to have nested structures. * * All created objects are (grand) children to the passed in @p parent menu, so that they get * deleted whenever the menu is destroyed. * * @param c The Client for which the menu is invoked, passed to the callback * @param parent The Parent for the created Menus or Actions * @return QList< QAction* > List of QActions obtained from asking the registered callbacks * @see registerUseractionsMenuCallback - **/ + */ QList actionsForUserActionMenu(AbstractClient *c, QMenu *parent); KConfigGroup config() const; const QHash &shortcutCallbacks() const { return m_shortcutCallbacks; } QHash > &screenEdgeCallbacks() { return m_screenEdgeCallbacks; } int registerCallback(QScriptValue value); public Q_SLOTS: Q_SCRIPTABLE void stop(); Q_SCRIPTABLE virtual void run() = 0; void slotPendingDBusCall(QDBusPendingCallWatcher *watcher); private Q_SLOTS: void globalShortcutTriggered(); bool borderActivated(ElectricBorder edge); /** * @brief Slot invoked when a menu action is destroyed. Used to remove the action and callback * from the map of actions. * * @param object The destroyed action - **/ + */ void actionDestroyed(QObject *object); Q_SIGNALS: Q_SCRIPTABLE void print(const QString &text); void runningChanged(bool); protected: bool running() const { return m_running; } void setRunning(bool running) { if (m_running == running) { return; } m_running = running; emit runningChanged(m_running); } int scriptId() const { return m_scriptId; } private: /** * @brief Parses the @p value to either a QMenu or QAction. * * @param value The ScriptValue describing either a menu or action * @param parent The parent to use for the created menu or action * @return QAction* The parsed action or menu action, if parsing fails returns @c null. - **/ + */ QAction *scriptValueToAction(QScriptValue &value, QMenu *parent); /** * @brief Creates a new QAction from the provided data and registers it for invoking the * @p callback when the action is triggered. * * The created action is added to the map of actions and callbacks shared with the global * shortcuts. * * @param title The title of the action * @param checkable Whether the action is checkable * @param checked Whether the checkable action is checked * @param callback The callback to invoke when the action is triggered * @param parent The parent to be used for the new created action * @return QAction* The created action - **/ + */ QAction *createAction(const QString &title, bool checkable, bool checked, QScriptValue &callback, QMenu *parent); /** * @brief Parses the @p items and creates a QMenu from it. * * @param title The title of the Menu. * @param items JavaScript Array containing Menu items. * @param parent The parent to use for the new created menu * @return QAction* The menu action for the new Menu - **/ + */ QAction *createMenu(const QString &title, QScriptValue &items, QMenu *parent); int m_scriptId; QString m_fileName; QString m_pluginName; bool m_running; QHash m_shortcutCallbacks; QHash > m_screenEdgeCallbacks; QHash m_callbacks; /** * @brief List of registered functions to call when the UserActionsMenu is about to show * to add further entries. - **/ + */ QList m_userActionsMenuCallbacks; }; class Script : public AbstractScript, QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Scripting") public: Script(int id, QString scriptName, QString pluginName, QObject *parent = nullptr); ~Script() override; QScriptEngine *engine() { return m_engine; } bool registerTouchScreenCallback(int edge, QScriptValue callback); bool unregisterTouchScreenCallback(int edge); public Q_SLOTS: Q_SCRIPTABLE void run() override; Q_SIGNALS: Q_SCRIPTABLE void printError(const QString &text); private Q_SLOTS: /** * A nice clean way to handle exceptions in scripting. * TODO: Log to file, show from notifier.. - **/ + */ void sigException(const QScriptValue &exception); /** * Callback for when loadScriptFromFile has finished. - **/ + */ void slotScriptLoadedFromFile(); private: void installScriptFunctions(QScriptEngine *engine); /** * Read the script from file into a byte array. * If file cannot be read an empty byte array is returned. - **/ + */ QByteArray loadScriptFromFile(const QString &fileName); QScriptEngine *m_engine; QDBusMessage m_invocationContext; bool m_starting; QScopedPointer m_agent; QHash m_touchScreenEdgeCallbacks; }; class ScriptUnloaderAgent : public QScriptEngineAgent { public: explicit ScriptUnloaderAgent(Script *script); void scriptUnload(qint64 id) override; private: Script *m_script; }; class DeclarativeScript : public AbstractScript { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Scripting") public: explicit DeclarativeScript(int id, QString scriptName, QString pluginName, QObject *parent = nullptr); ~DeclarativeScript() override; public Q_SLOTS: Q_SCRIPTABLE void run() override; private Q_SLOTS: void createComponent(); private: QQmlContext *m_context; QQmlComponent *m_component; }; class JSEngineGlobalMethodsWrapper : public QObject { Q_OBJECT Q_ENUMS(ClientAreaOption) public: //------------------------------------------------------------------ //enums copy&pasted from kwinglobals.h for exporting enum ClientAreaOption { ///< geometry where a window will be initially placed after being mapped PlacementArea, ///< window movement snapping area? ignore struts MovementArea, ///< geometry to which a window will be maximized MaximizeArea, ///< like MaximizeArea, but ignore struts - used e.g. for topmenu MaximizeFullArea, ///< area for fullscreen windows FullScreenArea, ///< whole workarea (all screens together) WorkArea, ///< whole area (all screens together), ignore struts FullArea, ///< one whole screen, ignore struts ScreenArea }; explicit JSEngineGlobalMethodsWrapper(DeclarativeScript *parent); ~JSEngineGlobalMethodsWrapper() override; public Q_SLOTS: QVariant readConfig(const QString &key, QVariant defaultValue = QVariant()); void registerWindow(QQuickWindow *window); bool registerShortcut(const QString &name, const QString &text, const QKeySequence& keys, QJSValue function); private: DeclarativeScript *m_script; }; /** * The heart of KWin::Scripting. Infinite power lies beyond - **/ + */ class KWIN_EXPORT Scripting : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Scripting") private: explicit Scripting(QObject *parent); QStringList scriptList; QList scripts; /** * Lock to protect the scripts member variable. - **/ + */ QScopedPointer m_scriptsLock; // Preferably call ONLY at load time void runScripts(); public: ~Scripting() override; Q_SCRIPTABLE Q_INVOKABLE int loadScript(const QString &filePath, const QString &pluginName = QString()); Q_SCRIPTABLE Q_INVOKABLE int loadDeclarativeScript(const QString &filePath, const QString &pluginName = QString()); Q_SCRIPTABLE Q_INVOKABLE bool isScriptLoaded(const QString &pluginName) const; Q_SCRIPTABLE Q_INVOKABLE bool unloadScript(const QString &pluginName); /** * @brief Invokes all registered callbacks to add actions to the UserActionsMenu. * * @param c The Client for which the UserActionsMenu is about to be shown * @param parent The parent menu to which to add created child menus and items * @return QList< QAction* > List of all actions aggregated from all scripts. - **/ + */ QList actionsForUserActionMenu(AbstractClient *c, QMenu *parent); QQmlEngine *qmlEngine() const; QQmlEngine *qmlEngine(); QQmlContext *declarativeScriptSharedContext() const; QQmlContext *declarativeScriptSharedContext(); QtScriptWorkspaceWrapper *workspaceWrapper() const; AbstractScript *findScript(const QString &pluginName) const; static Scripting *self(); static Scripting *create(QObject *parent); public Q_SLOTS: void scriptDestroyed(QObject *object); Q_SCRIPTABLE void start(); private Q_SLOTS: void slotScriptsQueried(); private: void init(); LoadScriptList queryScriptsToLoad(); static Scripting *s_self; QQmlEngine *m_qmlEngine; QQmlContext *m_declarativeScriptSharedContext; QtScriptWorkspaceWrapper *m_workspaceWrapper; }; inline QQmlEngine *Scripting::qmlEngine() const { return m_qmlEngine; } inline QQmlEngine *Scripting::qmlEngine() { return m_qmlEngine; } inline QQmlContext *Scripting::declarativeScriptSharedContext() const { return m_declarativeScriptSharedContext; } inline QQmlContext *Scripting::declarativeScriptSharedContext() { return m_declarativeScriptSharedContext; } inline QtScriptWorkspaceWrapper *Scripting::workspaceWrapper() const { return m_workspaceWrapper; } inline Scripting *Scripting::self() { return s_self; } } #endif diff --git a/scripting/scripting_model.h b/scripting/scripting_model.h index cbb0299fe..b98d6fbd9 100644 --- a/scripting/scripting_model.h +++ b/scripting/scripting_model.h @@ -1,379 +1,379 @@ /******************************************************************** 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_SCRIPTING_MODEL_H #define KWIN_SCRIPTING_MODEL_H #include #include #include namespace KWin { class AbstractClient; class Client; namespace ScriptingClientModel { class AbstractLevel; class ClientModel : public QAbstractItemModel { Q_OBJECT Q_ENUMS(Exclude) Q_ENUMS(LevelRestriction) Q_PROPERTY(Exclusions exclusions READ exclusions WRITE setExclusions NOTIFY exclusionsChanged) public: enum Exclusion { NoExclusion = 0, // window types DesktopWindowsExclusion = 1 << 0, DockWindowsExclusion = 1 << 1, UtilityWindowsExclusion = 1 << 2, SpecialWindowsExclusion = 1 << 3, // windows with flags SkipTaskbarExclusion = 1 << 4, SkipPagerExclusion = 1 << 5, SwitchSwitcherExclusion = 1 << 6, // based on state OtherDesktopsExclusion = 1 << 7, OtherActivitiesExclusion = 1 << 8, MinimizedExclusion = 1 << 9, NonSelectedWindowTabExclusion = 1 << 10, NotAcceptingFocusExclusion = 1 << 11 }; Q_DECLARE_FLAGS(Exclusions, Exclusion) Q_FLAGS(Exclusions) enum LevelRestriction { NoRestriction = 0, VirtualDesktopRestriction = 1 << 0, ScreenRestriction = 1 << 1, ActivityRestriction = 1 << 2 }; Q_DECLARE_FLAGS(LevelRestrictions, LevelRestriction) Q_FLAGS(LevelRestrictions) explicit ClientModel(QObject *parent); ~ClientModel() override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &child) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QHash roleNames() const override; void setExclusions(ClientModel::Exclusions exclusions); Exclusions exclusions() const; Q_SIGNALS: void exclusionsChanged(); private Q_SLOTS: void levelBeginInsert(int rowStart, int rowEnd, quint32 parentId); void levelEndInsert(); void levelBeginRemove(int rowStart, int rowEnd, quint32 parentId); void levelEndRemove(); protected: enum ClientModelRoles { ClientRole = Qt::UserRole, ScreenRole, DesktopRole, ActivityRole }; void setLevels(QList restrictions); private: QModelIndex parentForId(quint32 childId) const; const AbstractLevel *getLevel(const QModelIndex &index) const; AbstractLevel *m_root; Exclusions m_exclusions; }; /** * @brief The data structure of the Model. * * The model is implemented as a Tree consisting of AbstractLevels as the levels of the tree. * A non leaf level is represented by the inheriting class ForkLevel, the last level above a * leaf is represented by the inheriting class ClientLevel, which contains the Clients - each * Client is one leaf. * * In case the tree would only consist of Clients - leafs - it has always one ClientLevel as the root * of the tree. * * The number of levels in the tree is controlled by the LevelRestrictions. For each existing * LevelRestriction a new Level is created, if there are no more restrictions a ClientLevel is created. * * To build up the tree the static factory method @ref create has to be used. It will recursively * build up the tree. After the tree has been build up use @ref init to initialize the tree which * will add the Clients to the ClientLevel. * * Each element of the tree has a unique id which can be used by the QAbstractItemModel as the * internal id for its QModelIndex. Note: the ids have no ordering, if trying to get a specific element * the tree performs a depth-first search. - **/ + */ class AbstractLevel : public QObject { Q_OBJECT public: ~AbstractLevel() override; virtual int count() const = 0; virtual void init() = 0; virtual quint32 idForRow(int row) const = 0; uint screen() const; uint virtualDesktop() const; const QString &activity() const; ClientModel::LevelRestrictions restrictions() const; void setRestrictions(ClientModel::LevelRestrictions restrictions); ClientModel::LevelRestriction restriction() const; void setRestriction(ClientModel::LevelRestriction restriction); quint32 id() const; AbstractLevel *parentLevel() const; virtual const AbstractLevel *levelForId(quint32 id) const = 0; virtual AbstractLevel *parentForId(quint32 child) const = 0; virtual int rowForId(quint32 child) const = 0; virtual AbstractClient *clientForId(quint32 child) const = 0; virtual void setScreen(uint screen); virtual void setVirtualDesktop(uint virtualDesktop); virtual void setActivity(const QString &activity); static AbstractLevel *create(const QList &restrictions, ClientModel::LevelRestrictions parentRestrictions, ClientModel *model, AbstractLevel *parent = nullptr); Q_SIGNALS: void beginInsert(int rowStart, int rowEnd, quint32 parentId); void endInsert(); void beginRemove(int rowStart, int rowEnd, quint32 parentId); void endRemove(); protected: AbstractLevel(ClientModel *model, AbstractLevel *parent); ClientModel *model() const; private: ClientModel *m_model; AbstractLevel *m_parent; uint m_screen; uint m_virtualDesktop; QString m_activity; ClientModel::LevelRestriction m_restriction; ClientModel::LevelRestrictions m_restrictions; quint32 m_id; }; class ForkLevel : public AbstractLevel { Q_OBJECT public: ForkLevel(const QList &childRestrictions, ClientModel *model, AbstractLevel *parent); ~ForkLevel() override; int count() const override; void init() override; quint32 idForRow(int row) const override; void addChild(AbstractLevel *child); void setScreen(uint screen) override; void setVirtualDesktop(uint virtualDesktop) override; void setActivity(const QString &activity) override; const AbstractLevel *levelForId(quint32 id) const override; AbstractLevel *parentForId(quint32 child) const override; int rowForId(quint32 child) const override; AbstractClient *clientForId(quint32 child) const override; private Q_SLOTS: void desktopCountChanged(uint previousCount, uint newCount); void screenCountChanged(int previousCount, int newCount); void activityAdded(const QString &id); void activityRemoved(const QString &id); private: QList m_children; QList m_childRestrictions; }; /** * @brief The actual leafs of the model's tree containing the Client's in this branch of the tree. * * This class groups all the Clients of one branch of the tree and takes care of updating the tree * when a Client changes its state in a way that it should be excluded/included or gets added or * removed. * * The Clients in this group are not sorted in any particular way. It's a simple list which only * gets added to. If some sorting should be applied, use a QSortFilterProxyModel. - **/ + */ class ClientLevel : public AbstractLevel { Q_OBJECT public: explicit ClientLevel(ClientModel *model, AbstractLevel *parent); ~ClientLevel() override; void init() override; int count() const override; quint32 idForRow(int row) const override; bool containsId(quint32 id) const; int rowForId(quint32 row) const override; AbstractClient *clientForId(quint32 child) const override; const AbstractLevel *levelForId(quint32 id) const override; AbstractLevel *parentForId(quint32 child) const override; public Q_SLOTS: void clientAdded(KWin::AbstractClient *client); void clientRemoved(KWin::AbstractClient *client); private Q_SLOTS: // uses sender() void reInit(); private: void checkClient(KWin::AbstractClient *client); void setupClientConnections(AbstractClient *client); void addClient(AbstractClient *client); void removeClient(AbstractClient *client); bool shouldAdd(AbstractClient *client) const; bool exclude(AbstractClient *client) const; bool containsClient(AbstractClient *client) const; QMap m_clients; }; class SimpleClientModel : public ClientModel { Q_OBJECT public: SimpleClientModel(QObject *parent = nullptr); ~SimpleClientModel() override; }; class ClientModelByScreen : public ClientModel { Q_OBJECT public: ClientModelByScreen(QObject *parent = nullptr); ~ClientModelByScreen() override; }; class ClientModelByScreenAndDesktop : public ClientModel { Q_OBJECT public: ClientModelByScreenAndDesktop(QObject *parent = nullptr); ~ClientModelByScreenAndDesktop() override; }; /** * @brief Custom QSortFilterProxyModel to filter on Client caption, role and class. - **/ + */ class ClientFilterModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(KWin::ScriptingClientModel::ClientModel *clientModel READ clientModel WRITE setClientModel NOTIFY clientModelChanged) Q_PROPERTY(QString filter READ filter WRITE setFilter NOTIFY filterChanged) public: ClientFilterModel(QObject *parent = nullptr); ~ClientFilterModel() override; ClientModel *clientModel() const; const QString &filter() const; public Q_SLOTS: void setClientModel(ClientModel *clientModel); void setFilter(const QString &filter); protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; Q_SIGNALS: void clientModelChanged(); void filterChanged(); private: ClientModel *m_clientModel; QString m_filter; }; inline int ClientLevel::count() const { return m_clients.count(); } inline const QString &AbstractLevel::activity() const { return m_activity; } inline AbstractLevel *AbstractLevel::parentLevel() const { return m_parent; } inline ClientModel *AbstractLevel::model() const { return m_model; } inline uint AbstractLevel::screen() const { return m_screen; } inline uint AbstractLevel::virtualDesktop() const { return m_virtualDesktop; } inline ClientModel::LevelRestriction AbstractLevel::restriction() const { return m_restriction; } inline ClientModel::LevelRestrictions AbstractLevel::restrictions() const { return m_restrictions; } inline quint32 AbstractLevel::id() const { return m_id; } inline ClientModel::Exclusions ClientModel::exclusions() const { return m_exclusions; } inline ClientModel *ClientFilterModel::clientModel() const { return m_clientModel; } inline const QString &ClientFilterModel::filter() const { return m_filter; } } // namespace Scripting } // namespace KWin Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::ScriptingClientModel::ClientModel::Exclusions) Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::ScriptingClientModel::ClientModel::LevelRestrictions) #endif // KWIN_SCRIPTING_MODEL_H diff --git a/scripting/scriptingutils.h b/scripting/scriptingutils.h index ee194fc48..a3f861910 100644 --- a/scripting/scriptingutils.h +++ b/scripting/scriptingutils.h @@ -1,369 +1,369 @@ /******************************************************************** 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_SCRIPTINGUTILS_H #define KWIN_SCRIPTINGUTILS_H #include "input.h" #include "workspace.h" #include "screenedge.h" #include "scripting_logging.h" #include #include #include #include namespace KWin { /** * Validates that argument at @p index of given @p context is of required type. * Throws a type error in the scripting context if there is a type mismatch. * @param context The scripting context in which the argument type needs to be validated. * @param index The argument index to validate * @returns @c true if the argument is of required type, @c false otherwise - **/ + */ template bool validateArgumentType(QScriptContext *context, int index) { const bool result = context->argument(index).toVariant().canConvert(); if (!result) { context->throwError(QScriptContext::TypeError, i18nc("KWin Scripting function received incorrect value for an expected type", "%1 is not of required type", context->argument(index).toString())); } return result; } /** * Validates that the argument of @p context is of specified type. * Throws a type error in the scripting context if there is a type mismatch. * @param context The scripting context in which the argument type needs to be validated. * @returns @c true if the argument is of required type, @c false otherwise - **/ + */ template bool validateArgumentType(QScriptContext *context) { return validateArgumentType(context, 0); } template bool validateArgumentType(QScriptContext *context) { if (!validateArgumentType(context)) { return false; } return validateArgumentType(context, 1); } template bool validateArgumentType(QScriptContext *context) { if (!validateArgumentType(context)) { return false; } return validateArgumentType(context, 2); } template bool validateArgumentType(QScriptContext *context) { if (!validateArgumentType(context)) { return false; } return validateArgumentType(context, 3); } /** * Validates that the argument count of @p context is at least @p min and @p max. * Throws a syntax error in the script context if argument count mismatch. * @param context The ScriptContext for which the argument count needs to be validated * @param min The minimum number of arguments. * @param max The maximum number of arguments * @returns @c true if the argument count is correct, otherwise @c false - **/ + */ bool validateParameters(QScriptContext *context, int min, int max); template QScriptValue globalShortcut(QScriptContext *context, QScriptEngine *engine) { T script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (context->argumentCount() != 4) { qCDebug(KWIN_SCRIPTING) << "Incorrect number of arguments! Expected: title, text, keySequence, callback"; return engine->undefinedValue(); } QAction* a = new QAction(script); a->setObjectName(context->argument(0).toString()); a->setText(context->argument(1).toString()); const QKeySequence shortcut = QKeySequence(context->argument(2).toString()); KGlobalAccel::self()->setShortcut(a, QList() << shortcut); script->registerShortcut(a, context->argument(3)); input()->registerShortcut(shortcut, a); return engine->newVariant(true); } template void callGlobalShortcutCallback(T script, QObject *sender) { QAction *a = qobject_cast(sender); if (!a) { return; } QHash::const_iterator it = script->shortcutCallbacks().find(a); if (it == script->shortcutCallbacks().end()) { return; } QScriptValue value(it.value()); QScriptValueList arguments; arguments << value.engine()->newQObject(a); value.call(QScriptValue(), arguments); } template QScriptValue registerScreenEdge(QScriptContext *context, QScriptEngine *engine) { T script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (!validateParameters(context, 2, 2)) { return engine->undefinedValue(); } if (!validateArgumentType(context)) { return engine->undefinedValue(); } if (!context->argument(1).isFunction()) { context->throwError(QScriptContext::SyntaxError, i18nc("KWin Scripting error thrown due to incorrect argument", "Second argument to registerScreenEdge needs to be a callback")); } const int edge = context->argument(0).toVariant().toInt(); QHash >::iterator it = script->screenEdgeCallbacks().find(edge); if (it == script->screenEdgeCallbacks().end()) { // not yet registered ScreenEdges::self()->reserve(static_cast(edge), script, "borderActivated"); script->screenEdgeCallbacks().insert(edge, QList() << context->argument(1)); } else { it->append(context->argument(1)); } return engine->newVariant(true); } template QScriptValue unregisterScreenEdge(QScriptContext *context, QScriptEngine *engine) { T script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (!validateParameters(context, 1, 1)) { return engine->undefinedValue(); } if (!validateArgumentType(context)) { return engine->undefinedValue(); } const int edge = context->argument(0).toVariant().toInt(); QHash >::iterator it = script->screenEdgeCallbacks().find(edge); if (it == script->screenEdgeCallbacks().end()) { //not previously registered return engine->newVariant(false); } ScreenEdges::self()->unreserve(static_cast(edge), script); script->screenEdgeCallbacks().erase(it); return engine->newVariant(true); } template QScriptValue registerTouchScreenEdge(QScriptContext *context, QScriptEngine *engine) { auto script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (!validateParameters(context, 2, 2)) { return engine->undefinedValue(); } if (!validateArgumentType(context)) { return engine->undefinedValue(); } if (!context->argument(1).isFunction()) { context->throwError(QScriptContext::SyntaxError, i18nc("KWin Scripting error thrown due to incorrect argument", "Second argument to registerTouchScreenEdge needs to be a callback")); } const int edge = context->argument(0).toVariant().toInt(); const auto ret = script->registerTouchScreenCallback(edge, context->argument(1)); return engine->newVariant(ret); } template QScriptValue unregisterTouchScreenEdge(QScriptContext *context, QScriptEngine *engine) { auto script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (!validateParameters(context, 1, 1)) { return engine->undefinedValue(); } if (!validateArgumentType(context)) { return engine->undefinedValue(); } const int edge = context->argument(0).toVariant().toInt(); const auto ret = script->unregisterTouchScreenCallback(edge); return engine->newVariant(ret); } template QScriptValue registerUserActionsMenu(QScriptContext *context, QScriptEngine *engine) { T script = qobject_cast(context->callee().data().toQObject()); if (!script) { return engine->undefinedValue(); } if (!validateParameters(context, 1, 1)) { return engine->undefinedValue(); } if (!context->argument(0).isFunction()) { context->throwError(QScriptContext::SyntaxError, i18nc("KWin Scripting error thrown due to incorrect argument", "Argument for registerUserActionsMenu needs to be a callback")); return engine->undefinedValue(); } script->registerUseractionsMenuCallback(context->argument(0)); return engine->newVariant(true); } template void screenEdgeActivated(T *script, int edge) { QHash >::iterator it = script->screenEdgeCallbacks().find(edge); if (it != script->screenEdgeCallbacks().end()) { foreach (const QScriptValue &value, it.value()) { QScriptValue callback(value); callback.call(); } } } template QScriptValue scriptingAssert(QScriptContext *context, QScriptEngine *engine, int min, int max, T defaultVal = T()) { if (!validateParameters(context, min, max)) { return engine->undefinedValue(); } switch (context->argumentCount()) { case 1: if (!validateArgumentType(context)) { return engine->undefinedValue(); } break; case 2: if (max == 2) { if (!validateArgumentType(context)) { return engine->undefinedValue(); } } else { if (!validateArgumentType(context)) { return engine->undefinedValue(); } } break; case 3: if (!validateArgumentType(context)) { return engine->undefinedValue(); } break; } if (max == 2) { if (context->argument(0).toVariant().value() != defaultVal) { if (context->argumentCount() == max) { context->throwError(QScriptContext::UnknownError, context->argument(max - 1).toString()); } else { context->throwError(QScriptContext::UnknownError, i18nc("Assertion failed in KWin script with given value", "Assertion failed: %1", context->argument(0).toString())); } return engine->undefinedValue(); } } else { if (context->argument(0).toVariant().value() != context->argument(1).toVariant().value()) { if (context->argumentCount() == max) { context->throwError(QScriptContext::UnknownError, context->argument(max - 1).toString()); } else { context->throwError(QScriptContext::UnknownError, i18nc("Assertion failed in KWin script with expected value and actual value", "Assertion failed: Expected %1, got %2", context->argument(0).toString(), context->argument(1).toString())); } return engine->undefinedValue(); } } return engine->newVariant(true); } inline void registerGlobalShortcutFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue shortcutFunc = engine->newFunction(function); shortcutFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("registerShortcut"), shortcutFunc); } inline void registerScreenEdgeFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue shortcutFunc = engine->newFunction(function); shortcutFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("registerScreenEdge"), shortcutFunc); } inline void unregisterScreenEdgeFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue shortcutFunc = engine->newFunction(function); shortcutFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("unregisterScreenEdge"), shortcutFunc); } inline void registerTouchScreenEdgeFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue touchScreenFunc = engine->newFunction(function); touchScreenFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("registerTouchScreenEdge"), touchScreenFunc); } inline void unregisterTouchScreenEdgeFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue touchScreenFunc = engine->newFunction(function); touchScreenFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("unregisterTouchScreenEdge"), touchScreenFunc); } inline void registerUserActionsMenuFunction(QObject *parent, QScriptEngine *engine, QScriptEngine::FunctionSignature function) { QScriptValue shortcutFunc = engine->newFunction(function); shortcutFunc.setData(engine->newQObject(parent)); engine->globalObject().setProperty(QStringLiteral("registerUserActionsMenu"), shortcutFunc); } } // namespace KWin #endif // KWIN_SCRIPTINGUTILS_H diff --git a/scripting/workspace_wrapper.h b/scripting/workspace_wrapper.h index 352959288..901d56234 100644 --- a/scripting/workspace_wrapper.h +++ b/scripting/workspace_wrapper.h @@ -1,380 +1,380 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2010 Rohan Prabhu 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_SCRIPTING_WORKSPACE_WRAPPER_H #define KWIN_SCRIPTING_WORKSPACE_WRAPPER_H #include #include #include #include #include #include namespace KWin { // forward declarations class AbstractClient; class Client; class WorkspaceWrapper : public QObject { Q_OBJECT Q_ENUMS(ClientAreaOption) Q_ENUMS(ElectricBorder) Q_PROPERTY(int currentDesktop READ currentDesktop WRITE setCurrentDesktop NOTIFY currentDesktopChanged) Q_PROPERTY(KWin::AbstractClient *activeClient READ activeClient WRITE setActiveClient NOTIFY clientActivated) // TODO: write and notify? Q_PROPERTY(QSize desktopGridSize READ desktopGridSize NOTIFY desktopLayoutChanged) Q_PROPERTY(int desktopGridWidth READ desktopGridWidth NOTIFY desktopLayoutChanged) Q_PROPERTY(int desktopGridHeight READ desktopGridHeight NOTIFY desktopLayoutChanged) Q_PROPERTY(int workspaceWidth READ workspaceWidth) Q_PROPERTY(int workspaceHeight READ workspaceHeight) Q_PROPERTY(QSize workspaceSize READ workspaceSize) /** * The number of desktops currently used. Minimum number of desktops is 1, maximum 20. - **/ + */ Q_PROPERTY(int desktops READ numberOfDesktops WRITE setNumberOfDesktops NOTIFY numberDesktopsChanged) /** * The same of the display, that is all screens. * @deprecated since 5.0 use virtualScreenSize - **/ + */ Q_PROPERTY(QSize displaySize READ displaySize) /** * The width of the display, that is width of all combined screens. * @deprecated since 5.0 use virtualScreenSize - **/ + */ Q_PROPERTY(int displayWidth READ displayWidth) /** * The height of the display, that is height of all combined screens. * @deprecated since 5.0 use virtualScreenSize - **/ + */ Q_PROPERTY(int displayHeight READ displayHeight) Q_PROPERTY(int activeScreen READ activeScreen) Q_PROPERTY(int numScreens READ numScreens NOTIFY numberScreensChanged) Q_PROPERTY(QString currentActivity READ currentActivity NOTIFY currentActivityChanged) Q_PROPERTY(QStringList activities READ activityList NOTIFY activitiesChanged) /** * The bounding size of all screens combined. Overlapping areas * are not counted multiple times. * @see virtualScreenGeometry - **/ + */ Q_PROPERTY(QSize virtualScreenSize READ virtualScreenSize NOTIFY virtualScreenSizeChanged) /** * The bounding geometry of all outputs combined. Always starts at (0,0) and has * virtualScreenSize as it's size. * @see virtualScreenSize - **/ + */ Q_PROPERTY(QRect virtualScreenGeometry READ virtualScreenGeometry NOTIFY virtualScreenGeometryChanged) private: Q_DISABLE_COPY(WorkspaceWrapper) Q_SIGNALS: void desktopPresenceChanged(KWin::AbstractClient *client, int desktop); void currentDesktopChanged(int desktop, KWin::AbstractClient *client); void clientAdded(KWin::AbstractClient *client); void clientRemoved(KWin::AbstractClient *client); void clientManaging(KWin::Client *client); void clientMinimized(KWin::AbstractClient *client); void clientUnminimized(KWin::AbstractClient *client); void clientRestored(KWin::Client *client); void clientMaximizeSet(KWin::AbstractClient *client, bool h, bool v); void killWindowCalled(KWin::Client *client); void clientActivated(KWin::AbstractClient *client); void clientFullScreenSet(KWin::Client *client, bool fullScreen, bool user); void clientSetKeepAbove(KWin::Client *client, bool keepAbove); /** * Signal emitted whenever the number of desktops changed. * To get the current number of desktops use the property desktops. * @param oldNumberOfDesktops The previous number of desktops. - **/ + */ void numberDesktopsChanged(uint oldNumberOfDesktops); /** * Signal emitted whenever the layout of virtual desktops changed. * That is desktopGrid(Size/Width/Height) will have new values. * @since 4.11 - **/ + */ void desktopLayoutChanged(); /** * The demands attention state for Client @p c changed to @p set. * @param c The Client for which demands attention changed * @param set New value of demands attention - **/ + */ void clientDemandsAttentionChanged(KWin::AbstractClient *client, bool set); /** * Signal emitted when the number of screens changes. * @param count The new number of screens - **/ + */ void numberScreensChanged(int count); /** * This signal is emitted when the size of @p screen changes. * Don't forget to fetch an updated client area. - **/ + */ void screenResized(int screen); /** * Signal emitted whenever the current activity changed. * @param id id of the new activity - **/ + */ void currentActivityChanged(const QString &id); /** * Signal emitted whenever the list of activities changed. * @param id id of the new activity - **/ + */ void activitiesChanged(const QString &id); /** * This signal is emitted when a new activity is added * @param id id of the new activity - **/ + */ void activityAdded(const QString &id); /** * This signal is emitted when the activity * is removed * @param id id of the removed activity - **/ + */ void activityRemoved(const QString &id); /** * Emitted whenever the virtualScreenSize changes. * @see virtualScreenSize() * @since 5.0 - **/ + */ void virtualScreenSizeChanged(); /** * Emitted whenever the virtualScreenGeometry changes. * @see virtualScreenGeometry() * @since 5.0 - **/ + */ void virtualScreenGeometryChanged(); public: //------------------------------------------------------------------ //enums copy&pasted from kwinglobals.h because qtscript is evil enum ClientAreaOption { ///< geometry where a window will be initially placed after being mapped PlacementArea, ///< window movement snapping area? ignore struts MovementArea, ///< geometry to which a window will be maximized MaximizeArea, ///< like MaximizeArea, but ignore struts - used e.g. for topmenu MaximizeFullArea, ///< area for fullscreen windows FullScreenArea, ///< whole workarea (all screens together) WorkArea, ///< whole area (all screens together), ignore struts FullArea, ///< one whole screen, ignore struts ScreenArea }; enum ElectricBorder { ElectricTop, ElectricTopRight, ElectricRight, ElectricBottomRight, ElectricBottom, ElectricBottomLeft, ElectricLeft, ElectricTopLeft, ELECTRIC_COUNT, ElectricNone }; protected: explicit WorkspaceWrapper(QObject* parent = nullptr); public: #define GETTERSETTERDEF( rettype, getter, setter ) \ rettype getter() const; \ void setter( rettype val ); GETTERSETTERDEF(int, numberOfDesktops, setNumberOfDesktops) GETTERSETTERDEF(int, currentDesktop, setCurrentDesktop) GETTERSETTERDEF(KWin::AbstractClient*, activeClient, setActiveClient) #undef GETTERSETTERDEF QSize desktopGridSize() const; int desktopGridWidth() const; int desktopGridHeight() const; int workspaceWidth() const; int workspaceHeight() const; QSize workspaceSize() const; int displayWidth() const; int displayHeight() const; QSize displaySize() const; int activeScreen() const; int numScreens() const; QString currentActivity() const; QStringList activityList() const; QSize virtualScreenSize() const; QRect virtualScreenGeometry() const; /** * Returns the geometry a Client can use with the specified option. * This method should be preferred over other methods providing screen sizes as the * various options take constraints such as struts set on panels into account. * This method is also multi screen aware, but there are also options to get full areas. * @param option The type of area which should be considered * @param screen The screen for which the area should be considered * @param desktop The desktop for which the area should be considered, in general there should not be a difference * @returns The specified screen geometry - **/ + */ Q_SCRIPTABLE QRect clientArea(ClientAreaOption option, int screen, int desktop) const; /** * Overloaded method for convenience. * @param option The type of area which should be considered * @param point The coordinates which have to be included in the area * @param desktop The desktop for which the area should be considered, in general there should not be a difference * @returns The specified screen geometry - **/ + */ Q_SCRIPTABLE QRect clientArea(ClientAreaOption option, const QPoint& point, int desktop) const; /** * Overloaded method for convenience. * @param client The Client for which the area should be retrieved * @returns The specified screen geometry - **/ + */ Q_SCRIPTABLE QRect clientArea(ClientAreaOption option, const KWin::AbstractClient *client) const; /** * Returns the name for the given @p desktop. - **/ + */ Q_SCRIPTABLE QString desktopName(int desktop) const; /** * Provides support information about the currently running KWin instance. - **/ + */ Q_SCRIPTABLE QString supportInformation() const; /** * Finds the Client with the given @p windowId. * @param windowId The window Id of the Client * @return The found Client or @c null - **/ + */ Q_SCRIPTABLE KWin::Client *getClient(qulonglong windowId); public Q_SLOTS: // all the available key bindings void slotSwitchDesktopNext(); void slotSwitchDesktopPrevious(); void slotSwitchDesktopRight(); void slotSwitchDesktopLeft(); void slotSwitchDesktopUp(); void slotSwitchDesktopDown(); void slotSwitchToNextScreen(); void slotWindowToNextScreen(); void slotToggleShowDesktop(); void slotWindowMaximize(); void slotWindowMaximizeVertical(); void slotWindowMaximizeHorizontal(); void slotWindowMinimize(); void slotWindowShade(); void slotWindowRaise(); void slotWindowLower(); void slotWindowRaiseOrLower(); void slotActivateAttentionWindow(); void slotWindowPackLeft(); void slotWindowPackRight(); void slotWindowPackUp(); void slotWindowPackDown(); void slotWindowGrowHorizontal(); void slotWindowGrowVertical(); void slotWindowShrinkHorizontal(); void slotWindowShrinkVertical(); void slotWindowQuickTileLeft(); void slotWindowQuickTileRight(); void slotWindowQuickTileTop(); void slotWindowQuickTileBottom(); void slotWindowQuickTileTopLeft(); void slotWindowQuickTileTopRight(); void slotWindowQuickTileBottomLeft(); void slotWindowQuickTileBottomRight(); void slotSwitchWindowUp(); void slotSwitchWindowDown(); void slotSwitchWindowRight(); void slotSwitchWindowLeft(); void slotIncreaseWindowOpacity(); void slotLowerWindowOpacity(); void slotWindowOperations(); void slotWindowClose(); void slotWindowMove(); void slotWindowResize(); void slotWindowAbove(); void slotWindowBelow(); void slotWindowOnAllDesktops(); void slotWindowFullScreen(); void slotWindowNoBorder(); void slotWindowToNextDesktop(); void slotWindowToPreviousDesktop(); void slotWindowToDesktopRight(); void slotWindowToDesktopLeft(); void slotWindowToDesktopUp(); void slotWindowToDesktopDown(); /** * Shows an outline at the specified @p geometry. * If an outline is already shown the outline is moved to the new position. * Use hideOutline to remove the outline again. - **/ + */ void showOutline(const QRect &geometry); /** * Overloaded method for convenience. - **/ + */ void showOutline(int x, int y, int width, int height); /** * Hides the outline previously shown by showOutline. - **/ + */ void hideOutline(); private Q_SLOTS: void setupAbstractClientConnections(AbstractClient *client); void setupClientConnections(Client *client); }; class QtScriptWorkspaceWrapper : public WorkspaceWrapper { Q_OBJECT public: /** * List of Clients currently managed by KWin. - **/ + */ Q_INVOKABLE QList clientList() const; explicit QtScriptWorkspaceWrapper(QObject* parent = nullptr); }; class DeclarativeScriptWorkspaceWrapper : public WorkspaceWrapper { Q_OBJECT Q_PROPERTY(QQmlListProperty clients READ clients) public: QQmlListProperty clients(); static int countClientList(QQmlListProperty *clients); static KWin::AbstractClient *atClientList(QQmlListProperty *clients, int index); explicit DeclarativeScriptWorkspaceWrapper(QObject* parent = nullptr); }; } #endif diff --git a/shadow.h b/shadow.h index fd1506c66..953f28f68 100644 --- a/shadow.h +++ b/shadow.h @@ -1,192 +1,192 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 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_SHADOW_H #define KWIN_SHADOW_H #include #include #include namespace KDecoration2 { class Decoration; class DecorationShadow; } namespace KWayland { namespace Server { class ShadowInterface; } } namespace KWin { class Toplevel; /** * @short Class representing a Window's Shadow to be rendered by the Compositor. * * This class holds all information about the Shadow to be rendered together with the * window during the Compositing stage. The Shadow consists of several pixmaps and offsets. * For a complete description please refer to https://community.kde.org/KWin/Shadow * * To create a Shadow instance use the static factory method createShadow which will * create an instance for the currently used Compositing Backend. It will read the X11 Property * and create the Shadow and all required data (such as WindowQuads). If there is no Shadow * defined for the Toplevel the factory method returns @c NULL. * * @author Martin Gräßlin * @todo React on Toplevel size changes. - **/ + */ class KWIN_EXPORT Shadow : public QObject { Q_OBJECT public: ~Shadow() override; /** * @return Region of the shadow. - **/ + */ const QRegion &shadowRegion() const { return m_shadowRegion; }; /** * @return Cached Shadow Quads - **/ + */ const WindowQuadList &shadowQuads() const { return m_shadowQuads; }; WindowQuadList &shadowQuads() { return m_shadowQuads; }; /** * This method updates the Shadow when the property has been changed. * It is the responsibility of the owner of the Shadow to call this method * whenever the owner receives a PropertyNotify event. * This method will invoke a re-read of the Property. In case the Property has * been withdrawn the method returns @c false. In that case the owner should * delete the Shadow. * @returns @c true when the shadow has been updated, @c false if the property is not set anymore. - **/ + */ virtual bool updateShadow(); /** * Factory Method to create the shadow from the property. * This method takes care of creating an instance of the * Shadow class for the current Compositing Backend. * * If there is no shadow defined for @p toplevel this method * will return @c NULL. * @param toplevel The Toplevel for which the shadow should be created * @return Created Shadow or @c NULL in case there is no shadow defined. - **/ + */ static Shadow *createShadow(Toplevel *toplevel); /** * Reparents the shadow to @p toplevel. * Used when a window is deleted. * @param toplevel The new parent - **/ + */ void setToplevel(Toplevel *toplevel); bool hasDecorationShadow() const { return !m_decorationShadow.isNull(); } QImage decorationShadowImage() const; QWeakPointer decorationShadow() const { return m_decorationShadow.toWeakRef(); } public Q_SLOTS: void geometryChanged(); protected: Shadow(Toplevel *toplevel); enum ShadowElements { ShadowElementTop, ShadowElementTopRight, ShadowElementRight, ShadowElementBottomRight, ShadowElementBottom, ShadowElementBottomLeft, ShadowElementLeft, ShadowElementTopLeft, ShadowElementsCount }; inline const QPixmap &shadowPixmap(ShadowElements element) const { return m_shadowElements[element]; }; QSize elementSize(ShadowElements element) const; int topOffset() const { return m_topOffset; }; int rightOffset() const { return m_rightOffset; }; int bottomOffset() const { return m_bottomOffset; }; int leftOffset() const { return m_leftOffset; }; virtual void buildQuads(); void updateShadowRegion(); Toplevel *topLevel() { return m_topLevel; }; void setShadowRegion(const QRegion ®ion) { m_shadowRegion = region; }; virtual bool prepareBackend() = 0; WindowQuadList m_shadowQuads; void setShadowElement(const QPixmap &shadow, ShadowElements element); private: static Shadow *createShadowFromX11(Toplevel *toplevel); static Shadow *createShadowFromDecoration(Toplevel *toplevel); static Shadow *createShadowFromWayland(Toplevel *toplevel); static QVector readX11ShadowProperty(xcb_window_t id); bool init(const QVector &data); bool init(KDecoration2::Decoration *decoration); bool init(const QPointer &shadow); Toplevel *m_topLevel; // shadow pixmaps QPixmap m_shadowElements[ShadowElementsCount]; // shadow offsets int m_topOffset; int m_rightOffset; int m_bottomOffset; int m_leftOffset; // caches QRegion m_shadowRegion; QSize m_cachedSize; // Decoration based shadows QSharedPointer m_decorationShadow; }; } #endif // KWIN_SHADOW_H diff --git a/shell_client.h b/shell_client.h index 62e037c18..f25625bc1 100644 --- a/shell_client.h +++ b/shell_client.h @@ -1,309 +1,309 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin Copyright (C) 2018 David Edmundson 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_SHELL_CLIENT_H #define KWIN_SHELL_CLIENT_H #include "abstract_client.h" #include namespace KWayland { namespace Server { class ShellSurfaceInterface; class ServerSideDecorationInterface; class ServerSideDecorationPaletteInterface; class AppMenuInterface; class PlasmaShellSurfaceInterface; class XdgDecorationInterface; } } namespace KWin { /** * @brief The reason for which the server pinged a client surface - **/ + */ enum class PingReason { CloseWindow = 0, FocusWindow }; class KWIN_EXPORT ShellClient : public AbstractClient { Q_OBJECT public: ShellClient(KWayland::Server::ShellSurfaceInterface *surface); ShellClient(KWayland::Server::XdgShellSurfaceInterface *surface); ShellClient(KWayland::Server::XdgShellPopupInterface *surface); ~ShellClient() override; QStringList activities() const override; QPoint clientContentPos() const override; QSize clientSize() const override; QRect transparentRect() const override; NET::WindowType windowType(bool direct = false, int supported_types = 0) const override; void debug(QDebug &stream) const override; double opacity() const override; void setOpacity(double opacity) override; QByteArray windowRole() const override; void blockActivityUpdates(bool b = true) override; QString captionNormal() const override { return m_caption; } QString captionSuffix() const override { return m_captionSuffix; } void closeWindow() override; AbstractClient *findModal(bool allow_itself = false) override; bool isCloseable() const override; bool isFullScreenable() const override; bool isFullScreen() const override; bool isMaximizable() const override; bool isMinimizable() const override; bool isMovable() const override; bool isMovableAcrossScreens() const override; bool isResizable() const override; bool isShown(bool shaded_is_shown) const override; bool isHiddenInternal() const override { return m_unmapped || m_hidden; } void hideClient(bool hide) override; MaximizeMode maximizeMode() const override; MaximizeMode requestedMaximizeMode() const override; QRect geometryRestore() const override { return m_geomMaximizeRestore; } bool noBorder() const override; void setFullScreen(bool set, bool user = true) override; void setNoBorder(bool set) override; void updateDecoration(bool check_workspace_pos, bool force = false) override; void setOnAllActivities(bool set) override; void takeFocus() override; bool userCanSetFullScreen() const override; bool userCanSetNoBorder() const override; bool wantsInput() const override; bool dockWantsInput() const override; using AbstractClient::resizeWithChecks; void resizeWithChecks(int w, int h, ForceGeometry_t force = NormalGeometrySet) override; using AbstractClient::setGeometry; void setGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) override; bool hasStrut() const override; quint32 windowId() const override { return m_windowId; } /** * The process for this client. * Note that processes started by kwin will share its process id. * @since 5.11 * @returns the process if for this client. - **/ + */ pid_t pid() const override; bool isLockScreen() const override; bool isInputMethod() const override; virtual QWindow *internalWindow() const; void installPlasmaShellSurface(KWayland::Server::PlasmaShellSurfaceInterface *surface); void installServerSideDecoration(KWayland::Server::ServerSideDecorationInterface *decoration); void installAppMenu(KWayland::Server::AppMenuInterface *appmenu); void installPalette(KWayland::Server::ServerSideDecorationPaletteInterface *palette); void installXdgDecoration(KWayland::Server::XdgDecorationInterface *decoration); bool isInitialPositionSet() const override; bool isTransient() const override; bool hasTransientPlacementHint() const override; QRect transientPlacement(const QRect &bounds) const override; QMatrix4x4 inputTransformation() const override; bool setupCompositing() override; void finishCompositing(ReleaseReason releaseReason = ReleaseReason::Release) override; void showOnScreenEdge() override; void killWindow() override; // TODO: const-ref void placeIn(QRect &area); bool hasPopupGrab() const override; void popupDone() override; void updateColorScheme() override; bool isPopupWindow() const override; bool isLocalhost() const override { return true; } bool supportsWindowRules() const override; protected: void addDamage(const QRegion &damage) override; bool belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const override; void doSetActive() override; bool belongsToDesktop() const override; Layer layerForDock() const override; void changeMaximize(bool horizontal, bool vertical, bool adjust) override; void setGeometryRestore(const QRect &geo) override { m_geomMaximizeRestore = geo; } void doResizeSync() override; bool isWaitingForMoveResizeSync() const override; bool acceptsFocus() const override; void doMinimize() override; void updateCaption() override; virtual bool requestGeometry(const QRect &rect); virtual void doSetGeometry(const QRect &rect); void unmap(); void markAsMapped(); void setClientSize(const QSize &size) { m_clientSize = size; } bool isUnmapped() const { return m_unmapped; } private Q_SLOTS: void clientFullScreenChanged(bool fullScreen); private: /** * Called when the shell is created. - **/ + */ void init(); /** * Called for the XDG case when the shell surface is committed to the surface. * At this point all initial properties should have been set by the client. - **/ + */ void finishInit(); template void initSurface(T *shellSurface); void createDecoration(const QRect &oldgeom); void destroyClient(); void createWindowId(); void updateIcon(); void setTransient(); bool shouldExposeToWindowManagement(); void updateClientOutputs(); void updateWindowMargins(); KWayland::Server::XdgShellSurfaceInterface::States xdgSurfaceStates() const; void updateShowOnScreenEdge(); void updateMaximizeMode(MaximizeMode maximizeMode); // called on surface commit and processes all m_pendingConfigureRequests up to m_lastAckedConfigureReqest void updatePendingGeometry(); QPoint popupOffset(const QRect &anchorRect, const Qt::Edges anchorEdge, const Qt::Edges gravity, const QSize popupSize) const; static void deleteClient(ShellClient *c); QSize toWindowGeometry(const QSize &geometry) const; KWayland::Server::ShellSurfaceInterface *m_shellSurface; KWayland::Server::XdgShellSurfaceInterface *m_xdgShellSurface; KWayland::Server::XdgShellPopupInterface *m_xdgShellPopup; // size of the last buffer QSize m_clientSize; // last size we requested or empty if we haven't sent an explicit request to the client // if empty the client should choose their own default size QSize m_requestedClientSize = QSize(0, 0); struct PendingConfigureRequest { //note for wl_shell we have no serial, so serialId and m_lastAckedConfigureRequest will always be 0 //meaning we treat a surface commit as having processed all requests quint32 serialId = 0; // position to apply after a resize operation has been completed QPoint positionAfterResize; MaximizeMode maximizeMode; }; QVector m_pendingConfigureRequests; quint32 m_lastAckedConfigureRequest = 0; //mode in use by the current buffer MaximizeMode m_maximizeMode = MaximizeRestore; //mode we currently want to be, could be pending on client updating, could be not sent yet MaximizeMode m_requestedMaximizeMode = MaximizeRestore; QRect m_geomFsRestore; //size and position of the window before it was set to fullscreen bool m_closing = false; quint32 m_windowId = 0; bool m_unmapped = true; QRect m_geomMaximizeRestore; // size and position of the window before it was set to maximize NET::WindowType m_windowType = NET::Normal; QPointer m_plasmaShellSurface; QPointer m_appMenuInterface; QPointer m_paletteInterface; KWayland::Server::ServerSideDecorationInterface *m_serverDecoration = nullptr; KWayland::Server::XdgDecorationInterface *m_xdgDecoration = nullptr; bool m_userNoBorder = false; bool m_fullScreen = false; bool m_transient = false; bool m_hidden = false; bool m_internal; bool m_hasPopupGrab = false; qreal m_opacity = 1.0; class RequestGeometryBlocker { //TODO rename ConfigureBlocker when this class is Xdg only public: RequestGeometryBlocker(ShellClient *client) : m_client(client) { m_client->m_requestGeometryBlockCounter++; } ~RequestGeometryBlocker() { m_client->m_requestGeometryBlockCounter--; if (m_client->m_requestGeometryBlockCounter == 0) { m_client->requestGeometry(m_client->m_blockedRequestGeometry); } } private: ShellClient *m_client; }; friend class RequestGeometryBlocker; int m_requestGeometryBlockCounter = 0; QRect m_blockedRequestGeometry; QString m_caption; QString m_captionSuffix; QHash m_pingSerials; QMargins m_windowMargins; bool m_compositingSetup = false; bool m_isInitialized = false; }; } Q_DECLARE_METATYPE(KWin::ShellClient*) #endif diff --git a/sm.cpp b/sm.cpp index cb39bec8e..6cc2130f2 100644 --- a/sm.cpp +++ b/sm.cpp @@ -1,533 +1,533 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ #include "sm.h" #include #include #include #include #include #include "workspace.h" #include "client.h" #include #include #include #include namespace KWin { static bool gs_sessionManagerIsKSMServer = false; static KConfig *sessionConfig(QString id, QString key) { static KConfig *config = nullptr; static QString lastId; static QString lastKey; static QString pattern = QString(QLatin1String("session/%1_%2_%3")).arg(qApp->applicationName()); if (id != lastId || key != lastKey) { delete config; config = nullptr; } lastId = id; lastKey = key; if (!config) { config = new KConfig(pattern.arg(id).arg(key), KConfig::SimpleConfig); } return config; } static const char* const window_type_names[] = { "Unknown", "Normal" , "Desktop", "Dock", "Toolbar", "Menu", "Dialog", "Override", "TopMenu", "Utility", "Splash" }; // change also the two functions below when adding new entries static const char* windowTypeToTxt(NET::WindowType type) { if (type >= NET::Unknown && type <= NET::Splash) return window_type_names[ type + 1 ]; // +1 (unknown==-1) if (type == -2) // undefined (not really part of NET::WindowType) return "Undefined"; qFatal("Unknown Window Type"); return NULL; } static NET::WindowType txtToWindowType(const char* txt) { for (int i = NET::Unknown; i <= NET::Splash; ++i) if (qstrcmp(txt, window_type_names[ i + 1 ]) == 0) // +1 return static_cast< NET::WindowType >(i); return static_cast< NET::WindowType >(-2); // undefined } void Workspace::saveState(QSessionManager &sm) { // If the session manager is ksmserver, save stacking // order, active window, active desktop etc. in phase 1, // as ksmserver assures no interaction will be done // before the WM finishes phase 1. Saving in phase 2 is // too late, as possible user interaction may change some things. // Phase2 is still needed though (ICCCM 5.2) KConfig *config = sessionConfig(sm.sessionId(), sm.sessionKey()); if (!sm.isPhase2()) { KConfigGroup cg(config, "Session"); cg.writeEntry("AllowsInteraction", sm.allowsInteraction()); sessionSaveStarted(); if (gs_sessionManagerIsKSMServer) // save stacking order etc. before "save file?" etc. dialogs change it storeSession(config, SMSavePhase0); config->markAsClean(); // don't write Phase #1 data to disk sm.release(); // Qt doesn't automatically release in this case (bug?) sm.requestPhase2(); return; } storeSession(config, gs_sessionManagerIsKSMServer ? SMSavePhase2 : SMSavePhase2Full); config->sync(); // inform the smserver on how to clean-up after us const QString localFilePath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1Char('/') + config->name(); if (QFile::exists(localFilePath)) { // expectable for the sync sm.setDiscardCommand(QStringList() << QStringLiteral("rm") << localFilePath); } } // I bet this is broken, just like everywhere else in KDE void Workspace::commitData(QSessionManager &sm) { if (!sm.isPhase2()) sessionSaveStarted(); } // Workspace /** * Stores the current session in the config file * * @see loadSessionInfo - **/ + */ void Workspace::storeSession(KConfig* config, SMSavePhase phase) { KConfigGroup cg(config, "Session"); int count = 0; int active_client = -1; for (ClientList::Iterator it = clients.begin(); it != clients.end(); ++it) { Client* c = (*it); if (c->windowType() > NET::Splash) { //window types outside this are not tooltips/menus/OSDs //typically these will be unmanaged and not in this list anyway, but that is not enforced continue; } QByteArray sessionId = c->sessionId(); QByteArray wmCommand = c->wmCommand(); if (sessionId.isEmpty()) // remember also applications that are not XSMP capable // and use the obsolete WM_COMMAND / WM_SAVE_YOURSELF if (wmCommand.isEmpty()) continue; count++; if (c->isActive()) active_client = count; if (phase == SMSavePhase2 || phase == SMSavePhase2Full) storeClient(cg, count, c); } if (phase == SMSavePhase0) { // it would be much simpler to save these values to the config file, // but both Qt and KDE treat phase1 and phase2 separately, // which results in different sessionkey and different config file :( session_active_client = active_client; session_desktop = VirtualDesktopManager::self()->current(); } else if (phase == SMSavePhase2) { cg.writeEntry("count", count); cg.writeEntry("active", session_active_client); cg.writeEntry("desktop", session_desktop); } else { // SMSavePhase2Full cg.writeEntry("count", count); cg.writeEntry("active", session_active_client); cg.writeEntry("desktop", VirtualDesktopManager::self()->current()); } } void Workspace::storeClient(KConfigGroup &cg, int num, Client *c) { c->setSessionActivityOverride(false); //make sure we get the real values QString n = QString::number(num); cg.writeEntry(QLatin1String("sessionId") + n, c->sessionId().constData()); cg.writeEntry(QLatin1String("windowRole") + n, c->windowRole().constData()); cg.writeEntry(QLatin1String("wmCommand") + n, c->wmCommand().constData()); cg.writeEntry(QLatin1String("resourceName") + n, c->resourceName().constData()); cg.writeEntry(QLatin1String("resourceClass") + n, c->resourceClass().constData()); cg.writeEntry(QLatin1String("geometry") + n, QRect(c->calculateGravitation(true), c->clientSize())); // FRAME cg.writeEntry(QLatin1String("restore") + n, c->geometryRestore()); cg.writeEntry(QLatin1String("fsrestore") + n, c->geometryFSRestore()); cg.writeEntry(QLatin1String("maximize") + n, (int) c->maximizeMode()); cg.writeEntry(QLatin1String("fullscreen") + n, (int) c->fullScreenMode()); cg.writeEntry(QLatin1String("desktop") + n, c->desktop()); // the config entry is called "iconified" for back. comp. reasons // (kconf_update script for updating session files would be too complicated) cg.writeEntry(QLatin1String("iconified") + n, c->isMinimized()); cg.writeEntry(QLatin1String("opacity") + n, c->opacity()); // the config entry is called "sticky" for back. comp. reasons cg.writeEntry(QLatin1String("sticky") + n, c->isOnAllDesktops()); cg.writeEntry(QLatin1String("shaded") + n, c->isShade()); // the config entry is called "staysOnTop" for back. comp. reasons cg.writeEntry(QLatin1String("staysOnTop") + n, c->keepAbove()); cg.writeEntry(QLatin1String("keepBelow") + n, c->keepBelow()); cg.writeEntry(QLatin1String("skipTaskbar") + n, c->originalSkipTaskbar()); cg.writeEntry(QLatin1String("skipPager") + n, c->skipPager()); cg.writeEntry(QLatin1String("skipSwitcher") + n, c->skipSwitcher()); // not really just set by user, but name kept for back. comp. reasons cg.writeEntry(QLatin1String("userNoBorder") + n, c->userNoBorder()); cg.writeEntry(QLatin1String("windowType") + n, windowTypeToTxt(c->windowType())); cg.writeEntry(QLatin1String("shortcut") + n, c->shortcut().toString()); cg.writeEntry(QLatin1String("stackingOrder") + n, unconstrained_stacking_order.indexOf(c)); // KConfig doesn't support long so we need to live with less precision on 64-bit systems cg.writeEntry(QLatin1String("tabGroup") + n, static_cast(reinterpret_cast(c->tabGroup()))); cg.writeEntry(QLatin1String("activities") + n, c->activities()); } void Workspace::storeSubSession(const QString &name, QSet sessionIds) { //TODO clear it first KConfigGroup cg(KSharedConfig::openConfig(), QLatin1String("SubSession: ") + name); int count = 0; int active_client = -1; for (ClientList::Iterator it = clients.begin(); it != clients.end(); ++it) { Client* c = (*it); if (c->windowType() > NET::Splash) { continue; } QByteArray sessionId = c->sessionId(); QByteArray wmCommand = c->wmCommand(); if (sessionId.isEmpty()) // remember also applications that are not XSMP capable // and use the obsolete WM_COMMAND / WM_SAVE_YOURSELF if (wmCommand.isEmpty()) continue; if (!sessionIds.contains(sessionId)) continue; qCDebug(KWIN_CORE) << "storing" << sessionId; count++; if (c->isActive()) active_client = count; storeClient(cg, count, c); } cg.writeEntry("count", count); cg.writeEntry("active", active_client); //cg.writeEntry( "desktop", currentDesktop()); } /** * Loads the session information from the config file. * * @see storeSession - **/ + */ void Workspace::loadSessionInfo(const QString &key) { // NOTICE: qApp->sessionKey() is outdated when this gets invoked // the key parameter is cached from the application constructor. session.clear(); KConfigGroup cg(sessionConfig(qApp->sessionId(), key), "Session"); addSessionInfo(cg); } void Workspace::addSessionInfo(KConfigGroup &cg) { m_initialDesktop = cg.readEntry("desktop", 1); int count = cg.readEntry("count", 0); int active_client = cg.readEntry("active", 0); for (int i = 1; i <= count; i++) { QString n = QString::number(i); SessionInfo* info = new SessionInfo; session.append(info); info->sessionId = cg.readEntry(QLatin1String("sessionId") + n, QString()).toLatin1(); info->windowRole = cg.readEntry(QLatin1String("windowRole") + n, QString()).toLatin1(); info->wmCommand = cg.readEntry(QLatin1String("wmCommand") + n, QString()).toLatin1(); info->resourceName = cg.readEntry(QLatin1String("resourceName") + n, QString()).toLatin1(); info->resourceClass = cg.readEntry(QLatin1String("resourceClass") + n, QString()).toLower().toLatin1(); info->geometry = cg.readEntry(QLatin1String("geometry") + n, QRect()); info->restore = cg.readEntry(QLatin1String("restore") + n, QRect()); info->fsrestore = cg.readEntry(QLatin1String("fsrestore") + n, QRect()); info->maximized = cg.readEntry(QLatin1String("maximize") + n, 0); info->fullscreen = cg.readEntry(QLatin1String("fullscreen") + n, 0); info->desktop = cg.readEntry(QLatin1String("desktop") + n, 0); info->minimized = cg.readEntry(QLatin1String("iconified") + n, false); info->opacity = cg.readEntry(QLatin1String("opacity") + n, 1.0); info->onAllDesktops = cg.readEntry(QLatin1String("sticky") + n, false); info->shaded = cg.readEntry(QLatin1String("shaded") + n, false); info->keepAbove = cg.readEntry(QLatin1String("staysOnTop") + n, false); info->keepBelow = cg.readEntry(QLatin1String("keepBelow") + n, false); info->skipTaskbar = cg.readEntry(QLatin1String("skipTaskbar") + n, false); info->skipPager = cg.readEntry(QLatin1String("skipPager") + n, false); info->skipSwitcher = cg.readEntry(QLatin1String("skipSwitcher") + n, false); info->noBorder = cg.readEntry(QLatin1String("userNoBorder") + n, false); info->windowType = txtToWindowType(cg.readEntry(QLatin1String("windowType") + n, QString()).toLatin1().constData()); info->shortcut = cg.readEntry(QLatin1String("shortcut") + n, QString()); info->active = (active_client == i); info->stackingOrder = cg.readEntry(QLatin1String("stackingOrder") + n, -1); info->tabGroup = cg.readEntry(QLatin1String("tabGroup") + n, 0); info->tabGroupClient = NULL; info->activities = cg.readEntry(QLatin1String("activities") + n, QStringList()); } } void Workspace::loadSubSessionInfo(const QString &name) { KConfigGroup cg(KSharedConfig::openConfig(), QLatin1String("SubSession: ") + name); addSessionInfo(cg); } static bool sessionInfoWindowTypeMatch(Client* c, SessionInfo* info) { if (info->windowType == -2) { // undefined (not really part of NET::WindowType) return !c->isSpecialWindow(); } return info->windowType == c->windowType(); } /** * Returns a SessionInfo for client \a c. The returned session * info is removed from the storage. It's up to the caller to delete it. * * This function is called when a new window is mapped and must be managed. * We try to find a matching entry in the session. * * May return 0 if there's no session info for the client. - **/ + */ SessionInfo* Workspace::takeSessionInfo(Client* c) { SessionInfo *realInfo = 0; QByteArray sessionId = c->sessionId(); QByteArray windowRole = c->windowRole(); QByteArray wmCommand = c->wmCommand(); QByteArray resourceName = c->resourceName(); QByteArray resourceClass = c->resourceClass(); // First search ``session'' if (! sessionId.isEmpty()) { // look for a real session managed client (algorithm suggested by ICCCM) foreach (SessionInfo * info, session) { if (realInfo) break; if (info->sessionId == sessionId && sessionInfoWindowTypeMatch(c, info)) { if (! windowRole.isEmpty()) { if (info->windowRole == windowRole) { realInfo = info; session.removeAll(info); } } else { if (info->windowRole.isEmpty() && info->resourceName == resourceName && info->resourceClass == resourceClass) { realInfo = info; session.removeAll(info); } } } } } else { // look for a sessioninfo with matching features. foreach (SessionInfo * info, session) { if (realInfo) break; if (info->resourceName == resourceName && info->resourceClass == resourceClass && sessionInfoWindowTypeMatch(c, info)) { if (wmCommand.isEmpty() || info->wmCommand == wmCommand) { realInfo = info; session.removeAll(info); } } } } // Set tabGroupClient for other clients in the same group if (realInfo && realInfo->tabGroup) { foreach (SessionInfo * info, session) { if (!info->tabGroupClient && info->tabGroup == realInfo->tabGroup) info->tabGroupClient = c; } } return realInfo; } // KWin's focus stealing prevention causes problems with user interaction // during session save, as it prevents possible dialogs from getting focus. // Therefore it's temporarily disabled during session saving. Start of // session saving can be detected in SessionManager::saveState() above, // but Qt doesn't have API for saying when session saved finished (either // successfully, or was canceled). Therefore, create another connection // to session manager, that will provide this information. // Similarly the remember feature of window-specific settings should be disabled // during KDE shutdown when windows may move e.g. because of Kicker going away // (struts changing). When session saving starts, it can be cancelled, in which // case the shutdown_cancelled callback is invoked, or it's a checkpoint that // is immediatelly followed by save_complete, or finally it's a shutdown that // is immediatelly followed by die callback. So getting save_yourself with shutdown // set disables window-specific settings remembering, getting shutdown_cancelled // re-enables, otherwise KWin will go away after die. static void save_yourself(SmcConn conn_P, SmPointer ptr, int, Bool shutdown, int, Bool) { SessionSaveDoneHelper* session = reinterpret_cast< SessionSaveDoneHelper* >(ptr); if (conn_P != session->connection()) return; if (shutdown) RuleBook::self()->setUpdatesDisabled(true); SmcSaveYourselfDone(conn_P, True); } static void die(SmcConn conn_P, SmPointer ptr) { SessionSaveDoneHelper* session = reinterpret_cast< SessionSaveDoneHelper* >(ptr); if (conn_P != session->connection()) return; // session->saveDone(); we will quit anyway session->close(); } static void save_complete(SmcConn conn_P, SmPointer ptr) { SessionSaveDoneHelper* session = reinterpret_cast< SessionSaveDoneHelper* >(ptr); if (conn_P != session->connection()) return; session->saveDone(); } static void shutdown_cancelled(SmcConn conn_P, SmPointer ptr) { SessionSaveDoneHelper* session = reinterpret_cast< SessionSaveDoneHelper* >(ptr); if (conn_P != session->connection()) return; RuleBook::self()->setUpdatesDisabled(false); // re-enable // no need to differentiate between successful finish and cancel session->saveDone(); } void SessionSaveDoneHelper::saveDone() { if (Workspace::self()) Workspace::self()->sessionSaveDone(); } SessionSaveDoneHelper::SessionSaveDoneHelper() { SmcCallbacks calls; calls.save_yourself.callback = save_yourself; calls.save_yourself.client_data = reinterpret_cast< SmPointer >(this); calls.die.callback = die; calls.die.client_data = reinterpret_cast< SmPointer >(this); calls.save_complete.callback = save_complete; calls.save_complete.client_data = reinterpret_cast< SmPointer >(this); calls.shutdown_cancelled.callback = shutdown_cancelled; calls.shutdown_cancelled.client_data = reinterpret_cast< SmPointer >(this); char* id = NULL; char err[ 11 ]; conn = SmcOpenConnection(NULL, 0, 1, 0, SmcSaveYourselfProcMask | SmcDieProcMask | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask, &calls, NULL, &id, 10, err); if (id != NULL) free(id); if (conn == NULL) return; // no SM // detect ksmserver char* vendor = SmcVendor(conn); gs_sessionManagerIsKSMServer = qstrcmp(vendor, "KDE") == 0; free(vendor); // set the required properties, mostly dummy values SmPropValue propvalue[ 5 ]; SmProp props[ 5 ]; propvalue[ 0 ].length = sizeof(unsigned char); unsigned char value0 = SmRestartNever; // so that this extra SM connection doesn't interfere propvalue[ 0 ].value = &value0; props[ 0 ].name = const_cast< char* >(SmRestartStyleHint); props[ 0 ].type = const_cast< char* >(SmCARD8); props[ 0 ].num_vals = 1; props[ 0 ].vals = &propvalue[ 0 ]; struct passwd* entry = getpwuid(geteuid()); propvalue[ 1 ].length = entry != NULL ? strlen(entry->pw_name) : 0; propvalue[ 1 ].value = (SmPointer)(entry != NULL ? entry->pw_name : ""); props[ 1 ].name = const_cast< char* >(SmUserID); props[ 1 ].type = const_cast< char* >(SmARRAY8); props[ 1 ].num_vals = 1; props[ 1 ].vals = &propvalue[ 1 ]; propvalue[ 2 ].length = 0; propvalue[ 2 ].value = (SmPointer)(""); props[ 2 ].name = const_cast< char* >(SmRestartCommand); props[ 2 ].type = const_cast< char* >(SmLISTofARRAY8); props[ 2 ].num_vals = 1; props[ 2 ].vals = &propvalue[ 2 ]; propvalue[ 3 ].length = strlen("kwinsmhelper"); propvalue[ 3 ].value = (SmPointer)"kwinsmhelper"; props[ 3 ].name = const_cast< char* >(SmProgram); props[ 3 ].type = const_cast< char* >(SmARRAY8); props[ 3 ].num_vals = 1; props[ 3 ].vals = &propvalue[ 3 ]; propvalue[ 4 ].length = 0; propvalue[ 4 ].value = (SmPointer)(""); props[ 4 ].name = const_cast< char* >(SmCloneCommand); props[ 4 ].type = const_cast< char* >(SmLISTofARRAY8); props[ 4 ].num_vals = 1; props[ 4 ].vals = &propvalue[ 4 ]; SmProp* p[ 5 ] = { &props[ 0 ], &props[ 1 ], &props[ 2 ], &props[ 3 ], &props[ 4 ] }; SmcSetProperties(conn, 5, p); notifier = new QSocketNotifier(IceConnectionNumber(SmcGetIceConnection(conn)), QSocketNotifier::Read, this); connect(notifier, SIGNAL(activated(int)), SLOT(processData())); } SessionSaveDoneHelper::~SessionSaveDoneHelper() { close(); } void SessionSaveDoneHelper::close() { if (conn != NULL) { delete notifier; SmcCloseConnection(conn, 0, NULL); } conn = NULL; } void SessionSaveDoneHelper::processData() { if (conn != NULL) IceProcessMessages(SmcGetIceConnection(conn), 0, 0); } void Workspace::sessionSaveDone() { session_saving = false; foreach (Client * c, clients) { c->setSessionActivityOverride(false); } } } // namespace diff --git a/tabbox/clientmodel.h b/tabbox/clientmodel.h index e8bfdedb1..250b66eab 100644 --- a/tabbox/clientmodel.h +++ b/tabbox/clientmodel.h @@ -1,114 +1,114 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 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 CLIENTMODEL_H #define CLIENTMODEL_H #include "tabboxhandler.h" #include /** * @file * This file defines the class ClientModel, the model for TabBoxClients. * * @author Martin Gräßlin * @since 4.4 - **/ + */ namespace KWin { namespace TabBox { /** * The model for TabBoxClients used in TabBox. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class ClientModel : public QAbstractItemModel { Q_OBJECT public: enum { ClientRole = Qt::UserRole, ///< The TabBoxClient CaptionRole = Qt::UserRole + 1, ///< The caption of TabBoxClient DesktopNameRole = Qt::UserRole + 2, ///< The name of the desktop the TabBoxClient is on IconRole = Qt::UserRole + 3, // TODO: to be removed WIdRole = Qt::UserRole + 5, ///< The window ID of TabBoxClient MinimizedRole = Qt::UserRole + 6, ///< TabBoxClient is minimized CloseableRole = Qt::UserRole + 7 ///< TabBoxClient can be closed }; explicit ClientModel(QObject* parent = nullptr); ~ClientModel() override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; int columnCount(const QModelIndex& parent = QModelIndex()) const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QHash roleNames() const override; Q_INVOKABLE QString longestCaption() const; /** * @param client The TabBoxClient whose index should be returned * @return Returns the ModelIndex of given TabBoxClient or an invalid ModelIndex * if the model does not contain the given TabBoxClient. - **/ + */ QModelIndex index(QWeakPointer client) const; /** * Generates a new list of TabBoxClients based on the current config. * Calling this method will reset the model. If partialReset is true * the top of the list is kept as a starting point. If not the * current active client is used as the starting point to generate the * list. * @param desktop The desktop for which the list should be created * @param partialReset Keep the currently selected client or regenerate everything - **/ + */ void createClientList(int desktop, bool partialReset = false); /** * This method is provided as a overload for current desktop * @see createClientList - **/ + */ void createClientList(bool partialReset = false); /** * @return Returns the current list of TabBoxClients. - **/ + */ TabBoxClientList clientList() const { return m_clientList; } public Q_SLOTS: void close(int index); /** * Activates the client at @p index and closes the TabBox. * @param index The row index - **/ + */ void activate(int index); private: TabBoxClientList m_clientList; }; } // namespace Tabbox } // namespace KWin #endif // CLIENTMODEL_H diff --git a/tabbox/desktopchain.h b/tabbox/desktopchain.h index c74324711..a69b771f4 100644 --- a/tabbox/desktopchain.h +++ b/tabbox/desktopchain.h @@ -1,148 +1,148 @@ /******************************************************************** 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_TABBOX_DESKTOP_CHAIN_H #define KWIN_TABBOX_DESKTOP_CHAIN_H // Qt #include #include #include namespace KWin { namespace TabBox { /** * @brief A chain for last recently used virtual desktops. - **/ + */ class DesktopChain { public: /** * Creates a last recently used virtual desktop chain with the given @p initialSize. - **/ + */ explicit DesktopChain(uint initialSize = 0); /** * Returns the next desktop in the chain starting from @p indexDesktop. * In case that the @p indexDesktop is the last desktop of the chain, the method wraps around * and returns the first desktop stored in the chain. * In case the chain is valid, but does not contain the @p indexDesktop, the first element of * the chain is returned. * In case the chain is not valid, the always valid virtual desktop with identifier @c 1 * is returned. * @param indexDesktop The id of the virtual desktop which should be used as a starting point * @return The next virtual desktop in the chain - **/ + */ uint next(uint indexDesktop) const; /** * Adds the @p desktop to the chain. The @p desktop becomes the first element of the * chain. All desktops in the chain from the previous index of @p desktop are moved * one position in the chain. * @param desktop The new desktop to be the top most element in the chain. - **/ + */ void add(uint desktop); /** * Resizes the chain from @p previousSize to @p newSize. * In case the chain grows new elements are added with a meaning full id in the range * [previousSize, newSize]. * In case the chain shrinks it is ensured that no element points to a virtual desktop * with an id larger than @p newSize. * @param previousSize The previous size of the desktop chain * @param newSize The size to be used for the desktop chain - **/ + */ void resize(uint previousSize, uint newSize); private: /** * Initializes the chain with default values. - **/ + */ void init(); QVector m_chain; }; /** * @brief A manager for multiple desktop chains. * * This manager keeps track of multiple desktop chains which have a given identifier. * A common usage for this is to have a different desktop chain for each Activity. - **/ + */ class DesktopChainManager : public QObject { Q_OBJECT public: explicit DesktopChainManager(QObject *parent = nullptr); ~DesktopChainManager() override; /** * Returns the next virtual desktop starting from @p indexDesktop in the currently used chain. * @param indexDesktop The id of the virtual desktop which should be used as a starting point * @return The next virtual desktop in the currently used chain * @see DesktopChain::next - **/ + */ uint next(uint indexDesktop) const; public Q_SLOTS: /** * Adds the @p currentDesktop to the currently used desktop chain. * @param previousDesktop The previously used desktop, should be the top element of the chain * @param currentDesktop The desktop which should be the new top element of the chain - **/ + */ void addDesktop(uint previousDesktop, uint currentDesktop); /** * Resizes all managed desktop chains from @p previousSize to @p newSize. * @param previousSize The previously used size for the chains * @param newSize The size to be used for the chains * @see DesktopChain::resize - **/ + */ void resize(uint previousSize, uint newSize); /** * Switches to the desktop chain identified by the given @p identifier. * If there is no chain yet for the given @p identifier a new chain is created and used. * @param identifier The identifier of the desktop chain to be used - **/ + */ void useChain(const QString &identifier); private: typedef QHash< QString, DesktopChain > DesktopChains; /** * Creates a new desktop chain for the given @p identifier and adds it to the list * of identifiers. * @returns Position of the new chain in the managed list of chains - **/ + */ DesktopChains::Iterator addNewChain(const QString &identifier); /** * Creates the very first list to be used when an @p identifier comes in. * The dummy chain which is used by default gets copied and used for this chain. - **/ + */ void createFirstChain(const QString &identifier); DesktopChains::Iterator m_currentChain; DesktopChains m_chains; /** * The maximum size to be used for a new desktop chain - **/ + */ uint m_maxChainSize; }; } // TabBox } // namespace KWin #endif diff --git a/tabbox/desktopmodel.h b/tabbox/desktopmodel.h index 10786d36d..6816641a9 100644 --- a/tabbox/desktopmodel.h +++ b/tabbox/desktopmodel.h @@ -1,90 +1,90 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 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 DESKTOPMODEL_H #define DESKTOPMODEL_H #include /** * @file * This file defines the class DesktopModel, the model for desktops. * * @author Martin Gräßlin * @since 4.4 - **/ + */ namespace KWin { namespace TabBox { class ClientModel; /** * The model for desktops used in TabBox. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class DesktopModel : public QAbstractItemModel { public: enum { DesktopRole = Qt::UserRole, ///< Desktop number DesktopNameRole = Qt::UserRole + 1, ///< Desktop name ClientModelRole = Qt::UserRole + 2 ///< Clients on this desktop }; explicit DesktopModel(QObject* parent = nullptr); ~DesktopModel() override; QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; int columnCount(const QModelIndex& parent = QModelIndex()) const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex& child) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; QHash roleNames() const override; Q_INVOKABLE QString longestCaption() const; /** * Generates a new list of desktops based on the current config. * Calling this method will reset the model. - **/ + */ void createDesktopList(); /** * @return The current list of desktops. - **/ + */ QList< int > desktopList() const { return m_desktopList; } /** * @param desktop The desktop whose ModelIndex should be retrieved * @return The ModelIndex of given desktop or an invalid ModelIndex if * the desktop is not in the model. - **/ + */ QModelIndex desktopIndex(int desktop) const; private: QList< int > m_desktopList; QMap< int, ClientModel* > m_clientModels; }; } // namespace Tabbox } // namespace KWin #endif // DESKTOPMODEL_H diff --git a/tabbox/switcheritem.h b/tabbox/switcheritem.h index 77314854c..7f4ff9bca 100644 --- a/tabbox/switcheritem.h +++ b/tabbox/switcheritem.h @@ -1,118 +1,118 @@ /******************************************************************** 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_TABBOX_SWITCHERITEM_H #define KWIN_TABBOX_SWITCHERITEM_H #include #include class QAbstractItemModel; namespace KWin { namespace TabBox { class SwitcherItem : public QObject { Q_OBJECT Q_PROPERTY(QAbstractItemModel *model READ model NOTIFY modelChanged) Q_PROPERTY(QRect screenGeometry READ screenGeometry NOTIFY screenGeometryChanged) Q_PROPERTY(bool visible READ isVisible NOTIFY visibleChanged) Q_PROPERTY(bool allDesktops READ isAllDesktops NOTIFY allDesktopsChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(bool noModifierGrab READ noModifierGrab NOTIFY noModifierGrabChanged) /** * The main QML item that will be displayed in the Dialog - **/ + */ Q_PROPERTY(QObject *item READ item WRITE setItem NOTIFY itemChanged) Q_CLASSINFO("DefaultProperty", "item") public: SwitcherItem(QObject *parent = nullptr); ~SwitcherItem() override; QAbstractItemModel *model() const; QRect screenGeometry() const; bool isVisible() const; bool isAllDesktops() const; int currentIndex() const; void setCurrentIndex(int index); QObject *item() const; void setItem(QObject *item); bool noModifierGrab() const { return m_noModifierGrab; } // for usage from outside void setModel(QAbstractItemModel *model); void setAllDesktops(bool all); void setVisible(bool visible); void setNoModifierGrab(bool set); Q_SIGNALS: void visibleChanged(); void currentIndexChanged(int index); void modelChanged(); void allDesktopsChanged(); void screenGeometryChanged(); void itemChanged(); void noModifierGrabChanged(); private: QAbstractItemModel *m_model; QObject *m_item; bool m_visible; bool m_allDesktops; int m_currentIndex; QMetaObject::Connection m_selectedIndexConnection; bool m_noModifierGrab = false; }; inline QAbstractItemModel *SwitcherItem::model() const { return m_model; } inline bool SwitcherItem::isVisible() const { return m_visible; } inline bool SwitcherItem::isAllDesktops() const { return m_allDesktops; } inline int SwitcherItem::currentIndex() const { return m_currentIndex; } inline QObject *SwitcherItem::item() const { return m_item; } } // TabBox } // KWin #endif // KWIN_TABBOX_SWITCHERITEM_H diff --git a/tabbox/tabbox.cpp b/tabbox/tabbox.cpp index 5911dac4d..a11cf6fb3 100644 --- a/tabbox/tabbox.cpp +++ b/tabbox/tabbox.cpp @@ -1,1544 +1,1544 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 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 . *********************************************************************/ //#define QT_CLEAN_NAMESPACE // own #include "tabbox.h" // tabbox #include "tabbox/clientmodel.h" #include "tabbox/desktopmodel.h" #include "tabbox/tabboxconfig.h" #include "tabbox/desktopchain.h" #include "tabbox/tabbox_logging.h" #include "tabbox/x11_filter.h" // kwin #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include "client.h" #include "effects.h" #include "input.h" #include "keyboard_input.h" #include "pointer_input.h" #include "focuschain.h" #include "screenedge.h" #include "screens.h" #include "unmanaged.h" #include "virtualdesktops.h" #include "workspace.h" #include "xcbutils.h" // Qt #include #include // KDE #include #include #include #include #include // X11 #include #include // xcb #include // specify externals before namespace namespace KWin { namespace TabBox { TabBoxHandlerImpl::TabBoxHandlerImpl(TabBox* tabBox) : TabBoxHandler(tabBox) , m_tabBox(tabBox) , m_desktopFocusChain(new DesktopChainManager(this)) { // connects for DesktopFocusChainManager VirtualDesktopManager *vds = VirtualDesktopManager::self(); connect(vds, SIGNAL(countChanged(uint,uint)), m_desktopFocusChain, SLOT(resize(uint,uint))); connect(vds, SIGNAL(currentChanged(uint,uint)), m_desktopFocusChain, SLOT(addDesktop(uint,uint))); #ifdef KWIN_BUILD_ACTIVITIES if (Activities::self()) { connect(Activities::self(), SIGNAL(currentChanged(QString)), m_desktopFocusChain, SLOT(useChain(QString))); } #endif } TabBoxHandlerImpl::~TabBoxHandlerImpl() { } int TabBoxHandlerImpl::activeScreen() const { return screens()->current(); } int TabBoxHandlerImpl::currentDesktop() const { return VirtualDesktopManager::self()->current(); } QString TabBoxHandlerImpl::desktopName(TabBoxClient* client) const { if (TabBoxClientImpl* c = static_cast< TabBoxClientImpl* >(client)) { if (!c->client()->isOnAllDesktops()) return VirtualDesktopManager::self()->name(c->client()->desktop()); } return VirtualDesktopManager::self()->name(VirtualDesktopManager::self()->current()); } QString TabBoxHandlerImpl::desktopName(int desktop) const { return VirtualDesktopManager::self()->name(desktop); } QWeakPointer TabBoxHandlerImpl::nextClientFocusChain(TabBoxClient* client) const { if (TabBoxClientImpl* c = static_cast< TabBoxClientImpl* >(client)) { auto next = FocusChain::self()->nextMostRecentlyUsed(c->client()); if (next) return next->tabBoxClient(); } return QWeakPointer(); } QWeakPointer< TabBoxClient > TabBoxHandlerImpl::firstClientFocusChain() const { if (auto c = FocusChain::self()->firstMostRecentlyUsed()) { return QWeakPointer(c->tabBoxClient()); } else { return QWeakPointer(); } } bool TabBoxHandlerImpl::isInFocusChain(TabBoxClient *client) const { if (TabBoxClientImpl *c = static_cast(client)) { return FocusChain::self()->contains(c->client()); } return false; } int TabBoxHandlerImpl::nextDesktopFocusChain(int desktop) const { return m_desktopFocusChain->next(desktop); } int TabBoxHandlerImpl::numberOfDesktops() const { return VirtualDesktopManager::self()->count(); } QWeakPointer TabBoxHandlerImpl::activeClient() const { if (Workspace::self()->activeClient()) return Workspace::self()->activeClient()->tabBoxClient(); else return QWeakPointer(); } bool TabBoxHandlerImpl::checkDesktop(TabBoxClient* client, int desktop) const { auto current = (static_cast< TabBoxClientImpl* >(client))->client(); switch (config().clientDesktopMode()) { case TabBoxConfig::AllDesktopsClients: return true; case TabBoxConfig::ExcludeCurrentDesktopClients: return !current->isOnDesktop(desktop); default: // TabBoxConfig::OnlyCurrentDesktopClients return current->isOnDesktop(desktop); } } bool TabBoxHandlerImpl::checkActivity(TabBoxClient* client) const { auto current = (static_cast< TabBoxClientImpl* >(client))->client(); switch (config().clientActivitiesMode()) { case TabBoxConfig::AllActivitiesClients: return true; case TabBoxConfig::ExcludeCurrentActivityClients: return !current->isOnCurrentActivity(); default: // TabBoxConfig::OnlyCurrentActivityClients return current->isOnCurrentActivity(); } } bool TabBoxHandlerImpl::checkApplications(TabBoxClient* client) const { auto current = (static_cast< TabBoxClientImpl* >(client))->client(); TabBoxClientImpl* c; QListIterator< QWeakPointer > i(clientList()); switch (config().clientApplicationsMode()) { case TabBoxConfig::OneWindowPerApplication: // check if the list already contains an entry of this application while (i.hasNext()) { QSharedPointer client = i.next().toStrongRef(); if (!client) { continue; } if ((c = dynamic_cast< TabBoxClientImpl* >(client.data()))) { if (AbstractClient::belongToSameApplication(c->client(), current, AbstractClient::SameApplicationCheck::AllowCrossProcesses)) { return false; } } } return true; case TabBoxConfig::AllWindowsCurrentApplication: { QSharedPointer pointer = tabBox->activeClient().toStrongRef(); if (!pointer) { return false; } if ((c = dynamic_cast< TabBoxClientImpl* >(pointer.data()))) { if (AbstractClient::belongToSameApplication(c->client(), current, AbstractClient::SameApplicationCheck::AllowCrossProcesses)) { return true; } } return false; } default: // TabBoxConfig::AllWindowsAllApplications return true; } } bool TabBoxHandlerImpl::checkMinimized(TabBoxClient* client) const { switch (config().clientMinimizedMode()) { case TabBoxConfig::ExcludeMinimizedClients: return !client->isMinimized(); case TabBoxConfig::OnlyMinimizedClients: return client->isMinimized(); default: // TabBoxConfig::IgnoreMinimizedStatus return true; } } bool TabBoxHandlerImpl::checkMultiScreen(TabBoxClient* client) const { auto current = (static_cast< TabBoxClientImpl* >(client))->client(); switch (config().clientMultiScreenMode()) { case TabBoxConfig::IgnoreMultiScreen: return true; case TabBoxConfig::ExcludeCurrentScreenClients: return current->screen() != screens()->current(); default: // TabBoxConfig::OnlyCurrentScreenClients return current->screen() == screens()->current(); } } QWeakPointer TabBoxHandlerImpl::clientToAddToList(TabBoxClient* client, int desktop) const { if (!client) { return QWeakPointer(); } AbstractClient* ret = nullptr; AbstractClient* current = (static_cast< TabBoxClientImpl* >(client))->client(); bool addClient = checkDesktop(client, desktop) && checkActivity(client) && checkApplications(client) && checkMinimized(client) && checkMultiScreen(client); addClient = addClient && current->wantsTabFocus() && !current->skipSwitcher(); if (addClient) { // don't add windows that have modal dialogs AbstractClient* modal = current->findModal(); if (modal == nullptr || modal == current) ret = current; else if (!clientList().contains(modal->tabBoxClient())) ret = modal; else { // nothing } } if (ret) return ret->tabBoxClient(); else return QWeakPointer(); } TabBoxClientList TabBoxHandlerImpl::stackingOrder() const { ToplevelList stacking = Workspace::self()->stackingOrder(); TabBoxClientList ret; foreach (Toplevel *toplevel, stacking) { if (auto client = qobject_cast(toplevel)) { ret.append(client->tabBoxClient()); } } return ret; } bool TabBoxHandlerImpl::isKWinCompositing() const { return Workspace::self()->compositing(); } void TabBoxHandlerImpl::raiseClient(TabBoxClient* c) const { Workspace::self()->raiseClient(static_cast(c)->client()); } void TabBoxHandlerImpl::restack(TabBoxClient *c, TabBoxClient *under) { Workspace::self()->restack(static_cast(c)->client(), static_cast(under)->client(), true); } void TabBoxHandlerImpl::elevateClient(TabBoxClient *c, QWindow *tabbox, bool b) const { auto cl = static_cast(c)->client(); cl->elevate(b); if (Toplevel *w = Workspace::self()->findInternal(tabbox)) w->elevate(b); } void TabBoxHandlerImpl::shadeClient(TabBoxClient *c, bool b) const { Client *cl = dynamic_cast(static_cast(c)->client()); if (!cl) { // shading is X11 specific return; } cl->cancelShadeHoverTimer(); // stop core shading action if (!b && cl->shadeMode() == ShadeNormal) cl->setShade(ShadeHover); else if (b && cl->shadeMode() == ShadeHover) cl->setShade(ShadeNormal); } QWeakPointer TabBoxHandlerImpl::desktopClient() const { foreach (Toplevel *toplevel, Workspace::self()->stackingOrder()) { auto client = qobject_cast(toplevel); if (client && client->isDesktop() && client->isOnCurrentDesktop() && client->screen() == screens()->current()) { return client->tabBoxClient(); } } return QWeakPointer(); } void TabBoxHandlerImpl::activateAndClose() { m_tabBox->accept(); } void TabBoxHandlerImpl::highlightWindows(TabBoxClient *window, QWindow *controller) { if (!effects) { return; } QVector windows; if (window) { windows << static_cast(window)->client()->effectWindow(); } if (auto t = Workspace::self()->findToplevel(controller)) { windows << t->effectWindow(); } static_cast(effects)->highlightWindows(windows); } bool TabBoxHandlerImpl::noModifierGrab() const { return m_tabBox->noModifierGrab(); } /********************************************************* * TabBoxClientImpl *********************************************************/ TabBoxClientImpl::TabBoxClientImpl(AbstractClient *client) : TabBoxClient() , m_client(client) { } TabBoxClientImpl::~TabBoxClientImpl() { } QString TabBoxClientImpl::caption() const { if (m_client->isDesktop()) return i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop"); return m_client->caption(); } QIcon TabBoxClientImpl::icon() const { if (m_client->isDesktop()) { return QIcon::fromTheme(QStringLiteral("user-desktop")); } return m_client->icon(); } WId TabBoxClientImpl::window() const { return m_client->windowId(); } bool TabBoxClientImpl::isMinimized() const { return m_client->isMinimized(); } int TabBoxClientImpl::x() const { return m_client->x(); } int TabBoxClientImpl::y() const { return m_client->y(); } int TabBoxClientImpl::width() const { return m_client->width(); } int TabBoxClientImpl::height() const { return m_client->height(); } bool TabBoxClientImpl::isCloseable() const { return m_client->isCloseable(); } void TabBoxClientImpl::close() { m_client->closeWindow(); } bool TabBoxClientImpl::isFirstInTabBox() const { return m_client->isFirstInTabBox(); } QUuid TabBoxClientImpl::internalId() const { return m_client->internalId(); } /********************************************************* * TabBox *********************************************************/ TabBox *TabBox::s_self = nullptr; TabBox *TabBox::create(QObject *parent) { Q_ASSERT(!s_self); s_self = new TabBox(parent); return s_self; } TabBox::TabBox(QObject *parent) : QObject(parent) , m_displayRefcount(0) , m_desktopGrab(false) , m_tabGrab(false) , m_noModifierGrab(false) , m_forcedGlobalMouseGrab(false) , m_ready(false) { m_isShown = false; m_defaultConfig = TabBoxConfig(); m_defaultConfig.setTabBoxMode(TabBoxConfig::ClientTabBox); m_defaultConfig.setClientDesktopMode(TabBoxConfig::OnlyCurrentDesktopClients); m_defaultConfig.setClientActivitiesMode(TabBoxConfig::OnlyCurrentActivityClients); m_defaultConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsAllApplications); m_defaultConfig.setClientMinimizedMode(TabBoxConfig::IgnoreMinimizedStatus); m_defaultConfig.setShowDesktopMode(TabBoxConfig::DoNotShowDesktopClient); m_defaultConfig.setClientMultiScreenMode(TabBoxConfig::IgnoreMultiScreen); m_defaultConfig.setClientSwitchingMode(TabBoxConfig::FocusChainSwitching); m_alternativeConfig = TabBoxConfig(); m_alternativeConfig.setTabBoxMode(TabBoxConfig::ClientTabBox); m_alternativeConfig.setClientDesktopMode(TabBoxConfig::AllDesktopsClients); m_alternativeConfig.setClientActivitiesMode(TabBoxConfig::OnlyCurrentActivityClients); m_alternativeConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsAllApplications); m_alternativeConfig.setClientMinimizedMode(TabBoxConfig::IgnoreMinimizedStatus); m_alternativeConfig.setShowDesktopMode(TabBoxConfig::DoNotShowDesktopClient); m_alternativeConfig.setClientMultiScreenMode(TabBoxConfig::IgnoreMultiScreen); m_alternativeConfig.setClientSwitchingMode(TabBoxConfig::FocusChainSwitching); m_defaultCurrentApplicationConfig = m_defaultConfig; m_defaultCurrentApplicationConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsCurrentApplication); m_alternativeCurrentApplicationConfig = m_alternativeConfig; m_alternativeCurrentApplicationConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsCurrentApplication); m_desktopConfig = TabBoxConfig(); m_desktopConfig.setTabBoxMode(TabBoxConfig::DesktopTabBox); m_desktopConfig.setShowTabBox(true); m_desktopConfig.setShowDesktopMode(TabBoxConfig::DoNotShowDesktopClient); m_desktopConfig.setDesktopSwitchingMode(TabBoxConfig::MostRecentlyUsedDesktopSwitching); m_desktopListConfig = TabBoxConfig(); m_desktopListConfig.setTabBoxMode(TabBoxConfig::DesktopTabBox); m_desktopListConfig.setShowTabBox(true); m_desktopListConfig.setShowDesktopMode(TabBoxConfig::DoNotShowDesktopClient); m_desktopListConfig.setDesktopSwitchingMode(TabBoxConfig::StaticDesktopSwitching); m_tabBox = new TabBoxHandlerImpl(this); QTimer::singleShot(0, this, SLOT(handlerReady())); m_tabBoxMode = TabBoxDesktopMode; // init variables connect(&m_delayedShowTimer, SIGNAL(timeout()), this, SLOT(show())); connect(Workspace::self(), SIGNAL(configChanged()), this, SLOT(reconfigure())); } TabBox::~TabBox() { s_self = nullptr; } void TabBox::handlerReady() { m_tabBox->setConfig(m_defaultConfig); reconfigure(); m_ready = true; } template void TabBox::key(const char *actionName, Slot slot, const QKeySequence &shortcut) { QAction *a = new QAction(this); a->setProperty("componentName", QStringLiteral(KWIN_NAME)); a->setObjectName(QString::fromUtf8(actionName)); a->setText(i18n(actionName)); KGlobalAccel::self()->setShortcut(a, QList() << shortcut); input()->registerShortcut(shortcut, a, TabBox::self(), slot); auto cuts = KGlobalAccel::self()->shortcut(a); globalShortcutChanged(a, cuts.isEmpty() ? QKeySequence() : cuts.first()); } static const char s_windows[] = I18N_NOOP("Walk Through Windows"); static const char s_windowsRev[] = I18N_NOOP("Walk Through Windows (Reverse)"); static const char s_windowsAlt[] = I18N_NOOP("Walk Through Windows Alternative"); static const char s_windowsAltRev[] = I18N_NOOP("Walk Through Windows Alternative (Reverse)"); static const char s_app[] = I18N_NOOP("Walk Through Windows of Current Application"); static const char s_appRev[] = I18N_NOOP("Walk Through Windows of Current Application (Reverse)"); static const char s_appAlt[] = I18N_NOOP("Walk Through Windows of Current Application Alternative"); static const char s_appAltRev[] = I18N_NOOP("Walk Through Windows of Current Application Alternative (Reverse)"); static const char s_desktops[] = I18N_NOOP("Walk Through Desktops"); static const char s_desktopsRev[] = I18N_NOOP("Walk Through Desktops (Reverse)"); static const char s_desktopList[] = I18N_NOOP("Walk Through Desktop List"); static const char s_desktopListRev[] = I18N_NOOP("Walk Through Desktop List (Reverse)"); void TabBox::initShortcuts() { key(s_windows, &TabBox::slotWalkThroughWindows, Qt::ALT + Qt::Key_Tab); key(s_windowsRev, &TabBox::slotWalkBackThroughWindows, Qt::ALT + Qt::SHIFT + Qt::Key_Backtab); key(s_app, &TabBox::slotWalkThroughCurrentAppWindows, Qt::ALT + Qt::Key_QuoteLeft); key(s_appRev, &TabBox::slotWalkBackThroughCurrentAppWindows, Qt::ALT + Qt::Key_AsciiTilde); key(s_windowsAlt, &TabBox::slotWalkThroughWindowsAlternative); key(s_windowsAltRev, &TabBox::slotWalkBackThroughWindowsAlternative); key(s_appAlt, &TabBox::slotWalkThroughCurrentAppWindowsAlternative); key(s_appAltRev, &TabBox::slotWalkBackThroughCurrentAppWindowsAlternative); key(s_desktops, &TabBox::slotWalkThroughDesktops); key(s_desktopsRev, &TabBox::slotWalkBackThroughDesktops); key(s_desktopList, &TabBox::slotWalkThroughDesktopList); key(s_desktopListRev, &TabBox::slotWalkBackThroughDesktopList); connect(KGlobalAccel::self(), &KGlobalAccel::globalShortcutChanged, this, &TabBox::globalShortcutChanged); } void TabBox::globalShortcutChanged(QAction *action, const QKeySequence &seq) { if (qstrcmp(qPrintable(action->objectName()), s_windows) == 0) { m_cutWalkThroughWindows = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_windowsRev) == 0) { m_cutWalkThroughWindowsReverse = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_app) == 0) { m_cutWalkThroughCurrentAppWindows = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_appRev) == 0) { m_cutWalkThroughCurrentAppWindowsReverse = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_windowsAlt) == 0) { m_cutWalkThroughWindowsAlternative = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_windowsAltRev) == 0) { m_cutWalkThroughWindowsAlternativeReverse = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_appAlt) == 0) { m_cutWalkThroughCurrentAppWindowsAlternative = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_appAltRev) == 0) { m_cutWalkThroughCurrentAppWindowsAlternativeReverse = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_desktops) == 0) { m_cutWalkThroughDesktops = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_desktopsRev) == 0) { m_cutWalkThroughDesktopsReverse = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_desktopList) == 0) { m_cutWalkThroughDesktopList = seq; } else if (qstrcmp(qPrintable(action->objectName()), s_desktopListRev) == 0) { m_cutWalkThroughDesktopListReverse = seq; } } void TabBox::setMode(TabBoxMode mode) { m_tabBoxMode = mode; switch(mode) { case TabBoxWindowsMode: m_tabBox->setConfig(m_defaultConfig); break; case TabBoxWindowsAlternativeMode: m_tabBox->setConfig(m_alternativeConfig); break; case TabBoxCurrentAppWindowsMode: m_tabBox->setConfig(m_defaultCurrentApplicationConfig); break; case TabBoxCurrentAppWindowsAlternativeMode: m_tabBox->setConfig(m_alternativeCurrentApplicationConfig); break; case TabBoxDesktopMode: m_tabBox->setConfig(m_desktopConfig); break; case TabBoxDesktopListMode: m_tabBox->setConfig(m_desktopListConfig); break; } } void TabBox::reset(bool partial_reset) { switch(m_tabBox->config().tabBoxMode()) { case TabBoxConfig::ClientTabBox: m_tabBox->createModel(partial_reset); if (!partial_reset) { if (Workspace::self()->activeClient()) setCurrentClient(Workspace::self()->activeClient()); // it's possible that the active client is not part of the model // in that case the index is invalid if (!m_tabBox->currentIndex().isValid()) setCurrentIndex(m_tabBox->first()); } else { if (!m_tabBox->currentIndex().isValid() || !m_tabBox->client(m_tabBox->currentIndex())) setCurrentIndex(m_tabBox->first()); } break; case TabBoxConfig::DesktopTabBox: m_tabBox->createModel(); if (!partial_reset) setCurrentDesktop(VirtualDesktopManager::self()->current()); break; } emit tabBoxUpdated(); } void TabBox::nextPrev(bool next) { setCurrentIndex(m_tabBox->nextPrev(next), false); emit tabBoxUpdated(); } AbstractClient* TabBox::currentClient() { if (TabBoxClientImpl* client = static_cast< TabBoxClientImpl* >(m_tabBox->client(m_tabBox->currentIndex()))) { if (!Workspace::self()->hasClient(client->client())) return nullptr; return client->client(); } else return nullptr; } QList TabBox::currentClientList() { TabBoxClientList list = m_tabBox->clientList(); QList ret; foreach (const QWeakPointer &clientPointer, list) { QSharedPointer client = clientPointer.toStrongRef(); if (!client) continue; if (const TabBoxClientImpl* c = static_cast< const TabBoxClientImpl* >(client.data())) ret.append(c->client()); } return ret; } int TabBox::currentDesktop() { return m_tabBox->desktop(m_tabBox->currentIndex()); } QList< int > TabBox::currentDesktopList() { return m_tabBox->desktopList(); } void TabBox::setCurrentClient(AbstractClient *newClient) { setCurrentIndex(m_tabBox->index(newClient->tabBoxClient())); } void TabBox::setCurrentDesktop(int newDesktop) { setCurrentIndex(m_tabBox->desktopIndex(newDesktop)); } void TabBox::setCurrentIndex(QModelIndex index, bool notifyEffects) { if (!index.isValid()) return; m_tabBox->setCurrentIndex(index); if (notifyEffects) { emit tabBoxUpdated(); } } void TabBox::show() { emit tabBoxAdded(m_tabBoxMode); if (isDisplayed()) { m_isShown = false; return; } workspace()->setShowingDesktop(false); reference(); m_isShown = true; m_tabBox->show(); } void TabBox::hide(bool abort) { m_delayedShowTimer.stop(); if (m_isShown) { m_isShown = false; unreference(); } emit tabBoxClosed(); if (isDisplayed()) qCDebug(KWIN_TABBOX) << "Tab box was not properly closed by an effect"; m_tabBox->hide(abort); if (kwinApp()->x11Connection()) { Xcb::sync(); } } void TabBox::reconfigure() { KSharedConfigPtr c = kwinApp()->config(); KConfigGroup config = c->group("TabBox"); loadConfig(c->group("TabBox"), m_defaultConfig); loadConfig(c->group("TabBoxAlternative"), m_alternativeConfig); m_defaultCurrentApplicationConfig = m_defaultConfig; m_defaultCurrentApplicationConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsCurrentApplication); m_alternativeCurrentApplicationConfig = m_alternativeConfig; m_alternativeCurrentApplicationConfig.setClientApplicationsMode(TabBoxConfig::AllWindowsCurrentApplication); m_tabBox->setConfig(m_defaultConfig); m_delayShow = config.readEntry("ShowDelay", true); m_delayShowTime = config.readEntry("DelayTime", 90); const QString defaultDesktopLayout = QStringLiteral("org.kde.breeze.desktop"); m_desktopConfig.setLayoutName(config.readEntry("DesktopLayout", defaultDesktopLayout)); m_desktopListConfig.setLayoutName(config.readEntry("DesktopListLayout", defaultDesktopLayout)); QList *borders = &m_borderActivate; QString borderConfig = QStringLiteral("BorderActivate"); for (int i = 0; i < 2; ++i) { foreach (ElectricBorder border, *borders) { ScreenEdges::self()->unreserve(border, this); } borders->clear(); QStringList list = config.readEntry(borderConfig, QStringList()); foreach (const QString &s, list) { bool ok; const int i = s.toInt(&ok); if (!ok) continue; borders->append(ElectricBorder(i)); ScreenEdges::self()->reserve(ElectricBorder(i), this, "toggle"); } borders = &m_borderAlternativeActivate; borderConfig = QStringLiteral("BorderAlternativeActivate"); } auto touchConfig = [this, config] (const QString &key, QHash &actions, TabBoxMode mode, const QStringList &defaults = QStringList{}) { // fist erase old config for (auto it = actions.begin(); it != actions.end(); ) { delete it.value(); it = actions.erase(it); } // now new config const QStringList list = config.readEntry(key, defaults); for (const auto &s : list) { bool ok; const int i = s.toInt(&ok); if (!ok) { continue; } QAction *a = new QAction(this); connect(a, &QAction::triggered, this, std::bind(&TabBox::toggleMode, this, mode)); ScreenEdges::self()->reserveTouch(ElectricBorder(i), a); actions.insert(ElectricBorder(i), a); } }; touchConfig(QStringLiteral("TouchBorderActivate"), m_touchActivate, TabBoxWindowsMode, QStringList{QString::number(int(ElectricLeft))}); touchConfig(QStringLiteral("TouchBorderAlternativeActivate"), m_touchAlternativeActivate, TabBoxWindowsAlternativeMode); } void TabBox::loadConfig(const KConfigGroup& config, TabBoxConfig& tabBoxConfig) { tabBoxConfig.setClientDesktopMode(TabBoxConfig::ClientDesktopMode( config.readEntry("DesktopMode", TabBoxConfig::defaultDesktopMode()))); tabBoxConfig.setClientActivitiesMode(TabBoxConfig::ClientActivitiesMode( config.readEntry("ActivitiesMode", TabBoxConfig::defaultActivitiesMode()))); tabBoxConfig.setClientApplicationsMode(TabBoxConfig::ClientApplicationsMode( config.readEntry("ApplicationsMode", TabBoxConfig::defaultApplicationsMode()))); tabBoxConfig.setClientMinimizedMode(TabBoxConfig::ClientMinimizedMode( config.readEntry("MinimizedMode", TabBoxConfig::defaultMinimizedMode()))); tabBoxConfig.setShowDesktopMode(TabBoxConfig::ShowDesktopMode( config.readEntry("ShowDesktopMode", TabBoxConfig::defaultShowDesktopMode()))); tabBoxConfig.setClientMultiScreenMode(TabBoxConfig::ClientMultiScreenMode( config.readEntry("MultiScreenMode", TabBoxConfig::defaultMultiScreenMode()))); tabBoxConfig.setClientSwitchingMode(TabBoxConfig::ClientSwitchingMode( config.readEntry("SwitchingMode", TabBoxConfig::defaultSwitchingMode()))); tabBoxConfig.setShowTabBox(config.readEntry("ShowTabBox", TabBoxConfig::defaultShowTabBox())); tabBoxConfig.setHighlightWindows(config.readEntry("HighlightWindows", TabBoxConfig::defaultHighlightWindow())); tabBoxConfig.setLayoutName(config.readEntry("LayoutName", TabBoxConfig::defaultLayoutName())); } void TabBox::delayedShow() { if (isDisplayed() || m_delayedShowTimer.isActive()) // already called show - no need to call it twice return; if (!m_delayShowTime) { show(); return; } m_delayedShowTimer.setSingleShot(true); m_delayedShowTimer.start(m_delayShowTime); } bool TabBox::handleMouseEvent(QMouseEvent *event) { if (!m_isShown && isDisplayed()) { // tabbox has been replaced, check effects if (effects && static_cast(effects)->checkInputWindowEvent(event)) { return true; } } switch (event->type()) { case QEvent::MouseMove: if (!m_tabBox->containsPos(event->globalPos())) { // filter out all events which are not on the TabBox window. // We don't want windows to react on the mouse events return true; } return false; case QEvent::MouseButtonPress: if ((!m_isShown && isDisplayed()) || !m_tabBox->containsPos(event->globalPos())) { close(); // click outside closes tab return true; } // fall through case QEvent::MouseButtonRelease: default: // we do not filter it out, the intenal filter takes care return false; } return false; } bool TabBox::handleWheelEvent(QWheelEvent *event) { if (!m_isShown && isDisplayed()) { // tabbox has been replaced, check effects if (effects && static_cast(effects)->checkInputWindowEvent(event)) { return true; } } if (event->angleDelta().y() == 0) { return false; } const QModelIndex index = m_tabBox->nextPrev(event->angleDelta().y() > 0); if (index.isValid()) { setCurrentIndex(index); } return true; } void TabBox::grabbedKeyEvent(QKeyEvent* event) { emit tabBoxKeyEvent(event); if (!m_isShown && isDisplayed()) { // tabbox has been replaced, check effects return; } if (m_noModifierGrab) { if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return || event->key() == Qt::Key_Space) { accept(); return; } } m_tabBox->grabbedKeyEvent(event); } struct KeySymbolsDeleter { static inline void cleanup(xcb_key_symbols_t *symbols) { xcb_key_symbols_free(symbols); } }; /** * Handles alt-tab / control-tab - **/ + */ static bool areKeySymXsDepressed(const uint keySyms[], int nKeySyms) { Xcb::QueryKeymap keys; QScopedPointer symbols(xcb_key_symbols_alloc(connection())); if (symbols.isNull() || !keys) { return false; } const auto keymap = keys->keys; bool depressed = false; for (int iKeySym = 0; iKeySym < nKeySyms; iKeySym++) { uint keySymX = keySyms[ iKeySym ]; xcb_keycode_t *keyCodes = xcb_key_symbols_get_keycode(symbols.data(), keySymX); if (!keyCodes) { continue; } int j = 0; while (keyCodes[j] != XCB_NO_SYMBOL) { const xcb_keycode_t keyCodeX = keyCodes[j++]; int i = keyCodeX / 8; char mask = 1 << (keyCodeX - (i * 8)); if (i < 0 || i >= 32) { continue; } qCDebug(KWIN_TABBOX) << iKeySym << ": keySymX=0x" << QString::number(keySymX, 16) << " i=" << i << " mask=0x" << QString::number(mask, 16) << " keymap[i]=0x" << QString::number(keymap[i], 16); if (keymap[i] & mask) { depressed = true; break; } } free(keyCodes); } return depressed; } static bool areModKeysDepressedX11(const QKeySequence &seq) { uint rgKeySyms[10]; int nKeySyms = 0; int mod = seq[seq.count()-1] & Qt::KeyboardModifierMask; if (mod & Qt::SHIFT) { rgKeySyms[nKeySyms++] = XK_Shift_L; rgKeySyms[nKeySyms++] = XK_Shift_R; } if (mod & Qt::CTRL) { rgKeySyms[nKeySyms++] = XK_Control_L; rgKeySyms[nKeySyms++] = XK_Control_R; } if (mod & Qt::ALT) { rgKeySyms[nKeySyms++] = XK_Alt_L; rgKeySyms[nKeySyms++] = XK_Alt_R; } if (mod & Qt::META) { // It would take some code to determine whether the Win key // is associated with Super or Meta, so check for both. // See bug #140023 for details. rgKeySyms[nKeySyms++] = XK_Super_L; rgKeySyms[nKeySyms++] = XK_Super_R; rgKeySyms[nKeySyms++] = XK_Meta_L; rgKeySyms[nKeySyms++] = XK_Meta_R; } return areKeySymXsDepressed(rgKeySyms, nKeySyms); } static bool areModKeysDepressedWayland(const QKeySequence &seq) { const int mod = seq[seq.count()-1] & Qt::KeyboardModifierMask; const Qt::KeyboardModifiers mods = input()->modifiersRelevantForGlobalShortcuts(); if ((mod & Qt::SHIFT) && mods.testFlag(Qt::ShiftModifier)) { return true; } if ((mod & Qt::CTRL) && mods.testFlag(Qt::ControlModifier)) { return true; } if ((mod & Qt::ALT) && mods.testFlag(Qt::AltModifier)) { return true; } if ((mod & Qt::META) && mods.testFlag(Qt::MetaModifier)) { return true; } return false; } static bool areModKeysDepressed(const QKeySequence& seq) { if (seq.isEmpty()) return false; if (kwinApp()->shouldUseWaylandForCompositing()) { return areModKeysDepressedWayland(seq); } else { return areModKeysDepressedX11(seq); } } void TabBox::navigatingThroughWindows(bool forward, const QKeySequence &shortcut, TabBoxMode mode) { if (!m_ready || isGrabbed() || !Workspace::self()->isOnCurrentHead()) { return; } if (!options->focusPolicyIsReasonable()) { //ungrabXKeyboard(); // need that because of accelerator raw mode // CDE style raise / lower CDEWalkThroughWindows(forward); } else { if (areModKeysDepressed(shortcut)) { if (startKDEWalkThroughWindows(mode)) KDEWalkThroughWindows(forward); } else // if the shortcut has no modifiers, don't show the tabbox, // don't grab, but simply go to the next window KDEOneStepThroughWindows(forward, mode); } } void TabBox::slotWalkThroughWindows() { navigatingThroughWindows(true, m_cutWalkThroughWindows, TabBoxWindowsMode); } void TabBox::slotWalkBackThroughWindows() { navigatingThroughWindows(false, m_cutWalkThroughWindowsReverse, TabBoxWindowsMode); } void TabBox::slotWalkThroughWindowsAlternative() { navigatingThroughWindows(true, m_cutWalkThroughWindowsAlternative, TabBoxWindowsAlternativeMode); } void TabBox::slotWalkBackThroughWindowsAlternative() { navigatingThroughWindows(false, m_cutWalkThroughWindowsAlternativeReverse, TabBoxWindowsAlternativeMode); } void TabBox::slotWalkThroughCurrentAppWindows() { navigatingThroughWindows(true, m_cutWalkThroughCurrentAppWindows, TabBoxCurrentAppWindowsMode); } void TabBox::slotWalkBackThroughCurrentAppWindows() { navigatingThroughWindows(false, m_cutWalkThroughCurrentAppWindowsReverse, TabBoxCurrentAppWindowsMode); } void TabBox::slotWalkThroughCurrentAppWindowsAlternative() { navigatingThroughWindows(true, m_cutWalkThroughCurrentAppWindowsAlternative, TabBoxCurrentAppWindowsAlternativeMode); } void TabBox::slotWalkBackThroughCurrentAppWindowsAlternative() { navigatingThroughWindows(false, m_cutWalkThroughCurrentAppWindowsAlternativeReverse, TabBoxCurrentAppWindowsAlternativeMode); } void TabBox::slotWalkThroughDesktops() { if (!m_ready || isGrabbed() || !Workspace::self()->isOnCurrentHead()) { return; } if (areModKeysDepressed(m_cutWalkThroughDesktops)) { if (startWalkThroughDesktops()) walkThroughDesktops(true); } else { oneStepThroughDesktops(true); } } void TabBox::slotWalkBackThroughDesktops() { if (!m_ready || isGrabbed() || !Workspace::self()->isOnCurrentHead()) { return; } if (areModKeysDepressed(m_cutWalkThroughDesktopsReverse)) { if (startWalkThroughDesktops()) walkThroughDesktops(false); } else { oneStepThroughDesktops(false); } } void TabBox::slotWalkThroughDesktopList() { if (!m_ready || isGrabbed() || !Workspace::self()->isOnCurrentHead()) { return; } if (areModKeysDepressed(m_cutWalkThroughDesktopList)) { if (startWalkThroughDesktopList()) walkThroughDesktops(true); } else { oneStepThroughDesktopList(true); } } void TabBox::slotWalkBackThroughDesktopList() { if (!m_ready || isGrabbed() || !Workspace::self()->isOnCurrentHead()) { return; } if (areModKeysDepressed(m_cutWalkThroughDesktopListReverse)) { if (startWalkThroughDesktopList()) walkThroughDesktops(false); } else { oneStepThroughDesktopList(false); } } void TabBox::shadeActivate(AbstractClient *c) { if ((c->shadeMode() == ShadeNormal || c->shadeMode() == ShadeHover) && options->isShadeHover()) c->setShade(ShadeActivated); } bool TabBox::toggle(ElectricBorder eb) { if (m_borderAlternativeActivate.contains(eb)) { return toggleMode(TabBoxWindowsAlternativeMode); } else { return toggleMode(TabBoxWindowsMode); } } bool TabBox::toggleMode(TabBoxMode mode) { if (!options->focusPolicyIsReasonable()) return false; // not supported. if (isDisplayed()) { accept(); return true; } if (!establishTabBoxGrab()) return false; m_noModifierGrab = m_tabGrab = true; setMode(mode); reset(); show(); return true; } bool TabBox::startKDEWalkThroughWindows(TabBoxMode mode) { if (!establishTabBoxGrab()) return false; m_tabGrab = true; m_noModifierGrab = false; setMode(mode); reset(); return true; } bool TabBox::startWalkThroughDesktops(TabBoxMode mode) { if (!establishTabBoxGrab()) return false; m_desktopGrab = true; m_noModifierGrab = false; setMode(mode); reset(); return true; } bool TabBox::startWalkThroughDesktops() { return startWalkThroughDesktops(TabBoxDesktopMode); } bool TabBox::startWalkThroughDesktopList() { return startWalkThroughDesktops(TabBoxDesktopListMode); } void TabBox::KDEWalkThroughWindows(bool forward) { nextPrev(forward); delayedShow(); } void TabBox::walkThroughDesktops(bool forward) { nextPrev(forward); delayedShow(); } void TabBox::CDEWalkThroughWindows(bool forward) { AbstractClient* c = nullptr; // this function find the first suitable client for unreasonable focus // policies - the topmost one, with some exceptions (can't be keepabove/below, // otherwise it gets stuck on them) // Q_ASSERT(Workspace::self()->block_stacking_updates == 0); for (int i = Workspace::self()->stackingOrder().size() - 1; i >= 0 ; --i) { auto it = qobject_cast(Workspace::self()->stackingOrder().at(i)); if (it && it->isOnCurrentActivity() && it->isOnCurrentDesktop() && !it->isSpecialWindow() && it->isShown(false) && it->wantsTabFocus() && !it->keepAbove() && !it->keepBelow()) { c = it; break; } } AbstractClient* nc = c; bool options_traverse_all; { KConfigGroup group(kwinApp()->config(), "TabBox"); options_traverse_all = group.readEntry("TraverseAll", false); } AbstractClient* firstClient = nullptr; do { nc = forward ? nextClientStatic(nc) : previousClientStatic(nc); if (!firstClient) { // When we see our first client for the second time, // it's time to stop. firstClient = nc; } else if (nc == firstClient) { // No candidates found. nc = nullptr; break; } } while (nc && nc != c && ((!options_traverse_all && !nc->isOnDesktop(currentDesktop())) || nc->isMinimized() || !nc->wantsTabFocus() || nc->keepAbove() || nc->keepBelow() || !nc->isOnCurrentActivity())); if (nc) { if (c && c != nc) Workspace::self()->lowerClient(c); if (options->focusPolicyIsReasonable()) { Workspace::self()->activateClient(nc); shadeActivate(nc); } else { if (!nc->isOnDesktop(currentDesktop())) setCurrentDesktop(nc->desktop()); Workspace::self()->raiseClient(nc); } } } void TabBox::KDEOneStepThroughWindows(bool forward, TabBoxMode mode) { setMode(mode); reset(); nextPrev(forward); if (AbstractClient* c = currentClient()) { Workspace::self()->activateClient(c); shadeActivate(c); } } void TabBox::oneStepThroughDesktops(bool forward, TabBoxMode mode) { setMode(mode); reset(); nextPrev(forward); if (currentDesktop() != -1) setCurrentDesktop(currentDesktop()); } void TabBox::oneStepThroughDesktops(bool forward) { oneStepThroughDesktops(forward, TabBoxDesktopMode); } void TabBox::oneStepThroughDesktopList(bool forward) { oneStepThroughDesktops(forward, TabBoxDesktopListMode); } void TabBox::keyPress(int keyQt) { enum Direction { Backward = -1, Steady = 0, Forward = 1 }; Direction direction(Steady); auto contains = [](const QKeySequence &shortcut, int key) -> bool { for (int i = 0; i < shortcut.count(); ++i) { if (shortcut[i] == key) { return true; } } return false; }; // tests whether a shortcut matches and handles pitfalls on ShiftKey invocation auto directionFor = [keyQt, contains](const QKeySequence &forward, const QKeySequence &backward) -> Direction { if (contains(forward, keyQt)) return Forward; if (contains(backward, keyQt)) return Backward; if (!(keyQt & Qt::ShiftModifier)) return Steady; // Before testing the unshifted key (Ctrl+A vs. Ctrl+Shift+a etc.), see whether this is +Shift+Tab // and check that against +Shift+Backtab (as well) Qt::KeyboardModifiers mods = Qt::ShiftModifier|Qt::ControlModifier|Qt::AltModifier|Qt::MetaModifier|Qt::KeypadModifier|Qt::GroupSwitchModifier; mods &= keyQt; if ((keyQt & ~mods) == Qt::Key_Tab) { if (contains(forward, mods | Qt::Key_Backtab)) return Forward; if (contains(backward, mods | Qt::Key_Backtab)) return Backward; } // if the shortcuts do not match, try matching again after filtering the shift key from keyQt // it is needed to handle correctly the ALT+~ shorcut for example as it is coded as ALT+SHIFT+~ in keyQt if (contains(forward, keyQt & ~Qt::ShiftModifier)) return Forward; if (contains(backward, keyQt & ~Qt::ShiftModifier)) return Backward; return Steady; }; if (m_tabGrab) { static const int ModeCount = 4; static const TabBoxMode modes[ModeCount] = { TabBoxWindowsMode, TabBoxWindowsAlternativeMode, TabBoxCurrentAppWindowsMode, TabBoxCurrentAppWindowsAlternativeMode }; static const QKeySequence cuts[2*ModeCount] = { // forward m_cutWalkThroughWindows, m_cutWalkThroughWindowsAlternative, m_cutWalkThroughCurrentAppWindows, m_cutWalkThroughCurrentAppWindowsAlternative, // backward m_cutWalkThroughWindowsReverse, m_cutWalkThroughWindowsAlternativeReverse, m_cutWalkThroughCurrentAppWindowsReverse, m_cutWalkThroughCurrentAppWindowsAlternativeReverse }; bool testedCurrent = false; // in case of collision, prefer to stay in the current mode int i = 0, j = 0; while (true) { if (!testedCurrent && modes[i] != mode()) { ++j; i = (i+1) % ModeCount; continue; } if (testedCurrent && modes[i] == mode()) { break; } testedCurrent = true; direction = directionFor(cuts[i], cuts[i+ModeCount]); if (direction != Steady) { if (modes[i] != mode()) { accept(false); setMode(modes[i]); auto replayWithChangedTabboxMode = [this, direction]() { reset(); nextPrev(direction == Forward); }; QTimer::singleShot(50, this, replayWithChangedTabboxMode); } break; } else if (++j > ModeCount) { // guarding counter for invalid modes qCDebug(KWIN_TABBOX) << "Invalid TabBoxMode"; return; } i = (i+1) % ModeCount; } if (direction != Steady) { qCDebug(KWIN_TABBOX) << "== " << cuts[i].toString() << " or " << cuts[i+ModeCount].toString(); KDEWalkThroughWindows(direction == Forward); } } else if (m_desktopGrab) { direction = directionFor(m_cutWalkThroughDesktops, m_cutWalkThroughDesktopsReverse); if (direction == Steady) direction = directionFor(m_cutWalkThroughDesktopList, m_cutWalkThroughDesktopListReverse); if (direction != Steady) walkThroughDesktops(direction == Forward); } if (m_desktopGrab || m_tabGrab) { if (((keyQt & ~Qt::KeyboardModifierMask) == Qt::Key_Escape) && direction == Steady) { // if Escape is part of the shortcut, don't cancel close(true); } else if (direction == Steady) { QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, keyQt & ~Qt::KeyboardModifierMask, Qt::NoModifier); grabbedKeyEvent(event); } } } void TabBox::close(bool abort) { if (isGrabbed()) { removeTabBoxGrab(); } hide(abort); input()->pointer()->setEnableConstraints(true); m_tabGrab = false; m_desktopGrab = false; m_noModifierGrab = false; } void TabBox::accept(bool closeTabBox) { AbstractClient *c = currentClient(); if (closeTabBox) close(); if (c) { Workspace::self()->activateClient(c); shadeActivate(c); if (c->isDesktop()) Workspace::self()->setShowingDesktop(!Workspace::self()->showingDesktop()); } } void TabBox::modifiersReleased() { if (m_noModifierGrab) { return; } if (m_tabGrab) { bool old_control_grab = m_desktopGrab; accept(); m_desktopGrab = old_control_grab; } if (m_desktopGrab) { bool old_tab_grab = m_tabGrab; int desktop = currentDesktop(); close(); m_tabGrab = old_tab_grab; if (desktop != -1) { setCurrentDesktop(desktop); VirtualDesktopManager::self()->setCurrent(desktop); } } } int TabBox::nextDesktopStatic(int iDesktop) const { DesktopNext functor; return functor(iDesktop, true); } int TabBox::previousDesktopStatic(int iDesktop) const { DesktopPrevious functor; return functor(iDesktop, true); } /** * Auxiliary functions to travers all clients according to the static * order. Useful for the CDE-style Alt-tab feature. - **/ + */ AbstractClient* TabBox::nextClientStatic(AbstractClient* c) const { const auto &list = Workspace::self()->allClientList(); if (!c || list.isEmpty()) return 0; int pos = list.indexOf(c); if (pos == -1) return list.first(); ++pos; if (pos == list.count()) return list.first(); return list.at(pos); } /** * Auxiliary functions to travers all clients according to the static * order. Useful for the CDE-style Alt-tab feature. - **/ + */ AbstractClient* TabBox::previousClientStatic(AbstractClient* c) const { const auto &list = Workspace::self()->allClientList(); if (!c || list.isEmpty()) return 0; int pos = list.indexOf(c); if (pos == -1) return list.last(); if (pos == 0) return list.last(); --pos; return list.at(pos); } bool TabBox::establishTabBoxGrab() { if (kwinApp()->shouldUseWaylandForCompositing()) { m_forcedGlobalMouseGrab = true; return true; } updateXTime(); if (!grabXKeyboard()) return false; // Don't try to establish a global mouse grab using XGrabPointer, as that would prevent // using Alt+Tab while DND (#44972). However force passive grabs on all windows // in order to catch MouseRelease events and close the tabbox (#67416). // All clients already have passive grabs in their wrapper windows, so check only // the active client, which may not have it. assert(!m_forcedGlobalMouseGrab); m_forcedGlobalMouseGrab = true; if (Workspace::self()->activeClient() != nullptr) Workspace::self()->activeClient()->updateMouseGrab(); m_x11EventFilter.reset(new X11Filter); return true; } void TabBox::removeTabBoxGrab() { if (kwinApp()->shouldUseWaylandForCompositing()) { m_forcedGlobalMouseGrab = false; return; } updateXTime(); ungrabXKeyboard(); assert(m_forcedGlobalMouseGrab); m_forcedGlobalMouseGrab = false; if (Workspace::self()->activeClient() != nullptr) Workspace::self()->activeClient()->updateMouseGrab(); m_x11EventFilter.reset(); } } // namespace TabBox } // namespace diff --git a/tabbox/tabbox.h b/tabbox/tabbox.h index 755fd890c..7a0bd13e9 100644 --- a/tabbox/tabbox.h +++ b/tabbox/tabbox.h @@ -1,376 +1,376 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 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_TABBOX_H #define KWIN_TABBOX_H #include #include #include #include "utils.h" #include "tabbox/tabboxhandler.h" class KConfigGroup; class QAction; class QMouseEvent; class QKeyEvent; class QWheelEvent; namespace KWin { class Workspace; class AbstractClient; class Client; class X11EventFilter; namespace TabBox { class DesktopChainManager; class TabBoxConfig; class TabBox; class TabBoxHandlerImpl : public TabBoxHandler { public: explicit TabBoxHandlerImpl(TabBox* tabBox); ~TabBoxHandlerImpl() override; int activeScreen() const override; QWeakPointer< TabBoxClient > activeClient() const override; int currentDesktop() const override; QString desktopName(TabBoxClient* client) const override; QString desktopName(int desktop) const override; bool isKWinCompositing() const override; QWeakPointer< TabBoxClient > nextClientFocusChain(TabBoxClient* client) const override; QWeakPointer< TabBoxClient > firstClientFocusChain() const override; bool isInFocusChain (TabBoxClient* client) const override; int nextDesktopFocusChain(int desktop) const override; int numberOfDesktops() const override; TabBoxClientList stackingOrder() const override; void elevateClient(TabBoxClient* c, QWindow *tabbox, bool elevate) const override; void raiseClient(TabBoxClient *client) const override; void restack(TabBoxClient *c, TabBoxClient *under) override; void shadeClient(TabBoxClient *c, bool b) const override; QWeakPointer< TabBoxClient > clientToAddToList(KWin::TabBox::TabBoxClient* client, int desktop) const override; QWeakPointer< TabBoxClient > desktopClient() const override; void activateAndClose() override; void highlightWindows(TabBoxClient *window = nullptr, QWindow *controller = nullptr) override; bool noModifierGrab() const override; private: bool checkDesktop(TabBoxClient* client, int desktop) const; bool checkActivity(TabBoxClient* client) const; bool checkApplications(TabBoxClient* client) const; bool checkMinimized(TabBoxClient* client) const; bool checkMultiScreen(TabBoxClient* client) const; TabBox* m_tabBox; DesktopChainManager* m_desktopFocusChain; }; class TabBoxClientImpl : public TabBoxClient { public: explicit TabBoxClientImpl(AbstractClient *client); ~TabBoxClientImpl() override; QString caption() const override; QIcon icon() const override; WId window() const override; bool isMinimized() const override; int x() const override; int y() const override; int width() const override; int height() const override; bool isCloseable() const override; void close() override; bool isFirstInTabBox() const override; QUuid internalId() const override; AbstractClient* client() const { return m_client; } private: AbstractClient* m_client; }; class KWIN_EXPORT TabBox : public QObject { Q_OBJECT public: ~TabBox() override; /** * Returns the currently displayed client ( only works in TabBoxWindowsMode ). * Returns 0 if no client is displayed. - **/ + */ AbstractClient *currentClient(); /** * Returns the list of clients potentially displayed ( only works in * TabBoxWindowsMode ). * Returns an empty list if no clients are available. - **/ + */ QList currentClientList(); /** * Returns the currently displayed virtual desktop ( only works in * TabBoxDesktopListMode ) * Returns -1 if no desktop is displayed. - **/ + */ int currentDesktop(); /** * Returns the list of desktops potentially displayed ( only works in * TabBoxDesktopListMode ) * Returns an empty list if no are available. - **/ + */ QList< int > currentDesktopList(); /** * Change the currently selected client, and notify the effects. * * @see setCurrentDesktop - **/ + */ void setCurrentClient(AbstractClient *newClient); /** * Change the currently selected desktop, and notify the effects. * * @see setCurrentClient - **/ + */ void setCurrentDesktop(int newDesktop); /** * Sets the current mode to \a mode, either TabBoxDesktopListMode or TabBoxWindowsMode * * @see mode - **/ + */ void setMode(TabBoxMode mode); TabBoxMode mode() const { return m_tabBoxMode; } /** * Resets the tab box to display the active client in TabBoxWindowsMode, or the * current desktop in TabBoxDesktopListMode - **/ + */ void reset(bool partial_reset = false); /** * Shows the next or previous item, depending on \a next - **/ + */ void nextPrev(bool next = true); /** * Shows the tab box after some delay. * * If the 'ShowDelay' setting is false, show() is simply called. * * Otherwise, we start a timer for the delay given in the settings and only * do a show() when it times out. * * This means that you can alt-tab between windows and you don't see the * tab box immediately. Not only does this make alt-tabbing faster, it gives * less 'flicker' to the eyes. You don't need to see the tab box if you're * just quickly switching between 2 or 3 windows. It seems to work quite * nicely. - **/ + */ void delayedShow(); /** * Notify effects that the tab box is being hidden. - **/ + */ void hide(bool abort = false); /** * Increases the reference count, preventing the default tabbox from showing. * * @see unreference * @see isDisplayed - **/ + */ void reference() { ++m_displayRefcount; } /** * Decreases the reference count. Only when the reference count is 0 will * the default tab box be shown. - **/ + */ void unreference() { --m_displayRefcount; } /** * Returns whether the tab box is being displayed, either natively or by an * effect. * * @see reference * @see unreference - **/ + */ bool isDisplayed() const { return m_displayRefcount > 0; } /** * @returns @c true if TabBox is shown, @c false if replaced by Effect - **/ + */ bool isShown() const { return m_isShown; } bool handleMouseEvent(QMouseEvent *event); bool handleWheelEvent(QWheelEvent *event); void grabbedKeyEvent(QKeyEvent* event); bool isGrabbed() const { return m_tabGrab || m_desktopGrab; } void initShortcuts(); AbstractClient* nextClientStatic(AbstractClient*) const; AbstractClient* previousClientStatic(AbstractClient*) const; int nextDesktopStatic(int iDesktop) const; int previousDesktopStatic(int iDesktop) const; void keyPress(int key); void modifiersReleased(); bool forcedGlobalMouseGrab() const { return m_forcedGlobalMouseGrab; } bool noModifierGrab() const { return m_noModifierGrab; } void setCurrentIndex(QModelIndex index, bool notifyEffects = true); static TabBox *self(); static TabBox *create(QObject *parent); public Q_SLOTS: /** * Notify effects that the tab box is being shown, and only display the * default tab box QFrame if no effect has referenced the tab box. - **/ + */ void show(); void close(bool abort = false); void accept(bool closeTabBox = true); void slotWalkThroughDesktops(); void slotWalkBackThroughDesktops(); void slotWalkThroughDesktopList(); void slotWalkBackThroughDesktopList(); void slotWalkThroughWindows(); void slotWalkBackThroughWindows(); void slotWalkThroughWindowsAlternative(); void slotWalkBackThroughWindowsAlternative(); void slotWalkThroughCurrentAppWindows(); void slotWalkBackThroughCurrentAppWindows(); void slotWalkThroughCurrentAppWindowsAlternative(); void slotWalkBackThroughCurrentAppWindowsAlternative(); void handlerReady(); bool toggle(ElectricBorder eb); Q_SIGNALS: void tabBoxAdded(int); void tabBoxClosed(); void tabBoxUpdated(); void tabBoxKeyEvent(QKeyEvent*); private: explicit TabBox(QObject *parent); void loadConfig(const KConfigGroup& config, TabBoxConfig& tabBoxConfig); bool startKDEWalkThroughWindows(TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode bool startWalkThroughDesktops(TabBoxMode mode); // TabBoxDesktopMode | TabBoxDesktopListMode bool startWalkThroughDesktops(); bool startWalkThroughDesktopList(); void navigatingThroughWindows(bool forward, const QKeySequence &shortcut, TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode void KDEWalkThroughWindows(bool forward); void CDEWalkThroughWindows(bool forward); void walkThroughDesktops(bool forward); void KDEOneStepThroughWindows(bool forward, TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode void oneStepThroughDesktops(bool forward, TabBoxMode mode); // TabBoxDesktopMode | TabBoxDesktopListMode void oneStepThroughDesktops(bool forward); void oneStepThroughDesktopList(bool forward); bool establishTabBoxGrab(); void removeTabBoxGrab(); template void key(const char *actionName, Slot slot, const QKeySequence &shortcut = QKeySequence()); void shadeActivate(AbstractClient *c); bool toggleMode(TabBoxMode mode); private Q_SLOTS: void reconfigure(); void globalShortcutChanged(QAction *action, const QKeySequence &seq); private: TabBoxMode m_tabBoxMode; TabBoxHandlerImpl* m_tabBox; bool m_delayShow; int m_delayShowTime; QTimer m_delayedShowTimer; int m_displayRefcount; TabBoxConfig m_defaultConfig; TabBoxConfig m_alternativeConfig; TabBoxConfig m_defaultCurrentApplicationConfig; TabBoxConfig m_alternativeCurrentApplicationConfig; TabBoxConfig m_desktopConfig; TabBoxConfig m_desktopListConfig; // false if an effect has referenced the tabbox // true if tabbox is active (independent on showTabbox setting) bool m_isShown; bool m_desktopGrab; bool m_tabGrab; // true if tabbox is in modal mode which does not require holding a modifier bool m_noModifierGrab; QKeySequence m_cutWalkThroughDesktops, m_cutWalkThroughDesktopsReverse; QKeySequence m_cutWalkThroughDesktopList, m_cutWalkThroughDesktopListReverse; QKeySequence m_cutWalkThroughWindows, m_cutWalkThroughWindowsReverse; QKeySequence m_cutWalkThroughWindowsAlternative, m_cutWalkThroughWindowsAlternativeReverse; QKeySequence m_cutWalkThroughCurrentAppWindows, m_cutWalkThroughCurrentAppWindowsReverse; QKeySequence m_cutWalkThroughCurrentAppWindowsAlternative, m_cutWalkThroughCurrentAppWindowsAlternativeReverse; bool m_forcedGlobalMouseGrab; bool m_ready; // indicates whether the config is completely loaded QList m_borderActivate, m_borderAlternativeActivate; QHash m_touchActivate; QHash m_touchAlternativeActivate; QScopedPointer m_x11EventFilter; static TabBox *s_self; }; inline TabBox *TabBox::self() { return s_self; } } // namespace TabBox } // namespace #endif diff --git a/tabbox/tabboxconfig.h b/tabbox/tabboxconfig.h index d77a710bc..f93f58c73 100644 --- a/tabbox/tabboxconfig.h +++ b/tabbox/tabboxconfig.h @@ -1,326 +1,326 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 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 TABBOXCONFIG_H #define TABBOXCONFIG_H #include /** * @file * This file defines the class TabBoxConfig. * * @author Martin Gräßlin * @since 4.4 - **/ + */ namespace KWin { namespace TabBox { class TabBoxConfigPrivate; /** * The TabBoxConfig class holds all configuration options for the TabBox. * The TabBoxHandler contains a pointer to an object of this class and is * used by all classes of TabBox. The config defines what kind of data the * TabBox is displaying and how the layout looks like. There can be different * Config sets and by setting a new config in the TabBoxHandler the behaviour * of the TabBox is changed immediately. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class TabBoxConfig { public: /** * ClientDesktopMode defines whether windows from the current desktop or from all * desktops are included in the TabBoxClient List in the TabBoxClientModel - **/ + */ enum ClientDesktopMode { AllDesktopsClients, ///< TabBoxClients from all desktops are included. OnlyCurrentDesktopClients, ///< Only TabBoxClients on current desktop are included ExcludeCurrentDesktopClients ///< Exclude TabBoxClients on current desktop }; /** * ClientActivitiesMode defines whether windows from the current activity or from all * activities are included in the TabBoxClient List in the TabBoxClientModel - **/ + */ enum ClientActivitiesMode { AllActivitiesClients, ///< TabBoxClients from all Activities are included. OnlyCurrentActivityClients, ///< Only TabBoxClients on current activity are included ExcludeCurrentActivityClients ///< Exclude TabBoxClients on current activity }; /** * ClientApplicationsMode defines which windows from the current application or from all * applications are included in the TabBoxClient List in the TabBoxClientModel - **/ + */ enum ClientApplicationsMode { AllWindowsAllApplications, ///< TabBoxClients from all applications are included OneWindowPerApplication, ///< Only one TabBoxClient for each application is included AllWindowsCurrentApplication ///< Only TabBoxClients for the current application are included }; /** * ClientMinimizedMode defines which windows are included in the TabBoxClient List * in the TabBoxClientModel based on whether they are minimized or not - **/ + */ enum ClientMinimizedMode { IgnoreMinimizedStatus, ///< TabBoxClients are included no matter they are minimized or not ExcludeMinimizedClients, ///< Exclude minimized TabBoxClients OnlyMinimizedClients ///< Only minimized TabBoxClients are included }; /** * ShowDesktopMode defines whether a TabBoxClient representing the desktop * is included in the TabBoxClient List in the TabBoxClientModel - **/ + */ enum ShowDesktopMode { DoNotShowDesktopClient, ///< A TabBoxClient representing the desktop is not included ShowDesktopClient ///< A TabBoxClient representing the desktop is included }; /** * ClientActivitiesMode defines whether windows from the current activity or from all * activities are included in the TabBoxClient List in the TabBoxClientModel - **/ + */ enum ClientMultiScreenMode { IgnoreMultiScreen, ///< TabBoxClients are included independently of the screen they are on OnlyCurrentScreenClients, ///< Only TabBoxClients on current screen are included ExcludeCurrentScreenClients ///< Exclude TabBoxClients from the current screen }; /** * ClientSwitchingMode defines the sorting of the TabBoxClients in the * TabBoxClientModel. - **/ + */ enum ClientSwitchingMode { FocusChainSwitching, ///< Sort by recently used. Most recently used TabBoxClient is the first StackingOrderSwitching ///< Sort by current stacking order }; /** * DesktopSwitchingMode defines the sorting of the desktops in the * TabBoxDesktopModel. - **/ + */ enum DesktopSwitchingMode { MostRecentlyUsedDesktopSwitching,///< Sort by recently used. Most recently used desktop is the first StaticDesktopSwitching///< Static sorting in numerical ascending order }; /** * TabBoxMode defines what kind of items the TabBox is displaying and which * Model is used - **/ + */ enum TabBoxMode { ClientTabBox,///< TabBox uses TabBoxClientModel DesktopTabBox///< TabBox uses TabBoxDesktopModel }; TabBoxConfig(); ~TabBoxConfig(); TabBoxConfig& operator=(const TabBoxConfig& object); // getters /** * @return If the TabBox should be shown or not * This option does not apply for TabBoxMode DesktopTabBox. * @see setShowTabBox * @see defaultShowTabBox - **/ + */ bool isShowTabBox() const; /** * @return If Highlight Window effect should be used. * This option does not apply for TabBoxMode DesktopTabBox. * @see setHighlightWindows * @see defaultHighlightWindows - **/ + */ bool isHighlightWindows() const; /** * @return The current TabBoxMode * @see setTabBoxMode - **/ + */ TabBoxMode tabBoxMode() const; /** * @return The current ClientDesktopMode * This option only applies for TabBoxMode ClientTabBox. * @see setClientDesktopMode * @see defaultDesktopMode - **/ + */ ClientDesktopMode clientDesktopMode() const; /** * @return The current ClientActivitiesMode * This option only applies for TabBoxMode ClientTabBox. * @see setClientActivitiesMode * @see defaultActivitiesMode - **/ + */ ClientActivitiesMode clientActivitiesMode() const; /** * @return The current ClientApplicationsMode * This option only applies for TabBoxMode ClientTabBox. * @see setClientApplicationsMode * @see defaultApplicationsMode - **/ + */ ClientApplicationsMode clientApplicationsMode() const; /** * @return The current ClientMinimizedMode * This option only applies for TabBoxMode ClientTabBox. * @see setClientMinimizedMode * @see defaultMinimizedMode - **/ + */ ClientMinimizedMode clientMinimizedMode() const; /** * @return The current ShowDesktopMode * This option only applies for TabBoxMode ClientTabBox. * @see setShowDesktopMode * @see defaultShowDesktopMode - **/ + */ ShowDesktopMode showDesktopMode() const; /** * @return The current ClientMultiScreenMode * This option only applies for TabBoxMode ClientTabBox. * @see setClientMultiScreenMode * @see defaultMultiScreenMode - **/ + */ ClientMultiScreenMode clientMultiScreenMode() const; /** * @return The current ClientSwitchingMode. * This option only applies for TabBoxMode ClientTabBox. * @see setClientSwitchingMode * @see defaultSwitchingMode - **/ + */ ClientSwitchingMode clientSwitchingMode() const; /** * @return The current DesktopSwitchingMode * This option only applies for TabBoxMode DesktopTabBox. * @see setDesktopSwitchingMode - **/ + */ DesktopSwitchingMode desktopSwitchingMode() const; /** * @return Then name of the current ItemLayout * @see setlayoutName - **/ + */ QString& layoutName() const; // setters /** * @param show The tabbox should be shown or not. * This option does not apply for TabBoxMode DesktopTabBox. * @see isShowTabBox - **/ + */ void setShowTabBox(bool show); /** * @param highlight Highlight Windows effect should be used or not. * This option does not apply for TabBoxMode DesktopTabBox. * @see isHighlightWindows - **/ + */ void setHighlightWindows(bool highlight); /** * @param mode The new TabBoxMode to be used. * @see tabBoxMode - **/ + */ void setTabBoxMode(TabBoxMode mode); /** * @param desktopMode The new ClientDesktopMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientDesktopMode - **/ + */ void setClientDesktopMode(ClientDesktopMode desktopMode); /** * @param activitiesMode The new ClientActivitiesMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientActivitiesMode - **/ + */ void setClientActivitiesMode(ClientActivitiesMode activitiesMode); /** * @param applicationsMode The new ClientApplicationsMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientApplicationsMode - **/ + */ void setClientApplicationsMode(ClientApplicationsMode applicationsMode); /** * @param minimizedMode The new ClientMinimizedMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientMinimizedMode - **/ + */ void setClientMinimizedMode(ClientMinimizedMode minimizedMode); /** * @param showDesktopMode The new ShowDesktopMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see showDesktopMode - **/ + */ void setShowDesktopMode(ShowDesktopMode showDesktopMode); /** * @param multiScreenMode The new ClientMultiScreenMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientMultiScreenMode - **/ + */ void setClientMultiScreenMode(ClientMultiScreenMode multiScreenMode); /** * @param switchingMode The new ClientSwitchingMode to be used. * This option only applies for TabBoxMode ClientTabBox. * @see clientSwitchingMode - **/ + */ void setClientSwitchingMode(ClientSwitchingMode switchingMode); /** * @param switchingMode The new DesktopSwitchingMode to be used. * This option only applies for TabBoxMode DesktopTabBox. * @see desktopSwitchingMode - **/ + */ void setDesktopSwitchingMode(DesktopSwitchingMode switchingMode); /** * @param name The new ItemLayout config name * @see layoutName - **/ + */ void setLayoutName(const QString& name); // some static methods to access default values static ClientDesktopMode defaultDesktopMode() { return OnlyCurrentDesktopClients; } static ClientActivitiesMode defaultActivitiesMode() { return OnlyCurrentActivityClients; } static ClientApplicationsMode defaultApplicationsMode() { return AllWindowsAllApplications; } static ClientMinimizedMode defaultMinimizedMode() { return IgnoreMinimizedStatus; } static ShowDesktopMode defaultShowDesktopMode() { return DoNotShowDesktopClient; } static ClientMultiScreenMode defaultMultiScreenMode() { return IgnoreMultiScreen; } static ClientSwitchingMode defaultSwitchingMode() { return FocusChainSwitching; } static bool defaultShowTabBox() { return true; } static bool defaultHighlightWindow() { return true; } static QString defaultLayoutName() { return QStringLiteral("org.kde.breeze.desktop"); } private: TabBoxConfigPrivate* d; }; } // namespace TabBox } // namespace KWin #endif // TABBOXCONFIG_H diff --git a/tabbox/tabboxhandler.cpp b/tabbox/tabboxhandler.cpp index fa952725a..9b251ecdc 100644 --- a/tabbox/tabboxhandler.cpp +++ b/tabbox/tabboxhandler.cpp @@ -1,656 +1,656 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 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 . *********************************************************************/ // own #include "tabboxhandler.h" #include #include #include "xcbutils.h" // tabbox #include "clientmodel.h" #include "desktopmodel.h" #include "tabboxconfig.h" #include "thumbnailitem.h" #include "scripting/scripting.h" #include "switcheritem.h" #include "tabbox_logging.h" // Qt #include #include #include #include #include #include #include #include #include #include #include // KDE #include #include #include #include namespace KWin { namespace TabBox { class TabBoxHandlerPrivate { public: TabBoxHandlerPrivate(TabBoxHandler *q); ~TabBoxHandlerPrivate(); /** * Updates the current highlight window state - **/ + */ void updateHighlightWindows(); /** * Ends window highlighting - **/ + */ void endHighlightWindows(bool abort = false); void show(); QQuickWindow *window() const; SwitcherItem *switcherItem() const; ClientModel* clientModel() const; DesktopModel* desktopModel() const; TabBoxHandler *q; // public pointer // members TabBoxConfig config; QScopedPointer m_qmlContext; QScopedPointer m_qmlComponent; QObject *m_mainItem; QMap m_clientTabBoxes; QMap m_desktopTabBoxes; ClientModel* m_clientModel; DesktopModel* m_desktopModel; QModelIndex index; /** * Indicates if the tabbox is shown. - **/ + */ bool isShown; TabBoxClient *lastRaisedClient, *lastRaisedClientSucc; int wheelAngleDelta = 0; private: QObject *createSwitcherItem(bool desktopMode); }; TabBoxHandlerPrivate::TabBoxHandlerPrivate(TabBoxHandler *q) : m_qmlContext() , m_qmlComponent() , m_mainItem(nullptr) { this->q = q; isShown = false; lastRaisedClient = nullptr; lastRaisedClientSucc = nullptr; config = TabBoxConfig(); m_clientModel = new ClientModel(q); m_desktopModel = new DesktopModel(q); } TabBoxHandlerPrivate::~TabBoxHandlerPrivate() { for (auto it = m_clientTabBoxes.constBegin(); it != m_clientTabBoxes.constEnd(); ++it) { delete it.value(); } for (auto it = m_desktopTabBoxes.constBegin(); it != m_desktopTabBoxes.constEnd(); ++it) { delete it.value(); } } QQuickWindow *TabBoxHandlerPrivate::window() const { if (!m_mainItem) { return nullptr; } if (QQuickWindow *w = qobject_cast(m_mainItem)) { return w; } return m_mainItem->findChild(); } #ifndef KWIN_UNIT_TEST SwitcherItem *TabBoxHandlerPrivate::switcherItem() const { if (!m_mainItem) { return nullptr; } if (SwitcherItem *i = qobject_cast(m_mainItem)) { return i; } else if (QQuickWindow *w = qobject_cast(m_mainItem)) { return w->contentItem()->findChild(); } return m_mainItem->findChild(); } #endif ClientModel* TabBoxHandlerPrivate::clientModel() const { return m_clientModel; } DesktopModel* TabBoxHandlerPrivate::desktopModel() const { return m_desktopModel; } void TabBoxHandlerPrivate::updateHighlightWindows() { if (!isShown || config.tabBoxMode() != TabBoxConfig::ClientTabBox) return; TabBoxClient *currentClient = q->client(index); QWindow *w = window(); if (q->isKWinCompositing()) { if (lastRaisedClient) q->elevateClient(lastRaisedClient, w, false); lastRaisedClient = currentClient; if (currentClient) q->elevateClient(currentClient, w, true); } else { if (lastRaisedClient) { q->shadeClient(lastRaisedClient, true); if (lastRaisedClientSucc) q->restack(lastRaisedClient, lastRaisedClientSucc); // TODO lastRaisedClient->setMinimized( lastRaisedClientWasMinimized ); } lastRaisedClient = currentClient; if (lastRaisedClient) { q->shadeClient(lastRaisedClient, false); // TODO if ( (lastRaisedClientWasMinimized = lastRaisedClient->isMinimized()) ) // lastRaisedClient->setMinimized( false ); TabBoxClientList order = q->stackingOrder(); int succIdx = order.count() + 1; for (int i=0; iraiseClient(lastRaisedClient); } } if (config.isShowTabBox() && w) { q->highlightWindows(currentClient, w); } else { q->highlightWindows(currentClient); } } void TabBoxHandlerPrivate::endHighlightWindows(bool abort) { TabBoxClient *currentClient = q->client(index); if (config.isHighlightWindows() && q->isKWinCompositing()) { foreach (const QWeakPointer &clientPointer, q->stackingOrder()) { if (QSharedPointer client = clientPointer.toStrongRef()) if (client != currentClient) // to not mess up with wanted ShadeActive/ShadeHover state q->shadeClient(client.data(), true); } } QWindow *w = window(); if (currentClient) q->elevateClient(currentClient, w, false); if (abort && lastRaisedClient && lastRaisedClientSucc) q->restack(lastRaisedClient, lastRaisedClientSucc); lastRaisedClient = nullptr; lastRaisedClientSucc = nullptr; // highlight windows q->highlightWindows(); } #ifndef KWIN_UNIT_TEST QObject *TabBoxHandlerPrivate::createSwitcherItem(bool desktopMode) { // first try look'n'feel package QString file = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("plasma/look-and-feel/%1/contents/%2") .arg(config.layoutName()) .arg(desktopMode ? QStringLiteral("desktopswitcher/DesktopSwitcher.qml") : QStringLiteral("windowswitcher/WindowSwitcher.qml"))); if (file.isNull()) { const QString folderName = QLatin1String(KWIN_NAME) + (desktopMode ? QLatin1String("/desktoptabbox/") : QLatin1String("/tabbox/")); auto findSwitcher = [this, desktopMode, folderName] { const QString type = desktopMode ? QStringLiteral("KWin/DesktopSwitcher") : QStringLiteral("KWin/WindowSwitcher"); auto offers = KPackage::PackageLoader::self()->findPackages(type, folderName, [this] (const KPluginMetaData &data) { return data.pluginId().compare(config.layoutName(), Qt::CaseInsensitive) == 0; } ); if (offers.isEmpty()) { // load default offers = KPackage::PackageLoader::self()->findPackages(type, folderName, [] (const KPluginMetaData &data) { return data.pluginId().compare(QStringLiteral("informative"), Qt::CaseInsensitive) == 0; } ); if (offers.isEmpty()) { qCDebug(KWIN_TABBOX) << "could not find default window switcher layout"; return KPluginMetaData(); } } return offers.first(); }; auto service = findSwitcher(); if (!service.isValid()) { return nullptr; } if (service.value(QStringLiteral("X-Plasma-API")) != QLatin1String("declarativeappletscript")) { qCDebug(KWIN_TABBOX) << "Window Switcher Layout is no declarativeappletscript"; return nullptr; } auto findScriptFile = [service, folderName] { const QString pluginName = service.pluginId(); const QString scriptName = service.value(QStringLiteral("X-Plasma-MainScript")); return QStandardPaths::locate(QStandardPaths::GenericDataLocation, folderName + pluginName + QLatin1String("/contents/") + scriptName); }; file = findScriptFile(); } if (file.isNull()) { qCDebug(KWIN_TABBOX) << "Could not find QML file for window switcher"; return nullptr; } m_qmlComponent->loadUrl(QUrl::fromLocalFile(file)); if (m_qmlComponent->isError()) { qCDebug(KWIN_TABBOX) << "Component failed to load: " << m_qmlComponent->errors(); QStringList args; args << QStringLiteral("--passivepopup") << i18n("The Window Switcher installation is broken, resources are missing.\n" "Contact your distribution about this.") << QStringLiteral("20"); KProcess::startDetached(QStringLiteral("kdialog"), args); } else { QObject *object = m_qmlComponent->create(m_qmlContext.data()); if (desktopMode) { m_desktopTabBoxes.insert(config.layoutName(), object); } else { m_clientTabBoxes.insert(config.layoutName(), object); } return object; } return nullptr; } #endif void TabBoxHandlerPrivate::show() { #ifndef KWIN_UNIT_TEST if (m_qmlContext.isNull()) { qmlRegisterType("org.kde.kwin", 2, 0, "Switcher"); m_qmlContext.reset(new QQmlContext(Scripting::self()->qmlEngine())); } if (m_qmlComponent.isNull()) { m_qmlComponent.reset(new QQmlComponent(Scripting::self()->qmlEngine())); } const bool desktopMode = (config.tabBoxMode() == TabBoxConfig::DesktopTabBox); auto findMainItem = [this](const QMap &tabBoxes) -> QObject* { auto it = tabBoxes.constFind(config.layoutName()); if (it != tabBoxes.constEnd()) { return it.value(); } return nullptr; }; m_mainItem = nullptr; m_mainItem = desktopMode ? findMainItem(m_desktopTabBoxes) : findMainItem(m_clientTabBoxes); if (!m_mainItem) { m_mainItem = createSwitcherItem(desktopMode); if (!m_mainItem) { return; } } if (SwitcherItem *item = switcherItem()) { // In case the model isn't yet set (see below), index will be reset and therefore we // need to save the current index row (https://bugs.kde.org/show_bug.cgi?id=333511). int indexRow = index.row(); if (!item->model()) { QAbstractItemModel *model = nullptr; if (desktopMode) { model = desktopModel(); } else { model = clientModel(); } item->setModel(model); } item->setAllDesktops(config.clientDesktopMode() == TabBoxConfig::AllDesktopsClients); item->setCurrentIndex(indexRow); item->setNoModifierGrab(q->noModifierGrab()); // everything is prepared, so let's make the whole thing visible item->setVisible(true); } if (QWindow *w = window()) { wheelAngleDelta = 0; w->installEventFilter(q); // pretend to activate the window to enable accessibility notifications QWindowSystemInterface::handleWindowActivated(w, Qt::TabFocusReason); } #endif } /*********************************************** * TabBoxHandler ***********************************************/ TabBoxHandler::TabBoxHandler(QObject *parent) : QObject(parent) { KWin::TabBox::tabBox = this; d = new TabBoxHandlerPrivate(this); } TabBoxHandler::~TabBoxHandler() { delete d; } const KWin::TabBox::TabBoxConfig& TabBoxHandler::config() const { return d->config; } void TabBoxHandler::setConfig(const TabBoxConfig& config) { d->config = config; emit configChanged(); } void TabBoxHandler::show() { d->isShown = true; d->lastRaisedClient = nullptr; d->lastRaisedClientSucc = nullptr; if (d->config.isShowTabBox()) { d->show(); } if (d->config.isHighlightWindows()) { if (kwinApp()->x11Connection()) { Xcb::sync(); } // TODO this should be // QMetaObject::invokeMethod(this, "initHighlightWindows", Qt::QueuedConnection); // but we somehow need to cross > 1 event cycle (likely because of queued invocation in the effects) // to ensure the EffectWindow is present when updateHighlightWindows, thus elevating the window/tabbox QTimer::singleShot(1, this, SLOT(initHighlightWindows())); } } void TabBoxHandler::initHighlightWindows() { if (isKWinCompositing()) { foreach (const QWeakPointer &clientPointer, stackingOrder()) { if (QSharedPointer client = clientPointer.toStrongRef()) shadeClient(client.data(), false); } } d->updateHighlightWindows(); } void TabBoxHandler::hide(bool abort) { d->isShown = false; if (d->config.isHighlightWindows()) { d->endHighlightWindows(abort); } #ifndef KWIN_UNIT_TEST if (SwitcherItem *item = d->switcherItem()) { item->setVisible(false); } #endif if (QQuickWindow *w = d->window()) { w->hide(); w->destroy(); } d->m_mainItem = nullptr; } QModelIndex TabBoxHandler::nextPrev(bool forward) const { QModelIndex ret; QAbstractItemModel* model; switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: model = d->clientModel(); break; case TabBoxConfig::DesktopTabBox: model = d->desktopModel(); break; default: Q_UNREACHABLE(); } if (forward) { int column = d->index.column() + 1; int row = d->index.row(); if (column == model->columnCount()) { column = 0; row++; if (row == model->rowCount()) row = 0; } ret = model->index(row, column); if (!ret.isValid()) ret = model->index(0, 0); } else { int column = d->index.column() - 1; int row = d->index.row(); if (column < 0) { column = model->columnCount() - 1; row--; if (row < 0) row = model->rowCount() - 1; } ret = model->index(row, column); if (!ret.isValid()) { row = model->rowCount() - 1; for (int i = model->columnCount() - 1; i >= 0; i--) { ret = model->index(row, i); if (ret.isValid()) break; } } } if (ret.isValid()) return ret; else return d->index; } QModelIndex TabBoxHandler::desktopIndex(int desktop) const { if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox) return QModelIndex(); return d->desktopModel()->desktopIndex(desktop); } QList< int > TabBoxHandler::desktopList() const { if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox) return QList< int >(); return d->desktopModel()->desktopList(); } int TabBoxHandler::desktop(const QModelIndex& index) const { if (!index.isValid() || (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox)) return -1; QVariant ret = d->desktopModel()->data(index, DesktopModel::DesktopRole); if (ret.isValid()) return ret.toInt(); else return -1; } void TabBoxHandler::setCurrentIndex(const QModelIndex& index) { if (d->index == index) { return; } if (!index.isValid()) { return; } d->index = index; if (d->config.tabBoxMode() == TabBoxConfig::ClientTabBox) { if (d->config.isHighlightWindows()) { d->updateHighlightWindows(); } } emit selectedIndexChanged(); } const QModelIndex& TabBoxHandler::currentIndex() const { return d->index; } void TabBoxHandler::grabbedKeyEvent(QKeyEvent* event) const { if (!d->m_mainItem || !d->window()) { return; } QCoreApplication::sendEvent(d->window(), event); } bool TabBoxHandler::containsPos(const QPoint& pos) const { if (!d->m_mainItem) { return false; } QWindow *w = d->window(); if (w) { return w->geometry().contains(pos); } return false; } QModelIndex TabBoxHandler::index(QWeakPointer client) const { return d->clientModel()->index(client); } TabBoxClientList TabBoxHandler::clientList() const { if (d->config.tabBoxMode() != TabBoxConfig::ClientTabBox) return TabBoxClientList(); return d->clientModel()->clientList(); } TabBoxClient* TabBoxHandler::client(const QModelIndex& index) const { if ((!index.isValid()) || (d->config.tabBoxMode() != TabBoxConfig::ClientTabBox)) return nullptr; TabBoxClient* c = static_cast< TabBoxClient* >( d->clientModel()->data(index, ClientModel::ClientRole).value()); return c; } void TabBoxHandler::createModel(bool partialReset) { switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: { d->clientModel()->createClientList(partialReset); // TODO: C++11 use lambda function bool lastRaised = false; bool lastRaisedSucc = false; foreach (const QWeakPointer &clientPointer, stackingOrder()) { QSharedPointer client = clientPointer.toStrongRef(); if (!client) { continue; } if (client.data() == d->lastRaisedClient) { lastRaised = true; } if (client.data() == d->lastRaisedClientSucc) { lastRaisedSucc = true; } } if (d->lastRaisedClient && !lastRaised) d->lastRaisedClient = nullptr; if (d->lastRaisedClientSucc && !lastRaisedSucc) d->lastRaisedClientSucc = nullptr; break; } case TabBoxConfig::DesktopTabBox: d->desktopModel()->createDesktopList(); break; } } QModelIndex TabBoxHandler::first() const { QAbstractItemModel* model; switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: model = d->clientModel(); break; case TabBoxConfig::DesktopTabBox: model = d->desktopModel(); break; default: Q_UNREACHABLE(); } return model->index(0, 0); } bool TabBoxHandler::eventFilter(QObject *watched, QEvent *e) { if (e->type() == QEvent::Wheel && watched == d->window()) { QWheelEvent *event = static_cast(e); // On x11 the delta for vertical scrolling might also be on X for whatever reason const int delta = qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y()) ? event->angleDelta().x() : event->angleDelta().y(); d->wheelAngleDelta += delta; while (d->wheelAngleDelta <= -120) { d->wheelAngleDelta += 120; const QModelIndex index = nextPrev(true); if (index.isValid()) { setCurrentIndex(index); } } while (d->wheelAngleDelta >= 120) { d->wheelAngleDelta -= 120; const QModelIndex index = nextPrev(false); if (index.isValid()) { setCurrentIndex(index); } } return true; } // pass on return QObject::eventFilter(watched, e); } TabBoxHandler* tabBox = nullptr; TabBoxClient::TabBoxClient() { } TabBoxClient::~TabBoxClient() { } } // namespace TabBox } // namespace KWin diff --git a/tabbox/tabboxhandler.h b/tabbox/tabboxhandler.h index e586e06c4..89bc4a0f3 100644 --- a/tabbox/tabboxhandler.h +++ b/tabbox/tabboxhandler.h @@ -1,409 +1,409 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 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 TABBOXHANDLER_H #define TABBOXHANDLER_H #include "tabboxconfig.h" #include #include #include #include #include #include /** * @file * This file contains the classes which hide KWin core from tabbox. * It defines the pure virtual classes TabBoxHandler and TabBoxClient. * The classes have to be implemented in KWin Core. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class QKeyEvent; namespace KWin { /** * The TabBox is a model based view for displaying a list while switching windows or desktops. * This functionality is mostly referred to as Alt+Tab. TabBox itself does not provide support for * switching windows or desktops. This has to be done outside of TabBox inside an independent controller. * * The main entrance point to TabBox is the class TabBoxHandler, which has to be subclassed and implemented. * The class TabBoxClient, which represents a window client inside TabBox, has to be implemented as well. * * The behavior of the TabBox is defined by the TabBoxConfig and has to be set in the TabBoxHandler. * If the TabBox should be used to switch desktops as well as clients it is sufficient to just provide * different TabBoxConfig objects instead of creating an own handler for each mode. * * In order to use the TabBox the TabBoxConfig has to be set. This defines if the model for desktops or for * clients will be used. The model has to be initialized by calling TabBoxHandler::createModel(), as the * model is undefined when the TabBox is not active. The TabBox is activated by TabBoxHandler::show(). * Depending on the current set TabBoxConfig it is possible that the * highlight windows effect activated and that the view is not displayed at all. As already mentioned * the TabBox does not handle any updating of the selected item. This has to be done by invoking * TabBoxHandler::setCurrentIndex(). Nevertheless the TabBoxHandler provides methods to query for the * model index or the next or previous item, for a cursor position or for a given item (that is * TabBoxClient or desktop). By invoking TabBoxHandler::hide() the view, the * optional highlight windows effect are removed. The model is invalidated immediately. So if it is * necessary to retrieve the last selected item this has to be done before calling the hide method. * * The layout of the TabBox View and the items is completely customizable. Therefore TabBox provides * a widget LayoutConfig which includes a live preview (in kcmkwin/kwintabbox). The layout of items * can be defined by an xml document. That way the user is able to define own custom layouts. The view * itself is made up of two widgets: one to show the complete list and one to show only the selected * item. This way it is possible to have a view which shows for example a list containing only small * icons and nevertheless show the title of the currently selected client. - **/ + */ namespace TabBox { class DesktopModel; class ClientModel; class TabBoxConfig; class TabBoxClient; class TabBoxHandlerPrivate; typedef QList< QWeakPointer< TabBoxClient > > TabBoxClientList; /** * This class is a wrapper around KWin Workspace. It is used for accessing the * required core methods from inside TabBox and has to be implemented in KWin core. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class TabBoxHandler : public QObject { Q_OBJECT public: TabBoxHandler(QObject *parent); ~TabBoxHandler() override; /** * @return The id of the active screen - **/ + */ virtual int activeScreen() const = 0; /** * @return The current active TabBoxClient or NULL * if there is no active client. - **/ + */ virtual QWeakPointer activeClient() const = 0; /** * @param client The client which is starting point to find the next client * @return The next TabBoxClient in focus chain - **/ + */ virtual QWeakPointer nextClientFocusChain(TabBoxClient* client) const = 0; /** * This method is used by the ClientModel to find an entrance into the focus chain in case * there is no active Client. * * @return The first Client of the focus chain * @since 4.9.1 - **/ + */ virtual QWeakPointer firstClientFocusChain() const = 0; /** * Checks whether the given @p client is part of the focus chain at all. * This is useful to figure out whether the currently active Client can be used * as a starting point to construct the recently used list. * * In case the @p client is not in the focus chain it is recommended to use the * Client returned by firstClientFocusChain. * * The method accepts a @c null Client and in that case @c false is returned. * @param client The Client to check whether it is in the Focus Chain * @return @c true in case the Client is part of the focus chain, @c false otherwise. * @since 4.9.2 - **/ + */ virtual bool isInFocusChain(TabBoxClient* client) const = 0; /** * @param client The client whose desktop name should be retrieved * @return The desktop name of the given TabBoxClient. If the client is * on all desktops the name of current desktop will be returned. - **/ + */ virtual QString desktopName(TabBoxClient* client) const = 0; /** * @param desktop The desktop whose name should be retrieved * @return The desktop name of given desktop - **/ + */ virtual QString desktopName(int desktop) const = 0; /** * @return The number of current desktop - **/ + */ virtual int currentDesktop() const = 0; /** * @return The number of virtual desktops - **/ + */ virtual int numberOfDesktops() const = 0; /** * @param desktop The desktop which is the starting point to find the next desktop * @return The next desktop in the current focus chain. - **/ + */ virtual int nextDesktopFocusChain(int desktop) const = 0; /** * whether KWin is currently compositing and it's related features (elevating) can be used - **/ + */ virtual bool isKWinCompositing() const = 0; /** * De-/Elevate a client using the compositor (if enabled) - **/ + */ virtual void elevateClient(TabBoxClient* c, QWindow *tabbox, bool elevate) const = 0; /** * Raise a client (w/o activating it) - **/ + */ virtual void raiseClient(TabBoxClient* c) const = 0; /** * @param c The client to be restacked * @param under The client the other one will be placed below - **/ + */ virtual void restack(TabBoxClient *c, TabBoxClient *under) = 0; /** * Toggle between ShadeHover and ShadeNormal - not shaded windows are unaffected * @param c The client to be shaded * @param b Whether to un- or shade - **/ + */ virtual void shadeClient(TabBoxClient *c, bool b) const = 0; virtual void highlightWindows(TabBoxClient *window = nullptr, QWindow *controller = nullptr) = 0; /** * @return The current stacking order of TabBoxClients - **/ + */ virtual TabBoxClientList stackingOrder() const = 0; /** * Determines if given client will be added to the list: *
    *
  • Depends on desktop
  • *
  • if the client wants to have tab focus.
  • *
  • The client won't be added if it has modal dialogs
  • *
  • In that case the modal dialog will be returned if it isn't already * included
  • *
  • Won't be added if it isn't on active screen when using separate * screen focus
  • *
* @param client The client to be checked for inclusion * @param desktop The desktop the client should be on. This is irrelevant if allDesktops is set * @param allDesktops Add clients from all desktops or only from current * @return The client to be included in the list or NULL if it isn't to be included - **/ + */ virtual QWeakPointer clientToAddToList(TabBoxClient* client, int desktop) const = 0; /** * @return The first desktop window in the stacking order. - **/ + */ virtual QWeakPointer desktopClient() const = 0; /** * Activates the currently selected client and closes the TabBox. - **/ + */ virtual void activateAndClose() = 0; /** * @return The currently used TabBoxConfig - **/ + */ const TabBoxConfig& config() const; /** * Call this method when you want to change the currently used TabBoxConfig. * It fires the signal configChanged. * @param config Updates the currently used TabBoxConfig to config - **/ + */ void setConfig(const TabBoxConfig& config); /** * Call this method to show the TabBoxView. Depending on current * configuration this method might not do anything. * If highlight windows effect is to be used it will be activated. * Highlight windows and outline are not shown if * TabBoxConfig::TabBoxMode is TabBoxConfig::DesktopTabBox. * @see TabBoxConfig::isShowTabBox * @see TabBoxConfig::isHighlightWindows - **/ + */ void show(); /** * Hides the TabBoxView if shown. * Deactivates highlight windows effect if active. * @see show - **/ + */ void hide(bool abort = false); /** * Sets the current model index in the view and updates * highlight windows if active. * @param index The current Model index - **/ + */ void setCurrentIndex(const QModelIndex& index); /** * @returns the current index - **/ + */ const QModelIndex ¤tIndex() const; /** * Retrieves the next or previous item of the current item. * @param forward next or previous item * @return The next or previous item. If there is no matching item * the current item will be returned. - **/ + */ QModelIndex nextPrev(bool forward) const; /** * Initializes the model based on the current config. * This method has to be invoked before showing the TabBox. * It can also be invoked when clients are added or removed. * In that case partialReset has to be true. * * @param partialReset Keep the currently selected item or regenerate everything - **/ + */ void createModel(bool partialReset = false); /** * @param desktop The desktop whose index should be retrieved * @return The model index of given desktop. If TabBoxMode is not * TabBoxConfig::DesktopTabBox an invalid model index will be returned. - **/ + */ QModelIndex desktopIndex(int desktop) const; /** * @return The current list of desktops. * If TabBoxMode is not TabBoxConfig::DesktopTabBox an empty list will * be returned. * @see DesktopModel::desktopList - **/ + */ QList< int > desktopList() const; /** * @return The desktop for given model index. If the index is not valid * or TabBoxMode is not TabBoxConfig::DesktopTabBox -1 will be returned. * @see DesktopModel::desktopIndex - **/ + */ int desktop(const QModelIndex& index) const; /** * Handles additional grabbed key events by the TabBox controller. * @param event The key event which has been grabbed - **/ + */ virtual void grabbedKeyEvent(QKeyEvent* event) const; /** * @param pos The position to be tested in global coordinates * @return True if the view contains the point, otherwise false. - **/ + */ bool containsPos(const QPoint& pos) const; /** * @param client The TabBoxClient whose index should be returned * @return Returns the ModelIndex of given TabBoxClient or an invalid ModelIndex * if the model does not contain the given TabBoxClient. * @see ClientModel::index - **/ + */ QModelIndex index(QWeakPointer client) const; /** * @return Returns the current list of TabBoxClients. * If TabBoxMode is not TabBoxConfig::ClientTabBox an empty list will * be returned. * @see ClientModel::clientList - **/ + */ TabBoxClientList clientList() const; /** * @param index The index of the client to be returned * @return Returns the TabBoxClient at given model index. If * the index is invalid, does not point to a Client or the list * is empty, NULL will be returned. - **/ + */ TabBoxClient* client(const QModelIndex& index) const; /** * @return The first model index. That is the model index at position 0, 0. * It is valid, as desktop has at least one desktop and if there are no * clients an empty item is created. - **/ + */ QModelIndex first() const; bool eventFilter(QObject *watcher, QEvent *event) override; /** * @returns whether the TabBox operates in a no modifier grab mode. * In this mode a click on an item should directly accept and close the tabbox. - **/ + */ virtual bool noModifierGrab() const = 0; Q_SIGNALS: /** * This signal is fired when the TabBoxConfig changes * @see setConfig - **/ + */ void configChanged(); void selectedIndexChanged(); private Q_SLOTS: void initHighlightWindows(); private: friend class TabBoxHandlerPrivate; TabBoxHandlerPrivate* d; }; /** * This class is a wrapper around a KWin Client. It is used for accessing the * required client methods from inside TabBox and has to be implemented in KWin core. * * @author Martin Gräßlin * @since 4.4 - **/ + */ class TabBoxClient { public: TabBoxClient(); virtual ~TabBoxClient(); /** * @return The caption of the client - **/ + */ virtual QString caption() const = 0; /** * @param size Requested size of the icon * @return The icon of the client - **/ + */ virtual QIcon icon() const = 0; /** * @return The window Id of the client - **/ + */ virtual WId window() const = 0; /** * @return Minimized state of the client - **/ + */ virtual bool isMinimized() const = 0; virtual int x() const = 0; virtual int y() const = 0; virtual int width() const = 0; virtual int height() const = 0; virtual bool isCloseable() const = 0; virtual void close() = 0; virtual bool isFirstInTabBox() const = 0; virtual QUuid internalId() const = 0; }; /** * Pointer to the global TabBoxHandler object. - **/ + */ extern TabBoxHandler* tabBox; } // namespace TabBox } // namespace KWin #endif // TABBOXHANDLER_H diff --git a/tabgroup.h b/tabgroup.h index 868ab14f2..f4f6b4439 100644 --- a/tabgroup.h +++ b/tabgroup.h @@ -1,209 +1,209 @@ /******************************************************************************* KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011/2012 The KWin team 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_TABGROUP_H #define KWIN_TABGROUP_H #include #include "utils.h" namespace KWin { class AbstractClient; /** * This class represents a group of clients for use in window tabbing. All * clients in the group share the same geometry and state information; I.e if * one client changes then all others should also be changed. * * A group contains at least one client and DOES NOT contain multiple * copies of the same client. A client MUST NOT be in two groups at the same * time. All decorated clients SHOULD be in a group, even if it's a group of * one client. * * rohanp: Had to convert this object to a QObject to make it easier for adding * scripting interface to TabGroup. * * If a group contains multiple clients then only one will ever be mapped at * any given time. - **/ + */ class TabGroup { public: /** * Creates a new group containing \p c. - **/ + */ explicit TabGroup(AbstractClient* c); ~TabGroup(); enum State { None = 0, Minimized = 1<<0, Maximized = 1<<1, Shaded = 1<<2, Geometry = 1<<3, Desktop = 1<<4, Activity = 1<<5, Layer = 1<<6, QuickTile = 1<<7, All = 0xffffffff }; Q_DECLARE_FLAGS(States, State) /** * Activate next tab (flips) - **/ + */ void activateNext(); /** * Activate previous tab (flips) - **/ + */ void activatePrev(); /** * Allows to alter several attributes in random order and trigger a general update at the end * (must still be explicitly called) * this is to prevent side effects, mostly for geometry adjustments during maximization and QuickTiling - **/ + */ void blockStateUpdates(bool); /** * Close all clients in this group. - **/ + */ void closeAll(); /** * Whether client \p c is member of this group - **/ + */ bool contains(AbstractClient* c) const; /** * The amount of clients in this group - **/ + */ int count() const; /** * Returns whether or not this group contains the active client. - **/ + */ bool isActive() const; /** * Returns whether this group is empty (used by workspace to remove it) - **/ + */ bool isEmpty() const; /** * Returns the list of all the clients contained in this group in their current order. - **/ + */ const QVector &clients() const; /** * Returns the currently visible client. - **/ + */ AbstractClient* current() const; /** * Makes \p c the visible client in the group - force is only used when the window becomes ready for painting. * Any other usage just causes pointless action - **/ + */ void setCurrent(AbstractClient* c, bool force = false); /** * Alignes the dynamic Qt @param property of all clients to the one of @param c - **/ + */ void sync(const char *property, AbstractClient *c); /** * Returns combined minimum size of all clients in the group. - **/ + */ QSize minSize() const; /** * Returns combined maximum size of all clients in the group. - **/ + */ QSize maxSize() const; /** * Ensures that all the clients in the group have identical geometries and states using * \p main as the primary client to copy the settings off. If \p only is set then only * that client is updated to match \p main. - **/ + */ void updateStates(AbstractClient* main, States states, AbstractClient* only = NULL); /** * updates geometry restrictions of this group, basically called from Client::getWmNormalHints(), otherwise rather private - **/ + */ void updateMinMaxSize(); Q_SIGNALS: void minSizeChanged(); void maxSizeChanged(); private: friend class AbstractClient; friend class Client; // friend bool Client::tabTo(Client*, bool, bool); bool add(KWin::AbstractClient *c, AbstractClient *other, bool behind, bool activateC); void move(KWin::AbstractClient* c, KWin::AbstractClient* before, bool behind); // friend bool Client::untab(const QRect&); bool remove(KWin::AbstractClient *c); QVector m_clients; AbstractClient *m_current; QSize m_minSize; QSize m_maxSize; int m_stateUpdatesBlocked; States m_pendingUpdates; }; inline bool TabGroup::contains(AbstractClient* c) const { return c && m_clients.contains(c); } inline int TabGroup::count() const { return m_clients.count(); } inline const QVector &TabGroup::clients() const { return m_clients; } inline bool TabGroup::isEmpty() const { return m_clients.isEmpty(); } inline AbstractClient* TabGroup::current() const { return m_current; } inline QSize TabGroup::minSize() const { return m_minSize; } inline QSize TabGroup::maxSize() const { return m_maxSize; } } Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::TabGroup::States) #endif diff --git a/toplevel.cpp b/toplevel.cpp index 81e30eda1..a2a027702 100644 --- a/toplevel.cpp +++ b/toplevel.cpp @@ -1,809 +1,809 @@ /******************************************************************** 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 . *********************************************************************/ #include "toplevel.h" #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include "atoms.h" #include "client.h" #include "client_machine.h" #include "composite.h" #include "effects.h" #include "screens.h" #include "shadow.h" #include "workspace.h" #include "xcbutils.h" #include #include namespace KWin { Toplevel::Toplevel() : m_visual(XCB_NONE) , bit_depth(24) , info(NULL) , ready_for_painting(true) , m_isDamaged(false) , m_internalId(QUuid::createUuid()) , m_client() , damage_handle(None) , is_shape(false) , effect_window(NULL) , m_clientMachine(new ClientMachine(this)) , wmClientLeaderWin(0) , m_damageReplyPending(false) , m_screen(0) , m_skipCloseAnimation(false) { connect(this, SIGNAL(damaged(KWin::Toplevel*,QRect)), SIGNAL(needsRepaint())); connect(screens(), SIGNAL(changed()), SLOT(checkScreen())); connect(screens(), SIGNAL(countChanged(int,int)), SLOT(checkScreen())); setupCheckScreenConnection(); } Toplevel::~Toplevel() { assert(damage_handle == None); delete info; } QDebug& operator<<(QDebug& stream, const Toplevel* cl) { if (cl == NULL) return stream << "\'NULL\'"; cl->debug(stream); return stream; } QDebug& operator<<(QDebug& stream, const ToplevelList& list) { stream << "LIST:("; bool first = true; for (ToplevelList::ConstIterator it = list.begin(); it != list.end(); ++it) { if (!first) stream << ":"; first = false; stream << *it; } stream << ")"; return stream; } QRect Toplevel::decorationRect() const { return rect(); } void Toplevel::detectShape(Window id) { const bool wasShape = is_shape; is_shape = Xcb::Extensions::self()->hasShape(id); if (wasShape != is_shape) { emit shapedChanged(); } } // used only by Deleted::copy() void Toplevel::copyToDeleted(Toplevel* c) { m_internalId = c->internalId(); geom = c->geom; m_visual = c->m_visual; bit_depth = c->bit_depth; info = c->info; m_client.reset(c->m_client, false); ready_for_painting = c->ready_for_painting; damage_handle = None; damage_region = c->damage_region; repaints_region = c->repaints_region; layer_repaints_region = c->layer_repaints_region; is_shape = c->is_shape; effect_window = c->effect_window; if (effect_window != NULL) effect_window->setWindow(this); resource_name = c->resourceName(); resource_class = c->resourceClass(); m_clientMachine = c->m_clientMachine; m_clientMachine->setParent(this); wmClientLeaderWin = c->wmClientLeader(); opaque_region = c->opaqueRegion(); m_screen = c->m_screen; m_skipCloseAnimation = c->m_skipCloseAnimation; m_internalFBO = c->m_internalFBO; } // before being deleted, remove references to everything that's now // owner by Deleted void Toplevel::disownDataPassedToDeleted() { info = NULL; } QRect Toplevel::visibleRect() const { QRect r = decorationRect(); if (hasShadow() && !shadow()->shadowRegion().isEmpty()) { r |= shadow()->shadowRegion().boundingRect(); } return r.translated(geometry().topLeft()); } Xcb::Property Toplevel::fetchWmClientLeader() const { return Xcb::Property(false, window(), atoms->wm_client_leader, XCB_ATOM_WINDOW, 0, 10000); } void Toplevel::readWmClientLeader(Xcb::Property &prop) { wmClientLeaderWin = prop.value(window()); } void Toplevel::getWmClientLeader() { auto prop = fetchWmClientLeader(); readWmClientLeader(prop); } /** * Returns sessionId for this client, * taken either from its window or from the leader window. - **/ + */ QByteArray Toplevel::sessionId() const { QByteArray result = Xcb::StringProperty(window(), atoms->sm_client_id); if (result.isEmpty() && wmClientLeaderWin && wmClientLeaderWin != window()) result = Xcb::StringProperty(wmClientLeaderWin, atoms->sm_client_id); return result; } /** * Returns command property for this client, * taken either from its window or from the leader window. - **/ + */ QByteArray Toplevel::wmCommand() { QByteArray result = Xcb::StringProperty(window(), XCB_ATOM_WM_COMMAND); if (result.isEmpty() && wmClientLeaderWin && wmClientLeaderWin != window()) result = Xcb::StringProperty(wmClientLeaderWin, XCB_ATOM_WM_COMMAND); result.replace(0, ' '); return result; } void Toplevel::getWmClientMachine() { m_clientMachine->resolve(window(), wmClientLeader()); } /** * Returns client machine for this client, * taken either from its window or from the leader window. - **/ + */ QByteArray Toplevel::wmClientMachine(bool use_localhost) const { if (!m_clientMachine) { // this should never happen return QByteArray(); } if (use_localhost && m_clientMachine->isLocal()) { // special name for the local machine (localhost) return ClientMachine::localhost(); } return m_clientMachine->hostName(); } /** * Returns client leader window for this client. * Returns the client window itself if no leader window is defined. - **/ + */ Window Toplevel::wmClientLeader() const { if (wmClientLeaderWin) return wmClientLeaderWin; return window(); } void Toplevel::getResourceClass() { setResourceClass(QByteArray(info->windowClassName()).toLower(), QByteArray(info->windowClassClass()).toLower()); } void Toplevel::setResourceClass(const QByteArray &name, const QByteArray &className) { resource_name = name; resource_class = className; emit windowClassChanged(); } double Toplevel::opacity() const { if (info->opacity() == 0xffffffff) return 1.0; return info->opacity() * 1.0 / 0xffffffff; } void Toplevel::setOpacity(double new_opacity) { double old_opacity = opacity(); new_opacity = qBound(0.0, new_opacity, 1.0); if (old_opacity == new_opacity) return; info->setOpacity(static_cast< unsigned long >(new_opacity * 0xffffffff)); if (compositing()) { addRepaintFull(); emit opacityChanged(this, old_opacity); } } bool Toplevel::setupCompositing() { if (!compositing()) return false; if (damage_handle != XCB_NONE) return false; if (kwinApp()->operationMode() == Application::OperationModeX11 && !surface()) { damage_handle = xcb_generate_id(connection()); xcb_damage_create(connection(), damage_handle, frameId(), XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY); } damage_region = QRegion(0, 0, width(), height()); effect_window = new EffectWindowImpl(this); Compositor::self()->scene()->addToplevel(this); return true; } void Toplevel::finishCompositing(ReleaseReason releaseReason) { if (kwinApp()->operationMode() == Application::OperationModeX11 && damage_handle == XCB_NONE) return; if (effect_window->window() == this) { // otherwise it's already passed to Deleted, don't free data discardWindowPixmap(); delete effect_window; } if (damage_handle != XCB_NONE && releaseReason != ReleaseReason::Destroyed) { xcb_damage_destroy(connection(), damage_handle); } damage_handle = XCB_NONE; damage_region = QRegion(); repaints_region = QRegion(); effect_window = NULL; } void Toplevel::discardWindowPixmap() { addDamageFull(); if (effectWindow() != NULL && effectWindow()->sceneWindow() != NULL) effectWindow()->sceneWindow()->pixmapDiscarded(); } void Toplevel::damageNotifyEvent() { m_isDamaged = true; // Note: The rect is supposed to specify the damage extents, // but we don't know it at this point. No one who connects // to this signal uses the rect however. emit damaged(this, QRect()); } bool Toplevel::compositing() const { if (!Workspace::self()) { return false; } return Workspace::self()->compositing(); } void Client::damageNotifyEvent() { if (syncRequest.isPending && isResize()) { emit damaged(this, QRect()); m_isDamaged = true; return; } if (!ready_for_painting) { // avoid "setReadyForPainting()" function calling overhead if (syncRequest.counter == XCB_NONE) { // cannot detect complete redraw, consider done now setReadyForPainting(); setupWindowManagementInterface(); } } Toplevel::damageNotifyEvent(); } bool Toplevel::resetAndFetchDamage() { if (!m_isDamaged) return false; if (damage_handle == XCB_NONE) { m_isDamaged = false; return true; } xcb_connection_t *conn = connection(); // Create a new region and copy the damage region to it, // resetting the damaged state. xcb_xfixes_region_t region = xcb_generate_id(conn); xcb_xfixes_create_region(conn, region, 0, 0); xcb_damage_subtract(conn, damage_handle, 0, region); // Send a fetch-region request and destroy the region m_regionCookie = xcb_xfixes_fetch_region_unchecked(conn, region); xcb_xfixes_destroy_region(conn, region); m_isDamaged = false; m_damageReplyPending = true; return m_damageReplyPending; } void Toplevel::getDamageRegionReply() { if (!m_damageReplyPending) return; m_damageReplyPending = false; // Get the fetch-region reply xcb_xfixes_fetch_region_reply_t *reply = xcb_xfixes_fetch_region_reply(connection(), m_regionCookie, 0); if (!reply) return; // Convert the reply to a QRegion int count = xcb_xfixes_fetch_region_rectangles_length(reply); QRegion region; if (count > 1 && count < 16) { xcb_rectangle_t *rects = xcb_xfixes_fetch_region_rectangles(reply); QVector qrects; qrects.reserve(count); for (int i = 0; i < count; i++) qrects << QRect(rects[i].x, rects[i].y, rects[i].width, rects[i].height); region.setRects(qrects.constData(), count); } else region += QRect(reply->extents.x, reply->extents.y, reply->extents.width, reply->extents.height); damage_region += region; repaints_region += region; free(reply); } void Toplevel::addDamageFull() { if (!compositing()) return; damage_region = rect(); repaints_region |= rect(); emit damaged(this, rect()); } void Toplevel::resetDamage() { damage_region = QRegion(); } void Toplevel::addRepaint(const QRect& r) { if (!compositing()) { return; } repaints_region += r; emit needsRepaint(); } void Toplevel::addRepaint(int x, int y, int w, int h) { QRect r(x, y, w, h); addRepaint(r); } void Toplevel::addRepaint(const QRegion& r) { if (!compositing()) { return; } repaints_region += r; emit needsRepaint(); } void Toplevel::addLayerRepaint(const QRect& r) { if (!compositing()) { return; } layer_repaints_region += r; emit needsRepaint(); } void Toplevel::addLayerRepaint(int x, int y, int w, int h) { QRect r(x, y, w, h); addLayerRepaint(r); } void Toplevel::addLayerRepaint(const QRegion& r) { if (!compositing()) return; layer_repaints_region += r; emit needsRepaint(); } void Toplevel::addRepaintFull() { repaints_region = visibleRect().translated(-pos()); emit needsRepaint(); } void Toplevel::resetRepaints() { repaints_region = QRegion(); layer_repaints_region = QRegion(); } void Toplevel::addWorkspaceRepaint(int x, int y, int w, int h) { addWorkspaceRepaint(QRect(x, y, w, h)); } void Toplevel::addWorkspaceRepaint(const QRect& r2) { if (!compositing()) return; Compositor::self()->addRepaint(r2); } void Toplevel::setReadyForPainting() { if (!ready_for_painting) { ready_for_painting = true; if (compositing()) { addRepaintFull(); emit windowShown(this); if (auto *cl = dynamic_cast(this)) { if (cl->tabGroup() && cl->tabGroup()->current() == cl) cl->tabGroup()->setCurrent(cl, true); } } } } void Toplevel::deleteEffectWindow() { delete effect_window; effect_window = NULL; } void Toplevel::checkScreen() { if (screens()->count() == 1) { if (m_screen != 0) { m_screen = 0; emit screenChanged(); } } else { const int s = screens()->number(geometry().center()); if (s != m_screen) { m_screen = s; emit screenChanged(); } } qreal newScale = screens()->scale(m_screen); if (newScale != m_screenScale) { m_screenScale = newScale; emit screenScaleChanged(); } } void Toplevel::setupCheckScreenConnection() { connect(this, SIGNAL(geometryShapeChanged(KWin::Toplevel*,QRect)), SLOT(checkScreen())); connect(this, SIGNAL(geometryChanged()), SLOT(checkScreen())); checkScreen(); } void Toplevel::removeCheckScreenConnection() { disconnect(this, SIGNAL(geometryShapeChanged(KWin::Toplevel*,QRect)), this, SLOT(checkScreen())); disconnect(this, SIGNAL(geometryChanged()), this, SLOT(checkScreen())); } int Toplevel::screen() const { return m_screen; } qreal Toplevel::screenScale() const { return m_screenScale; } bool Toplevel::isOnScreen(int screen) const { return screens()->geometry(screen).intersects(geometry()); } bool Toplevel::isOnActiveScreen() const { return isOnScreen(screens()->current()); } void Toplevel::getShadow() { QRect dirtyRect; // old & new shadow region const QRect oldVisibleRect = visibleRect(); if (hasShadow()) { dirtyRect = shadow()->shadowRegion().boundingRect(); if (!effectWindow()->sceneWindow()->shadow()->updateShadow()) { effectWindow()->sceneWindow()->updateShadow(nullptr); } emit shadowChanged(); } else { Shadow::createShadow(this); } if (hasShadow()) dirtyRect |= shadow()->shadowRegion().boundingRect(); if (oldVisibleRect != visibleRect()) emit paddingChanged(this, oldVisibleRect); if (dirtyRect.isValid()) { dirtyRect.translate(pos()); addLayerRepaint(dirtyRect); } } bool Toplevel::hasShadow() const { if (effectWindow() && effectWindow()->sceneWindow()) { return effectWindow()->sceneWindow()->shadow() != NULL; } return false; } Shadow *Toplevel::shadow() { if (effectWindow() && effectWindow()->sceneWindow()) { return effectWindow()->sceneWindow()->shadow(); } else { return NULL; } } const Shadow *Toplevel::shadow() const { if (effectWindow() && effectWindow()->sceneWindow()) { return effectWindow()->sceneWindow()->shadow(); } else { return NULL; } } bool Toplevel::wantsShadowToBeRendered() const { return true; } void Toplevel::getWmOpaqueRegion() { const auto rects = info->opaqueRegion(); QRegion new_opaque_region; for (const auto &r : rects) { new_opaque_region += QRect(r.pos.x, r.pos.y, r.size.width, r.size.height); } opaque_region = new_opaque_region; } bool Toplevel::isClient() const { return false; } bool Toplevel::isDeleted() const { return false; } bool Toplevel::isOnCurrentActivity() const { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return true; } return isOnActivity(Activities::self()->current()); #else return true; #endif } void Toplevel::elevate(bool elevate) { if (!effectWindow()) { return; } effectWindow()->elevate(elevate); addWorkspaceRepaint(visibleRect()); } pid_t Toplevel::pid() const { return info->pid(); } xcb_window_t Toplevel::frameId() const { return m_client; } Xcb::Property Toplevel::fetchSkipCloseAnimation() const { return Xcb::Property(false, window(), atoms->kde_skip_close_animation, XCB_ATOM_CARDINAL, 0, 1); } void Toplevel::readSkipCloseAnimation(Xcb::Property &property) { setSkipCloseAnimation(property.toBool()); } void Toplevel::getSkipCloseAnimation() { Xcb::Property property = fetchSkipCloseAnimation(); readSkipCloseAnimation(property); } bool Toplevel::skipsCloseAnimation() const { return m_skipCloseAnimation; } void Toplevel::setSkipCloseAnimation(bool set) { if (set == m_skipCloseAnimation) { return; } m_skipCloseAnimation = set; emit skipCloseAnimationChanged(); } void Toplevel::setSurface(KWayland::Server::SurfaceInterface *surface) { if (m_surface == surface) { return; } using namespace KWayland::Server; if (m_surface) { disconnect(m_surface, &SurfaceInterface::damaged, this, &Toplevel::addDamage); disconnect(m_surface, &SurfaceInterface::sizeChanged, this, &Toplevel::discardWindowPixmap); } m_surface = surface; connect(m_surface, &SurfaceInterface::damaged, this, &Toplevel::addDamage); connect(m_surface, &SurfaceInterface::sizeChanged, this, &Toplevel::discardWindowPixmap); connect(m_surface, &SurfaceInterface::subSurfaceTreeChanged, this, [this] { // TODO improve to only update actual visual area if (ready_for_painting) { addDamageFull(); m_isDamaged = true; } } ); connect(m_surface, &SurfaceInterface::destroyed, this, [this] { m_surface = nullptr; } ); emit surfaceChanged(); } void Toplevel::addDamage(const QRegion &damage) { m_isDamaged = true; damage_region += damage; for (const QRect &r : damage) { emit damaged(this, r); } } QByteArray Toplevel::windowRole() const { return QByteArray(info->windowRole()); } void Toplevel::setDepth(int depth) { if (bit_depth == depth) { return; } const bool oldAlpha = hasAlpha(); bit_depth = depth; if (oldAlpha != hasAlpha()) { emit hasAlphaChanged(); } } QRegion Toplevel::inputShape() const { if (m_surface) { return m_surface->input(); } else { // TODO: maybe also for X11? return QRegion(); } } void Toplevel::setInternalFramebufferObject(const QSharedPointer &fbo) { if (m_internalFBO != fbo) { discardWindowPixmap(); m_internalFBO = fbo; } setDepth(32); } QMatrix4x4 Toplevel::inputTransformation() const { QMatrix4x4 m; m.translate(-x(), -y()); return m; } quint32 Toplevel::windowId() const { return window(); } QRect Toplevel::inputGeometry() const { return geometry(); } bool Toplevel::isLocalhost() const { if (!m_clientMachine) { return true; } return m_clientMachine->isLocal(); } } // namespace diff --git a/toplevel.h b/toplevel.h index 7b3dd452c..90ff1b508 100644 --- a/toplevel.h +++ b/toplevel.h @@ -1,958 +1,958 @@ /******************************************************************** 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 // c++ #include #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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is a window with a critical notification. - **/ + */ Q_PROPERTY(bool criticalNotification READ isCriticalNotification) /** * 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 https://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 https://standards.freedesktop.org/wm-spec/wm-spec-latest.html . - **/ + */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See https://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) /** * Whether this Toplevel represents the outline. * * @note It's always @c false if compositing is turned off. - **/ + */ Q_PROPERTY(bool outline READ isOutline) 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 @ref 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. * @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 isCriticalNotification() const; bool isOnScreenDisplay() const; bool isComboBox() const; bool isDNDIcon() const; virtual bool isLockScreen() const; virtual bool isInputMethod() const; virtual bool isOutline() 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 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 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: ~Toplevel() override; 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::isCriticalNotification() const { return windowType() == NET::CriticalNotification; } 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 bool Toplevel::isOutline() 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/touch_input.h b/touch_input.h index 526d125e6..5cce11859 100644 --- a/touch_input.h +++ b/touch_input.h @@ -1,106 +1,106 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013, 2016 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_TOUCH_INPUT_H #define KWIN_TOUCH_INPUT_H #include "input.h" #include #include #include #include namespace KWin { class InputRedirection; class Toplevel; namespace Decoration { class DecoratedClientImpl; } namespace LibInput { class Device; } class TouchInputRedirection : public InputDeviceHandler { Q_OBJECT public: explicit TouchInputRedirection(InputRedirection *parent); ~TouchInputRedirection() override; bool positionValid() const override; bool focusUpdatesBlocked() override; void init() override; void processDown(qint32 id, const QPointF &pos, quint32 time, LibInput::Device *device = nullptr); void processUp(qint32 id, quint32 time, LibInput::Device *device = nullptr); void processMotion(qint32 id, const QPointF &pos, quint32 time, LibInput::Device *device = nullptr); void cancel(); void frame(); void insertId(quint32 internalId, qint32 kwaylandId); void removeId(quint32 internalId); qint32 mappedId(quint32 internalId); void setDecorationPressId(qint32 id) { m_decorationId = id; } qint32 decorationPressId() const { return m_decorationId; } void setInternalPressId(qint32 id) { m_internalId = id; } qint32 internalPressId() const { return m_internalId; } QPointF position() const override { return m_lastPosition; } private: void cleanupInternalWindow(QWindow *old, QWindow *now) override; void cleanupDecoration(Decoration::DecoratedClientImpl *old, Decoration::DecoratedClientImpl *now) override; void focusUpdate(Toplevel *focusOld, Toplevel *focusNow) override; bool m_inited = false; qint32 m_decorationId = -1; qint32 m_internalId = -1; /** * external/kwayland - **/ + */ QHash m_idMapper; QMetaObject::Connection m_focusGeometryConnection; bool m_windowUpdatedInCycle = false; QPointF m_lastPosition; int m_touches = 0; }; } #endif diff --git a/useractions.cpp b/useractions.cpp index b0befe263..3c0002013 100644 --- a/useractions.cpp +++ b/useractions.cpp @@ -1,1926 +1,1926 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ /* This file contains things relevant to direct user actions, such as responses to global keyboard shortcuts, or selecting actions from the window operations menu. */ /////////////////////////////////////////////////////////////////////////////// // NOTE: if you change the menu, keep kde-workspace/libs/taskmanager/taskactions.cpp in sync ////////////////////////////////////////////////////////////////////////////// #include "useractions.h" #include "cursor.h" #include "client.h" #include "colorcorrection/manager.h" #include "composite.h" #include "input.h" #include "workspace.h" #include "effects.h" #include "platform.h" #include "screens.h" #include "shell_client.h" #include "virtualdesktops.h" #include "scripting/scripting.h" #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #include #endif #include "appmenu.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "killwindow.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif namespace KWin { UserActionsMenu::UserActionsMenu(QObject *parent) : QObject(parent) , m_menu(NULL) , m_desktopMenu(NULL) , m_screenMenu(NULL) , m_activityMenu(NULL) , m_addTabsMenu(NULL) , m_switchToTabMenu(NULL) , m_scriptsMenu(NULL) , m_resizeOperation(NULL) , m_moveOperation(NULL) , m_maximizeOperation(NULL) , m_shadeOperation(NULL) , m_keepAboveOperation(NULL) , m_keepBelowOperation(NULL) , m_fullScreenOperation(NULL) , m_noBorderOperation(NULL) , m_minimizeOperation(NULL) , m_closeOperation(NULL) , m_removeFromTabGroup(NULL) , m_closeTabGroup(NULL) , m_client(QWeakPointer()) { } UserActionsMenu::~UserActionsMenu() { discard(); } bool UserActionsMenu::isShown() const { return m_menu && m_menu->isVisible(); } bool UserActionsMenu::hasClient() const { return !m_client.isNull() && isShown(); } void UserActionsMenu::close() { if (!m_menu) { return; } m_menu->close(); m_client.clear(); } bool UserActionsMenu::isMenuClient(const AbstractClient *c) const { if (!c || m_client.isNull()) { return false; } return c == m_client.data(); } void UserActionsMenu::show(const QRect &pos, const QWeakPointer &cl) { if (!KAuthorized::authorizeAction(QStringLiteral("kwin_rmb"))) return; if (cl.isNull()) return; if (isShown()) // recursion return; if (cl.data()->isDesktop() || cl.data()->isDock()) return; m_client = cl; init(); Workspace *ws = Workspace::self(); int x = pos.left(); int y = pos.bottom(); const bool needsPopup = kwinApp()->shouldUseWaylandForCompositing(); if (y == pos.top()) { m_client.data()->blockActivityUpdates(true); if (needsPopup) { m_menu->popup(QPoint(x, y)); } else { m_menu->exec(QPoint(x, y)); } if (!m_client.isNull()) m_client.data()->blockActivityUpdates(false); } else { m_client.data()->blockActivityUpdates(true); QRect area = ws->clientArea(ScreenArea, QPoint(x, y), VirtualDesktopManager::self()->current()); menuAboutToShow(); // needed for sizeHint() to be correct :-/ int popupHeight = m_menu->sizeHint().height(); if (y + popupHeight < area.height()) { if (needsPopup) { m_menu->popup(QPoint(x, y)); } else { m_menu->exec(QPoint(x, y)); } } else { if (needsPopup) { m_menu->popup(QPoint(x, pos.top() - popupHeight)); } else { m_menu->exec(QPoint(x, pos.top() - popupHeight)); } } if (!m_client.isNull()) m_client.data()->blockActivityUpdates(false); } } void UserActionsMenu::grabInput() { m_menu->windowHandle()->setMouseGrabEnabled(true); m_menu->windowHandle()->setKeyboardGrabEnabled(true); } void UserActionsMenu::helperDialog(const QString& message, const QWeakPointer &c) { QStringList args; QString type; auto shortcut = [](const QString &name) { QAction* action = Workspace::self()->findChild(name); assert(action != NULL); const auto shortcuts = KGlobalAccel::self()->shortcut(action); return QStringLiteral("%1 (%2)").arg(action->text()) .arg(shortcuts.isEmpty() ? QString() : shortcuts.first().toString(QKeySequence::NativeText)); }; if (message == QStringLiteral("noborderaltf3")) { args << QStringLiteral("--msgbox") << i18n( "You have selected to show a window without its border.\n" "Without the border, you will not be able to enable the border " "again using the mouse: use the window operations menu instead, " "activated using the %1 keyboard shortcut.", shortcut(QStringLiteral("Window Operations Menu"))); type = QStringLiteral("altf3warning"); } else if (message == QLatin1String("fullscreenaltf3")) { args << QStringLiteral("--msgbox") << i18n( "You have selected to show a window in fullscreen mode.\n" "If the application itself does not have an option to turn the fullscreen " "mode off you will not be able to disable it " "again using the mouse: use the window operations menu instead, " "activated using the %1 keyboard shortcut.", shortcut(QStringLiteral("Window Operations Menu"))); type = QStringLiteral("altf3warning"); } else abort(); if (!type.isEmpty()) { KConfig cfg(QStringLiteral("kwin_dialogsrc")); KConfigGroup cg(&cfg, "Notification Messages"); // Depends on KMessageBox if (!cg.readEntry(type, true)) return; args << QStringLiteral("--dontagain") << QLatin1String("kwin_dialogsrc:") + type; } if (!c.isNull()) args << QStringLiteral("--embed") << QString::number(c.data()->windowId()); QtConcurrent::run([args]() { KProcess::startDetached(QStringLiteral("kdialog"), args); }); } QStringList configModules(bool controlCenter) { QStringList args; args << QStringLiteral("kwindecoration"); if (controlCenter) args << QStringLiteral("kwinoptions"); else if (KAuthorized::authorizeControlModule(QStringLiteral("kde-kwinoptions.desktop"))) args << QStringLiteral("kwinactions") << QStringLiteral("kwinfocus") << QStringLiteral("kwinmoving") << QStringLiteral("kwinadvanced") << QStringLiteral("kwinrules") << QStringLiteral("kwincompositing") << QStringLiteral("kwineffects") #ifdef KWIN_BUILD_TABBOX << QStringLiteral("kwintabbox") #endif << QStringLiteral("kwinscreenedges") << QStringLiteral("kwinscripts") ; return args; } void UserActionsMenu::init() { if (m_menu) { return; } m_menu = new QMenu; connect(m_menu, &QMenu::aboutToShow, this, &UserActionsMenu::menuAboutToShow); connect(m_menu, &QMenu::triggered, this, &UserActionsMenu::slotWindowOperation, Qt::QueuedConnection); QMenu *advancedMenu = new QMenu(m_menu); connect(advancedMenu, &QMenu::aboutToShow, [this, advancedMenu]() { advancedMenu->setPalette(m_client.data()->palette()); }); auto setShortcut = [](QAction *action, const QString &actionName) { const auto shortcuts = KGlobalAccel::self()->shortcut(Workspace::self()->findChild(actionName)); if (!shortcuts.isEmpty()) { action->setShortcut(shortcuts.first()); } }; m_moveOperation = advancedMenu->addAction(i18n("&Move")); m_moveOperation->setIcon(QIcon::fromTheme(QStringLiteral("transform-move"))); setShortcut(m_moveOperation, QStringLiteral("Window Move")); m_moveOperation->setData(Options::UnrestrictedMoveOp); m_resizeOperation = advancedMenu->addAction(i18n("&Resize")); setShortcut(m_resizeOperation, QStringLiteral("Window Resize")); m_resizeOperation->setData(Options::ResizeOp); m_keepAboveOperation = advancedMenu->addAction(i18n("Keep &Above Others")); m_keepAboveOperation->setIcon(QIcon::fromTheme(QStringLiteral("go-up"))); setShortcut(m_keepAboveOperation, QStringLiteral("Window Above Other Windows")); m_keepAboveOperation->setCheckable(true); m_keepAboveOperation->setData(Options::KeepAboveOp); m_keepBelowOperation = advancedMenu->addAction(i18n("Keep &Below Others")); m_keepBelowOperation->setIcon(QIcon::fromTheme(QStringLiteral("go-down"))); setShortcut(m_keepBelowOperation, QStringLiteral("Window Below Other Windows")); m_keepBelowOperation->setCheckable(true); m_keepBelowOperation->setData(Options::KeepBelowOp); m_fullScreenOperation = advancedMenu->addAction(i18n("&Fullscreen")); m_fullScreenOperation->setIcon(QIcon::fromTheme(QStringLiteral("view-fullscreen"))); setShortcut(m_fullScreenOperation, QStringLiteral("Window Fullscreen")); m_fullScreenOperation->setCheckable(true); m_fullScreenOperation->setData(Options::FullScreenOp); m_shadeOperation = advancedMenu->addAction(i18n("&Shade")); setShortcut(m_shadeOperation, QStringLiteral("Window Shade")); m_shadeOperation->setCheckable(true); m_shadeOperation->setData(Options::ShadeOp); m_noBorderOperation = advancedMenu->addAction(i18n("&No Border")); setShortcut(m_noBorderOperation, QStringLiteral("Window No Border")); m_noBorderOperation->setCheckable(true); m_noBorderOperation->setData(Options::NoBorderOp); advancedMenu->addSeparator(); m_shortcutOperation = advancedMenu->addAction(i18n("Window Short&cut...")); m_shortcutOperation->setIcon(QIcon::fromTheme(QStringLiteral("configure-shortcuts"))); setShortcut(m_shortcutOperation, QStringLiteral("Setup Window Shortcut")); m_shortcutOperation->setData(Options::SetupWindowShortcutOp); QAction *action = advancedMenu->addAction(i18n("Special &Window Settings...")); action->setIcon(QIcon::fromTheme(QStringLiteral("preferences-system-windows-actions"))); action->setData(Options::WindowRulesOp); m_rulesOperation = action; action = advancedMenu->addAction(i18n("S&pecial Application Settings...")); action->setIcon(QIcon::fromTheme(QStringLiteral("preferences-system-windows-actions"))); action->setData(Options::ApplicationRulesOp); m_applicationRulesOperation = action; if (!kwinApp()->config()->isImmutable() && !KAuthorized::authorizeControlModules(configModules(true)).isEmpty()) { advancedMenu->addSeparator(); action = advancedMenu->addAction(i18nc("Entry in context menu of window decoration to open the configuration module of KWin", "Window Manager S&ettings...")); action->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); connect(action, &QAction::triggered, this, [this]() { // opens the KWin configuration QStringList args; args << QStringLiteral("--icon") << QStringLiteral("preferences-system-windows"); const QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kservices5/kwinfocus.desktop")); if (!path.isEmpty()) { args << QStringLiteral("--desktopfile") << path; } args << configModules(false); QProcess *p = new Process(this); p->setArguments(args); p->setProcessEnvironment(kwinApp()->processStartupEnvironment()); p->setProgram(QStringLiteral("kcmshell5")); connect(p, static_cast(&QProcess::finished), p, &QProcess::deleteLater); connect(p, static_cast(&QProcess::error), this, [p] (QProcess::ProcessError e) { if (e == QProcess::FailedToStart) { qCDebug(KWIN_CORE) << "Failed to start kcmshell5"; } } ); p->start(); } ); } m_minimizeOperation = m_menu->addAction(i18n("Mi&nimize")); setShortcut(m_minimizeOperation, QStringLiteral("Window Minimize")); m_minimizeOperation->setData(Options::MinimizeOp); m_maximizeOperation = m_menu->addAction(i18n("Ma&ximize")); setShortcut(m_maximizeOperation, QStringLiteral("Window Maximize")); m_maximizeOperation->setCheckable(true); m_maximizeOperation->setData(Options::MaximizeOp); m_menu->addSeparator(); // Actions for window tabbing if (false) { m_removeFromTabGroup = m_menu->addAction(i18n("&Untab")); setShortcut(m_removeFromTabGroup, QStringLiteral("Untab")); m_removeFromTabGroup->setData(Options::RemoveTabFromGroupOp); m_closeTabGroup = m_menu->addAction(i18n("Close Entire &Group")); m_closeTabGroup->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); setShortcut(m_closeTabGroup, QStringLiteral("Close TabGroup")); m_closeTabGroup->setData(Options::CloseTabGroupOp); m_menu->addSeparator(); } m_menu->addSeparator(); action = m_menu->addMenu(advancedMenu); action->setText(i18n("&More Actions")); m_menu->addSeparator(); m_closeOperation = m_menu->addAction(i18n("&Close")); m_closeOperation->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); setShortcut(m_closeOperation, QStringLiteral("Window Close")); m_closeOperation->setData(Options::CloseOp); } void UserActionsMenu::discard() { delete m_menu; m_menu = NULL; m_desktopMenu = NULL; m_multipleDesktopsMenu = nullptr; m_screenMenu = NULL; m_activityMenu = NULL; m_switchToTabMenu = NULL; m_addTabsMenu = NULL; m_scriptsMenu = NULL; } void UserActionsMenu::menuAboutToShow() { if (m_client.isNull() || !m_menu) return; if (VirtualDesktopManager::self()->count() == 1) { delete m_desktopMenu; m_desktopMenu = 0; delete m_multipleDesktopsMenu; m_multipleDesktopsMenu = nullptr; } else { initDesktopPopup(); } if (screens()->count() == 1 || (!m_client.data()->isMovable() && !m_client.data()->isMovableAcrossScreens())) { delete m_screenMenu; m_screenMenu = NULL; } else { initScreenPopup(); } m_menu->setPalette(m_client.data()->palette()); m_resizeOperation->setEnabled(m_client.data()->isResizable()); m_moveOperation->setEnabled(m_client.data()->isMovableAcrossScreens()); m_maximizeOperation->setEnabled(m_client.data()->isMaximizable()); m_maximizeOperation->setChecked(m_client.data()->maximizeMode() == MaximizeFull); m_shadeOperation->setEnabled(m_client.data()->isShadeable()); m_shadeOperation->setChecked(m_client.data()->shadeMode() != ShadeNone); m_keepAboveOperation->setChecked(m_client.data()->keepAbove()); m_keepBelowOperation->setChecked(m_client.data()->keepBelow()); m_fullScreenOperation->setEnabled(m_client.data()->userCanSetFullScreen()); m_fullScreenOperation->setChecked(m_client.data()->isFullScreen()); m_noBorderOperation->setEnabled(m_client.data()->userCanSetNoBorder()); m_noBorderOperation->setChecked(m_client.data()->noBorder()); m_minimizeOperation->setEnabled(m_client.data()->isMinimizable()); m_closeOperation->setEnabled(m_client.data()->isCloseable()); m_shortcutOperation->setEnabled(m_client.data()->rules()->checkShortcut(QString()).isNull()); if (false) { initTabbingPopups(); m_addTabsMenu->setPalette(m_client.data()->palette()); } else { delete m_addTabsMenu; m_addTabsMenu = 0; } // drop the existing scripts menu delete m_scriptsMenu; m_scriptsMenu = NULL; // ask scripts whether they want to add entries for the given Client QList scriptActions = Scripting::self()->actionsForUserActionMenu(m_client.data(), m_scriptsMenu); if (!scriptActions.isEmpty()) { m_scriptsMenu = new QMenu(m_menu); m_scriptsMenu->setPalette(m_client.data()->palette()); m_scriptsMenu->addActions(scriptActions); QAction *action = m_scriptsMenu->menuAction(); // set it as the first item after desktop m_menu->insertAction(m_closeOperation, action); action->setText(i18n("&Extensions")); } m_rulesOperation->setEnabled(m_client.data()->supportsWindowRules()); m_applicationRulesOperation->setEnabled(m_client.data()->supportsWindowRules()); showHideActivityMenu(); } void UserActionsMenu::showHideActivityMenu() { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return; } const QStringList &openActivities_ = Activities::self()->running(); qCDebug(KWIN_CORE) << "activities:" << openActivities_.size(); if (openActivities_.size() < 2) { delete m_activityMenu; m_activityMenu = 0; } else { initActivityPopup(); } #endif } void UserActionsMenu::selectPopupClientTab(QAction* action) { if (!(!m_client.isNull() && m_client.data()->tabGroup()) || !action->data().isValid()) return; if (AbstractClient *other = action->data().value()) { m_client.data()->tabGroup()->setCurrent(other); return; } // failed conversion, try "1" & "2", being prev and next int direction = action->data().toInt(); if (direction == 1) m_client.data()->tabGroup()->activatePrev(); else if (direction == 2) m_client.data()->tabGroup()->activateNext(); } static QString shortCaption(const QString &s) { if (s.length() < 64) return s; QString ss = s; return ss.replace(32,s.length()-64, QStringLiteral("...")); } void UserActionsMenu::rebuildTabListPopup() { Q_ASSERT(m_switchToTabMenu); m_switchToTabMenu->clear(); // whatever happens "0x1" and "0x2" are no heap positions ;-) m_switchToTabMenu->addAction(i18nc("Switch to tab -> Previous", "Previous"))->setData(1); m_switchToTabMenu->addAction(i18nc("Switch to tab -> Next", "Next"))->setData(2); m_switchToTabMenu->addSeparator(); for (auto i = m_client.data()->tabGroup()->clients().constBegin(), end = m_client.data()->tabGroup()->clients().constEnd(); i != end; ++i) { if ((*i)->noBorder() || *i == m_client.data()->tabGroup()->current()) continue; // cannot tab there anyway m_switchToTabMenu->addAction(shortCaption((*i)->caption()))->setData(QVariant::fromValue(*i)); } } void UserActionsMenu::entabPopupClient(QAction* action) { if (m_client.isNull() || !action->data().isValid()) return; AbstractClient *other = action->data().value(); if (!Workspace::self()->allClientList().contains(other)) // might have been lost betwenn pop-up and selection return; AbstractClient *c = m_client.data(); if (!c) { return; } c->tabBehind(other, true); if (options->focusPolicyIsReasonable()) Workspace::self()->requestFocus(c); } void UserActionsMenu::rebuildTabGroupPopup() { Q_ASSERT(m_addTabsMenu); m_addTabsMenu->clear(); const auto &clientList = Workspace::self()->allClientList(); for (auto i = clientList.constBegin(), end = clientList.constEnd(); i != end; ++i) { if (*i == m_client.data() || (*i)->noBorder()) continue; m_addTabsMenu->addAction(shortCaption((*i)->caption()))->setData(QVariant::fromValue(*i)); } if (m_addTabsMenu->actions().isEmpty()) m_addTabsMenu->addAction(i18nc("There's no window available to be attached as tab to this one", "None available"))->setEnabled(false); } void UserActionsMenu::initTabbingPopups() { bool needTabManagers = false; if (m_client.data()->tabGroup() && m_client.data()->tabGroup()->count() > 1) { needTabManagers = true; if (!m_switchToTabMenu) { m_switchToTabMenu = new QMenu(i18n("Switch to Tab"), m_menu); connect(m_switchToTabMenu, &QMenu::triggered, this, &UserActionsMenu::selectPopupClientTab); connect(m_switchToTabMenu, &QMenu::aboutToShow, this, &UserActionsMenu::rebuildTabListPopup); m_menu->insertMenu(m_removeFromTabGroup, m_switchToTabMenu); } } else { delete m_switchToTabMenu; m_switchToTabMenu = 0; } if (!m_addTabsMenu) { m_addTabsMenu = new QMenu(i18n("&Attach as tab to"), m_menu); connect(m_addTabsMenu, &QMenu::triggered, this, &UserActionsMenu::entabPopupClient); connect(m_addTabsMenu, &QMenu::aboutToShow, this, &UserActionsMenu::rebuildTabGroupPopup); m_menu->insertMenu(m_removeFromTabGroup, m_addTabsMenu); } m_addTabsMenu->menuAction()->setEnabled(!m_client.data()->isFullScreen()); m_removeFromTabGroup->setVisible(needTabManagers); m_closeTabGroup->setVisible(needTabManagers); } void UserActionsMenu::initDesktopPopup() { if (kwinApp()->operationMode() == Application::OperationModeWaylandOnly || kwinApp()->operationMode() == Application::OperationModeXwayland) { if (m_multipleDesktopsMenu) { return; } m_multipleDesktopsMenu = new QMenu(m_menu); connect(m_multipleDesktopsMenu, &QMenu::triggered, this, &UserActionsMenu::slotToggleOnVirtualDesktop); connect(m_multipleDesktopsMenu, &QMenu::aboutToShow, this, &UserActionsMenu::multipleDesktopsPopupAboutToShow); QAction *action = m_multipleDesktopsMenu->menuAction(); // set it as the first item m_menu->insertAction(m_minimizeOperation, action); action->setText(i18n("&Desktops")); } else { if (m_desktopMenu) return; m_desktopMenu = new QMenu(m_menu); connect(m_desktopMenu, &QMenu::triggered, this, &UserActionsMenu::slotSendToDesktop); connect(m_desktopMenu, &QMenu::aboutToShow, this, &UserActionsMenu::desktopPopupAboutToShow); QAction *action = m_desktopMenu->menuAction(); // set it as the first item m_menu->insertAction(m_minimizeOperation, action); action->setText(i18n("Move To &Desktop")); } } void UserActionsMenu::initScreenPopup() { if (m_screenMenu) { return; } m_screenMenu = new QMenu(m_menu); connect(m_screenMenu, &QMenu::triggered, this, &UserActionsMenu::slotSendToScreen); connect(m_screenMenu, &QMenu::aboutToShow, this, &UserActionsMenu::screenPopupAboutToShow); QAction *action = m_screenMenu->menuAction(); // set it as the first item after desktop m_menu->insertAction(m_activityMenu ? m_activityMenu->menuAction() : m_minimizeOperation, action); action->setText(i18n("Move To &Screen")); } void UserActionsMenu::initActivityPopup() { if (m_activityMenu) return; m_activityMenu = new QMenu(m_menu); connect(m_activityMenu, &QMenu::triggered, this, &UserActionsMenu::slotToggleOnActivity); connect(m_activityMenu, &QMenu::aboutToShow, this, &UserActionsMenu::activityPopupAboutToShow); QAction *action = m_activityMenu->menuAction(); // set it as the first item m_menu->insertAction(m_minimizeOperation, action); action->setText(i18n("Ac&tivities")); //FIXME is that a good string? } void UserActionsMenu::desktopPopupAboutToShow() { if (!m_desktopMenu) return; const VirtualDesktopManager *vds = VirtualDesktopManager::self(); m_desktopMenu->clear(); m_desktopMenu->setPalette(m_client.data()->palette()); QActionGroup *group = new QActionGroup(m_desktopMenu); QAction *action = m_desktopMenu->addAction(i18n("&All Desktops")); action->setData(0); action->setCheckable(true); group->addAction(action); if (!m_client.isNull() && m_client.data()->isOnAllDesktops()) action->setChecked(true); m_desktopMenu->addSeparator(); const uint BASE = 10; for (uint i = 1; i <= vds->count(); ++i) { QString basic_name(QStringLiteral("%1 %2")); if (i < BASE) { basic_name.prepend(QLatin1Char('&')); } action = m_desktopMenu->addAction(basic_name.arg(i).arg(vds->name(i).replace(QLatin1Char('&'), QStringLiteral("&&")))); action->setData(i); action->setCheckable(true); group->addAction(action); if (!m_client.isNull() && !m_client.data()->isOnAllDesktops() && m_client.data()->isOnDesktop(i)) action->setChecked(true); } m_desktopMenu->addSeparator(); action = m_desktopMenu->addAction(i18nc("Create a new desktop and move there the window", "&New Desktop")); action->setData(vds->count() + 1); if (vds->count() >= vds->maximum()) action->setEnabled(false); } void UserActionsMenu::multipleDesktopsPopupAboutToShow() { if (!m_multipleDesktopsMenu) return; const VirtualDesktopManager *vds = VirtualDesktopManager::self(); m_multipleDesktopsMenu->clear(); m_multipleDesktopsMenu->setPalette(m_client.data()->palette()); QAction *action = m_multipleDesktopsMenu->addAction(i18n("&All Desktops")); action->setData(0); action->setCheckable(true); QActionGroup *allDesktopsGroup = new QActionGroup(m_multipleDesktopsMenu); allDesktopsGroup->addAction(action); if (!m_client.isNull() && m_client.data()->isOnAllDesktops()) { action->setChecked(true); } m_multipleDesktopsMenu->addSeparator(); const uint BASE = 10; for (uint i = 1; i <= vds->count(); ++i) { QString basic_name(QStringLiteral("%1 %2")); if (i < BASE) { basic_name.prepend(QLatin1Char('&')); } QWidgetAction *action = new QWidgetAction(m_multipleDesktopsMenu); QCheckBox *box = new QCheckBox(basic_name.arg(i).arg(vds->name(i).replace(QLatin1Char('&'), QStringLiteral("&&"))), m_multipleDesktopsMenu); action->setDefaultWidget(box); box->setBackgroundRole(m_multipleDesktopsMenu->backgroundRole()); box->setForegroundRole(m_multipleDesktopsMenu->foregroundRole()); box->setPalette(m_multipleDesktopsMenu->palette()); connect(box, &QCheckBox::clicked, action, &QAction::triggered); m_multipleDesktopsMenu->addAction(action); action->setData(i); if (!m_client.isNull() && !m_client.data()->isOnAllDesktops() && m_client.data()->isOnDesktop(i)) { box->setChecked(true); } } m_multipleDesktopsMenu->addSeparator(); action = m_multipleDesktopsMenu->addAction(i18nc("Create a new desktop and move there the window", "&New Desktop")); action->setData(vds->count() + 1); if (vds->count() >= vds->maximum()) action->setEnabled(false); } void UserActionsMenu::screenPopupAboutToShow() { if (!m_screenMenu) { return; } m_screenMenu->clear(); m_screenMenu->setPalette(m_client.data()->palette()); QActionGroup *group = new QActionGroup(m_screenMenu); for (int i = 0; icount(); ++i) { // assumption: there are not more than 9 screens attached. QAction *action = m_screenMenu->addAction(i18nc("@item:inmenu List of all Screens to send a window to. First argument is a number, second the output identifier. E.g. Screen 1 (HDMI1)", "Screen &%1 (%2)", (i+1), screens()->name(i))); action->setData(i); action->setCheckable(true); if (!m_client.isNull() && i == m_client.data()->screen()) { action->setChecked(true); } group->addAction(action); } } void UserActionsMenu::activityPopupAboutToShow() { if (!m_activityMenu) return; #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return; } m_activityMenu->clear(); m_activityMenu->setPalette(m_client.data()->palette()); QAction *action = m_activityMenu->addAction(i18n("&All Activities")); action->setData(QString()); action->setCheckable(true); static QPointer allActivitiesGroup; if (!allActivitiesGroup) { allActivitiesGroup = new QActionGroup(m_activityMenu); } allActivitiesGroup->addAction(action); if (!m_client.isNull() && m_client.data()->isOnAllActivities()) action->setChecked(true); m_activityMenu->addSeparator(); foreach (const QString &id, Activities::self()->running()) { KActivities::Info activity(id); QString name = activity.name(); name.replace('&', "&&"); QWidgetAction *action = new QWidgetAction(m_activityMenu); QCheckBox *box = new QCheckBox(name, m_activityMenu); action->setDefaultWidget(box); const QString icon = activity.icon(); if (!icon.isEmpty()) box->setIcon(QIcon::fromTheme(icon)); box->setBackgroundRole(m_activityMenu->backgroundRole()); box->setForegroundRole(m_activityMenu->foregroundRole()); box->setPalette(m_activityMenu->palette()); connect(box, &QCheckBox::clicked, action, &QAction::triggered); m_activityMenu->addAction(action); action->setData(id); if (!m_client.isNull() && !m_client.data()->isOnAllActivities() && m_client.data()->isOnActivity(id)) box->setChecked(true); } #endif } void UserActionsMenu::slotWindowOperation(QAction *action) { if (!action->data().isValid()) return; Options::WindowOperation op = static_cast< Options::WindowOperation >(action->data().toInt()); QWeakPointer c = (!m_client.isNull()) ? m_client : QWeakPointer(Workspace::self()->activeClient()); if (c.isNull()) return; QString type; switch(op) { case Options::FullScreenOp: if (!c.data()->isFullScreen() && c.data()->userCanSetFullScreen()) type = QStringLiteral("fullscreenaltf3"); break; case Options::NoBorderOp: if (!c.data()->noBorder() && c.data()->userCanSetNoBorder()) type = QStringLiteral("noborderaltf3"); break; default: break; }; if (!type.isEmpty()) helperDialog(type, c); // need to delay performing the window operation as we need to have the // user actions menu closed before we destroy the decoration. Otherwise Qt crashes qRegisterMetaType(); QMetaObject::invokeMethod(workspace(), "performWindowOperation", Qt::QueuedConnection, Q_ARG(KWin::AbstractClient*, c.data()), Q_ARG(Options::WindowOperation, op)); } void UserActionsMenu::slotSendToDesktop(QAction *action) { bool ok = false; uint desk = action->data().toUInt(&ok); if (!ok) { return; } if (m_client.isNull()) return; Workspace *ws = Workspace::self(); VirtualDesktopManager *vds = VirtualDesktopManager::self(); if (desk == 0) { // the 'on_all_desktops' menu entry m_client.data()->setOnAllDesktops(!m_client.data()->isOnAllDesktops()); return; } else if (desk > vds->count()) { vds->setCount(desk); } ws->sendClientToDesktop(m_client.data(), desk, false); } void UserActionsMenu::slotToggleOnVirtualDesktop(QAction *action) { bool ok = false; uint desk = action->data().toUInt(&ok); if (!ok) { return; } if (m_client.isNull()) { return; } VirtualDesktopManager *vds = VirtualDesktopManager::self(); if (desk == 0) { // the 'on_all_desktops' menu entry m_client.data()->setOnAllDesktops(!m_client.data()->isOnAllDesktops()); return; } else if (desk > vds->count()) { vds->setCount(desk); } VirtualDesktop *virtualDesktop = VirtualDesktopManager::self()->desktopForX11Id(desk); if (m_client.data()->desktops().contains(virtualDesktop)) { m_client.data()->leaveDesktop(virtualDesktop); } else { m_client.data()->enterDesktop(virtualDesktop); } } void UserActionsMenu::slotSendToScreen(QAction *action) { const int screen = action->data().toInt(); if (m_client.isNull()) { return; } if (screen >= screens()->count()) { return; } Workspace::self()->sendClientToScreen(m_client.data(), screen); } void UserActionsMenu::slotToggleOnActivity(QAction *action) { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return; } QString activity = action->data().toString(); if (m_client.isNull()) return; if (activity.isEmpty()) { // the 'on_all_activities' menu entry m_client.data()->setOnAllActivities(!m_client.data()->isOnAllActivities()); return; } Client *c = dynamic_cast(m_client.data()); if (!c) { return; } Activities::self()->toggleClientOnActivity(c, activity, false); if (m_activityMenu && m_activityMenu->isVisible() && m_activityMenu->actions().count()) { const bool isOnAll = m_client.data()->isOnAllActivities(); m_activityMenu->actions().at(0)->setChecked(isOnAll); if (isOnAll) { // toggleClientOnActivity interprets "on all" as "on none" and // susequent toggling ("off") would move the client to only that activity. // bug #330838 -> set all but "on all" off to "force proper usage" for (int i = 1; i < m_activityMenu->actions().count(); ++i) { if (QWidgetAction *qwa = qobject_cast(m_activityMenu->actions().at(i))) { if (QCheckBox *qcb = qobject_cast(qwa->defaultWidget())) { qcb->setChecked(false); } } } } } #else Q_UNUSED(action) #endif } //**************************************** // ShortcutDialog //**************************************** ShortcutDialog::ShortcutDialog(const QKeySequence& cut) : _shortcut(cut) { m_ui.setupUi(this); m_ui.keySequenceEdit->setKeySequence(cut); m_ui.warning->hide(); // Listen to changed shortcuts connect(m_ui.keySequenceEdit, &QKeySequenceEdit::editingFinished, this, &ShortcutDialog::keySequenceChanged); connect(m_ui.clearButton, &QToolButton::clicked, [this]{ _shortcut = QKeySequence(); }); m_ui.keySequenceEdit->setFocus(); setWindowFlags(Qt::Popup | Qt::X11BypassWindowManagerHint); } void ShortcutDialog::accept() { QKeySequence seq = shortcut(); if (!seq.isEmpty()) { if (seq[0] == Qt::Key_Escape) { reject(); return; } if (seq[0] == Qt::Key_Space || (seq[0] & Qt::KeyboardModifierMask) == 0) { // clear m_ui.keySequenceEdit->clear(); QDialog::accept(); return; } } QDialog::accept(); } void ShortcutDialog::done(int r) { QDialog::done(r); emit dialogDone(r == Accepted); } void ShortcutDialog::keySequenceChanged() { activateWindow(); // where is the kbd focus lost? cause of popup state? QKeySequence seq = m_ui.keySequenceEdit->keySequence(); if (_shortcut == seq) return; // don't try to update the same if (seq.isEmpty()) { // clear _shortcut = seq; return; } if (seq.count() > 1) { seq = QKeySequence(seq[0]); m_ui.keySequenceEdit->setKeySequence(seq); } // Check if the key sequence is used currently QString sc = seq.toString(); // NOTICE - seq.toString() & the entries in "conflicting" randomly get invalidated after the next call (if no sc has been set & conflicting isn't empty?!) QList conflicting = KGlobalAccel::getGlobalShortcutsByKey(seq); if (!conflicting.isEmpty()) { const KGlobalShortcutInfo &conflict = conflicting.at(0); m_ui.warning->setText(i18nc("'%1' is a keyboard shortcut like 'ctrl+w'", "%1 is already in use", sc)); m_ui.warning->setToolTip(i18nc("keyboard shortcut '%1' is used by action '%2' in application '%3'", "%1 is used by %2 in %3", sc, conflict.friendlyName(), conflict.componentFriendlyName())); m_ui.warning->show(); m_ui.keySequenceEdit->setKeySequence(shortcut()); } else if (seq != _shortcut) { m_ui.warning->hide(); if (QPushButton *ok = m_ui.buttonBox->button(QDialogButtonBox::Ok)) ok->setFocus(); } _shortcut = seq; } QKeySequence ShortcutDialog::shortcut() const { return _shortcut; } //**************************************** // Workspace //**************************************** void Workspace::slotIncreaseWindowOpacity() { if (!active_client) { return; } active_client->setOpacity(qMin(active_client->opacity() + 0.05, 1.0)); } void Workspace::slotLowerWindowOpacity() { if (!active_client) { return; } active_client->setOpacity(qMax(active_client->opacity() - 0.05, 0.05)); } void Workspace::closeActivePopup() { if (active_popup) { active_popup->close(); active_popup = NULL; active_popup_client = NULL; } m_userActionsMenu->close(); } template void Workspace::initShortcut(const QString &actionName, const QString &description, const QKeySequence &shortcut, Slot slot, const QVariant &data) { initShortcut(actionName, description, shortcut, this, slot, data); } template void Workspace::initShortcut(const QString &actionName, const QString &description, const QKeySequence &shortcut, T *receiver, Slot slot, const QVariant &data) { QAction *a = new QAction(this); a->setProperty("componentName", QStringLiteral(KWIN_NAME)); a->setObjectName(actionName); a->setText(description); if (data.isValid()) { a->setData(data); } KGlobalAccel::self()->setDefaultShortcut(a, QList() << shortcut); KGlobalAccel::self()->setShortcut(a, QList() << shortcut); input()->registerShortcut(shortcut, a, receiver, slot); } /** * Creates the global accel object \c keys. - **/ + */ void Workspace::initShortcuts() { #define IN_KWIN #include "kwinbindings.cpp" #ifdef KWIN_BUILD_TABBOX TabBox::TabBox::self()->initShortcuts(); #endif VirtualDesktopManager::self()->initShortcuts(); kwinApp()->platform()->colorCorrectManager()->initShortcuts(); m_userActionsMenu->discard(); // so that it's recreated next time } void Workspace::setupWindowShortcut(AbstractClient* c) { assert(client_keys_dialog == NULL); // TODO: PORT ME (KGlobalAccel related) //keys->setEnabled( false ); //disable_shortcuts_keys->setEnabled( false ); //client_keys->setEnabled( false ); client_keys_dialog = new ShortcutDialog(c->shortcut()); client_keys_client = c; connect(client_keys_dialog, &ShortcutDialog::dialogDone, this, &Workspace::setupWindowShortcutDone); QRect r = clientArea(ScreenArea, c); QSize size = client_keys_dialog->sizeHint(); QPoint pos = c->pos() + c->clientPos(); if (pos.x() + size.width() >= r.right()) pos.setX(r.right() - size.width()); if (pos.y() + size.height() >= r.bottom()) pos.setY(r.bottom() - size.height()); client_keys_dialog->move(pos); client_keys_dialog->show(); active_popup = client_keys_dialog; active_popup_client = c; } void Workspace::setupWindowShortcutDone(bool ok) { // keys->setEnabled( true ); // disable_shortcuts_keys->setEnabled( true ); // client_keys->setEnabled( true ); if (ok) client_keys_client->setShortcut(client_keys_dialog->shortcut().toString()); closeActivePopup(); client_keys_dialog->deleteLater(); client_keys_dialog = NULL; client_keys_client = NULL; if (active_client) active_client->takeFocus(); } void Workspace::clientShortcutUpdated(AbstractClient* c) { QString key = QStringLiteral("_k_session:%1").arg(c->window()); QAction* action = findChild(key); if (!c->shortcut().isEmpty()) { if (action == NULL) { // new shortcut action = new QAction(this); kwinApp()->platform()->setupActionForGlobalAccel(action); action->setProperty("componentName", QStringLiteral(KWIN_NAME)); action->setObjectName(key); action->setText(i18n("Activate Window (%1)", c->caption())); connect(action, &QAction::triggered, c, std::bind(&Workspace::activateClient, this, c, true)); } // no autoloading, since it's configured explicitly here and is not meant to be reused // (the key is the window id anyway, which is kind of random) KGlobalAccel::self()->setShortcut(action, QList() << c->shortcut(), KGlobalAccel::NoAutoloading); action->setEnabled(true); } else { KGlobalAccel::self()->removeAllShortcuts(action); delete action; } } void Workspace::performWindowOperation(AbstractClient* c, Options::WindowOperation op) { if (!c) return; if (op == Options::MoveOp || op == Options::UnrestrictedMoveOp) Cursor::setPos(c->geometry().center()); if (op == Options::ResizeOp || op == Options::UnrestrictedResizeOp) Cursor::setPos(c->geometry().bottomRight()); switch(op) { case Options::MoveOp: c->performMouseCommand(Options::MouseMove, Cursor::pos()); break; case Options::UnrestrictedMoveOp: c->performMouseCommand(Options::MouseUnrestrictedMove, Cursor::pos()); break; case Options::ResizeOp: c->performMouseCommand(Options::MouseResize, Cursor::pos()); break; case Options::UnrestrictedResizeOp: c->performMouseCommand(Options::MouseUnrestrictedResize, Cursor::pos()); break; case Options::CloseOp: QMetaObject::invokeMethod(c, "closeWindow", Qt::QueuedConnection); break; case Options::MaximizeOp: c->maximize(c->maximizeMode() == MaximizeFull ? MaximizeRestore : MaximizeFull); break; case Options::HMaximizeOp: c->maximize(c->maximizeMode() ^ MaximizeHorizontal); break; case Options::VMaximizeOp: c->maximize(c->maximizeMode() ^ MaximizeVertical); break; case Options::RestoreOp: c->maximize(MaximizeRestore); break; case Options::MinimizeOp: c->minimize(); break; case Options::ShadeOp: c->performMouseCommand(Options::MouseShade, Cursor::pos()); break; case Options::OnAllDesktopsOp: c->setOnAllDesktops(!c->isOnAllDesktops()); break; case Options::FullScreenOp: c->setFullScreen(!c->isFullScreen(), true); break; case Options::NoBorderOp: c->setNoBorder(!c->noBorder()); break; case Options::KeepAboveOp: { StackingUpdatesBlocker blocker(this); bool was = c->keepAbove(); c->setKeepAbove(!c->keepAbove()); if (was && !c->keepAbove()) raiseClient(c); break; } case Options::KeepBelowOp: { StackingUpdatesBlocker blocker(this); bool was = c->keepBelow(); c->setKeepBelow(!c->keepBelow()); if (was && !c->keepBelow()) lowerClient(c); break; } case Options::OperationsOp: c->performMouseCommand(Options::MouseShade, Cursor::pos()); break; case Options::WindowRulesOp: RuleBook::self()->edit(c, false); break; case Options::ApplicationRulesOp: RuleBook::self()->edit(c, true); break; case Options::SetupWindowShortcutOp: setupWindowShortcut(c); break; case Options::LowerOp: lowerClient(c); break; case Options::TabDragOp: // Handled by decoration itself case Options::NoOp: break; case Options::RemoveTabFromGroupOp: if (c->untab(c->geometry().translated(cascadeOffset(c))) && options->focusPolicyIsReasonable()) takeActivity(c, ActivityFocus | ActivityRaise); break; case Options::ActivateNextTabOp: if (c->tabGroup()) c->tabGroup()->activateNext(); break; case Options::ActivatePreviousTabOp: if (c->tabGroup()) c->tabGroup()->activatePrev(); break; case Options::CloseTabGroupOp: c->tabGroup()->closeAll(); break; } } /** * Called by the decoration in the new API to determine what buttons the user has configured for * window tab dragging and the operations menu. - **/ + */ Options::WindowOperation Client::mouseButtonToWindowOperation(Qt::MouseButtons button) { Options::MouseCommand com = Options::MouseNothing; bool active = isActive(); if (!wantsInput()) // we cannot be active, use it anyway active = true; if (button == Qt::LeftButton) com = active ? options->commandActiveTitlebar1() : options->commandInactiveTitlebar1(); else if (button == Qt::MidButton) com = active ? options->commandActiveTitlebar2() : options->commandInactiveTitlebar2(); else if (button == Qt::RightButton) com = active ? options->commandActiveTitlebar3() : options->commandInactiveTitlebar3(); // TODO: Complete the list if (com == Options::MouseDragTab) return Options::TabDragOp; if (com == Options::MouseOperationsMenu) return Options::OperationsOp; return Options::NoOp; } /** * Performs a mouse command on this client (see options.h) - **/ + */ bool Client::performMouseCommand(Options::MouseCommand command, const QPoint &globalPos) { bool replay = false; switch(command) { case Options::MouseShade : toggleShade(); cancelShadeHoverTimer(); break; case Options::MouseSetShade: setShade(ShadeNormal); cancelShadeHoverTimer(); break; case Options::MouseUnsetShade: setShade(ShadeNone); cancelShadeHoverTimer(); break; default: return AbstractClient::performMouseCommand(command, globalPos); } return replay; } void Workspace::slotActivateAttentionWindow() { if (attention_chain.count() > 0) activateClient(attention_chain.first()); } static uint senderValue(QObject *sender) { QAction *act = qobject_cast(sender); bool ok = false; uint i = -1; if (act) i = act->data().toUInt(&ok); if (ok) return i; return -1; } #define USABLE_ACTIVE_CLIENT (active_client && !(active_client->isDesktop() || active_client->isDock())) void Workspace::slotWindowToDesktop(uint i) { if (USABLE_ACTIVE_CLIENT) { if (i < 1) return; if (i >= 1 && i <= VirtualDesktopManager::self()->count()) sendClientToDesktop(active_client, i, true); } } static bool screenSwitchImpossible() { if (!screens()->isCurrentFollowsMouse()) return false; QStringList args; args << QStringLiteral("--passivepopup") << i18n("The window manager is configured to consider the screen with the mouse on it as active one.\n" "Therefore it is not possible to switch to a screen explicitly.") << QStringLiteral("20"); KProcess::startDetached(QStringLiteral("kdialog"), args); return true; } void Workspace::slotSwitchToScreen() { if (screenSwitchImpossible()) return; const int i = senderValue(sender()); if (i > -1) setCurrentScreen(i); } void Workspace::slotSwitchToNextScreen() { if (screenSwitchImpossible()) return; setCurrentScreen((screens()->current() + 1) % screens()->count()); } void Workspace::slotSwitchToPrevScreen() { if (screenSwitchImpossible()) return; setCurrentScreen((screens()->current() + screens()->count() - 1) % screens()->count()); } void Workspace::slotWindowToScreen() { if (USABLE_ACTIVE_CLIENT) { const int i = senderValue(sender()); if (i < 0) return; if (i >= 0 && i <= screens()->count()) { sendClientToScreen(active_client, i); } } } void Workspace::slotWindowToNextScreen() { if (USABLE_ACTIVE_CLIENT) sendClientToScreen(active_client, (active_client->screen() + 1) % screens()->count()); } void Workspace::slotWindowToPrevScreen() { if (USABLE_ACTIVE_CLIENT) sendClientToScreen(active_client, (active_client->screen() + screens()->count() - 1) % screens()->count()); } /** * Maximizes the active client. - **/ + */ void Workspace::slotWindowMaximize() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::MaximizeOp); } /** * Maximizes the active client vertically. - **/ + */ void Workspace::slotWindowMaximizeVertical() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::VMaximizeOp); } /** * Maximizes the active client horiozontally. - **/ + */ void Workspace::slotWindowMaximizeHorizontal() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::HMaximizeOp); } /** * Minimizes the active client. - **/ + */ void Workspace::slotWindowMinimize() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::MinimizeOp); } /** * Shades/unshades the active client respectively. - **/ + */ void Workspace::slotWindowShade() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::ShadeOp); } /** * Raises the active client. - **/ + */ void Workspace::slotWindowRaise() { if (USABLE_ACTIVE_CLIENT) raiseClient(active_client); } /** * Lowers the active client. - **/ + */ void Workspace::slotWindowLower() { if (USABLE_ACTIVE_CLIENT) { lowerClient(active_client); // As this most likely makes the window no longer visible change the // keyboard focus to the next available window. //activateNextClient( c ); // Doesn't work when we lower a child window if (active_client->isActive() && options->focusPolicyIsReasonable()) { if (options->isNextFocusPrefersMouse()) { AbstractClient *next = clientUnderMouse(active_client->screen()); if (next && next != active_client) requestFocus(next, false); } else { activateClient(topClientOnDesktop(VirtualDesktopManager::self()->current(), -1)); } } } } /** * Does a toggle-raise-and-lower on the active client. - **/ + */ void Workspace::slotWindowRaiseOrLower() { if (USABLE_ACTIVE_CLIENT) raiseOrLowerClient(active_client); } void Workspace::slotWindowOnAllDesktops() { if (USABLE_ACTIVE_CLIENT) active_client->setOnAllDesktops(!active_client->isOnAllDesktops()); } void Workspace::slotWindowFullScreen() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::FullScreenOp); } void Workspace::slotWindowNoBorder() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::NoBorderOp); } void Workspace::slotWindowAbove() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::KeepAboveOp); } void Workspace::slotWindowBelow() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::KeepBelowOp); } void Workspace::slotSetupWindowShortcut() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::SetupWindowShortcutOp); } /** * Toggles show desktop. - **/ + */ void Workspace::slotToggleShowDesktop() { setShowingDesktop(!showingDesktop()); } template void windowToDesktop(AbstractClient *c) { VirtualDesktopManager *vds = VirtualDesktopManager::self(); Workspace *ws = Workspace::self(); Direction functor; // TODO: why is options->isRollOverDesktops() not honored? const auto desktop = functor(nullptr, true); if (c && !c->isDesktop() && !c->isDock()) { ws->setMoveResizeClient(c); vds->setCurrent(desktop); ws->setMoveResizeClient(nullptr); } } /** * Moves the active client to the next desktop. - **/ + */ void Workspace::slotWindowToNextDesktop() { if (USABLE_ACTIVE_CLIENT) windowToNextDesktop(active_client); } void Workspace::windowToNextDesktop(AbstractClient* c) { windowToDesktop(c); } /** * Moves the active client to the previous desktop. - **/ + */ void Workspace::slotWindowToPreviousDesktop() { if (USABLE_ACTIVE_CLIENT) windowToPreviousDesktop(active_client); } void Workspace::windowToPreviousDesktop(AbstractClient* c) { windowToDesktop(c); } template void activeClientToDesktop() { VirtualDesktopManager *vds = VirtualDesktopManager::self(); Workspace *ws = Workspace::self(); const int current = vds->current(); Direction functor; const int d = functor(current, options->isRollOverDesktops()); if (d == current) { return; } ws->setMoveResizeClient(ws->activeClient()); vds->setCurrent(d); ws->setMoveResizeClient(nullptr); } void Workspace::slotWindowToDesktopRight() { if (USABLE_ACTIVE_CLIENT) { activeClientToDesktop(); } } void Workspace::slotWindowToDesktopLeft() { if (USABLE_ACTIVE_CLIENT) { activeClientToDesktop(); } } void Workspace::slotWindowToDesktopUp() { if (USABLE_ACTIVE_CLIENT) { activeClientToDesktop(); } } void Workspace::slotWindowToDesktopDown() { if (USABLE_ACTIVE_CLIENT) { activeClientToDesktop(); } } void Workspace::slotActivateNextTab() { if (active_client && active_client->tabGroup()) active_client->tabGroup()->activateNext(); } void Workspace::slotActivatePrevTab() { if (active_client && active_client->tabGroup()) active_client->tabGroup()->activatePrev(); } void Workspace::slotUntab() { if (active_client) active_client->untab(active_client->geometry().translated(cascadeOffset(active_client))); } /** * Kill Window feature, similar to xkill. - **/ + */ void Workspace::slotKillWindow() { if (m_windowKiller.isNull()) { m_windowKiller.reset(new KillWindow()); } m_windowKiller->start(); } /** * Switches to the nearest window in given direction. - **/ + */ void Workspace::switchWindow(Direction direction) { if (!active_client) return; AbstractClient *c = active_client; int desktopNumber = c->isOnAllDesktops() ? VirtualDesktopManager::self()->current() : c->desktop(); // Centre of the active window QPoint curPos(c->pos().x() + c->geometry().width() / 2, c->pos().y() + c->geometry().height() / 2); if (!switchWindow(c, direction, curPos, desktopNumber)) { auto opposite = [&] { switch(direction) { case DirectionNorth: return QPoint(curPos.x(), screens()->geometry().height()); case DirectionSouth: return QPoint(curPos.x(), 0); case DirectionEast: return QPoint(0, curPos.y()); case DirectionWest: return QPoint(screens()->geometry().width(), curPos.y()); default: Q_UNREACHABLE(); } }; switchWindow(c, direction, opposite(), desktopNumber); } } bool Workspace::switchWindow(AbstractClient *c, Direction direction, QPoint curPos, int d) { AbstractClient *switchTo = nullptr; int bestScore = 0; ToplevelList clist = stackingOrder(); for (ToplevelList::Iterator i = clist.begin(); i != clist.end(); ++i) { auto client = qobject_cast(*i); if (!client) { continue; } if (client->wantsTabFocus() && *i != c && client->isOnDesktop(d) && !client->isMinimized() && (*i)->isOnCurrentActivity()) { // Centre of the other window QPoint other(client->pos().x() + client->geometry().width() / 2, client->pos().y() + client->geometry().height() / 2); int distance; int offset; switch(direction) { case DirectionNorth: distance = curPos.y() - other.y(); offset = qAbs(other.x() - curPos.x()); break; case DirectionEast: distance = other.x() - curPos.x(); offset = qAbs(other.y() - curPos.y()); break; case DirectionSouth: distance = other.y() - curPos.y(); offset = qAbs(other.x() - curPos.x()); break; case DirectionWest: distance = curPos.x() - other.x(); offset = qAbs(other.y() - curPos.y()); break; default: distance = -1; offset = -1; } if (distance > 0) { // Inverse score int score = distance + offset + ((offset * offset) / distance); if (score < bestScore || !switchTo) { switchTo = client; bestScore = score; } } } } if (switchTo) { if (switchTo->tabGroup()) switchTo = switchTo->tabGroup()->current(); activateClient(switchTo); } return switchTo; } /** * Shows the window operations popup menu for the active client. - **/ + */ void Workspace::slotWindowOperations() { if (!active_client) return; QPoint pos = active_client->pos() + active_client->clientPos(); showWindowMenu(QRect(pos, pos), active_client); } void Workspace::showWindowMenu(const QRect &pos, AbstractClient* cl) { m_userActionsMenu->show(pos, cl); } void Workspace::showApplicationMenu(const QRect &pos, AbstractClient *c, int actionId) { ApplicationMenu::self()->showApplicationMenu(c->geometry().topLeft() + pos.bottomLeft(), c, actionId); } /** * Closes the active client. - **/ + */ void Workspace::slotWindowClose() { // TODO: why? // if ( tab_box->isVisible()) // return; if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::CloseOp); } /** * Starts keyboard move mode for the active client. - **/ + */ void Workspace::slotWindowMove() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::UnrestrictedMoveOp); } /** * Starts keyboard resize mode for the active client. - **/ + */ void Workspace::slotWindowResize() { if (USABLE_ACTIVE_CLIENT) performWindowOperation(active_client, Options::UnrestrictedResizeOp); } #undef USABLE_ACTIVE_CLIENT void AbstractClient::setShortcut(const QString& _cut) { QString cut = rules()->checkShortcut(_cut); auto updateShortcut = [this](const QKeySequence &cut = QKeySequence()) { if (_shortcut == cut) return; _shortcut = cut; setShortcutInternal(); }; if (cut.isEmpty()) { updateShortcut(); return; } if (cut == shortcut().toString()) { return; // no change } // Format: // base+(abcdef)base+(abcdef) // E.g. Alt+Ctrl+(ABCDEF);Meta+X,Meta+(ABCDEF) if (!cut.contains(QLatin1Char('(')) && !cut.contains(QLatin1Char(')')) && !cut.contains(QLatin1String(" - "))) { if (workspace()->shortcutAvailable(cut, this)) updateShortcut(QKeySequence(cut)); else updateShortcut(); return; } QList< QKeySequence > keys; QStringList groups = cut.split(QStringLiteral(" - ")); for (QStringList::ConstIterator it = groups.constBegin(); it != groups.constEnd(); ++it) { QRegExp reg(QStringLiteral("(.*\\+)\\((.*)\\)")); if (reg.indexIn(*it) > -1) { QString base = reg.cap(1); QString list = reg.cap(2); for (int i = 0; i < list.length(); ++i) { QKeySequence c(base + list[ i ]); if (!c.isEmpty()) keys.append(c); } } else { // regexp doesn't match, so it should be a normal shortcut QKeySequence c(*it); if (!c.isEmpty()) { keys.append(c); } } } for (auto it = keys.constBegin(); it != keys.constEnd(); ++it) { if (_shortcut == *it) // current one is in the list return; } for (auto it = keys.constBegin(); it != keys.constEnd(); ++it) { if (workspace()->shortcutAvailable(*it, this)) { updateShortcut(*it); return; } } updateShortcut(); } void AbstractClient::setShortcutInternal() { updateCaption(); workspace()->clientShortcutUpdated(this); } void Client::setShortcutInternal() { updateCaption(); #if 0 workspace()->clientShortcutUpdated(this); #else // Workaround for kwin<->kglobalaccel deadlock, when KWin has X grab and the kded // kglobalaccel module tries to create the key grab. KWin should preferably grab // they keys itself anyway :(. QTimer::singleShot(0, this, std::bind(&Workspace::clientShortcutUpdated, workspace(), this)); #endif } bool Workspace::shortcutAvailable(const QKeySequence &cut, AbstractClient* ignore) const { if (ignore && cut == ignore->shortcut()) return true; if (!KGlobalAccel::getGlobalShortcutsByKey(cut).isEmpty()) { return false; } for (auto it = m_allClients.constBegin(); it != m_allClients.constEnd(); ++it) { if ((*it) != ignore && (*it)->shortcut() == cut) return false; } return true; } } // namespace diff --git a/useractions.h b/useractions.h index df14142fe..294cbca77 100644 --- a/useractions.h +++ b/useractions.h @@ -1,303 +1,303 @@ /******************************************************************** 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_USERACTIONS_H #define KWIN_USERACTIONS_H #include "ui_shortcutdialog.h" #include // Qt #include #include class QAction; class QRect; namespace KWin { class AbstractClient; class Client; /** * @brief Menu shown for a Client. * * The UserActionsMenu implements the Menu which is shown on: * @li context-menu event on Window decoration * @li window menu button * @li Keyboard Shortcut (by default Alt+F3) * * The menu contains various window management related actions for the Client the menu is opened * for, this is normally the active Client. * * The menu which is shown is tried to be as close as possible to the menu implemented in * libtaskmanager, though there are differences as there are some actions only the window manager * can provide and on the other hand the libtaskmanager cares also about things like e.g. grouping. * * Whenever the menu is changed it should be tried to also adjust the menu in libtaskmanager. * * @author Martin Gräßlin - **/ + */ class KWIN_EXPORT UserActionsMenu : public QObject { Q_OBJECT public: explicit UserActionsMenu(QObject *parent = 0); ~UserActionsMenu() override; /** * Discards the constructed menu, so that it gets recreates * on next show event. * @see show - **/ + */ void discard(); /** * @returns Whether the menu is currently visible - **/ + */ bool isShown() const; /** * grabs keyboard and mouse, workaround(?) for bug #351112 - **/ + */ void grabInput(); /** * @returns Whether the menu has a Client set to operate on. - **/ + */ bool hasClient() const; /** * Checks whether the given Client @p c is the Client * for which the Menu is shown. * @param c The Client to compare * @returns Whether the Client is the one related to this Menu - **/ + */ bool isMenuClient(const AbstractClient *c) const; /** * Closes the Menu and prepares it for next usage. - **/ + */ void close(); /** * @brief Shows the menu at the given @p pos for the given @p client. * * @param pos The position where the menu should be shown. * @param client The Client for which the Menu has to be shown. - **/ + */ void show(const QRect &pos, const QWeakPointer &client); public Q_SLOTS: /** * Delayed initialization of the activity menu. * * The call to retrieve the current list of activities is performed in a thread and this * slot is invoked once the list has been fetched. Only task of this method is to decide * whether to show the activity menu and to invoke the initialization of it. * * @see initActivityPopup - **/ + */ void showHideActivityMenu(); private Q_SLOTS: /** * The menu will become visible soon. * * Adjust the items according to the respective Client. - **/ + */ void menuAboutToShow(); /** * Adjusts the add to tab group menu to the current value of the Client. - **/ + */ void rebuildTabGroupPopup(); /** * Adjusts the switch to tab menu to the current values of the Client. - **/ + */ void rebuildTabListPopup(); /** * Adds the Client as tab to the Client identified by the @p action. * * @param action The invoked action containing the Client to which the active Client should be tabbed. - **/ + */ void entabPopupClient(QAction *action); /** * Activates the selected tabbed Client. * * @param action The invoked action containing the tabbed Client which should be activated. - **/ + */ void selectPopupClientTab(QAction *action); /** * Adjusts the desktop popup to the current values and the location of * the Client. - **/ + */ void desktopPopupAboutToShow(); /** * Adjusts the multipleDesktopsMenu popup to the current values and the location of * the Client, Wayland only. - **/ + */ void multipleDesktopsPopupAboutToShow(); /** * Adjusts the screen popup to the current values and the location of * the Client. - **/ + */ void screenPopupAboutToShow(); /** * Adjusts the activity popup to the current values and the location of * the Client. - **/ + */ void activityPopupAboutToShow(); /** * Sends the client to desktop \a desk * * @param action Invoked Action containing the Desktop as data element - **/ + */ void slotSendToDesktop(QAction *action); /** * Toggle whether the Client is on a desktop (Wayland only) * * @param action Invoked Action containing the Desktop as data element - **/ + */ void slotToggleOnVirtualDesktop(QAction *action); /** * Sends the Client to screen \a screen * * @param action Invoked Action containing the Screen as data element - **/ + */ void slotSendToScreen(QAction *action); /** * Toggles whether the Client is on the \a activity * * @param action Invoked Action containing the Id of the Activity to toggle the Client on - **/ + */ void slotToggleOnActivity(QAction *action); /** * Performs a window operation. * * @param action Invoked Action containing the Window Operation to perform for the Client - **/ + */ void slotWindowOperation(QAction *action); private: /** * Creates the menu if not already created. - **/ + */ void init(); /** * Creates the Move To Desktop sub-menu. - **/ + */ void initDesktopPopup(); /** * Creates the Move To Screen sub-menu. - **/ + */ void initScreenPopup(); /** * Creates activity popup. * I'm going with checkable ones instead of "copy to" and "move to" menus; I *think* it's an easier way. * Oh, and an 'all' option too of course - **/ + */ void initActivityPopup(); /** * Creates the Window Tabbing related menus. - **/ + */ void initTabbingPopups(); /** * Shows a helper Dialog to inform the user how to get back in case he triggered * an action which hides the window decoration (e.g. NoBorder or Fullscreen). * @param message The message type to be shown * @param c The Client for which the dialog should be shown. - **/ + */ void helperDialog(const QString &message, const QWeakPointer &c); /** * The actual main context menu which is show when the UserActionsMenu is invoked. - **/ + */ QMenu* m_menu; /** * The move to desktop sub menu. - **/ + */ QMenu* m_desktopMenu; /** * The move to desktop sub menu, with the Wayland protocol. - **/ + */ QMenu* m_multipleDesktopsMenu; /** * The move to screen sub menu. - **/ + */ QMenu* m_screenMenu; /** * The activities sub menu. - **/ + */ QMenu* m_activityMenu; /** * Menu to add the group to other group. - **/ + */ QMenu* m_addTabsMenu; /** * Menu to change tab. - **/ + */ QMenu* m_switchToTabMenu; /** * Menu for further entries added by scripts. - **/ + */ QMenu* m_scriptsMenu; QAction* m_resizeOperation; QAction* m_moveOperation; QAction* m_maximizeOperation; QAction* m_shadeOperation; QAction* m_keepAboveOperation; QAction* m_keepBelowOperation; QAction* m_fullScreenOperation; QAction* m_noBorderOperation; QAction* m_minimizeOperation; QAction* m_closeOperation; QAction* m_shortcutOperation; /** * Remove client from group. - **/ + */ QAction* m_removeFromTabGroup; /** * Close all clients in the group. - **/ + */ QAction* m_closeTabGroup; /** * The Client for which the menu is shown. - **/ + */ QWeakPointer m_client; QAction *m_rulesOperation = nullptr; QAction *m_applicationRulesOperation = nullptr; }; class ShortcutDialog : public QDialog { Q_OBJECT public: explicit ShortcutDialog(const QKeySequence& cut); void accept() override; QKeySequence shortcut() const; public Q_SLOTS: void keySequenceChanged(); Q_SIGNALS: void dialogDone(bool ok); protected: void done(int r) override; private: Ui::ShortcutDialog m_ui; QKeySequence _shortcut; }; } // namespace #endif // KWIN_USERACTIONS_H diff --git a/utils.h b/utils.h index a12473e6e..658647141 100644 --- a/utils.h +++ b/utils.h @@ -1,247 +1,247 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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_UTILS_H #define KWIN_UTILS_H // cmake stuff #include #include // kwin #include // KDE #include // Qt #include #include #include #include #include #include // system #include Q_DECLARE_LOGGING_CATEGORY(KWIN_CORE) Q_DECLARE_LOGGING_CATEGORY(KWIN_VIRTUALKEYBOARD) namespace KWin { // window types that are supported as normal windows (i.e. KWin actually manages them) const NET::WindowTypes SUPPORTED_MANAGED_WINDOW_TYPES_MASK = NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask /*| NET::OverrideMask*/ | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask | NET::NotificationMask | NET::OnScreenDisplayMask | NET::CriticalNotificationMask; // window types that are supported as unmanaged (mainly for compositing) const NET::WindowTypes SUPPORTED_UNMANAGED_WINDOW_TYPES_MASK = NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask /*| NET::OverrideMask*/ | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask | NET::DropdownMenuMask | NET::PopupMenuMask | NET::TooltipMask | NET::NotificationMask | NET::ComboBoxMask | NET::DNDIconMask | NET::OnScreenDisplayMask | NET::CriticalNotificationMask; const QPoint invalidPoint(INT_MIN, INT_MIN); class Toplevel; class Client; class Unmanaged; class Deleted; class Group; class Options; typedef QList< Toplevel* > ToplevelList; typedef QList< Client* > ClientList; typedef QList< const Client* > ConstClientList; typedef QList< Unmanaged* > UnmanagedList; typedef QList< Deleted* > DeletedList; typedef QList< Group* > GroupList; extern Options* options; enum Layer { UnknownLayer = -1, FirstLayer = 0, DesktopLayer = FirstLayer, BelowLayer, NormalLayer, DockLayer, AboveLayer, NotificationLayer, // layer for windows of type notification ActiveLayer, // active fullscreen, or active dialog CriticalNotificationLayer, // layer for notifications that should be shown even on top of fullscreen OnScreenDisplayLayer, // layer for On Screen Display windows such as volume feedback UnmanagedLayer, // layer for override redirect windows. NumLayers // number of layers, must be last }; // yes, I know this is not 100% like standard operator++ inline void operator++(Layer& lay) { lay = static_cast< Layer >(lay + 1); } enum StrutArea { StrutAreaInvalid = 0, // Null StrutAreaTop = 1 << 0, StrutAreaRight = 1 << 1, StrutAreaBottom = 1 << 2, StrutAreaLeft = 1 << 3, StrutAreaAll = StrutAreaTop | StrutAreaRight | StrutAreaBottom | StrutAreaLeft }; Q_DECLARE_FLAGS(StrutAreas, StrutArea) class StrutRect : public QRect { public: explicit StrutRect(QRect rect = QRect(), StrutArea area = StrutAreaInvalid); StrutRect(const StrutRect& other); inline StrutArea area() const { return m_area; }; private: StrutArea m_area; }; typedef QVector StrutRects; enum ShadeMode { ShadeNone, // not shaded ShadeNormal, // normally shaded - isShade() is true only here ShadeHover, // "shaded", but visible due to hover unshade ShadeActivated // "shaded", but visible due to alt+tab to the window }; /** * Maximize mode. These values specify how a window is maximized. * * @note these values are written to session files, don't change the order - **/ + */ enum MaximizeMode { MaximizeRestore = 0, ///< The window is not maximized in any direction. MaximizeVertical = 1, ///< The window is maximized vertically. MaximizeHorizontal = 2, ///< The window is maximized horizontally. /// Equal to @p MaximizeVertical | @p MaximizeHorizontal MaximizeFull = MaximizeVertical | MaximizeHorizontal }; inline MaximizeMode operator^(MaximizeMode m1, MaximizeMode m2) { return MaximizeMode(int(m1) ^ int(m2)); } enum class QuickTileFlag { None = 0, Left = 1 << 0, Right = 1 << 1, Top = 1 << 2, Bottom = 1 << 3, Horizontal = Left | Right, Vertical = Top | Bottom, Maximize = Left | Right | Top | Bottom, }; Q_DECLARE_FLAGS(QuickTileMode, QuickTileFlag) template using ScopedCPointer = QScopedPointer; void KWIN_EXPORT updateXTime(); void KWIN_EXPORT grabXServer(); void KWIN_EXPORT ungrabXServer(); bool KWIN_EXPORT grabXKeyboard(xcb_window_t w = XCB_WINDOW_NONE); void KWIN_EXPORT ungrabXKeyboard(); /** * Small helper class which performs grabXServer in the ctor and * ungrabXServer in the dtor. Use this class to ensure that grab and * ungrab are matched. * * To simplify usage consider using the macro GRAB_SERVER_DURING_CONTEXT - **/ + */ class XServerGrabber { public: XServerGrabber() { grabXServer(); } ~XServerGrabber() { ungrabXServer(); } }; #define GRAB_SERVER_DURING_CONTEXT XServerGrabber xserverGrabber; // the docs say it's UrgencyHint, but it's often #defined as XUrgencyHint #ifndef UrgencyHint #define UrgencyHint XUrgencyHint #endif // converting between X11 mouse/keyboard state mask and Qt button/keyboard states Qt::MouseButton x11ToQtMouseButton(int button); Qt::MouseButton KWIN_EXPORT x11ToQtMouseButton(int button); Qt::MouseButtons KWIN_EXPORT x11ToQtMouseButtons(int state); Qt::KeyboardModifiers KWIN_EXPORT x11ToQtKeyboardModifiers(int state); /** * Separate the concept of an unet QPoint and 0,0 - **/ + */ class ClearablePoint { public: inline bool isValid() const { return m_valid; } inline void clear(){ m_valid = false; } inline void setPoint(const QPoint &point) { m_point = point; m_valid = true; } inline QPoint point() const { return m_point; } private: QPoint m_point; bool m_valid = false; }; /** * QProcess subclass which unblocks SIGUSR in the child process. - **/ + */ class KWIN_EXPORT Process : public QProcess { Q_OBJECT public: explicit Process(QObject *parent = nullptr); ~Process() override; protected: void setupChildProcess() override; }; } // namespace // Must be outside namespace Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::StrutAreas) Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::QuickTileMode) #endif diff --git a/virtualdesktops.h b/virtualdesktops.h index 801ea1d7f..229d8d188 100644 --- a/virtualdesktops.h +++ b/virtualdesktops.h @@ -1,730 +1,730 @@ /******************************************************************** 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); ~VirtualDesktop() override; 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: ~VirtualDesktopManager() override; /** * @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 position The position of the desktop. It should be in range [0, count]. * @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 position, 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 numberOfDesktops or connect to the * countChanged signal. * * In case the @ref 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 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 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/wayland_server.h b/wayland_server.h index 1f68e5b50..686458a88 100644 --- a/wayland_server.h +++ b/wayland_server.h @@ -1,298 +1,298 @@ /******************************************************************** 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_WAYLAND_SERVER_H #define KWIN_WAYLAND_SERVER_H #include #include "keyboard_input.h" #include class QThread; class QProcess; class QWindow; namespace KWayland { namespace Client { class ConnectionThread; class Registry; class Compositor; class Seat; class DataDeviceManager; class ShmPool; class Surface; } namespace Server { class AppMenuManagerInterface; class ClientConnection; class CompositorInterface; class Display; class DataDeviceInterface; class IdleInterface; class ShellInterface; class SeatInterface; class DataDeviceManagerInterface; class ServerSideDecorationManagerInterface; class ServerSideDecorationPaletteManagerInterface; class SurfaceInterface; class OutputInterface; class PlasmaShellInterface; class PlasmaShellSurfaceInterface; class PlasmaVirtualDesktopManagementInterface; class PlasmaWindowManagementInterface; class QtSurfaceExtensionInterface; class OutputManagementInterface; class OutputConfigurationInterface; class XdgDecorationManagerInterface; class XdgShellInterface; class XdgForeignInterface; class XdgOutputManagerInterface; class KeyStateInterface; } } namespace KWin { class ShellClient; class AbstractClient; class Toplevel; class KWIN_EXPORT WaylandServer : public QObject { Q_OBJECT public: enum class InitalizationFlag { NoOptions = 0x0, LockScreen = 0x1, NoLockScreenIntegration = 0x2, NoGlobalShortcuts = 0x4 }; Q_DECLARE_FLAGS(InitalizationFlags, InitalizationFlag) ~WaylandServer() override; bool init(const QByteArray &socketName = QByteArray(), InitalizationFlags flags = InitalizationFlag::NoOptions); void terminateClientConnections(); KWayland::Server::Display *display() { return m_display; } KWayland::Server::CompositorInterface *compositor() { return m_compositor; } KWayland::Server::SeatInterface *seat() { return m_seat; } KWayland::Server::DataDeviceManagerInterface *dataDeviceManager() { return m_dataDeviceManager; } KWayland::Server::ShellInterface *shell() { return m_shell; } KWayland::Server::PlasmaVirtualDesktopManagementInterface *virtualDesktopManagement() { return m_virtualDesktopManagement; } KWayland::Server::PlasmaWindowManagementInterface *windowManagement() { return m_windowManagement; } KWayland::Server::ServerSideDecorationManagerInterface *decorationManager() const { return m_decorationManager; } KWayland::Server::XdgOutputManagerInterface *xdgOutputManager() const { return m_xdgOutputManager; } QList clients() const { return m_clients; } QList internalClients() const { return m_internalClients; } void removeClient(ShellClient *c); ShellClient *findClient(quint32 id) const; ShellClient *findClient(KWayland::Server::SurfaceInterface *surface) const; AbstractClient *findAbstractClient(KWayland::Server::SurfaceInterface *surface) const; ShellClient *findClient(QWindow *w) const; /** * @returns a transient parent of a surface imported with the foreign protocol, if any - **/ + */ KWayland::Server::SurfaceInterface *findForeignTransientForSurface(KWayland::Server::SurfaceInterface *surface); /** * @returns file descriptor for Xwayland to connect to. - **/ + */ int createXWaylandConnection(); void destroyXWaylandConnection(); /** * @returns file descriptor to the input method server's socket. - **/ + */ int createInputMethodConnection(); void destroyInputMethodConnection(); /** * @returns true if screen is locked. - **/ + */ bool isScreenLocked() const; /** * @returns whether integration with KScreenLocker is available. - **/ + */ bool hasScreenLockerIntegration() const; /** * @returns whether any kind of global shortcuts are supported. - **/ + */ bool hasGlobalShortcutSupport() const; void createInternalConnection(); void initWorkspace(); KWayland::Server::ClientConnection *xWaylandConnection() const { return m_xwayland.client; } KWayland::Server::ClientConnection *inputMethodConnection() const { return m_inputMethodServerConnection; } KWayland::Server::ClientConnection *internalConnection() const { return m_internalConnection.server; } KWayland::Server::ClientConnection *screenLockerClientConnection() const { return m_screenLockerClientConnection; } KWayland::Client::Compositor *internalCompositor() { return m_internalConnection.compositor; } KWayland::Client::Seat *internalSeat() { return m_internalConnection.seat; } KWayland::Client::DataDeviceManager *internalDataDeviceManager() { return m_internalConnection.ddm; } KWayland::Client::ShmPool *internalShmPool() { return m_internalConnection.shm; } KWayland::Client::ConnectionThread *internalClientConection() { return m_internalConnection.client; } KWayland::Client::Registry *internalClientRegistry() { return m_internalConnection.registry; } void dispatch(); quint32 createWindowId(KWayland::Server::SurfaceInterface *surface); /** * Struct containing information for a created Wayland connection through a * socketpair. - **/ + */ struct SocketPairConnection { /** * ServerSide Connection - **/ + */ KWayland::Server::ClientConnection *connection = nullptr; /** * client-side file descriptor for the socket - **/ + */ int fd = -1; }; /** * Creates a Wayland connection using a socket pair. - **/ + */ SocketPairConnection createConnection(); void simulateUserActivity(); void updateKeyState(KWin::Xkb::LEDs leds); Q_SIGNALS: void shellClientAdded(KWin::ShellClient*); void shellClientRemoved(KWin::ShellClient*); void terminatingInternalClientConnection(); void initialized(); void foreignTransientChanged(KWayland::Server::SurfaceInterface *child); private: void shellClientShown(Toplevel *t); void initOutputs(); void syncOutputsToWayland(); quint16 createClientId(KWayland::Server::ClientConnection *c); void destroyInternalConnection(); void configurationChangeRequested(KWayland::Server::OutputConfigurationInterface *config); template void createSurface(T *surface); void initScreenLocker(); KWayland::Server::Display *m_display = nullptr; KWayland::Server::CompositorInterface *m_compositor = nullptr; KWayland::Server::SeatInterface *m_seat = nullptr; KWayland::Server::DataDeviceManagerInterface *m_dataDeviceManager = nullptr; KWayland::Server::ShellInterface *m_shell = nullptr; KWayland::Server::XdgShellInterface *m_xdgShell5 = nullptr; KWayland::Server::XdgShellInterface *m_xdgShell6 = nullptr; KWayland::Server::XdgShellInterface *m_xdgShell = nullptr; KWayland::Server::PlasmaShellInterface *m_plasmaShell = nullptr; KWayland::Server::PlasmaWindowManagementInterface *m_windowManagement = nullptr; KWayland::Server::PlasmaVirtualDesktopManagementInterface *m_virtualDesktopManagement = nullptr; KWayland::Server::ServerSideDecorationManagerInterface *m_decorationManager = nullptr; KWayland::Server::OutputManagementInterface *m_outputManagement = nullptr; KWayland::Server::AppMenuManagerInterface *m_appMenuManager = nullptr; KWayland::Server::ServerSideDecorationPaletteManagerInterface *m_paletteManager = nullptr; KWayland::Server::IdleInterface *m_idle = nullptr; KWayland::Server::XdgOutputManagerInterface *m_xdgOutputManager = nullptr; KWayland::Server::XdgDecorationManagerInterface *m_xdgDecorationManager = nullptr; struct { KWayland::Server::ClientConnection *client = nullptr; QMetaObject::Connection destroyConnection; } m_xwayland; KWayland::Server::ClientConnection *m_inputMethodServerConnection = nullptr; KWayland::Server::ClientConnection *m_screenLockerClientConnection = nullptr; struct { KWayland::Server::ClientConnection *server = nullptr; KWayland::Client::ConnectionThread *client = nullptr; QThread *clientThread = nullptr; KWayland::Client::Registry *registry = nullptr; KWayland::Client::Compositor *compositor = nullptr; KWayland::Client::Seat *seat = nullptr; KWayland::Client::DataDeviceManager *ddm = nullptr; KWayland::Client::ShmPool *shm = nullptr; bool interfacesAnnounced = false; } m_internalConnection; KWayland::Server::XdgForeignInterface *m_XdgForeign = nullptr; KWayland::Server::KeyStateInterface *m_keyState = nullptr; QList m_clients; QList m_internalClients; QHash m_clientIds; InitalizationFlags m_initFlags; QVector m_plasmaShellSurfaces; KWIN_SINGLETON(WaylandServer) }; inline WaylandServer *waylandServer() { return WaylandServer::self(); } } // namespace KWin #endif diff --git a/workspace.cpp b/workspace.cpp index f7bc1bc7e..a2ffafcd6 100644 --- a/workspace.cpp +++ b/workspace.cpp @@ -1,1788 +1,1788 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 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 . *********************************************************************/ // own #include "workspace.h" // kwin libs #include // kwin #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include "appmenu.h" #include "atoms.h" #include "client.h" #include "composite.h" #include "cursor.h" #include "dbusinterface.h" #include "deleted.h" #include "effects.h" #include "focuschain.h" #include "group.h" #include "input.h" #include "logind.h" #include "moving_client_x11_filter.h" #include "killwindow.h" #include "netinfo.h" #include "outline.h" #include "placement.h" #include "rules.h" #include "screenedge.h" #include "screens.h" #include "platform.h" #include "scripting/scripting.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "unmanaged.h" #include "useractions.h" #include "virtualdesktops.h" #include "shell_client.h" #include "was_user_interaction_x11_filter.h" #include "wayland_server.h" #include "xcbutils.h" #include "main.h" #include "decorations/decorationbridge.h" // KDE #include #include #include #include // Qt #include namespace KWin { extern int screen_number; extern bool is_multihead; ColorMapper::ColorMapper(QObject *parent) : QObject(parent) , m_default(defaultScreen()->default_colormap) , m_installed(defaultScreen()->default_colormap) { } ColorMapper::~ColorMapper() { } void ColorMapper::update() { xcb_colormap_t cmap = m_default; if (Client *c = dynamic_cast(Workspace::self()->activeClient())) { if (c->colormap() != XCB_COLORMAP_NONE) { cmap = c->colormap(); } } if (cmap != m_installed) { xcb_install_colormap(connection(), cmap); m_installed = cmap; } } Workspace* Workspace::_self = 0; Workspace::Workspace(const QString &sessionKey) : QObject(0) , m_compositor(NULL) // Unsorted , active_popup(NULL) , active_popup_client(NULL) , m_initialDesktop(1) , active_client(0) , last_active_client(0) , most_recently_raised(0) , movingClient(0) , delayfocus_client(0) , force_restacking(false) , showing_desktop(false) , was_user_interaction(false) , session_saving(false) , block_focus(0) , m_userActionsMenu(new UserActionsMenu(this)) , client_keys_dialog(NULL) , client_keys_client(NULL) , global_shortcuts_disabled_for_client(false) , workspaceInit(true) , startup(0) , set_active_client_recursion(0) , block_stacking_updates(0) { // If KWin was already running it saved its configuration after loosing the selection -> Reread QFuture reparseConfigFuture = QtConcurrent::run(options, &Options::reparseConfiguration); ApplicationMenu::create(this); _self = this; #ifdef KWIN_BUILD_ACTIVITIES Activities *activities = nullptr; if (kwinApp()->usesKActivities()) { activities = Activities::create(this); } if (activities) { connect(activities, SIGNAL(currentChanged(QString)), SLOT(updateCurrentActivity(QString))); } #endif // PluginMgr needs access to the config file, so we need to wait for it for finishing reparseConfigFuture.waitForFinished(); options->loadConfig(); options->loadCompositingConfig(false); delayFocusTimer = 0; if (!sessionKey.isEmpty()) loadSessionInfo(sessionKey); connect(qApp, &QGuiApplication::commitDataRequest, this, &Workspace::commitData); connect(qApp, &QGuiApplication::saveStateRequest, this, &Workspace::saveState); RuleBook::create(this)->load(); ScreenEdges::create(this); // VirtualDesktopManager needs to be created prior to init shortcuts // and prior to TabBox, due to TabBox connecting to signals // actual initialization happens in init() VirtualDesktopManager::create(this); //dbus interface new VirtualDesktopManagerDBusInterface(VirtualDesktopManager::self()); #ifdef KWIN_BUILD_TABBOX // need to create the tabbox before compositing scene is setup TabBox::TabBox::create(this); #endif if (Compositor::self()) { m_compositor = Compositor::self(); } else { m_compositor = Compositor::create(this); } connect(this, &Workspace::currentDesktopChanged, m_compositor, &Compositor::addRepaintFull); connect(m_compositor, &QObject::destroyed, this, [this] { m_compositor = nullptr; }); auto decorationBridge = Decoration::DecorationBridge::create(this); decorationBridge->init(); connect(this, &Workspace::configChanged, decorationBridge, &Decoration::DecorationBridge::reconfigure); new DBusInterface(this); Outline::create(this); initShortcuts(); init(); } void Workspace::init() { KSharedConfigPtr config = kwinApp()->config(); kwinApp()->createScreens(); Screens *screens = Screens::self(); // get screen support connect(screens, SIGNAL(changed()), SLOT(desktopResized())); screens->setConfig(config); screens->reconfigure(); connect(options, SIGNAL(configChanged()), screens, SLOT(reconfigure())); ScreenEdges *screenEdges = ScreenEdges::self(); screenEdges->setConfig(config); screenEdges->init(); connect(options, SIGNAL(configChanged()), screenEdges, SLOT(reconfigure())); connect(VirtualDesktopManager::self(), SIGNAL(layoutChanged(int,int)), screenEdges, SLOT(updateLayout())); connect(this, &Workspace::clientActivated, screenEdges, &ScreenEdges::checkBlocking); FocusChain *focusChain = FocusChain::create(this); connect(this, &Workspace::clientRemoved, focusChain, &FocusChain::remove); connect(this, &Workspace::clientActivated, focusChain, &FocusChain::setActiveClient); connect(VirtualDesktopManager::self(), SIGNAL(countChanged(uint,uint)), focusChain, SLOT(resize(uint,uint))); connect(VirtualDesktopManager::self(), SIGNAL(currentChanged(uint,uint)), focusChain, SLOT(setCurrentDesktop(uint,uint))); connect(options, SIGNAL(separateScreenFocusChanged(bool)), focusChain, SLOT(setSeparateScreenFocus(bool))); focusChain->setSeparateScreenFocus(options->isSeparateScreenFocus()); // create VirtualDesktopManager and perform dependency injection VirtualDesktopManager *vds = VirtualDesktopManager::self(); connect(vds, &VirtualDesktopManager::desktopRemoved, this, [this](KWin::VirtualDesktop *desktop) { //Wayland if (kwinApp()->operationMode() == Application::OperationModeWaylandOnly || kwinApp()->operationMode() == Application::OperationModeXwayland) { for (auto it = m_allClients.constBegin(); it != m_allClients.constEnd(); ++it) { if (!(*it)->desktops().contains(desktop)) { continue; } if ((*it)->desktops().count() > 1) { (*it)->leaveDesktop(desktop); } else { sendClientToDesktop(*it, qMin(desktop->x11DesktopNumber(), VirtualDesktopManager::self()->count()), true); } } //X11 } else { for (auto it = m_allClients.constBegin(); it != m_allClients.constEnd(); ++it) { if (!(*it)->isOnAllDesktops() && ((*it)->desktop() > static_cast(VirtualDesktopManager::self()->count()))) { sendClientToDesktop(*it, VirtualDesktopManager::self()->count(), true); } } } } ); connect(vds, SIGNAL(countChanged(uint,uint)), SLOT(slotDesktopCountChanged(uint,uint))); connect(vds, SIGNAL(currentChanged(uint,uint)), SLOT(slotCurrentDesktopChanged(uint,uint))); vds->setNavigationWrappingAround(options->isRollOverDesktops()); connect(options, SIGNAL(rollOverDesktopsChanged(bool)), vds, SLOT(setNavigationWrappingAround(bool))); vds->setConfig(config); // Now we know how many desktops we'll have, thus we initialize the positioning object Placement::create(this); // positioning object needs to be created before the virtual desktops are loaded. vds->load(); vds->updateLayout(); //makes sure any autogenerated id is saved, necessary as in case of xwayland, load will be called 2 times // load is needed to be called again when starting xwayalnd to sync to RootInfo, see BUG 385260 vds->save(); if (!VirtualDesktopManager::self()->setCurrent(m_initialDesktop)) VirtualDesktopManager::self()->setCurrent(1); reconfigureTimer.setSingleShot(true); updateToolWindowsTimer.setSingleShot(true); connect(&reconfigureTimer, SIGNAL(timeout()), this, SLOT(slotReconfigure())); connect(&updateToolWindowsTimer, SIGNAL(timeout()), this, SLOT(slotUpdateToolWindows())); // TODO: do we really need to reconfigure everything when fonts change? // maybe just reconfigure the decorations? Move this into libkdecoration? QDBusConnection::sessionBus().connect(QString(), QStringLiteral("/KDEPlatformTheme"), QStringLiteral("org.kde.KDEPlatformTheme"), QStringLiteral("refreshFonts"), this, SLOT(reconfigure())); active_client = NULL; initWithX11(); Scripting::create(this); if (auto w = waylandServer()) { connect(w, &WaylandServer::shellClientAdded, this, [this] (ShellClient *c) { setupClientConnections(c); c->updateDecoration(false); updateClientLayer(c); if (!c->isInternal()) { QRect area = clientArea(PlacementArea, Screens::self()->current(), c->desktop()); bool placementDone = false; if (c->isInitialPositionSet()) { placementDone = true; } if (c->isFullScreen()) { placementDone = true; } if (c->maximizeMode() == MaximizeMode::MaximizeFull) { placementDone = true; } if (c->rules()->checkPosition(invalidPoint, true) != invalidPoint) { placementDone = true; } if (!placementDone) { c->placeIn(area); } m_allClients.append(c); if (!unconstrained_stacking_order.contains(c)) unconstrained_stacking_order.append(c); // Raise if it hasn't got any stacking position yet if (!stacking_order.contains(c)) // It'll be updated later, and updateToolWindows() requires stacking_order.append(c); // c to be in stacking_order } markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); if (c->wantsInput() && !c->isMinimized()) { activateClient(c); } updateTabbox(); connect(c, &ShellClient::windowShown, this, [this, c] { updateClientLayer(c); // TODO: when else should we send the client through placement? if (c->hasTransientPlacementHint()) { QRect area = clientArea(PlacementArea, Screens::self()->current(), c->desktop()); c->placeIn(area); } markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); if (c->wantsInput()) { activateClient(c); } } ); connect(c, &ShellClient::windowHidden, this, [this] { // TODO: update tabbox if it's displayed markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); } ); } ); connect(w, &WaylandServer::shellClientRemoved, this, [this] (ShellClient *c) { m_allClients.removeAll(c); if (c == most_recently_raised) { most_recently_raised = nullptr; } if (c == delayfocus_client) { cancelDelayFocus(); } if (c == last_active_client) { last_active_client = nullptr; } if (client_keys_client == c) { setupWindowShortcutDone(false); } if (!c->shortcut().isEmpty()) { c->setShortcut(QString()); // Remove from client_keys } clientHidden(c); emit clientRemoved(c); markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); updateTabbox(); } ); } // SELI TODO: This won't work with unreasonable focus policies, // and maybe in rare cases also if the selected client doesn't // want focus workspaceInit = false; // broadcast that Workspace is ready, but first process all events. QMetaObject::invokeMethod(this, "workspaceInitialized", Qt::QueuedConnection); // TODO: ungrabXServer() } void Workspace::initWithX11() { if (!kwinApp()->x11Connection()) { connect(kwinApp(), &Application::x11ConnectionChanged, this, &Workspace::initWithX11, Qt::UniqueConnection); return; } disconnect(kwinApp(), &Application::x11ConnectionChanged, this, &Workspace::initWithX11); atoms->retrieveHelpers(); // first initialize the extensions Xcb::Extensions::self(); ColorMapper *colormaps = new ColorMapper(this); connect(this, &Workspace::clientActivated, colormaps, &ColorMapper::update); // Call this before XSelectInput() on the root window startup = new KStartupInfo( KStartupInfo::DisableKWinModule | KStartupInfo::AnnounceSilenceChanges, this); // Select windowmanager privileges selectWmInputEventMask(); // Compatibility int32_t data = 1; xcb_change_property(connection(), XCB_PROP_MODE_APPEND, rootWindow(), atoms->kwin_running, atoms->kwin_running, 32, 1, &data); if (kwinApp()->operationMode() == Application::OperationModeX11) { m_wasUserInteractionFilter.reset(new WasUserInteractionX11Filter); m_movingClientFilter.reset(new MovingClientX11Filter); } updateXTime(); // Needed for proper initialization of user_time in Client ctor const uint32_t nullFocusValues[] = {true}; m_nullFocus.reset(new Xcb::Window(QRect(-1, -1, 1, 1), XCB_WINDOW_CLASS_INPUT_ONLY, XCB_CW_OVERRIDE_REDIRECT, nullFocusValues)); m_nullFocus->map(); RootInfo *rootInfo = RootInfo::create(); const auto vds = VirtualDesktopManager::self(); vds->setRootInfo(rootInfo); // load again to sync to RootInfo, see BUG 385260 vds->load(); vds->updateRootInfo(); rootInfo->setCurrentDesktop(vds->currentDesktop()->x11DesktopNumber()); // TODO: only in X11 mode // Extra NETRootInfo instance in Client mode is needed to get the values of the properties NETRootInfo client_info(connection(), NET::ActiveWindow | NET::CurrentDesktop); if (!qApp->isSessionRestored()) { m_initialDesktop = client_info.currentDesktop(); vds->setCurrent(m_initialDesktop); } // TODO: better value rootInfo->setActiveWindow(None); focusToNull(); if (!qApp->isSessionRestored()) ++block_focus; // Because it will be set below { // Begin updates blocker block StackingUpdatesBlocker blocker(this); Xcb::Tree tree(rootWindow()); xcb_window_t *wins = xcb_query_tree_children(tree.data()); QVector windowAttributes(tree->children_len); QVector windowGeometries(tree->children_len); // Request the attributes and geometries of all toplevel windows for (int i = 0; i < tree->children_len; i++) { windowAttributes[i] = Xcb::WindowAttributes(wins[i]); windowGeometries[i] = Xcb::WindowGeometry(wins[i]); } // Get the replies for (int i = 0; i < tree->children_len; i++) { Xcb::WindowAttributes attr(windowAttributes.at(i)); if (attr.isNull()) { continue; } if (attr->override_redirect) { if (attr->map_state == XCB_MAP_STATE_VIEWABLE && attr->_class != XCB_WINDOW_CLASS_INPUT_ONLY) // ### This will request the attributes again createUnmanaged(wins[i]); } else if (attr->map_state != XCB_MAP_STATE_UNMAPPED) { if (Application::wasCrash()) { fixPositionAfterCrash(wins[i], windowGeometries.at(i).data()); } // ### This will request the attributes again createClient(wins[i], true); } } // Propagate clients, will really happen at the end of the updates blocker block updateStackingOrder(true); saveOldScreenSizes(); updateClientArea(); // NETWM spec says we have to set it to (0,0) if we don't support it NETPoint* viewports = new NETPoint[VirtualDesktopManager::self()->count()]; rootInfo->setDesktopViewport(VirtualDesktopManager::self()->count(), *viewports); delete[] viewports; QRect geom; for (int i = 0; i < screens()->count(); i++) { geom |= screens()->geometry(i); } NETSize desktop_geometry; desktop_geometry.width = geom.width(); desktop_geometry.height = geom.height(); rootInfo->setDesktopGeometry(desktop_geometry); setShowingDesktop(false); } // End updates blocker block // TODO: only on X11? AbstractClient* new_active_client = nullptr; if (!qApp->isSessionRestored()) { --block_focus; new_active_client = findClient(Predicate::WindowMatch, client_info.activeWindow()); } if (new_active_client == NULL && activeClient() == NULL && should_get_focus.count() == 0) { // No client activated in manage() if (new_active_client == NULL) new_active_client = topClientOnDesktop(VirtualDesktopManager::self()->current(), -1); if (new_active_client == NULL && !desktops.isEmpty()) new_active_client = findDesktop(true, VirtualDesktopManager::self()->current()); } if (new_active_client != NULL) activateClient(new_active_client); } Workspace::~Workspace() { blockStackingUpdates(true); // TODO: grabXServer(); // Use stacking_order, so that kwin --replace keeps stacking order const ToplevelList stack = stacking_order; // "mutex" the stackingorder, since anything trying to access it from now on will find // many dangeling pointers and crash stacking_order.clear(); for (ToplevelList::const_iterator it = stack.constBegin(), end = stack.constEnd(); it != end; ++it) { Client *c = qobject_cast(const_cast(*it)); if (!c) { continue; } // Only release the window c->releaseWindow(true); // No removeClient() is called, it does more than just removing. // However, remove from some lists to e.g. prevent performTransiencyCheck() // from crashing. clients.removeAll(c); m_allClients.removeAll(c); desktops.removeAll(c); } Client::cleanupX11(); for (UnmanagedList::iterator it = unmanaged.begin(), end = unmanaged.end(); it != end; ++it) (*it)->release(ReleaseReason::KWinShutsDown); if (auto c = kwinApp()->x11Connection()) { xcb_delete_property(c, kwinApp()->x11RootWindow(), atoms->kwin_running); } for (auto it = deleted.begin(); it != deleted.end();) { emit deletedRemoved(*it); it = deleted.erase(it); } delete RuleBook::self(); kwinApp()->config()->sync(); RootInfo::destroy(); delete startup; delete Placement::self(); delete client_keys_dialog; foreach (SessionInfo * s, session) delete s; // TODO: ungrabXServer(); Xcb::Extensions::destroy(); _self = 0; } void Workspace::setupClientConnections(AbstractClient *c) { connect(c, &Toplevel::needsRepaint, m_compositor, &Compositor::scheduleRepaint); connect(c, &AbstractClient::desktopPresenceChanged, this, &Workspace::desktopPresenceChanged); connect(c, &AbstractClient::minimizedChanged, this, std::bind(&Workspace::clientMinimizedChanged, this, c)); } Client* Workspace::createClient(xcb_window_t w, bool is_mapped) { StackingUpdatesBlocker blocker(this); Client* c = new Client(); setupClientConnections(c); connect(c, &Client::blockingCompositingChanged, m_compositor, &Compositor::updateClientCompositeBlocking); connect(c, SIGNAL(clientFullScreenSet(KWin::Client*,bool,bool)), ScreenEdges::self(), SIGNAL(checkBlocking())); if (!c->manage(w, is_mapped)) { Client::deleteClient(c); return NULL; } addClient(c); return c; } Unmanaged* Workspace::createUnmanaged(xcb_window_t w) { if (m_compositor && m_compositor->checkForOverlayWindow(w)) return NULL; Unmanaged* c = new Unmanaged(); if (!c->track(w)) { Unmanaged::deleteUnmanaged(c); return NULL; } connect(c, &Unmanaged::needsRepaint, m_compositor, &Compositor::scheduleRepaint); addUnmanaged(c); emit unmanagedAdded(c); return c; } void Workspace::addClient(Client* c) { Group* grp = findGroup(c->window()); emit clientAdded(c); if (grp != NULL) grp->gotLeader(c); if (c->isDesktop()) { desktops.append(c); if (active_client == NULL && should_get_focus.isEmpty() && c->isOnCurrentDesktop()) requestFocus(c); // TODO: Make sure desktop is active after startup if there's no other window active } else { FocusChain::self()->update(c, FocusChain::Update); clients.append(c); m_allClients.append(c); } if (!unconstrained_stacking_order.contains(c)) unconstrained_stacking_order.append(c); // Raise if it hasn't got any stacking position yet if (!stacking_order.contains(c)) // It'll be updated later, and updateToolWindows() requires stacking_order.append(c); // c to be in stacking_order markXStackingOrderAsDirty(); updateClientArea(); // This cannot be in manage(), because the client got added only now updateClientLayer(c); if (c->isDesktop()) { raiseClient(c); // If there's no active client, make this desktop the active one if (activeClient() == NULL && should_get_focus.count() == 0) activateClient(findDesktop(true, VirtualDesktopManager::self()->current())); } c->checkActiveModal(); checkTransients(c->window()); // SELI TODO: Does this really belong here? updateStackingOrder(true); // Propagate new client if (c->isUtility() || c->isMenu() || c->isToolbar()) updateToolWindows(true); updateTabbox(); } void Workspace::addUnmanaged(Unmanaged* c) { unmanaged.append(c); markXStackingOrderAsDirty(); } /** * Destroys the client \a c - **/ + */ void Workspace::removeClient(Client* c) { if (c == active_popup_client) closeActivePopup(); if (m_userActionsMenu->isMenuClient(c)) { m_userActionsMenu->close(); } c->untab(QRect(), true); if (client_keys_client == c) setupWindowShortcutDone(false); if (!c->shortcut().isEmpty()) { c->setShortcut(QString()); // Remove from client_keys clientShortcutUpdated(c); // Needed, since this is otherwise delayed by setShortcut() and wouldn't run } Q_ASSERT(clients.contains(c) || desktops.contains(c)); // TODO: if marked client is removed, notify the marked list clients.removeAll(c); m_allClients.removeAll(c); desktops.removeAll(c); markXStackingOrderAsDirty(); attention_chain.removeAll(c); Group* group = findGroup(c->window()); if (group != NULL) group->lostLeader(); if (c == most_recently_raised) most_recently_raised = 0; should_get_focus.removeAll(c); Q_ASSERT(c != active_client); if (c == last_active_client) last_active_client = 0; if (c == delayfocus_client) cancelDelayFocus(); emit clientRemoved(c); updateStackingOrder(true); updateClientArea(); updateTabbox(); } void Workspace::removeUnmanaged(Unmanaged* c) { assert(unmanaged.contains(c)); unmanaged.removeAll(c); emit unmanagedRemoved(c); markXStackingOrderAsDirty(); } void Workspace::addDeleted(Deleted* c, Toplevel *orig) { assert(!deleted.contains(c)); deleted.append(c); const int unconstraintedIndex = unconstrained_stacking_order.indexOf(orig); if (unconstraintedIndex != -1) { unconstrained_stacking_order.replace(unconstraintedIndex, c); } else { unconstrained_stacking_order.append(c); } const int index = stacking_order.indexOf(orig); if (index != -1) { stacking_order.replace(index, c); } else { stacking_order.append(c); } markXStackingOrderAsDirty(); connect(c, &Deleted::needsRepaint, m_compositor, &Compositor::scheduleRepaint); } void Workspace::removeDeleted(Deleted* c) { assert(deleted.contains(c)); emit deletedRemoved(c); deleted.removeAll(c); unconstrained_stacking_order.removeAll(c); stacking_order.removeAll(c); markXStackingOrderAsDirty(); if (c->wasClient() && m_compositor) { m_compositor->updateCompositeBlocking(); } } void Workspace::updateToolWindows(bool also_hide) { // TODO: What if Client's transiency/group changes? should this be called too? (I'm paranoid, am I not?) if (!options->isHideUtilityWindowsForInactive()) { for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) if (!(*it)->tabGroup() || (*it)->tabGroup()->current() == *it) (*it)->hideClient(false); return; } const Group* group = nullptr; auto client = active_client; // Go up in transiency hiearchy, if the top is found, only tool transients for the top mainwindow // will be shown; if a group transient is group, all tools in the group will be shown while (client != nullptr) { if (!client->isTransient()) break; if (client->groupTransient()) { group = client->group(); break; } client = client->transientFor(); } // Use stacking order only to reduce flicker, it doesn't matter if block_stacking_updates == 0, // I.e. if it's not up to date // SELI TODO: But maybe it should - what if a new client has been added that's not in stacking order yet? QVector to_show, to_hide; for (ToplevelList::ConstIterator it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { auto c = qobject_cast(*it); if (!c) { continue; } if (c->isUtility() || c->isMenu() || c->isToolbar()) { bool show = true; if (!c->isTransient()) { if (!c->group() || c->group()->members().count() == 1) // Has its own group, keep always visible show = true; else if (client != NULL && c->group() == client->group()) show = true; else show = false; } else { if (group != NULL && c->group() == group) show = true; else if (client != NULL && client->hasTransient(c, true)) show = true; else show = false; } if (!show && also_hide) { const auto mainclients = c->mainClients(); // Don't hide utility windows which are standalone(?) or // have e.g. kicker as mainwindow if (mainclients.isEmpty()) show = true; for (auto it2 = mainclients.constBegin(); it2 != mainclients.constEnd(); ++it2) { if ((*it2)->isSpecialWindow()) show = true; } if (!show) to_hide.append(c); } if (show) to_show.append(c); } } // First show new ones, then hide for (int i = to_show.size() - 1; i >= 0; --i) // From topmost // TODO: Since this is in stacking order, the order of taskbar entries changes :( to_show.at(i)->hideClient(false); if (also_hide) { for (auto it = to_hide.constBegin(); it != to_hide.constEnd(); ++it) // From bottommost (*it)->hideClient(true); updateToolWindowsTimer.stop(); } else // setActiveClient() is after called with NULL client, quickly followed // by setting a new client, which would result in flickering resetUpdateToolWindowsTimer(); } void Workspace::resetUpdateToolWindowsTimer() { updateToolWindowsTimer.start(200); } void Workspace::slotUpdateToolWindows() { updateToolWindows(true); } void Workspace::slotReloadConfig() { reconfigure(); } void Workspace::reconfigure() { reconfigureTimer.start(200); } /** * Reread settings - **/ + */ void Workspace::slotReconfigure() { qCDebug(KWIN_CORE) << "Workspace::slotReconfigure()"; reconfigureTimer.stop(); bool borderlessMaximizedWindows = options->borderlessMaximizedWindows(); kwinApp()->config()->reparseConfiguration(); options->updateSettings(); emit configChanged(); m_userActionsMenu->discard(); updateToolWindows(true); RuleBook::self()->load(); for (auto it = m_allClients.begin(); it != m_allClients.end(); ++it) { (*it)->setupWindowRules(true); (*it)->applyWindowRules(); RuleBook::self()->discardUsed(*it, false); } if (borderlessMaximizedWindows != options->borderlessMaximizedWindows() && !options->borderlessMaximizedWindows()) { // in case borderless maximized windows option changed and new option // is to have borders, we need to unset the borders for all maximized windows for (auto it = m_allClients.begin(); it != m_allClients.end(); ++it) { if ((*it)->maximizeMode() == MaximizeFull) (*it)->checkNoBorder(); } } } void Workspace::slotCurrentDesktopChanged(uint oldDesktop, uint newDesktop) { closeActivePopup(); ++block_focus; StackingUpdatesBlocker blocker(this); updateClientVisibilityOnDesktopChange(newDesktop); // Restore the focus on this desktop --block_focus; activateClientOnNewDesktop(newDesktop); emit currentDesktopChanged(oldDesktop, movingClient); } void Workspace::updateClientVisibilityOnDesktopChange(uint newDesktop) { for (ToplevelList::ConstIterator it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { Client *c = qobject_cast(*it); if (!c) { continue; } if (!c->isOnDesktop(newDesktop) && c != movingClient && c->isOnCurrentActivity()) { (c)->updateVisibility(); } } // Now propagate the change, after hiding, before showing if (rootInfo()) { rootInfo()->setCurrentDesktop(VirtualDesktopManager::self()->current()); } if (movingClient && !movingClient->isOnDesktop(newDesktop)) { movingClient->setDesktop(newDesktop); } for (int i = stacking_order.size() - 1; i >= 0 ; --i) { Client *c = qobject_cast(stacking_order.at(i)); if (!c) { continue; } if (c->isOnDesktop(newDesktop) && c->isOnCurrentActivity()) c->updateVisibility(); } if (showingDesktop()) // Do this only after desktop change to avoid flicker setShowingDesktop(false); } void Workspace::activateClientOnNewDesktop(uint desktop) { AbstractClient* c = NULL; if (options->focusPolicyIsReasonable()) { c = findClientToActivateOnDesktop(desktop); } // If "unreasonable focus policy" and active_client is on_all_desktops and // under mouse (Hence == old_active_client), conserve focus. // (Thanks to Volker Schatz ) else if (active_client && active_client->isShown(true) && active_client->isOnCurrentDesktop()) c = active_client; if (c == NULL && !desktops.isEmpty()) c = findDesktop(true, desktop); if (c != active_client) setActiveClient(NULL); if (c) requestFocus(c); else if (!desktops.isEmpty()) requestFocus(findDesktop(true, desktop)); else focusToNull(); } AbstractClient *Workspace::findClientToActivateOnDesktop(uint desktop) { if (movingClient != NULL && active_client == movingClient && FocusChain::self()->contains(active_client, desktop) && active_client->isShown(true) && active_client->isOnCurrentDesktop()) { // A requestFocus call will fail, as the client is already active return active_client; } // from actiavtion.cpp if (options->isNextFocusPrefersMouse()) { ToplevelList::const_iterator it = stackingOrder().constEnd(); while (it != stackingOrder().constBegin()) { Client *client = qobject_cast(*(--it)); if (!client) { continue; } if (!(client->isShown(false) && client->isOnDesktop(desktop) && client->isOnCurrentActivity() && client->isOnActiveScreen())) continue; if (client->geometry().contains(Cursor::pos())) { if (!client->isDesktop()) return client; break; // unconditional break - we do not pass the focus to some client below an unusable one } } } return FocusChain::self()->getForActivation(desktop); } /** * Updates the current activity when it changes * do *not* call this directly; it does not set the activity. * * Shows/Hides windows according to the stacking order - **/ + */ void Workspace::updateCurrentActivity(const QString &new_activity) { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return; } //closeActivePopup(); ++block_focus; // TODO: Q_ASSERT( block_stacking_updates == 0 ); // Make sure stacking_order is up to date StackingUpdatesBlocker blocker(this); // Optimized Desktop switching: unmapping done from back to front // mapping done from front to back => less exposure events //Notify::raise((Notify::Event) (Notify::DesktopChange+new_desktop)); for (ToplevelList::ConstIterator it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { Client *c = qobject_cast(*it); if (!c) { continue; } if (!c->isOnActivity(new_activity) && c != movingClient && c->isOnCurrentDesktop()) { c->updateVisibility(); } } // Now propagate the change, after hiding, before showing //rootInfo->setCurrentDesktop( currentDesktop() ); /* TODO someday enable dragging windows to other activities if ( movingClient && !movingClient->isOnDesktop( new_desktop )) { movingClient->setDesktop( new_desktop ); */ for (int i = stacking_order.size() - 1; i >= 0 ; --i) { Client *c = qobject_cast(stacking_order.at(i)); if (!c) { continue; } if (c->isOnActivity(new_activity)) c->updateVisibility(); } //FIXME not sure if I should do this either if (showingDesktop()) // Do this only after desktop change to avoid flicker setShowingDesktop(false); // Restore the focus on this desktop --block_focus; AbstractClient* c = 0; //FIXME below here is a lot of focuschain stuff, probably all wrong now if (options->focusPolicyIsReasonable()) { // Search in focus chain c = FocusChain::self()->getForActivation(VirtualDesktopManager::self()->current()); } // If "unreasonable focus policy" and active_client is on_all_desktops and // under mouse (Hence == old_active_client), conserve focus. // (Thanks to Volker Schatz ) else if (active_client && active_client->isShown(true) && active_client->isOnCurrentDesktop() && active_client->isOnCurrentActivity()) c = active_client; if (c == NULL && !desktops.isEmpty()) c = findDesktop(true, VirtualDesktopManager::self()->current()); if (c != active_client) setActiveClient(NULL); if (c) requestFocus(c); else if (!desktops.isEmpty()) requestFocus(findDesktop(true, VirtualDesktopManager::self()->current())); else focusToNull(); // Not for the very first time, only if something changed and there are more than 1 desktops //if ( effects != NULL && old_desktop != 0 && old_desktop != new_desktop ) // static_cast( effects )->desktopChanged( old_desktop ); if (compositing() && m_compositor) m_compositor->addRepaintFull(); #else Q_UNUSED(new_activity) #endif } void Workspace::slotDesktopCountChanged(uint previousCount, uint newCount) { Q_UNUSED(previousCount) Placement::self()->reinitCascading(0); resetClientAreas(newCount); } void Workspace::resetClientAreas(uint desktopCount) { // Make it +1, so that it can be accessed as [1..numberofdesktops] workarea.clear(); workarea.resize(desktopCount + 1); restrictedmovearea.clear(); restrictedmovearea.resize(desktopCount + 1); screenarea.clear(); updateClientArea(true); } void Workspace::selectWmInputEventMask() { uint32_t presentMask = 0; Xcb::WindowAttributes attr(rootWindow()); if (!attr.isNull()) { presentMask = attr->your_event_mask; } Xcb::selectInput(rootWindow(), presentMask | XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_COLOR_MAP_CHANGE | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_FOCUS_CHANGE | // For NotifyDetailNone XCB_EVENT_MASK_EXPOSURE ); } /** * Sends client \a c to desktop \a desk. * * Takes care of transients as well. - **/ + */ void Workspace::sendClientToDesktop(AbstractClient* c, int desk, bool dont_activate) { if ((desk < 1 && desk != NET::OnAllDesktops) || desk > static_cast(VirtualDesktopManager::self()->count())) return; int old_desktop = c->desktop(); bool was_on_desktop = c->isOnDesktop(desk) || c->isOnAllDesktops(); c->setDesktop(desk); if (c->desktop() != desk) // No change or desktop forced return; desk = c->desktop(); // Client did range checking if (c->isOnDesktop(VirtualDesktopManager::self()->current())) { if (c->wantsTabFocus() && options->focusPolicyIsReasonable() && !was_on_desktop && // for stickyness changes !dont_activate) requestFocus(c); else restackClientUnderActive(c); } else raiseClient(c); c->checkWorkspacePosition( QRect(), old_desktop ); auto transients_stacking_order = ensureStackingOrder(c->transients()); for (auto it = transients_stacking_order.constBegin(); it != transients_stacking_order.constEnd(); ++it) sendClientToDesktop(*it, desk, dont_activate); updateClientArea(); } /** * checks whether the X Window with the input focus is on our X11 screen * if the window cannot be determined or inspected, resturn depends on whether there's actually * more than one screen * * this is NOT in any way related to XRandR multiscreen * - **/ + */ extern bool is_multihead; // main.cpp bool Workspace::isOnCurrentHead() { if (!is_multihead) { return true; } Xcb::CurrentInput currentInput; if (currentInput.window() == XCB_WINDOW_NONE) { return !is_multihead; } Xcb::WindowGeometry geometry(currentInput.window()); if (geometry.isNull()) { // should not happen return !is_multihead; } return rootWindow() == geometry->root; } void Workspace::sendClientToScreen(AbstractClient* c, int screen) { c->sendToScreen(screen); } void Workspace::sendPingToWindow(xcb_window_t window, xcb_timestamp_t timestamp) { if (rootInfo()) { rootInfo()->sendPing(window, timestamp); } } /** * Delayed focus functions - **/ + */ void Workspace::delayFocus() { requestFocus(delayfocus_client); cancelDelayFocus(); } void Workspace::requestDelayFocus(AbstractClient* c) { delayfocus_client = c; delete delayFocusTimer; delayFocusTimer = new QTimer(this); connect(delayFocusTimer, SIGNAL(timeout()), this, SLOT(delayFocus())); delayFocusTimer->setSingleShot(true); delayFocusTimer->start(options->delayFocusInterval()); } void Workspace::cancelDelayFocus() { delete delayFocusTimer; delayFocusTimer = 0; } bool Workspace::checkStartupNotification(xcb_window_t w, KStartupInfoId &id, KStartupInfoData &data) { return startup->checkStartup(w, id, data) == KStartupInfo::Match; } /** * Puts the focus on a dummy window * Just using XSetInputFocus() with None would block keyboard input - **/ + */ void Workspace::focusToNull() { if (m_nullFocus) { m_nullFocus->focus(); } } void Workspace::setShowingDesktop(bool showing) { const bool changed = showing != showing_desktop; if (rootInfo() && changed) { rootInfo()->setShowingDesktop(showing); } showing_desktop = showing; AbstractClient *topDesk = nullptr; { // for the blocker RAII StackingUpdatesBlocker blocker(this); // updateLayer & lowerClient would invalidate stacking_order for (int i = stacking_order.count() - 1; i > -1; --i) { AbstractClient *c = qobject_cast(stacking_order.at(i)); if (c && c->isOnCurrentDesktop()) { if (c->isDock()) { c->updateLayer(); } else if (c->isDesktop() && c->isShown(true)) { c->updateLayer(); lowerClient(c); if (!topDesk) topDesk = c; if (auto group = c->group()) { foreach (Client *cm, group->members()) { cm->updateLayer(); } } } } } } // ~StackingUpdatesBlocker if (showing_desktop && topDesk) { requestFocus(topDesk); } else if (!showing_desktop && changed) { const auto client = FocusChain::self()->getForActivation(VirtualDesktopManager::self()->current()); if (client) { activateClient(client); } } if (changed) emit showingDesktopChanged(showing); } void Workspace::disableGlobalShortcutsForClient(bool disable) { if (global_shortcuts_disabled_for_client == disable) return; QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.kglobalaccel"), QStringLiteral("/kglobalaccel"), QStringLiteral("org.kde.KGlobalAccel"), QStringLiteral("blockGlobalShortcuts")); message.setArguments(QList() << disable); QDBusConnection::sessionBus().asyncCall(message); global_shortcuts_disabled_for_client = disable; // Update also Alt+LMB actions etc. for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it) (*it)->updateMouseGrab(); } QString Workspace::supportInformation() const { QString support; const QString yes = QStringLiteral("yes\n"); const QString no = QStringLiteral("no\n"); support.append(ki18nc("Introductory text shown in the support information.", "KWin Support Information:\n" "The following information should be used when requesting support on e.g. https://forum.kde.org.\n" "It provides information about the currently running instance, which options are used,\n" "what OpenGL driver and which effects are running.\n" "Please post the information provided underneath this introductory text to a paste bin service\n" "like https://paste.kde.org instead of pasting into support threads.\n").toString()); support.append(QStringLiteral("\n==========================\n\n")); // all following strings are intended for support. They need to be pasted to e.g forums.kde.org // it is expected that the support will happen in English language or that the people providing // help understand English. Because of that all texts are not translated support.append(QStringLiteral("Version\n")); support.append(QStringLiteral("=======\n")); support.append(QStringLiteral("KWin version: ")); support.append(QStringLiteral(KWIN_VERSION_STRING)); support.append(QStringLiteral("\n")); support.append(QStringLiteral("Qt Version: ")); support.append(QString::fromUtf8(qVersion())); support.append(QStringLiteral("\n")); support.append(QStringLiteral("Qt compile version: %1\n").arg(QStringLiteral(QT_VERSION_STR))); support.append(QStringLiteral("XCB compile version: %1\n\n").arg(QStringLiteral(XCB_VERSION_STRING))); support.append(QStringLiteral("Operation Mode: ")); switch (kwinApp()->operationMode()) { case Application::OperationModeX11: support.append(QStringLiteral("X11 only")); break; case Application::OperationModeWaylandOnly: support.append(QStringLiteral("Wayland Only")); break; case Application::OperationModeXwayland: support.append(QStringLiteral("Xwayland")); break; } support.append(QStringLiteral("\n\n")); support.append(QStringLiteral("Build Options\n")); support.append(QStringLiteral("=============\n")); support.append(QStringLiteral("KWIN_BUILD_DECORATIONS: ")); #ifdef KWIN_BUILD_DECORATIONS support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("KWIN_BUILD_TABBOX: ")); #ifdef KWIN_BUILD_TABBOX support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("KWIN_BUILD_ACTIVITIES: ")); #ifdef KWIN_BUILD_ACTIVITIES support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_DRM: ")); #if HAVE_DRM support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_GBM: ")); #if HAVE_GBM support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_EGL_STREAMS: ")); #if HAVE_EGL_STREAMS support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_X11_XCB: ")); #if HAVE_X11_XCB support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_EPOXY_GLX: ")); #if HAVE_EPOXY_GLX support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("HAVE_WAYLAND_EGL: ")); #if HAVE_WAYLAND_EGL support.append(yes); #else support.append(no); #endif support.append(QStringLiteral("\n")); if (auto c = kwinApp()->x11Connection()) { support.append(QStringLiteral("X11\n")); support.append(QStringLiteral("===\n")); auto x11setup = xcb_get_setup(c); support.append(QStringLiteral("Vendor: %1\n").arg(QString::fromUtf8(QByteArray::fromRawData(xcb_setup_vendor(x11setup), xcb_setup_vendor_length(x11setup))))); support.append(QStringLiteral("Vendor Release: %1\n").arg(x11setup->release_number)); support.append(QStringLiteral("Protocol Version/Revision: %1/%2\n").arg(x11setup->protocol_major_version).arg(x11setup->protocol_minor_version)); const auto extensions = Xcb::Extensions::self()->extensions(); for (const auto &e : extensions) { support.append(QStringLiteral("%1: %2; Version: 0x%3\n").arg(QString::fromUtf8(e.name)) .arg(e.present ? yes.trimmed() : no.trimmed()) .arg(QString::number(e.version, 16))); } support.append(QStringLiteral("\n")); } if (auto bridge = Decoration::DecorationBridge::self()) { support.append(QStringLiteral("Decoration\n")); support.append(QStringLiteral("==========\n")); support.append(bridge->supportInformation()); support.append(QStringLiteral("\n")); } support.append(QStringLiteral("Platform\n")); support.append(QStringLiteral("==========\n")); support.append(kwinApp()->platform()->supportInformation()); support.append(QStringLiteral("\n")); support.append(QStringLiteral("Options\n")); support.append(QStringLiteral("=======\n")); const QMetaObject *metaOptions = options->metaObject(); auto printProperty = [] (const QVariant &variant) { if (variant.type() == QVariant::Size) { const QSize &s = variant.toSize(); return QStringLiteral("%1x%2").arg(QString::number(s.width())).arg(QString::number(s.height())); } if (QLatin1String(variant.typeName()) == QLatin1String("KWin::OpenGLPlatformInterface") || QLatin1String(variant.typeName()) == QLatin1String("KWin::Options::WindowOperation")) { return QString::number(variant.toInt()); } return variant.toString(); }; for (int i=0; ipropertyCount(); ++i) { const QMetaProperty property = metaOptions->property(i); if (QLatin1String(property.name()) == QLatin1String("objectName")) { continue; } support.append(QStringLiteral("%1: %2\n").arg(property.name()).arg(printProperty(options->property(property.name())))); } support.append(QStringLiteral("\nScreen Edges\n")); support.append(QStringLiteral( "============\n")); const QMetaObject *metaScreenEdges = ScreenEdges::self()->metaObject(); for (int i=0; ipropertyCount(); ++i) { const QMetaProperty property = metaScreenEdges->property(i); if (QLatin1String(property.name()) == QLatin1String("objectName")) { continue; } support.append(QStringLiteral("%1: %2\n").arg(property.name()).arg(printProperty(ScreenEdges::self()->property(property.name())))); } support.append(QStringLiteral("\nScreens\n")); support.append(QStringLiteral( "=======\n")); support.append(QStringLiteral("Multi-Head: ")); if (is_multihead) { support.append(QStringLiteral("yes\n")); support.append(QStringLiteral("Head: %1\n").arg(screen_number)); } else { support.append(QStringLiteral("no\n")); } support.append(QStringLiteral("Active screen follows mouse: ")); if (screens()->isCurrentFollowsMouse()) support.append(QStringLiteral(" yes\n")); else support.append(QStringLiteral(" no\n")); support.append(QStringLiteral("Number of Screens: %1\n\n").arg(screens()->count())); for (int i=0; icount(); ++i) { const QRect geo = screens()->geometry(i); support.append(QStringLiteral("Screen %1:\n").arg(i)); support.append(QStringLiteral("---------\n")); support.append(QStringLiteral("Name: %1\n").arg(screens()->name(i))); support.append(QStringLiteral("Geometry: %1,%2,%3x%4\n") .arg(geo.x()) .arg(geo.y()) .arg(geo.width()) .arg(geo.height())); support.append(QStringLiteral("Scale: %1\n").arg(screens()->scale(i))); support.append(QStringLiteral("Refresh Rate: %1\n\n").arg(screens()->refreshRate(i))); } support.append(QStringLiteral("\nCompositing\n")); support.append(QStringLiteral( "===========\n")); if (effects) { support.append(QStringLiteral("Compositing is active\n")); switch (effects->compositingType()) { case OpenGL2Compositing: case OpenGLCompositing: { GLPlatform *platform = GLPlatform::instance(); if (platform->isGLES()) { support.append(QStringLiteral("Compositing Type: OpenGL ES 2.0\n")); } else { support.append(QStringLiteral("Compositing Type: OpenGL\n")); } support.append(QStringLiteral("OpenGL vendor string: ") + QString::fromUtf8(platform->glVendorString()) + QStringLiteral("\n")); support.append(QStringLiteral("OpenGL renderer string: ") + QString::fromUtf8(platform->glRendererString()) + QStringLiteral("\n")); support.append(QStringLiteral("OpenGL version string: ") + QString::fromUtf8(platform->glVersionString()) + QStringLiteral("\n")); support.append(QStringLiteral("OpenGL platform interface: ")); switch (platform->platformInterface()) { case GlxPlatformInterface: support.append(QStringLiteral("GLX")); break; case EglPlatformInterface: support.append(QStringLiteral("EGL")); break; default: support.append(QStringLiteral("UNKNOWN")); } support.append(QStringLiteral("\n")); if (platform->supports(LimitedGLSL) || platform->supports(GLSL)) support.append(QStringLiteral("OpenGL shading language version string: ") + QString::fromUtf8(platform->glShadingLanguageVersionString()) + QStringLiteral("\n")); support.append(QStringLiteral("Driver: ") + GLPlatform::driverToString(platform->driver()) + QStringLiteral("\n")); if (!platform->isMesaDriver()) support.append(QStringLiteral("Driver version: ") + GLPlatform::versionToString(platform->driverVersion()) + QStringLiteral("\n")); support.append(QStringLiteral("GPU class: ") + GLPlatform::chipClassToString(platform->chipClass()) + QStringLiteral("\n")); support.append(QStringLiteral("OpenGL version: ") + GLPlatform::versionToString(platform->glVersion()) + QStringLiteral("\n")); if (platform->supports(LimitedGLSL) || platform->supports(GLSL)) support.append(QStringLiteral("GLSL version: ") + GLPlatform::versionToString(platform->glslVersion()) + QStringLiteral("\n")); if (platform->isMesaDriver()) support.append(QStringLiteral("Mesa version: ") + GLPlatform::versionToString(platform->mesaVersion()) + QStringLiteral("\n")); if (platform->serverVersion() > 0) support.append(QStringLiteral("X server version: ") + GLPlatform::versionToString(platform->serverVersion()) + QStringLiteral("\n")); if (platform->kernelVersion() > 0) support.append(QStringLiteral("Linux kernel version: ") + GLPlatform::versionToString(platform->kernelVersion()) + QStringLiteral("\n")); support.append(QStringLiteral("Direct rendering: ")); support.append(QStringLiteral("Requires strict binding: ")); if (!platform->isLooseBinding()) { support.append(QStringLiteral("yes\n")); } else { support.append(QStringLiteral("no\n")); } support.append(QStringLiteral("GLSL shaders: ")); if (platform->supports(GLSL)) { if (platform->supports(LimitedGLSL)) { support.append(QStringLiteral(" limited\n")); } else { support.append(QStringLiteral(" yes\n")); } } else { support.append(QStringLiteral(" no\n")); } support.append(QStringLiteral("Texture NPOT support: ")); if (platform->supports(TextureNPOT)) { if (platform->supports(LimitedNPOT)) { support.append(QStringLiteral(" limited\n")); } else { support.append(QStringLiteral(" yes\n")); } } else { support.append(QStringLiteral(" no\n")); } support.append(QStringLiteral("Virtual Machine: ")); if (platform->isVirtualMachine()) { support.append(QStringLiteral(" yes\n")); } else { support.append(QStringLiteral(" no\n")); } support.append(QStringLiteral("OpenGL 2 Shaders are used\n")); support.append(QStringLiteral("Painting blocks for vertical retrace: ")); if (m_compositor->scene()->blocksForRetrace()) support.append(QStringLiteral(" yes\n")); else support.append(QStringLiteral(" no\n")); break; } case XRenderCompositing: support.append(QStringLiteral("Compositing Type: XRender\n")); break; case QPainterCompositing: support.append("Compositing Type: QPainter\n"); break; case NoCompositing: default: support.append(QStringLiteral("Something is really broken, neither OpenGL nor XRender is used")); } support.append(QStringLiteral("\nLoaded Effects:\n")); support.append(QStringLiteral( "---------------\n")); foreach (const QString &effect, static_cast(effects)->loadedEffects()) { support.append(effect + QStringLiteral("\n")); } support.append(QStringLiteral("\nCurrently Active Effects:\n")); support.append(QStringLiteral( "-------------------------\n")); foreach (const QString &effect, static_cast(effects)->activeEffects()) { support.append(effect + QStringLiteral("\n")); } support.append(QStringLiteral("\nEffect Settings:\n")); support.append(QStringLiteral( "----------------\n")); foreach (const QString &effect, static_cast(effects)->loadedEffects()) { support.append(static_cast(effects)->supportInformation(effect)); support.append(QStringLiteral("\n")); } } else { support.append(QStringLiteral("Compositing is not active\n")); } return support; } Client *Workspace::findClient(std::function func) const { if (Client *ret = Toplevel::findInList(clients, func)) { return ret; } if (Client *ret = Toplevel::findInList(desktops, func)) { return ret; } return nullptr; } AbstractClient *Workspace::findAbstractClient(std::function func) const { if (AbstractClient *ret = Toplevel::findInList(m_allClients, func)) { return ret; } if (Client *ret = Toplevel::findInList(desktops, func)) { return ret; } if (waylandServer()) { if (AbstractClient *ret = Toplevel::findInList(waylandServer()->internalClients(), func)) { return ret; } } return nullptr; } Unmanaged *Workspace::findUnmanaged(std::function func) const { return Toplevel::findInList(unmanaged, func); } Unmanaged *Workspace::findUnmanaged(xcb_window_t w) const { return findUnmanaged([w](const Unmanaged *u) { return u->window() == w; }); } Client *Workspace::findClient(Predicate predicate, xcb_window_t w) const { switch (predicate) { case Predicate::WindowMatch: return findClient([w](const Client *c) { return c->window() == w; }); case Predicate::WrapperIdMatch: return findClient([w](const Client *c) { return c->wrapperId() == w; }); case Predicate::FrameIdMatch: return findClient([w](const Client *c) { return c->frameId() == w; }); case Predicate::InputIdMatch: return findClient([w](const Client *c) { return c->inputId() == w; }); } return nullptr; } Toplevel *Workspace::findToplevel(std::function func) const { if (Client *ret = Toplevel::findInList(clients, func)) { return ret; } if (Client *ret = Toplevel::findInList(desktops, func)) { return ret; } if (Unmanaged *ret = Toplevel::findInList(unmanaged, func)) { return ret; } return nullptr; } Toplevel *Workspace::findToplevel(QWindow *w) const { if (!w) { return nullptr; } if (waylandServer()) { if (auto c = waylandServer()->findClient(w)) { return c; } } return findUnmanaged(w->winId()); } bool Workspace::hasClient(const AbstractClient *c) { if (auto cc = dynamic_cast(c)) { return hasClient(cc); } else { return findAbstractClient([c](const AbstractClient *test) { return test == c; }) != nullptr; } return false; } void Workspace::forEachAbstractClient(std::function< void (AbstractClient*) > func) { std::for_each(m_allClients.constBegin(), m_allClients.constEnd(), func); std::for_each(desktops.constBegin(), desktops.constEnd(), func); } Toplevel *Workspace::findInternal(QWindow *w) const { if (!w) { return nullptr; } if (kwinApp()->operationMode() == Application::OperationModeX11) { return findUnmanaged(w->winId()); } else { return waylandServer()->findClient(w); } } bool Workspace::compositing() const { return m_compositor && m_compositor->hasScene(); } void Workspace::markXStackingOrderAsDirty() { m_xStackingDirty = true; if (kwinApp()->x11Connection()) { m_xStackingQueryTree.reset(new Xcb::Tree(kwinApp()->x11RootWindow())); } } void Workspace::setWasUserInteraction() { if (was_user_interaction) { return; } was_user_interaction = true; // might be called from within the filter, so delay till we now the filter returned QTimer::singleShot(0, this, [this] { m_wasUserInteractionFilter.reset(); } ); } void Workspace::updateTabbox() { #ifdef KWIN_BUILD_TABBOX if (TabBox::TabBox::self()->isDisplayed()) { TabBox::TabBox::self()->reset(true); } #endif } } // namespace diff --git a/workspace.h b/workspace.h index bef70a983..2079d56dc 100644 --- a/workspace.h +++ b/workspace.h @@ -1,780 +1,780 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. 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_WORKSPACE_H #define KWIN_WORKSPACE_H // kwin #include "sm.h" #include "options.h" #include "utils.h" // Qt #include #include // std #include #include // TODO: Cleanup the order of things in this .h file class QStringList; class KConfig; class KConfigGroup; class KStartupInfo; class KStartupInfoId; class KStartupInfoData; namespace KWin { namespace Xcb { class Tree; class Window; } class AbstractClient; class Client; class KillWindow; class ShortcutDialog; class UserActionsMenu; class Compositor; class X11EventFilter; enum class Predicate; class KWIN_EXPORT Workspace : public QObject { Q_OBJECT public: explicit Workspace(const QString &sessionKey = QString()); ~Workspace() override; static Workspace* self() { return _self; } bool workspaceEvent(xcb_generic_event_t*); bool workspaceEvent(QEvent*); bool hasClient(const Client*); bool hasClient(const AbstractClient*); /** * @brief Finds the first Client matching the condition expressed by passed in @p func. * * Internally findClient uses the std::find_if algorithm and that determines how the function * needs to be implemented. An example usage for finding a Client with a matching windowId * @code * xcb_window_t w; // our test window * Client *client = findClient([w](const Client *c) -> bool { * return c->window() == w; * }); * @endcode * * For the standard cases of matching the window id with one of the Client's windows use * the simplified overload method findClient(Predicate, xcb_window_t). Above example * can be simplified to: * @code * xcb_window_t w; // our test window * Client *client = findClient(Predicate::WindowMatch, w); * @endcode * * @param func Unary function that accepts a Client* as argument and * returns a value convertible to bool. The value returned indicates whether the * Client* is considered a match in the context of this function. * The function shall not modify its argument. * This can either be a function pointer or a function object. * @return KWin::Client* The found Client or @c null * @see findClient(Predicate, xcb_window_t) - **/ + */ Client *findClient(std::function func) const; AbstractClient *findAbstractClient(std::function func) const; /** * @brief Finds the Client matching the given match @p predicate for the given window. * * @param predicate Which window should be compared * @param w The window id to test against * @return KWin::Client* The found Client or @c null * @see findClient(std::function) - **/ + */ Client *findClient(Predicate predicate, xcb_window_t w) const; void forEachClient(std::function func); void forEachAbstractClient(std::function func); Unmanaged *findUnmanaged(std::function func) const; /** * @brief Finds the Unmanaged with the given window id. * * @param w The window id to search for * @return KWin::Unmanaged* Found Unmanaged or @c null if there is no Unmanaged with given Id. - **/ + */ Unmanaged *findUnmanaged(xcb_window_t w) const; void forEachUnmanaged(std::function func); Toplevel *findToplevel(std::function func) const; /** * Finds the Toplevel for the KWin internal window @p w. * On Wayland this is normally a ShellClient. For X11 an Unmanaged. - **/ + */ Toplevel *findToplevel(QWindow *w) const; /** * @brief Finds a Toplevel for the internal window @p w. * * Internal window means a window created by KWin itself. On X11 this is an Unmanaged * and mapped by the window id, on Wayland a ShellClient mapped on the internal window id. * * @returns Toplevel - **/ + */ Toplevel *findInternal(QWindow *w) const; QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const; QRect clientArea(clientAreaOption, const AbstractClient* c) const; QRect clientArea(clientAreaOption, int screen, int desktop) const; QRegion restrictedMoveArea(int desktop, StrutAreas areas = StrutAreaAll) const; bool initializing() const; /** * Returns the active client, i.e. the client that has the focus (or None * if no client has the focus) - **/ + */ AbstractClient* activeClient() const; /** * Client that was activated, but it's not yet really activeClient(), because * we didn't process yet the matching FocusIn event. Used mostly in focus * stealing prevention code. - **/ + */ AbstractClient* mostRecentlyActivatedClient() const; AbstractClient* clientUnderMouse(int screen) const; void activateClient(AbstractClient*, bool force = false); void requestFocus(AbstractClient* c, bool force = false); enum ActivityFlag { ActivityFocus = 1 << 0, // focus the window ActivityFocusForce = 1 << 1 | ActivityFocus, // focus even if Dock etc. ActivityRaise = 1 << 2 // raise the window }; Q_DECLARE_FLAGS(ActivityFlags, ActivityFlag) void takeActivity(AbstractClient* c, ActivityFlags flags); bool allowClientActivation(const AbstractClient* c, xcb_timestamp_t time = -1U, bool focus_in = false, bool ignore_desktop = false); void restoreFocus(); void gotFocusIn(const AbstractClient*); void setShouldGetFocus(AbstractClient*); bool activateNextClient(AbstractClient* c); bool focusChangeEnabled() { return block_focus == 0; } /** * Indicates that the client c is being moved or resized by the user. - **/ + */ void setMoveResizeClient(AbstractClient* c); QPoint adjustClientPosition(AbstractClient* c, QPoint pos, bool unrestricted, double snapAdjust = 1.0); QRect adjustClientSize(AbstractClient* c, QRect moveResizeGeom, int mode); void raiseClient(AbstractClient* c, bool nogroup = false); void lowerClient(AbstractClient* c, bool nogroup = false); void raiseClientRequest(AbstractClient* c, NET::RequestSource src = NET::FromApplication, xcb_timestamp_t timestamp = 0); void lowerClientRequest(Client* c, NET::RequestSource src, xcb_timestamp_t timestamp); void lowerClientRequest(AbstractClient* c); void restackClientUnderActive(AbstractClient*); void restack(AbstractClient *c, AbstractClient *under, bool force = false); void updateClientLayer(AbstractClient* c); void raiseOrLowerClient(AbstractClient*); void resetUpdateToolWindowsTimer(); void restoreSessionStackingOrder(Client* c); void updateStackingOrder(bool propagate_new_clients = false); void forceRestacking(); void clientHidden(AbstractClient*); void clientAttentionChanged(AbstractClient* c, bool set); /** * @return List of clients currently managed by Workspace - **/ + */ const ClientList &clientList() const { return clients; } /** * @return List of unmanaged "clients" currently registered in Workspace - **/ + */ const UnmanagedList &unmanagedList() const { return unmanaged; } /** * @return List of desktop "clients" currently managed by Workspace - **/ + */ const ClientList &desktopList() const { return desktops; } /** * @return List of deleted "clients" currently managed by Workspace - **/ + */ const DeletedList &deletedList() const { return deleted; } /** * @returns List of all clients (either X11 or Wayland) currently managed by Workspace - **/ + */ const QList allClientList() const { return m_allClients; } void stackScreenEdgesUnderOverrideRedirect(); public: QPoint cascadeOffset(const AbstractClient *c) const; private: Compositor *m_compositor; //------------------------------------------------- // Unsorted public: bool isOnCurrentHead(); // True when performing Workspace::updateClientArea(). // The calls below are valid only in that case. bool inUpdateClientArea() const; QRegion previousRestrictedMoveArea(int desktop, StrutAreas areas = StrutAreaAll) const; QVector< QRect > previousScreenSizes() const; int oldDisplayWidth() const; int oldDisplayHeight() const; /** * Returns the list of clients sorted in stacking order, with topmost client * at the last position - **/ + */ const ToplevelList& stackingOrder() const; ToplevelList xStackingOrder() const; ClientList ensureStackingOrder(const ClientList& clients) const; QList ensureStackingOrder(const QList &clients) const; AbstractClient* topClientOnDesktop(int desktop, int screen, bool unconstrained = false, bool only_normal = true) const; AbstractClient* findDesktop(bool topmost, int desktop) const; void sendClientToDesktop(AbstractClient* c, int desktop, bool dont_activate); void windowToPreviousDesktop(AbstractClient* c); void windowToNextDesktop(AbstractClient* c); void sendClientToScreen(AbstractClient* c, int screen); void addManualOverlay(xcb_window_t id) { manual_overlays << id; } void removeManualOverlay(xcb_window_t id) { manual_overlays.removeOne(id); } /** * Shows the menu operations menu for the client and makes it active if * it's not already. - **/ + */ void showWindowMenu(const QRect& pos, AbstractClient* cl); const UserActionsMenu *userActionsMenu() const { return m_userActionsMenu; } void showApplicationMenu(const QRect &pos, AbstractClient *c, int actionId); void updateMinimizedOfTransients(AbstractClient*); void updateOnAllDesktopsOfTransients(AbstractClient*); void checkTransients(xcb_window_t w); void storeSession(KConfig* config, SMSavePhase phase); void storeClient(KConfigGroup &cg, int num, Client *c); void storeSubSession(const QString &name, QSet sessionIds); void loadSubSessionInfo(const QString &name); SessionInfo* takeSessionInfo(Client*); // D-Bus interface QString supportInformation() const; void setCurrentScreen(int new_screen); void setShowingDesktop(bool showing); bool showingDesktop() const; void sendPingToWindow(xcb_window_t w, xcb_timestamp_t timestamp); // Called from Client::pingWindow() void removeClient(Client*); // Only called from Client::destroyClient() or Client::releaseWindow() void setActiveClient(AbstractClient*); Group* findGroup(xcb_window_t leader) const; void addGroup(Group* group); void removeGroup(Group* group); Group* findClientLeaderGroup(const Client* c) const; void removeUnmanaged(Unmanaged*); // Only called from Unmanaged::release() void removeDeleted(Deleted*); void addDeleted(Deleted*, Toplevel*); bool checkStartupNotification(xcb_window_t w, KStartupInfoId& id, KStartupInfoData& data); void focusToNull(); // SELI TODO: Public? void clientShortcutUpdated(AbstractClient* c); bool shortcutAvailable(const QKeySequence &cut, AbstractClient* ignore = NULL) const; bool globalShortcutsDisabled() const; void disableGlobalShortcutsForClient(bool disable); void sessionSaveStarted(); void sessionSaveDone(); void setWasUserInteraction(); bool wasUserInteraction() const; bool sessionSaving() const; int packPositionLeft(const AbstractClient* cl, int oldx, bool left_edge) const; int packPositionRight(const AbstractClient* cl, int oldx, bool right_edge) const; int packPositionUp(const AbstractClient* cl, int oldy, bool top_edge) const; int packPositionDown(const AbstractClient* cl, int oldy, bool bottom_edge) const; void cancelDelayFocus(); void requestDelayFocus(AbstractClient*); /** * updates the mouse position to track whether a focus follow mouse focus change was caused by * an actual mouse move * is esp. called on enter/motion events of inactive windows * since an active window doesn't receive mouse events, it must also be invoked if a (potentially) * active window might be moved/resize away from the cursor (causing a leave event) - **/ + */ void updateFocusMousePosition(const QPoint& pos); QPoint focusMousePosition() const; /** * Returns a client that is currently being moved or resized by the user. * * If none of clients is being moved or resized, @c null will be returned. - **/ + */ AbstractClient* moveResizeClient() { return movingClient; } /** * @returns Whether we have a Compositor and it is active (Scene created) - **/ + */ bool compositing() const; void registerEventFilter(X11EventFilter *filter); void unregisterEventFilter(X11EventFilter *filter); void markXStackingOrderAsDirty(); void quickTileWindow(QuickTileMode mode); enum Direction { DirectionNorth, DirectionEast, DirectionSouth, DirectionWest }; void switchWindow(Direction direction); ShortcutDialog *shortcutDialog() const { return client_keys_dialog; } public Q_SLOTS: void performWindowOperation(KWin::AbstractClient* c, Options::WindowOperation op); // Keybindings //void slotSwitchToWindow( int ); void slotWindowToDesktop(uint i); //void slotWindowToListPosition( int ); void slotSwitchToScreen(); void slotWindowToScreen(); void slotSwitchToNextScreen(); void slotWindowToNextScreen(); void slotSwitchToPrevScreen(); void slotWindowToPrevScreen(); void slotToggleShowDesktop(); void slotWindowMaximize(); void slotWindowMaximizeVertical(); void slotWindowMaximizeHorizontal(); void slotWindowMinimize(); void slotWindowShade(); void slotWindowRaise(); void slotWindowLower(); void slotWindowRaiseOrLower(); void slotActivateAttentionWindow(); void slotWindowPackLeft(); void slotWindowPackRight(); void slotWindowPackUp(); void slotWindowPackDown(); void slotWindowGrowHorizontal(); void slotWindowGrowVertical(); void slotWindowShrinkHorizontal(); void slotWindowShrinkVertical(); void slotIncreaseWindowOpacity(); void slotLowerWindowOpacity(); void slotWindowOperations(); void slotWindowClose(); void slotWindowMove(); void slotWindowResize(); void slotWindowAbove(); void slotWindowBelow(); void slotWindowOnAllDesktops(); void slotWindowFullScreen(); void slotWindowNoBorder(); void slotWindowToNextDesktop(); void slotWindowToPreviousDesktop(); void slotWindowToDesktopRight(); void slotWindowToDesktopLeft(); void slotWindowToDesktopUp(); void slotWindowToDesktopDown(); void reconfigure(); void slotReconfigure(); void slotKillWindow(); void slotSetupWindowShortcut(); void setupWindowShortcutDone(bool); void updateClientArea(); void slotActivateNextTab(); // Slot to move left the active Client. void slotActivatePrevTab(); // Slot to move right the active Client. void slotUntab(); // Slot to remove the active client from its group. private Q_SLOTS: void desktopResized(); void selectWmInputEventMask(); void slotUpdateToolWindows(); void delayFocus(); void slotReloadConfig(); void updateCurrentActivity(const QString &new_activity); // virtual desktop handling void slotDesktopCountChanged(uint previousCount, uint newCount); void slotCurrentDesktopChanged(uint oldDesktop, uint newDesktop); // session management void saveState(QSessionManager &sm); void commitData(QSessionManager &sm); Q_SIGNALS: /** * Emitted after the Workspace has setup the complete initialization process. * This can be used to connect to for performing post-workspace initialization. - **/ + */ void workspaceInitialized(); //Signals required for the scripting interface void desktopPresenceChanged(KWin::AbstractClient*, int); void currentDesktopChanged(int, KWin::AbstractClient*); void clientAdded(KWin::Client*); void clientRemoved(KWin::AbstractClient*); void clientActivated(KWin::AbstractClient*); void clientDemandsAttentionChanged(KWin::AbstractClient*, bool); void clientMinimizedChanged(KWin::AbstractClient*); void groupAdded(KWin::Group*); void unmanagedAdded(KWin::Unmanaged*); void unmanagedRemoved(KWin::Unmanaged*); void deletedRemoved(KWin::Deleted*); void configChanged(); void showingDesktopChanged(bool showing); /** * This signels is emitted when ever the stacking order is change, ie. a window is risen * or lowered - **/ + */ void stackingOrderChanged(); private: void init(); void initWithX11(); void initShortcuts(); template void initShortcut(const QString &actionName, const QString &description, const QKeySequence &shortcut, Slot slot, const QVariant &data = QVariant()); template void initShortcut(const QString &actionName, const QString &description, const QKeySequence &shortcut, T *receiver, Slot slot, const QVariant &data = QVariant()); void setupWindowShortcut(AbstractClient* c); bool switchWindow(AbstractClient *c, Direction direction, QPoint curPos, int desktop); void propagateClients(bool propagate_new_clients); // Called only from updateStackingOrder ToplevelList constrainedStackingOrder(); void raiseClientWithinApplication(AbstractClient* c); void lowerClientWithinApplication(AbstractClient* c); bool allowFullClientRaising(const AbstractClient* c, xcb_timestamp_t timestamp); bool keepTransientAbove(const AbstractClient* mainwindow, const AbstractClient* transient); bool keepDeletedTransientAbove(const Toplevel *mainWindow, const Deleted *transient) const; void blockStackingUpdates(bool block); void updateToolWindows(bool also_hide); void fixPositionAfterCrash(xcb_window_t w, const xcb_get_geometry_reply_t *geom); void saveOldScreenSizes(); /// This is the right way to create a new client Client* createClient(xcb_window_t w, bool is_mapped); void setupClientConnections(AbstractClient *client); void addClient(Client* c); Unmanaged* createUnmanaged(xcb_window_t w); void addUnmanaged(Unmanaged* c); //--------------------------------------------------------------------- void closeActivePopup(); void updateClientArea(bool force); void resetClientAreas(uint desktopCount); void updateClientVisibilityOnDesktopChange(uint newDesktop); void activateClientOnNewDesktop(uint desktop); AbstractClient *findClientToActivateOnDesktop(uint desktop); QWidget* active_popup; AbstractClient* active_popup_client; int m_initialDesktop; void loadSessionInfo(const QString &key); void addSessionInfo(KConfigGroup &cg); QList session; void updateXStackingOrder(); void updateTabbox(); AbstractClient* active_client; AbstractClient* last_active_client; AbstractClient* most_recently_raised; // Used ONLY by raiseOrLowerClient() AbstractClient* movingClient; // Delay(ed) window focus timer and client QTimer* delayFocusTimer; AbstractClient* delayfocus_client; QPoint focusMousePos; ClientList clients; QList m_allClients; ClientList desktops; UnmanagedList unmanaged; DeletedList deleted; ToplevelList unconstrained_stacking_order; // Topmost last ToplevelList stacking_order; // Topmost last QVector manual_overlays; //Topmost last bool force_restacking; ToplevelList x_stacking; // From XQueryTree() std::unique_ptr m_xStackingQueryTree; bool m_xStackingDirty = false; QList should_get_focus; // Last is most recent QList attention_chain; bool showing_desktop; GroupList groups; bool was_user_interaction; QScopedPointer m_wasUserInteractionFilter; bool session_saving; int session_active_client; int session_desktop; int block_focus; /** * Holds the menu containing the user actions which is shown * on e.g. right click the window decoration. - **/ + */ UserActionsMenu *m_userActionsMenu; void modalActionsSwitch(bool enabled); ShortcutDialog* client_keys_dialog; AbstractClient* client_keys_client; bool global_shortcuts_disabled_for_client; // Timer to collect requests for 'reconfigure' QTimer reconfigureTimer; QTimer updateToolWindowsTimer; static Workspace* _self; bool workspaceInit; KStartupInfo* startup; QVector workarea; // Array of workareas for virtual desktops // Array of restricted areas that window cannot be moved into QVector restrictedmovearea; // Array of the previous restricted areas that window cannot be moved into QVector oldrestrictedmovearea; QVector< QVector > screenarea; // Array of workareas per xinerama screen for all virtual desktops QVector< QRect > oldscreensizes; // array of previous sizes of xinerama screens QSize olddisplaysize; // previous sizes od displayWidth()/displayHeight() int set_active_client_recursion; int block_stacking_updates; // When > 0, stacking updates are temporarily disabled bool blocked_propagating_new_clients; // Propagate also new clients after enabling stacking updates? QScopedPointer m_nullFocus; friend class StackingUpdatesBlocker; QScopedPointer m_windowKiller; QList m_eventFilters; QList m_genericEventFilters; QScopedPointer m_movingClientFilter; private: friend bool performTransiencyCheck(); friend Workspace *workspace(); }; /** * Helper for Workspace::blockStackingUpdates() being called in pairs (True/false) - **/ + */ class StackingUpdatesBlocker { public: explicit StackingUpdatesBlocker(Workspace* w) : ws(w) { ws->blockStackingUpdates(true); } ~StackingUpdatesBlocker() { ws->blockStackingUpdates(false); } private: Workspace* ws; }; class ColorMapper : public QObject { Q_OBJECT public: ColorMapper(QObject *parent); ~ColorMapper() override; public Q_SLOTS: void update(); private: xcb_colormap_t m_default; xcb_colormap_t m_installed; }; //--------------------------------------------------------- // Unsorted inline bool Workspace::initializing() const { return workspaceInit; } inline AbstractClient *Workspace::activeClient() const { return active_client; } inline AbstractClient *Workspace::mostRecentlyActivatedClient() const { return should_get_focus.count() > 0 ? should_get_focus.last() : active_client; } inline void Workspace::addGroup(Group* group) { emit groupAdded(group); groups.append(group); } inline void Workspace::removeGroup(Group* group) { groups.removeAll(group); } inline const ToplevelList& Workspace::stackingOrder() const { // TODO: Q_ASSERT( block_stacking_updates == 0 ); return stacking_order; } inline bool Workspace::wasUserInteraction() const { return was_user_interaction; } inline void Workspace::sessionSaveStarted() { session_saving = true; } inline bool Workspace::sessionSaving() const { return session_saving; } inline bool Workspace::showingDesktop() const { return showing_desktop; } inline bool Workspace::globalShortcutsDisabled() const { return global_shortcuts_disabled_for_client; } inline void Workspace::forceRestacking() { force_restacking = true; StackingUpdatesBlocker blocker(this); // Do restacking if not blocked } inline void Workspace::updateFocusMousePosition(const QPoint& pos) { focusMousePos = pos; } inline QPoint Workspace::focusMousePosition() const { return focusMousePos; } inline void Workspace::forEachClient(std::function< void (Client*) > func) { std::for_each(clients.constBegin(), clients.constEnd(), func); std::for_each(desktops.constBegin(), desktops.constEnd(), func); } inline void Workspace::forEachUnmanaged(std::function< void (Unmanaged*) > func) { std::for_each(unmanaged.constBegin(), unmanaged.constEnd(), func); } inline bool Workspace::hasClient(const Client* c) { return findClient([c](const Client *test) { return test == c; }); } inline Workspace *workspace() { return Workspace::_self; } } // namespace Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::Workspace::ActivityFlags) #endif diff --git a/x11eventfilter.h b/x11eventfilter.h index fd5a10111..5b60351fc 100644 --- a/x11eventfilter.h +++ b/x11eventfilter.h @@ -1,87 +1,87 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Fredrik Höglund 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 X11EVENTFILTER_H #define X11EVENTFILTER_H #include #include #include namespace KWin { class KWIN_EXPORT X11EventFilter { public: /** * Creates an event filter for the given event type. - **/ + */ X11EventFilter(int eventType, int opcode = 0, int genericEventType = 0); X11EventFilter(int eventType, int opcode, const QVector &genericEventTypes); X11EventFilter(const QVector &eventTypes); /** * Destroys the event filter. - **/ + */ virtual ~X11EventFilter(); /** * Returns the type of events to filter. - **/ + */ QVector eventTypes() const { return m_eventTypes; } /** * Returns the major opcode of the extension. * * Only used when the event type is XCB_GE_GENERIC. - **/ + */ int extension() const { return m_extension; } /** * Returns the types of generic events to filter. * * Only used when the event type is XCB_GE_GENERIC. - **/ + */ QVector genericEventTypes() const { return m_genericEventTypes; } /** * This method is called for every event of the filtered type. * * Return true to accept the event and stop further processing, and false otherwise. - **/ + */ virtual bool event(xcb_generic_event_t *event) = 0; /** * Whether the event filter is for XCB_GE_GENERIC events. - **/ + */ bool isGenericEvent() const; private: QVector m_eventTypes; int m_extension; QVector m_genericEventTypes; }; } // namespace KWin #endif diff --git a/xcbutils.h b/xcbutils.h index d26cb372a..d44629786 100644 --- a/xcbutils.h +++ b/xcbutils.h @@ -1,1885 +1,1885 @@ /******************************************************************** 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 @ref 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 @ref 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 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 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 - **/ + */ 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) { QVector rects; rects.reserve(region.rectCount()); for (const QRect &rect : region) { rects.append(Xcb::fromQt(rect)); } return rects; } static inline void defineCursor(xcb_window_t window, xcb_cursor_t cursor) { xcb_change_window_attributes(connection(), window, XCB_CW_CURSOR, &cursor); } static inline void setInputFocus(xcb_window_t window, uint8_t revertTo, xcb_timestamp_t time) { xcb_set_input_focus(connection(), revertTo, window, time); } static inline void setTransientFor(xcb_window_t window, xcb_window_t transient_for_window) { xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, window, XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32, 1, &transient_for_window); } static inline void sync() { auto *c = connection(); const auto cookie = xcb_get_input_focus(c); xcb_generic_error_t *error = nullptr; ScopedCPointer 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 diff --git a/xkb.h b/xkb.h index 02d3f9b10..aaeecd251 100644 --- a/xkb.h +++ b/xkb.h @@ -1,179 +1,179 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013, 2016, 2017 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_XKB_H #define KWIN_XKB_H #include "input.h" #include #include #include Q_DECLARE_LOGGING_CATEGORY(KWIN_XKB) struct xkb_context; struct xkb_keymap; struct xkb_state; struct xkb_compose_table; struct xkb_compose_state; typedef uint32_t xkb_mod_index_t; typedef uint32_t xkb_led_index_t; typedef uint32_t xkb_keysym_t; typedef uint32_t xkb_layout_index_t; namespace KWayland { namespace Server { class SeatInterface; } } namespace KWin { class KWIN_EXPORT Xkb : public QObject { Q_OBJECT public: Xkb(QObject *parent = nullptr); ~Xkb() override; void setConfig(KSharedConfigPtr config) { m_config = config; } void setNumLockConfig(KSharedConfigPtr config) { m_numLockConfig = config; } void reconfigure(); void installKeymap(int fd, uint32_t size); void updateModifiers(uint32_t modsDepressed, uint32_t modsLatched, uint32_t modsLocked, uint32_t group); void updateKey(uint32_t key, InputRedirection::KeyboardKeyState state); xkb_keysym_t toKeysym(uint32_t key); xkb_keysym_t currentKeysym() const { return m_keysym; } QString toString(xkb_keysym_t keysym); Qt::Key toQtKey(xkb_keysym_t keysym) const; xkb_keysym_t fromQtKey(Qt::Key key, Qt::KeyboardModifiers mods) const; xkb_keysym_t fromKeyEvent(QKeyEvent *event) const; Qt::KeyboardModifiers modifiers() const; Qt::KeyboardModifiers modifiersRelevantForGlobalShortcuts() const; bool shouldKeyRepeat(quint32 key) const; void switchToNextLayout(); void switchToPreviousLayout(); void switchToLayout(xkb_layout_index_t layout); enum class LED { NumLock = 1 << 0, CapsLock = 1 << 1, ScrollLock = 1 << 2 }; Q_DECLARE_FLAGS(LEDs, LED) LEDs leds() const { return m_leds; } xkb_keymap *keymap() const { return m_keymap; } xkb_state *state() const { return m_state; } quint32 currentLayout() const { return m_currentLayout; } QString layoutName() const; QMap layoutNames() const; quint32 numberOfLayouts() const; /** * Forwards the current modifier state to the Wayland seat - **/ + */ void forwardModifiers(); void setSeat(KWayland::Server::SeatInterface *seat); Q_SIGNALS: void ledsChanged(const LEDs &leds); private: xkb_keymap *loadKeymapFromConfig(); xkb_keymap *loadDefaultKeymap(); void updateKeymap(xkb_keymap *keymap); void createKeymapFile(); void updateModifiers(); void updateConsumedModifiers(uint32_t key); QString layoutName(xkb_layout_index_t layout) const; xkb_context *m_context; xkb_keymap *m_keymap; xkb_state *m_state; xkb_mod_index_t m_shiftModifier; xkb_mod_index_t m_capsModifier; xkb_mod_index_t m_controlModifier; xkb_mod_index_t m_altModifier; xkb_mod_index_t m_metaModifier; xkb_mod_index_t m_numModifier; xkb_led_index_t m_numLock; xkb_led_index_t m_capsLock; xkb_led_index_t m_scrollLock; Qt::KeyboardModifiers m_modifiers; Qt::KeyboardModifiers m_consumedModifiers; xkb_keysym_t m_keysym; quint32 m_currentLayout = 0; struct { xkb_compose_table *table = nullptr; xkb_compose_state *state = nullptr; } m_compose; LEDs m_leds; KSharedConfigPtr m_config; KSharedConfigPtr m_numLockConfig; struct { xkb_mod_index_t depressed = 0; xkb_mod_index_t latched = 0; xkb_mod_index_t locked = 0; } m_modifierState; enum class Ownership { Server, Client }; Ownership m_ownership = Ownership::Server; QPointer m_seat; }; inline Qt::KeyboardModifiers Xkb::modifiers() const { return m_modifiers; } } Q_DECLARE_METATYPE(KWin::Xkb::LED) Q_DECLARE_METATYPE(KWin::Xkb::LEDs) #endif diff --git a/xwl/clipboard.h b/xwl/clipboard.h index bec6569e2..1c9eac4d9 100644 --- a/xwl/clipboard.h +++ b/xwl/clipboard.h @@ -1,70 +1,70 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_XWL_CLIPBOARD #define KWIN_XWL_CLIPBOARD #include "selection.h" namespace KWayland { namespace Server { class DataDeviceInterface; } } namespace KWin { namespace Xwl { /** * Represents the X clipboard, which is on Wayland side just called * @e selection. - **/ + */ class Clipboard : public Selection { Q_OBJECT public: Clipboard(xcb_atom_t atom, QObject *parent); private: void doHandleXfixesNotify(xcb_xfixes_selection_notify_event_t *event) override; void x11OffersChanged(const QStringList &added, const QStringList &removed) override; /** * React to Wl selection change. - **/ + */ void wlSelectionChanged(KWayland::Server::DataDeviceInterface *ddi); /** * Check the current state of the selection and if a source needs * to be created or destroyed. - **/ + */ void checkWlSource(); QMetaObject::Connection m_checkConnection; Q_DISABLE_COPY(Clipboard) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/databridge.h b/xwl/databridge.h index cf368a409..dc43ee610 100644 --- a/xwl/databridge.h +++ b/xwl/databridge.h @@ -1,104 +1,104 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 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_XWL_DATABRIDGE #define KWIN_XWL_DATABRIDGE #include #include #include class xcb_xfixes_selection_notify_event_t; namespace KWayland { namespace Client { class DataDevice; } namespace Server { class DataDeviceInterface; class SurfaceInterface; } } namespace KWin { class Toplevel; namespace Xwl { class Xwayland; class Clipboard; class Dnd; enum class DragEventReply; /** * Interface class for all data sharing in the context of X selections * and Wayland's internal mechanism. * * Exists only once per Xwayland session. - **/ + */ class DataBridge : public QObject { Q_OBJECT public: static DataBridge *self(); explicit DataBridge(QObject *parent = nullptr); ~DataBridge() override; bool filterEvent(xcb_generic_event_t *event); DragEventReply dragMoveFilter(Toplevel *target, const QPoint &pos); KWayland::Client::DataDevice *dataDevice() const { return m_dataDevice; } KWayland::Server::DataDeviceInterface *dataDeviceIface() const { return m_dataDeviceInterface; } Dnd *dnd() const { return m_dnd; } private: void init(); bool handleXfixesNotify(xcb_xfixes_selection_notify_event_t *event); Clipboard *m_clipboard = nullptr; Dnd *m_dnd = nullptr; /* Internal data device interface */ KWayland::Client::DataDevice *m_dataDevice = nullptr; KWayland::Server::DataDeviceInterface *m_dataDeviceInterface = nullptr; Q_DISABLE_COPY(DataBridge) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/dnd.h b/xwl/dnd.h index 93b96e182..01fcc801b 100644 --- a/xwl/dnd.h +++ b/xwl/dnd.h @@ -1,93 +1,93 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_XWL_DND #define KWIN_XWL_DND #include "selection.h" #include namespace KWayland { namespace Client { class Surface; } namespace Server { class SurfaceInterface; } } namespace KWin { class Toplevel; namespace Xwl { class Drag; enum class DragEventReply; /** * Represents the drag and drop mechanism, on X side this is the XDND protocol. * For more information on XDND see: https://johnlindal.wixsite.com/xdnd - **/ + */ class Dnd : public Selection { Q_OBJECT public: explicit Dnd(xcb_atom_t atom, QObject *parent); static uint32_t version(); void doHandleXfixesNotify(xcb_xfixes_selection_notify_event_t *event) override; void x11OffersChanged(const QStringList &added, const QStringList &removed) override; bool handleClientMessage(xcb_client_message_event_t *event) override; DragEventReply dragMoveFilter(Toplevel *target, const QPoint &pos); KWayland::Server::SurfaceInterface *surfaceIface() const { return m_surfaceIface; } KWayland::Client::Surface *surface() const { return m_surface; } private: // start and end Wl native client drags (Wl -> Xwl) void startDrag(); void endDrag(); void clearOldDrag(Drag *drag); // active drag or null when no drag active Drag *m_currentDrag = nullptr; QVector m_oldDrags; KWayland::Client::Surface *m_surface; KWayland::Server::SurfaceInterface *m_surfaceIface = nullptr; Q_DISABLE_COPY(Dnd) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/drag.h b/xwl/drag.h index 598796377..8aedfc2a1 100644 --- a/xwl/drag.h +++ b/xwl/drag.h @@ -1,69 +1,69 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_XWL_DRAG #define KWIN_XWL_DRAG #include #include #include namespace KWin { class Toplevel; namespace Xwl { enum class DragEventReply; using DnDAction = KWayland::Client::DataDeviceManager::DnDAction; /** * An ongoing drag operation. - **/ + */ class Drag : public QObject { Q_OBJECT public: explicit Drag(QObject *parent = nullptr); ~Drag() override; static void sendClientMessage(xcb_window_t target, xcb_atom_t type, xcb_client_message_data_t *data); static DnDAction atomToClientAction(xcb_atom_t atom); static xcb_atom_t clientActionToAtom(DnDAction action); virtual bool handleClientMessage(xcb_client_message_event_t *event) = 0; virtual DragEventReply moveFilter(Toplevel *target, const QPoint &pos) = 0; virtual bool end() = 0; Q_SIGNALS: void finish(Drag *self); private: Q_DISABLE_COPY(Drag) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/selection.h b/xwl/selection.h index 803e3354b..f39167983 100644 --- a/xwl/selection.h +++ b/xwl/selection.h @@ -1,144 +1,144 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_XWL_SELECTION #define KWIN_XWL_SELECTION #include #include #include struct xcb_xfixes_selection_notify_event_t; class QTimer; namespace KWin { namespace Xwl { class TransferWltoX; class TransferXtoWl; class WlSource; class X11Source; /** * Base class representing generic X selections and their respective * Wayland counter-parts. * * The class needs to be subclassed and adjusted according to the * selection, but provides common fucntionality to be expected of all * selections. * * A selection should exist through the whole runtime of an Xwayland * session. * * Independently of each other the class holds the currently active * source instance and active transfers relative to the represented * selection. - **/ + */ class Selection : public QObject { Q_OBJECT public: static xcb_atom_t mimeTypeToAtom(const QString &mimeType); static xcb_atom_t mimeTypeToAtomLiteral(const QString &mimeType); static QStringList atomToMimeTypes(xcb_atom_t atom); static QString atomName(xcb_atom_t atom); static void sendSelectionNotify(xcb_selection_request_event_t *event, bool success); // on selection owner changes by X clients (Xwl -> Wl) bool handleXfixesNotify(xcb_xfixes_selection_notify_event_t *event); bool filterEvent(xcb_generic_event_t *event); xcb_atom_t atom() const { return m_atom; } xcb_window_t window() const { return m_window; } void overwriteRequestorWindow(xcb_window_t window); Q_SIGNALS: void transferFinished(xcb_timestamp_t eventTime); protected: Selection(xcb_atom_t atom, QObject *parent); void registerXfixes(); virtual void doHandleXfixesNotify(xcb_xfixes_selection_notify_event_t *event) = 0; virtual void x11OffersChanged(const QStringList &added, const QStringList &removed) = 0; virtual bool handleClientMessage(xcb_client_message_event_t *event) { Q_UNUSED(event); return false; } // sets the current provider of the selection void setWlSource(WlSource *source); WlSource *wlSource() const { return m_waylandSource; } void createX11Source(xcb_xfixes_selection_notify_event_t *event); X11Source *x11Source() const { return m_xSource; } // must be called in order to provide data from Wl to X void ownSelection(bool own); void setWindow(xcb_window_t window) { m_window = window; } private: bool handleSelectionRequest(xcb_selection_request_event_t *event); bool handleSelectionNotify(xcb_selection_notify_event_t *event); bool handlePropertyNotify(xcb_property_notify_event_t *event); void startTransferToWayland(xcb_atom_t target, qint32 fd); void startTransferToX(xcb_selection_request_event_t *event, qint32 fd); // Timeout transfers, which have become inactive due to client errors. void timeoutTransfers(); void startTimeoutTransfersTimer(); void endTimeoutTransfersTimer(); xcb_atom_t m_atom = XCB_ATOM_NONE; xcb_window_t m_window = XCB_WINDOW_NONE; xcb_window_t m_requestorWindow = XCB_WINDOW_NONE; xcb_timestamp_t m_timestamp; // Active source, if any. Only one of them at max can exist // at the same time. WlSource *m_waylandSource = nullptr; X11Source *m_xSource = nullptr; // active transfers QVector m_wlToXTransfers; QVector m_xToWlTransfers; QTimer *m_timeoutTransfers = nullptr; bool m_disownPending = false; Q_DISABLE_COPY(Selection) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/selection_source.h b/xwl/selection_source.h index 75a1dd52a..90d834e05 100644 --- a/xwl/selection_source.h +++ b/xwl/selection_source.h @@ -1,175 +1,175 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 2019 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_XWL_SELECTION_SOURCE #define KWIN_XWL_SELECTION_SOURCE #include #include #include class QSocketNotifier; struct xcb_selection_request_event_t; struct xcb_xfixes_selection_notify_event_t; namespace KWayland { namespace Client { class DataSource; } namespace Server { class DataDeviceInterface; class DataSourceInterface; } } namespace KWin { namespace Xwl { class Selection; /** * Base class representing a data source. - **/ + */ class SelectionSource : public QObject { Q_OBJECT public: SelectionSource(Selection *selection); xcb_timestamp_t timestamp() const { return m_timestamp; } void setTimestamp(xcb_timestamp_t time) { m_timestamp = time; } protected: Selection *selection() const { return m_selection; } void setWindow(xcb_window_t window) { m_window = window; } xcb_window_t window() const { return m_window; } private: xcb_timestamp_t m_timestamp = XCB_CURRENT_TIME; Selection *m_selection; xcb_window_t m_window; Q_DISABLE_COPY(SelectionSource) }; /** * Representing a Wayland native data source. - **/ + */ class WlSource : public SelectionSource { Q_OBJECT public: WlSource(Selection *selection, KWayland::Server::DataDeviceInterface *ddi); void setDataSourceIface(KWayland::Server::DataSourceInterface *dsi); bool handleSelectionRequest(xcb_selection_request_event_t *event); void sendTargets(xcb_selection_request_event_t *event); void sendTimestamp(xcb_selection_request_event_t *event); void receiveOffer(const QString &mime); void sendSelectionNotify(xcb_selection_request_event_t *event, bool success); Q_SIGNALS: void transferReady(xcb_selection_request_event_t *event, qint32 fd); private: bool checkStartTransfer(xcb_selection_request_event_t *event); KWayland::Server::DataDeviceInterface *m_ddi = nullptr; KWayland::Server::DataSourceInterface *m_dsi = nullptr; QVector m_offers; QMetaObject::Connection m_offerConnection; Q_DISABLE_COPY(WlSource) }; using Mimes = QVector >; /** * Representing an X data source. - **/ + */ class X11Source : public SelectionSource { Q_OBJECT public: X11Source(Selection *selection, xcb_xfixes_selection_notify_event_t *event); /** * @param ds must exist. * * X11Source does not take ownership of it in general, but if the function * is called again, it will delete the previous data source. - **/ + */ void setDataSource(KWayland::Client::DataSource *dataSource); KWayland::Client::DataSource *dataSource() const { return m_dataSource; } void getTargets(); Mimes offers() const { return m_offers; } void setOffers(const Mimes &offers); bool handleSelectionNotify(xcb_selection_notify_event_t *event); void setRequestor(xcb_window_t window) { setWindow(window); } Q_SIGNALS: void offersChanged(const QStringList &added, const QStringList &removed); void transferReady(xcb_atom_t target, qint32 fd); private: void handleTargets(); void startTransfer(const QString &mimeName, qint32 fd); xcb_window_t m_owner; KWayland::Client::DataSource *m_dataSource = nullptr; Mimes m_offers; Q_DISABLE_COPY(X11Source) }; } // namespace Xwl } // namespace KWin #endif diff --git a/xwl/transfer.h b/xwl/transfer.h index d57a58fea..e6aa18f0d 100644 --- a/xwl/transfer.h +++ b/xwl/transfer.h @@ -1,230 +1,230 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright 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_XWL_TRANSFER #define KWIN_XWL_TRANSFER #include #include #include #include namespace KWayland { namespace Client { class DataDevice; class DataSource; } namespace Server { class DataDeviceInterface; } } namespace KWin { namespace Xwl { /** * Represents for an arbitrary selection a data transfer between * sender and receiver. * * Lives for the duration of the transfer and must be cleaned up * externally afterwards. For that the owner should connect to the * @c finished() signal. - **/ + */ class Transfer : public QObject { Q_OBJECT public: Transfer(xcb_atom_t selection, qint32 fd, xcb_timestamp_t timestamp, QObject *parent = nullptr); virtual bool handlePropertyNotify(xcb_property_notify_event_t *event) = 0; void timeout(); xcb_timestamp_t timestamp() const { return m_timestamp; } Q_SIGNALS: void finished(); protected: void endTransfer(); xcb_atom_t atom() const { return m_atom; } qint32 fd() const { return m_fd; } void setIncr(bool set) { m_incr = set; } bool incr() const { return m_incr; } void resetTimeout() { m_timeout = false; } void createSocketNotifier(QSocketNotifier::Type type); void clearSocketNotifier(); QSocketNotifier *socketNotifier() const { return m_notifier; } private: void closeFd(); xcb_atom_t m_atom; qint32 m_fd; xcb_timestamp_t m_timestamp = XCB_CURRENT_TIME; QSocketNotifier *m_notifier = nullptr; bool m_incr = false; bool m_timeout = false; Q_DISABLE_COPY(Transfer) }; /** * Represents a transfer from a Wayland native source to an X window. - **/ + */ class TransferWltoX : public Transfer { Q_OBJECT public: TransferWltoX(xcb_atom_t selection, xcb_selection_request_event_t *request, qint32 fd, QObject *parent = nullptr); ~TransferWltoX() override; void startTransferFromSource(); bool handlePropertyNotify(xcb_property_notify_event_t *event) override; Q_SIGNALS: void selectionNotify(xcb_selection_request_event_t *event, bool success); private: void startIncr(); void readWlSource(); int flushSourceData(); void handlePropertyDelete(); xcb_selection_request_event_t *m_request = nullptr; /* contains all received data portioned in chunks * TODO: explain second QPair component */ QVector > m_chunks; bool m_propertyIsSet = false; bool m_flushPropertyOnDelete = false; Q_DISABLE_COPY(TransferWltoX) }; /** * Helper class for X to Wl transfers. - **/ + */ class DataReceiver { public: virtual ~DataReceiver(); void transferFromProperty(xcb_get_property_reply_t *reply); virtual void setData(const char *value, int length); QByteArray data() const; void partRead(int length); protected: void setDataInternal(QByteArray data) { m_data = data; } private: xcb_get_property_reply_t *m_propertyReply = nullptr; int m_propertyStart = 0; QByteArray m_data; }; /** * Compatibility receiver for clients only * supporting the NETSCAPE_URL scheme (Firefox) - **/ + */ class NetscapeUrlReceiver : public DataReceiver { public: void setData(const char *value, int length) override; }; /** * Compatibility receiver for clients only * supporting the text/x-moz-url scheme (Chromium on own drags) - **/ + */ class MozUrlReceiver : public DataReceiver { public: void setData(const char *value, int length) override; }; /** * Represents a transfer from an X window to a Wayland native client. - **/ + */ class TransferXtoWl : public Transfer { Q_OBJECT public: TransferXtoWl(xcb_atom_t selection, xcb_atom_t target, qint32 fd, xcb_timestamp_t timestamp, xcb_window_t parentWindow, QObject *parent = nullptr); ~TransferXtoWl() override; bool handleSelectionNotify(xcb_selection_notify_event_t *event); bool handlePropertyNotify(xcb_property_notify_event_t *event) override; private: void dataSourceWrite(); void startTransfer(); void getIncrChunk(); xcb_window_t m_window; DataReceiver *m_receiver = nullptr; Q_DISABLE_COPY(TransferXtoWl) }; } // namespace Xwl } // namespace KWin #endif