diff --git a/abstract_client.cpp b/abstract_client.cpp index 85713e50c..aa5b3c4d5 100644 --- a/abstract_client.cpp +++ b/abstract_client.cpp @@ -1,2050 +1,2050 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include "appmenu.h" #include "decorations/decoratedclient.h" #include "decorations/decorationpalette.h" #include "decorations/decorationbridge.h" #include "cursor.h" #include "effects.h" #include "focuschain.h" #include "outline.h" #include "screens.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "screenedge.h" #include "useractions.h" #include "workspace.h" #include "wayland_server.h" #include #include #include #include #include namespace KWin { QHash> AbstractClient::s_palettes; std::shared_ptr AbstractClient::s_defaultPalette; AbstractClient::AbstractClient() : Toplevel() #ifdef KWIN_BUILD_TABBOX , m_tabBoxClient(QSharedPointer(new TabBox::TabBoxClientImpl(this))) #endif , m_colorScheme(QStringLiteral("kdeglobals")) { connect(this, &AbstractClient::geometryShapeChanged, this, &AbstractClient::geometryChanged); auto signalMaximizeChanged = static_cast(&AbstractClient::clientMaximizedStateChanged); connect(this, signalMaximizeChanged, this, &AbstractClient::geometryChanged); connect(this, &AbstractClient::clientStepUserMovedResized, this, &AbstractClient::geometryChanged); connect(this, &AbstractClient::clientStartUserMovedResized, this, &AbstractClient::moveResizedChanged); connect(this, &AbstractClient::clientFinishUserMovedResized, this, &AbstractClient::moveResizedChanged); connect(this, &AbstractClient::clientStartUserMovedResized, this, &AbstractClient::removeCheckScreenConnection); connect(this, &AbstractClient::clientFinishUserMovedResized, this, &AbstractClient::setupCheckScreenConnection); connect(this, &AbstractClient::paletteChanged, this, &AbstractClient::triggerDecorationRepaint); connect(Decoration::DecorationBridge::self(), &QObject::destroyed, this, &AbstractClient::destroyDecoration); // If the user manually moved the window, don't restore it after the keyboard closes connect(this, &AbstractClient::clientFinishUserMovedResized, this, [this] () { m_keyboardGeometryRestore = QRect(); }); connect(this, qOverload(&AbstractClient::clientMaximizedStateChanged), this, [this] () { m_keyboardGeometryRestore = QRect(); }); connect(this, &AbstractClient::fullScreenChanged, this, [this] () { m_keyboardGeometryRestore = QRect(); }); // replace on-screen-display on size changes connect(this, &AbstractClient::geometryShapeChanged, this, [this] (Toplevel *c, const QRect &old) { Q_UNUSED(c) if (isOnScreenDisplay() && !frameGeometry().isEmpty() && old.size() != frameGeometry().size() && !isInitialPositionSet()) { GeometryUpdatesBlocker blocker(this); const QRect area = workspace()->clientArea(PlacementArea, Screens::self()->current(), desktop()); Placement::self()->place(this, area); setGeometryRestore(frameGeometry()); } } ); connect(this, &AbstractClient::paddingChanged, this, [this]() { m_visibleRectBeforeGeometryUpdate = visibleRect(); }); connect(ApplicationMenu::self(), &ApplicationMenu::applicationMenuEnabledChanged, this, [this] { emit hasApplicationMenuChanged(hasApplicationMenu()); }); } AbstractClient::~AbstractClient() { Q_ASSERT(m_blockGeometryUpdates == 0); Q_ASSERT(m_decoration.decoration == nullptr); } void AbstractClient::updateMouseGrab() { } bool AbstractClient::belongToSameApplication(const AbstractClient *c1, const AbstractClient *c2, SameApplicationChecks checks) { return c1->belongsToSameApplication(c2, checks); } bool AbstractClient::isTransient() const { return false; } void AbstractClient::setClientShown(bool shown) { Q_UNUSED(shown) } MaximizeMode AbstractClient::requestedMaximizeMode() const { return maximizeMode(); } xcb_timestamp_t AbstractClient::userTime() const { return XCB_TIME_CURRENT_TIME; } void AbstractClient::setSkipSwitcher(bool set) { set = rules()->checkSkipSwitcher(set); if (set == skipSwitcher()) return; m_skipSwitcher = set; doSetSkipSwitcher(); updateWindowRules(Rules::SkipSwitcher); emit skipSwitcherChanged(); } void AbstractClient::setSkipPager(bool b) { b = rules()->checkSkipPager(b); if (b == skipPager()) return; m_skipPager = b; doSetSkipPager(); updateWindowRules(Rules::SkipPager); emit skipPagerChanged(); } void AbstractClient::doSetSkipPager() { } void AbstractClient::setSkipTaskbar(bool b) { int was_wants_tab_focus = wantsTabFocus(); if (b == skipTaskbar()) return; m_skipTaskbar = b; doSetSkipTaskbar(); updateWindowRules(Rules::SkipTaskbar); if (was_wants_tab_focus != wantsTabFocus()) { FocusChain::self()->update(this, isActive() ? FocusChain::MakeFirst : FocusChain::Update); } emit skipTaskbarChanged(); } void AbstractClient::setOriginalSkipTaskbar(bool b) { m_originalSkipTaskbar = rules()->checkSkipTaskbar(b); setSkipTaskbar(m_originalSkipTaskbar); } void AbstractClient::doSetSkipTaskbar() { } void AbstractClient::doSetSkipSwitcher() { } void AbstractClient::setIcon(const QIcon &icon) { m_icon = icon; emit iconChanged(); } void AbstractClient::setActive(bool act) { if (m_active == act) { return; } m_active = act; const int ruledOpacity = m_active ? rules()->checkOpacityActive(qRound(opacity() * 100.0)) : rules()->checkOpacityInactive(qRound(opacity() * 100.0)); setOpacity(ruledOpacity / 100.0); workspace()->setActiveClient(act ? this : nullptr); if (!m_active) cancelAutoRaise(); if (!m_active && shadeMode() == ShadeActivated) setShade(ShadeNormal); StackingUpdatesBlocker blocker(workspace()); workspace()->updateClientLayer(this); // active windows may get different layer auto mainclients = mainClients(); for (auto it = mainclients.constBegin(); it != mainclients.constEnd(); ++it) if ((*it)->isFullScreen()) // fullscreens go high even if their transient is active workspace()->updateClientLayer(*it); doSetActive(); emit activeChanged(); updateMouseGrab(); } void AbstractClient::doSetActive() { } Layer AbstractClient::layer() const { if (m_layer == UnknownLayer) const_cast< AbstractClient* >(this)->m_layer = belongsToLayer(); return m_layer; } void AbstractClient::updateLayer() { if (layer() == belongsToLayer()) return; StackingUpdatesBlocker blocker(workspace()); invalidateLayer(); // invalidate, will be updated when doing restacking for (auto it = transients().constBegin(), end = transients().constEnd(); it != end; ++it) (*it)->updateLayer(); } void AbstractClient::invalidateLayer() { m_layer = UnknownLayer; } Layer AbstractClient::belongsToLayer() const { // NOTICE while showingDesktop, desktops move to the AboveLayer // (interchangeable w/ eg. yakuake etc. which will at first remain visible) // and the docks move into the NotificationLayer (which is between Above- and // ActiveLayer, so that active fullscreen windows will still cover everything) // Since the desktop is also activated, nothing should be in the ActiveLayer, though if (isInternal()) return UnmanagedLayer; if (isDesktop()) return workspace()->showingDesktop() ? AboveLayer : DesktopLayer; if (isSplash()) // no damn annoying splashscreens return NormalLayer; // getting in the way of everything else if (isDock()) { if (workspace()->showingDesktop()) return NotificationLayer; return layerForDock(); } if (isOnScreenDisplay()) return OnScreenDisplayLayer; if (isNotification()) return NotificationLayer; if (isCriticalNotification()) return CriticalNotificationLayer; if (workspace()->showingDesktop() && belongsToDesktop()) { return AboveLayer; } if (keepBelow()) return BelowLayer; if (isActiveFullScreen()) return ActiveLayer; if (keepAbove()) return AboveLayer; return NormalLayer; } bool AbstractClient::belongsToDesktop() const { return false; } Layer AbstractClient::layerForDock() const { // slight hack for the 'allow window to cover panel' Kicker setting // don't move keepbelow docks below normal window, but only to the same // layer, so that both may be raised to cover the other if (keepBelow()) return NormalLayer; if (keepAbove()) // slight hack for the autohiding panels return AboveLayer; return DockLayer; } void AbstractClient::setKeepAbove(bool b) { b = rules()->checkKeepAbove(b); if (b && !rules()->checkKeepBelow(false)) setKeepBelow(false); if (b == keepAbove()) { // force hint change if different if (info && bool(info->state() & NET::KeepAbove) != keepAbove()) info->setState(keepAbove() ? NET::KeepAbove : NET::States(), NET::KeepAbove); return; } m_keepAbove = b; if (info) { info->setState(keepAbove() ? NET::KeepAbove : NET::States(), NET::KeepAbove); } workspace()->updateClientLayer(this); updateWindowRules(Rules::Above); doSetKeepAbove(); emit keepAboveChanged(m_keepAbove); } void AbstractClient::doSetKeepAbove() { } void AbstractClient::setKeepBelow(bool b) { b = rules()->checkKeepBelow(b); if (b && !rules()->checkKeepAbove(false)) setKeepAbove(false); if (b == keepBelow()) { // force hint change if different if (info && bool(info->state() & NET::KeepBelow) != keepBelow()) info->setState(keepBelow() ? NET::KeepBelow : NET::States(), NET::KeepBelow); return; } m_keepBelow = b; if (info) { info->setState(keepBelow() ? NET::KeepBelow : NET::States(), NET::KeepBelow); } workspace()->updateClientLayer(this); updateWindowRules(Rules::Below); doSetKeepBelow(); emit keepBelowChanged(m_keepBelow); } void AbstractClient::doSetKeepBelow() { } void AbstractClient::startAutoRaise() { delete m_autoRaiseTimer; m_autoRaiseTimer = new QTimer(this); connect(m_autoRaiseTimer, &QTimer::timeout, this, &AbstractClient::autoRaise); m_autoRaiseTimer->setSingleShot(true); m_autoRaiseTimer->start(options->autoRaiseInterval()); } void AbstractClient::cancelAutoRaise() { delete m_autoRaiseTimer; m_autoRaiseTimer = nullptr; } void AbstractClient::autoRaise() { workspace()->raiseClient(this); cancelAutoRaise(); } bool AbstractClient::wantsTabFocus() const { return (isNormalWindow() || isDialog()) && wantsInput(); } bool AbstractClient::isSpecialWindow() const { // TODO return isDesktop() || isDock() || isSplash() || isToolbar() || isNotification() || isOnScreenDisplay() || isCriticalNotification(); } void AbstractClient::demandAttention(bool set) { if (isActive()) set = false; if (m_demandsAttention == set) return; m_demandsAttention = set; if (info) { info->setState(set ? NET::DemandsAttention : NET::States(), NET::DemandsAttention); } workspace()->clientAttentionChanged(this, set); emit demandsAttentionChanged(); } void AbstractClient::setDesktop(int desktop) { const int numberOfDesktops = VirtualDesktopManager::self()->count(); if (desktop != NET::OnAllDesktops) // Do range check desktop = qMax(1, qMin(numberOfDesktops, desktop)); desktop = qMin(numberOfDesktops, rules()->checkDesktop(desktop)); QVector desktops; if (desktop != NET::OnAllDesktops) { desktops << VirtualDesktopManager::self()->desktopForX11Id(desktop); } setDesktops(desktops); } void AbstractClient::setDesktops(QVector desktops) { //on x11 we can have only one desktop at a time if (kwinApp()->operationMode() == Application::OperationModeX11 && desktops.size() > 1) { desktops = QVector({desktops.last()}); } if (desktops == m_desktops) { return; } int was_desk = AbstractClient::desktop(); const bool wasOnCurrentDesktop = isOnCurrentDesktop() && was_desk >= 0; m_desktops = desktops; if (windowManagementInterface()) { if (m_desktops.isEmpty()) { windowManagementInterface()->setOnAllDesktops(true); } else { windowManagementInterface()->setOnAllDesktops(false); auto currentDesktops = windowManagementInterface()->plasmaVirtualDesktops(); for (auto desktop: m_desktops) { if (!currentDesktops.contains(desktop->id())) { windowManagementInterface()->addPlasmaVirtualDesktop(desktop->id()); } else { currentDesktops.removeOne(desktop->id()); } } for (auto desktopId: currentDesktops) { windowManagementInterface()->removePlasmaVirtualDesktop(desktopId); } } } if (info) { info->setDesktop(desktop()); } if ((was_desk == NET::OnAllDesktops) != (desktop() == NET::OnAllDesktops)) { // onAllDesktops changed workspace()->updateOnAllDesktopsOfTransients(this); } auto transients_stacking_order = workspace()->ensureStackingOrder(transients()); for (auto it = transients_stacking_order.constBegin(); it != transients_stacking_order.constEnd(); ++it) (*it)->setDesktops(desktops); if (isModal()) // if a modal dialog is moved, move the mainwindow with it as otherwise // the (just moved) modal dialog will confusingly return to the mainwindow with // the next desktop change { foreach (AbstractClient * c2, mainClients()) c2->setDesktops(desktops); } doSetDesktop(desktop(), was_desk); FocusChain::self()->update(this, FocusChain::MakeFirst); updateWindowRules(Rules::Desktop); emit desktopChanged(); if (wasOnCurrentDesktop != isOnCurrentDesktop()) emit desktopPresenceChanged(this, was_desk); emit x11DesktopIdsChanged(); } void AbstractClient::doSetDesktop(int desktop, int was_desk) { Q_UNUSED(desktop) Q_UNUSED(was_desk) } void AbstractClient::enterDesktop(VirtualDesktop *virtualDesktop) { if (m_desktops.contains(virtualDesktop)) { return; } auto desktops = m_desktops; desktops.append(virtualDesktop); setDesktops(desktops); } void AbstractClient::leaveDesktop(VirtualDesktop *virtualDesktop) { QVector currentDesktops; if (m_desktops.isEmpty()) { currentDesktops = VirtualDesktopManager::self()->desktops(); } else { currentDesktops = m_desktops; } if (!currentDesktops.contains(virtualDesktop)) { return; } auto desktops = currentDesktops; desktops.removeOne(virtualDesktop); setDesktops(desktops); } void AbstractClient::setOnAllDesktops(bool b) { if ((b && isOnAllDesktops()) || (!b && !isOnAllDesktops())) return; if (b) setDesktop(NET::OnAllDesktops); else setDesktop(VirtualDesktopManager::self()->current()); } QVector AbstractClient::x11DesktopIds() const { const auto desks = desktops(); QVector x11Ids; x11Ids.reserve(desks.count()); std::transform(desks.constBegin(), desks.constEnd(), std::back_inserter(x11Ids), [] (const VirtualDesktop *vd) { return vd->x11DesktopNumber(); } ); return x11Ids; } bool AbstractClient::isShadeable() const { return false; } void AbstractClient::setShade(bool set) { set ? setShade(ShadeNormal) : setShade(ShadeNone); } void AbstractClient::setShade(ShadeMode mode) { Q_UNUSED(mode) } ShadeMode AbstractClient::shadeMode() const { return ShadeNone; } AbstractClient::Position AbstractClient::titlebarPosition() const { // TODO: still needed, remove? return PositionTop; } bool AbstractClient::titlebarPositionUnderMouse() const { if (!isDecorated()) { return false; } const auto sectionUnderMouse = decoration()->sectionUnderMouse(); if (sectionUnderMouse == Qt::TitleBarArea) { return true; } // check other sections based on titlebarPosition switch (titlebarPosition()) { case AbstractClient::PositionTop: return (sectionUnderMouse == Qt::TopLeftSection || sectionUnderMouse == Qt::TopSection || sectionUnderMouse == Qt::TopRightSection); case AbstractClient::PositionLeft: return (sectionUnderMouse == Qt::TopLeftSection || sectionUnderMouse == Qt::LeftSection || sectionUnderMouse == Qt::BottomLeftSection); case AbstractClient::PositionRight: return (sectionUnderMouse == Qt::BottomRightSection || sectionUnderMouse == Qt::RightSection || sectionUnderMouse == Qt::TopRightSection); case AbstractClient::PositionBottom: return (sectionUnderMouse == Qt::BottomLeftSection || sectionUnderMouse == Qt::BottomSection || sectionUnderMouse == Qt::BottomRightSection); default: // nothing return false; } } void AbstractClient::setMinimized(bool set) { set ? minimize() : unminimize(); } void AbstractClient::minimize(bool avoid_animation) { if (!isMinimizable() || isMinimized()) return; if (isShade() && info) // NETWM restriction - KWindowInfo::isMinimized() == Hidden && !Shaded info->setState(NET::States(), NET::Shaded); m_minimized = true; doMinimize(); updateWindowRules(Rules::Minimize); FocusChain::self()->update(this, FocusChain::MakeFirstMinimized); // TODO: merge signal with s_minimized emit clientMinimized(this, !avoid_animation); emit minimizedChanged(); } void AbstractClient::unminimize(bool avoid_animation) { if (!isMinimized()) return; if (rules()->checkMinimize(false)) { return; } if (isShade() && info) // NETWM restriction - KWindowInfo::isMinimized() == Hidden && !Shaded info->setState(NET::Shaded, NET::Shaded); m_minimized = false; doMinimize(); updateWindowRules(Rules::Minimize); emit clientUnminimized(this, !avoid_animation); emit minimizedChanged(); } void AbstractClient::doMinimize() { } QPalette AbstractClient::palette() const { if (!m_palette) { return QPalette(); } return m_palette->palette(); } const Decoration::DecorationPalette *AbstractClient::decorationPalette() const { return m_palette.get(); } void AbstractClient::updateColorScheme(QString path) { if (path.isEmpty()) { path = QStringLiteral("kdeglobals"); } if (!m_palette || m_colorScheme != path) { m_colorScheme = path; if (m_palette) { disconnect(m_palette.get(), &Decoration::DecorationPalette::changed, this, &AbstractClient::handlePaletteChange); } auto it = s_palettes.find(m_colorScheme); if (it == s_palettes.end() || it->expired()) { m_palette = std::make_shared(m_colorScheme); if (m_palette->isValid()) { s_palettes[m_colorScheme] = m_palette; } else { if (!s_defaultPalette) { s_defaultPalette = std::make_shared(QStringLiteral("kdeglobals")); s_palettes[QStringLiteral("kdeglobals")] = s_defaultPalette; } m_palette = s_defaultPalette; } if (m_colorScheme == QStringLiteral("kdeglobals")) { s_defaultPalette = m_palette; } } else { m_palette = it->lock(); } connect(m_palette.get(), &Decoration::DecorationPalette::changed, this, &AbstractClient::handlePaletteChange); emit paletteChanged(palette()); emit colorSchemeChanged(); } } void AbstractClient::handlePaletteChange() { emit paletteChanged(palette()); } void AbstractClient::keepInArea(QRect area, bool partial) { if (partial) { // increase the area so that can have only 100 pixels in the area area.setLeft(qMin(area.left() - width() + 100, area.left())); area.setTop(qMin(area.top() - height() + 100, area.top())); area.setRight(qMax(area.right() + width() - 100, area.right())); area.setBottom(qMax(area.bottom() + height() - 100, area.bottom())); } if (!partial) { // resize to fit into area if (area.width() < width() || area.height() < height()) resizeWithChecks(qMin(area.width(), width()), qMin(area.height(), height())); } int tx = x(), ty = y(); if (frameGeometry().right() > area.right() && width() <= area.width()) tx = area.right() - width() + 1; if (frameGeometry().bottom() > area.bottom() && height() <= area.height()) ty = area.bottom() - height() + 1; if (!area.contains(frameGeometry().topLeft())) { if (tx < area.x()) tx = area.x(); if (ty < area.y()) ty = area.y(); } if (tx != x() || ty != y()) move(tx, ty); } QSize AbstractClient::maxSize() const { return rules()->checkMaxSize(QSize(INT_MAX, INT_MAX)); } QSize AbstractClient::minSize() const { return rules()->checkMinSize(QSize(0, 0)); } void AbstractClient::updateMoveResize(const QPointF ¤tGlobalCursor) { handleMoveResize(pos(), currentGlobalCursor.toPoint()); } bool AbstractClient::hasStrut() const { return false; } void AbstractClient::setupWindowManagementInterface() { if (m_windowManagementInterface) { // already setup return; } if (!waylandServer() || !surface()) { return; } if (!waylandServer()->windowManagement()) { return; } using namespace KWayland::Server; auto w = waylandServer()->windowManagement()->createWindow(waylandServer()->windowManagement()); w->setTitle(caption()); w->setVirtualDesktop(isOnAllDesktops() ? 0 : desktop() - 1); w->setActive(isActive()); w->setFullscreen(isFullScreen()); w->setKeepAbove(keepAbove()); w->setKeepBelow(keepBelow()); w->setMaximized(maximizeMode() == KWin::MaximizeFull); w->setMinimized(isMinimized()); w->setOnAllDesktops(isOnAllDesktops()); w->setDemandsAttention(isDemandingAttention()); w->setCloseable(isCloseable()); w->setMaximizeable(isMaximizable()); w->setMinimizeable(isMinimizable()); w->setFullscreenable(isFullScreenable()); w->setIcon(icon()); auto updateAppId = [this, w] { w->setAppId(QString::fromUtf8(m_desktopFileName.isEmpty() ? resourceClass() : m_desktopFileName)); }; updateAppId(); w->setSkipTaskbar(skipTaskbar()); w->setSkipSwitcher(skipSwitcher()); w->setPid(pid()); w->setShadeable(isShadeable()); w->setShaded(isShade()); w->setResizable(isResizable()); w->setMovable(isMovable()); w->setVirtualDesktopChangeable(true); // FIXME Matches X11Client::actionSupported(), but both should be implemented. w->setParentWindow(transientFor() ? transientFor()->windowManagementInterface() : nullptr); w->setGeometry(frameGeometry()); connect(this, &AbstractClient::skipTaskbarChanged, w, [w, this] { w->setSkipTaskbar(skipTaskbar()); } ); connect(this, &AbstractClient::skipSwitcherChanged, w, [w, this] { w->setSkipSwitcher(skipSwitcher()); } ); connect(this, &AbstractClient::captionChanged, w, [w, this] { w->setTitle(caption()); }); connect(this, &AbstractClient::activeChanged, w, [w, this] { w->setActive(isActive()); }); connect(this, &AbstractClient::fullScreenChanged, w, [w, this] { w->setFullscreen(isFullScreen()); }); connect(this, &AbstractClient::keepAboveChanged, w, &PlasmaWindowInterface::setKeepAbove); connect(this, &AbstractClient::keepBelowChanged, w, &PlasmaWindowInterface::setKeepBelow); connect(this, &AbstractClient::minimizedChanged, w, [w, this] { w->setMinimized(isMinimized()); }); connect(this, static_cast(&AbstractClient::clientMaximizedStateChanged), w, [w] (KWin::AbstractClient *c, MaximizeMode mode) { Q_UNUSED(c); w->setMaximized(mode == KWin::MaximizeFull); } ); connect(this, &AbstractClient::demandsAttentionChanged, w, [w, this] { w->setDemandsAttention(isDemandingAttention()); }); connect(this, &AbstractClient::iconChanged, w, [w, this] { w->setIcon(icon()); } ); connect(this, &AbstractClient::windowClassChanged, w, updateAppId); connect(this, &AbstractClient::desktopFileNameChanged, w, updateAppId); connect(this, &AbstractClient::shadeChanged, w, [w, this] { w->setShaded(isShade()); }); connect(this, &AbstractClient::transientChanged, w, [w, this] { w->setParentWindow(transientFor() ? transientFor()->windowManagementInterface() : nullptr); } ); connect(this, &AbstractClient::geometryChanged, w, [w, this] { w->setGeometry(frameGeometry()); } ); connect(w, &PlasmaWindowInterface::closeRequested, this, [this] { closeWindow(); }); connect(w, &PlasmaWindowInterface::moveRequested, this, [this] { Cursor::setPos(frameGeometry().center()); performMouseCommand(Options::MouseMove, Cursor::pos()); } ); connect(w, &PlasmaWindowInterface::resizeRequested, this, [this] { Cursor::setPos(frameGeometry().bottomRight()); performMouseCommand(Options::MouseResize, Cursor::pos()); } ); connect(w, &PlasmaWindowInterface::virtualDesktopRequested, this, [this] (quint32 desktop) { workspace()->sendClientToDesktop(this, desktop + 1, true); } ); connect(w, &PlasmaWindowInterface::fullscreenRequested, this, [this] (bool set) { setFullScreen(set, false); } ); connect(w, &PlasmaWindowInterface::minimizedRequested, this, [this] (bool set) { if (set) { minimize(); } else { unminimize(); } } ); connect(w, &PlasmaWindowInterface::maximizedRequested, this, [this] (bool set) { maximize(set ? MaximizeFull : MaximizeRestore); } ); connect(w, &PlasmaWindowInterface::keepAboveRequested, this, [this] (bool set) { setKeepAbove(set); } ); connect(w, &PlasmaWindowInterface::keepBelowRequested, this, [this] (bool set) { setKeepBelow(set); } ); connect(w, &PlasmaWindowInterface::demandsAttentionRequested, this, [this] (bool set) { demandAttention(set); } ); connect(w, &PlasmaWindowInterface::activeRequested, this, [this] (bool set) { if (set) { workspace()->activateClient(this, true); } } ); connect(w, &PlasmaWindowInterface::shadedRequested, this, [this] (bool set) { setShade(set); } ); for (const auto vd : m_desktops) { w->addPlasmaVirtualDesktop(vd->id()); } //this is only for the legacy connect(this, &AbstractClient::desktopChanged, w, [w, this] { if (isOnAllDesktops()) { w->setOnAllDesktops(true); return; } w->setVirtualDesktop(desktop() - 1); w->setOnAllDesktops(false); } ); //Plasma Virtual desktop management //show/hide when the window enters/exits from desktop connect(w, &PlasmaWindowInterface::enterPlasmaVirtualDesktopRequested, this, [this] (const QString &desktopId) { VirtualDesktop *vd = VirtualDesktopManager::self()->desktopForId(desktopId.toUtf8()); if (vd) { enterDesktop(vd); } } ); connect(w, &PlasmaWindowInterface::enterNewPlasmaVirtualDesktopRequested, this, [this] () { VirtualDesktopManager::self()->setCount(VirtualDesktopManager::self()->count() + 1); enterDesktop(VirtualDesktopManager::self()->desktops().last()); } ); connect(w, &PlasmaWindowInterface::leavePlasmaVirtualDesktopRequested, this, [this] (const QString &desktopId) { VirtualDesktop *vd = VirtualDesktopManager::self()->desktopForId(desktopId.toUtf8()); if (vd) { leaveDesktop(vd); } } ); m_windowManagementInterface = w; } void AbstractClient::destroyWindowManagementInterface() { if (m_windowManagementInterface) { m_windowManagementInterface->unmap(); m_windowManagementInterface = nullptr; } } Options::MouseCommand AbstractClient::getMouseCommand(Qt::MouseButton button, bool *handled) const { *handled = false; if (button == Qt::NoButton) { return Options::MouseNothing; } if (isActive()) { if (options->isClickRaise()) { *handled = true; return Options::MouseActivateRaiseAndPassClick; } } else { *handled = true; switch (button) { case Qt::LeftButton: return options->commandWindow1(); case Qt::MiddleButton: return options->commandWindow2(); case Qt::RightButton: return options->commandWindow3(); default: // all other buttons pass Activate & Pass Client return Options::MouseActivateAndPassClick; } } return Options::MouseNothing; } Options::MouseCommand AbstractClient::getWheelCommand(Qt::Orientation orientation, bool *handled) const { *handled = false; if (orientation != Qt::Vertical) { return Options::MouseNothing; } if (!isActive()) { *handled = true; return options->commandWindowWheel(); } return Options::MouseNothing; } bool AbstractClient::performMouseCommand(Options::MouseCommand cmd, const QPoint &globalPos) { bool replay = false; switch(cmd) { case Options::MouseRaise: workspace()->raiseClient(this); break; case Options::MouseLower: { workspace()->lowerClient(this); // used to be activateNextClient(this), then topClientOnDesktop // since this is a mouseOp it's however safe to use the client under the mouse instead if (isActive() && options->focusPolicyIsReasonable()) { AbstractClient *next = workspace()->clientUnderMouse(screen()); if (next && next != this) workspace()->requestFocus(next, false); } break; } case Options::MouseOperationsMenu: if (isActive() && options->isClickRaise()) autoRaise(); workspace()->showWindowMenu(QRect(globalPos, globalPos), this); break; case Options::MouseToggleRaiseAndLower: workspace()->raiseOrLowerClient(this); break; case Options::MouseActivateAndRaise: { replay = isActive(); // for clickraise mode bool mustReplay = !rules()->checkAcceptFocus(acceptsFocus()); if (mustReplay) { auto it = workspace()->stackingOrder().constEnd(), begin = workspace()->stackingOrder().constBegin(); while (mustReplay && --it != begin && *it != this) { AbstractClient *c = qobject_cast(*it); if (!c || (c->keepAbove() && !keepAbove()) || (keepBelow() && !c->keepBelow())) continue; // can never raise above "it" mustReplay = !(c->isOnCurrentDesktop() && c->isOnCurrentActivity() && c->frameGeometry().intersects(frameGeometry())); } } workspace()->takeActivity(this, Workspace::ActivityFocus | Workspace::ActivityRaise); screens()->setCurrent(globalPos); replay = replay || mustReplay; break; } case Options::MouseActivateAndLower: workspace()->requestFocus(this); workspace()->lowerClient(this); screens()->setCurrent(globalPos); replay = replay || !rules()->checkAcceptFocus(acceptsFocus()); break; case Options::MouseActivate: replay = isActive(); // for clickraise mode workspace()->takeActivity(this, Workspace::ActivityFocus); screens()->setCurrent(globalPos); replay = replay || !rules()->checkAcceptFocus(acceptsFocus()); break; case Options::MouseActivateRaiseAndPassClick: workspace()->takeActivity(this, Workspace::ActivityFocus | Workspace::ActivityRaise); screens()->setCurrent(globalPos); replay = true; break; case Options::MouseActivateAndPassClick: workspace()->takeActivity(this, Workspace::ActivityFocus); screens()->setCurrent(globalPos); replay = true; break; case Options::MouseMaximize: maximize(MaximizeFull); break; case Options::MouseRestore: maximize(MaximizeRestore); break; case Options::MouseMinimize: minimize(); break; case Options::MouseAbove: { StackingUpdatesBlocker blocker(workspace()); if (keepBelow()) setKeepBelow(false); else setKeepAbove(true); break; } case Options::MouseBelow: { StackingUpdatesBlocker blocker(workspace()); if (keepAbove()) setKeepAbove(false); else setKeepBelow(true); break; } case Options::MousePreviousDesktop: workspace()->windowToPreviousDesktop(this); break; case Options::MouseNextDesktop: workspace()->windowToNextDesktop(this); break; case Options::MouseOpacityMore: if (!isDesktop()) // No point in changing the opacity of the desktop setOpacity(qMin(opacity() + 0.1, 1.0)); break; case Options::MouseOpacityLess: if (!isDesktop()) // No point in changing the opacity of the desktop setOpacity(qMax(opacity() - 0.1, 0.1)); break; case Options::MouseClose: closeWindow(); break; case Options::MouseActivateRaiseAndMove: case Options::MouseActivateRaiseAndUnrestrictedMove: workspace()->raiseClient(this); workspace()->requestFocus(this); screens()->setCurrent(globalPos); // fallthrough case Options::MouseMove: case Options::MouseUnrestrictedMove: { if (!isMovableAcrossScreens()) break; if (isMoveResize()) finishMoveResize(false); setMoveResizePointerMode(PositionCenter); setMoveResizePointerButtonDown(true); setMoveOffset(QPoint(globalPos.x() - x(), globalPos.y() - y())); // map from global setInvertedMoveOffset(rect().bottomRight() - moveOffset()); setUnrestrictedMoveResize((cmd == Options::MouseActivateRaiseAndUnrestrictedMove || cmd == Options::MouseUnrestrictedMove)); if (!startMoveResize()) setMoveResizePointerButtonDown(false); updateCursor(); break; } case Options::MouseResize: case Options::MouseUnrestrictedResize: { if (!isResizable() || isShade()) break; if (isMoveResize()) finishMoveResize(false); setMoveResizePointerButtonDown(true); const QPoint moveOffset = QPoint(globalPos.x() - x(), globalPos.y() - y()); // map from global setMoveOffset(moveOffset); int x = moveOffset.x(), y = moveOffset.y(); bool left = x < width() / 3; bool right = x >= 2 * width() / 3; bool top = y < height() / 3; bool bot = y >= 2 * height() / 3; Position mode; if (top) mode = left ? PositionTopLeft : (right ? PositionTopRight : PositionTop); else if (bot) mode = left ? PositionBottomLeft : (right ? PositionBottomRight : PositionBottom); else mode = (x < width() / 2) ? PositionLeft : PositionRight; setMoveResizePointerMode(mode); setInvertedMoveOffset(rect().bottomRight() - moveOffset); setUnrestrictedMoveResize((cmd == Options::MouseUnrestrictedResize)); if (!startMoveResize()) setMoveResizePointerButtonDown(false); updateCursor(); break; } case Options::MouseNothing: default: replay = true; break; } return replay; } void AbstractClient::setTransientFor(AbstractClient *transientFor) { if (transientFor == this) { // cannot be transient for one self return; } if (m_transientFor == transientFor) { return; } m_transientFor = transientFor; emit transientChanged(); } const AbstractClient *AbstractClient::transientFor() const { return m_transientFor; } AbstractClient *AbstractClient::transientFor() { return m_transientFor; } bool AbstractClient::hasTransientPlacementHint() const { return false; } QRect AbstractClient::transientPlacement(const QRect &bounds) const { Q_UNUSED(bounds); Q_UNREACHABLE(); return QRect(); } bool AbstractClient::hasTransient(const AbstractClient *c, bool indirect) const { Q_UNUSED(indirect); return c->transientFor() == this; } QList< AbstractClient* > AbstractClient::mainClients() const { if (const AbstractClient *t = transientFor()) { return QList{const_cast< AbstractClient* >(t)}; } return QList(); } QList AbstractClient::allMainClients() const { auto result = mainClients(); foreach (const auto *cl, result) { result += cl->allMainClients(); } return result; } void AbstractClient::setModal(bool m) { // Qt-3.2 can have even modal normal windows :( if (m_modal == m) return; m_modal = m; emit modalChanged(); // Changing modality for a mapped window is weird (?) // _NET_WM_STATE_MODAL should possibly rather be _NET_WM_WINDOW_TYPE_MODAL_DIALOG } bool AbstractClient::isModal() const { return m_modal; } void AbstractClient::addTransient(AbstractClient *cl) { Q_ASSERT(!m_transients.contains(cl)); Q_ASSERT(cl != this); m_transients.append(cl); } void AbstractClient::removeTransient(AbstractClient *cl) { m_transients.removeAll(cl); if (cl->transientFor() == this) { cl->setTransientFor(nullptr); } } void AbstractClient::removeTransientFromList(AbstractClient *cl) { m_transients.removeAll(cl); } bool AbstractClient::isActiveFullScreen() const { if (!isFullScreen()) return false; const auto ac = workspace()->mostRecentlyActivatedClient(); // instead of activeClient() - avoids flicker // according to NETWM spec implementation notes suggests // "focused windows having state _NET_WM_STATE_FULLSCREEN" to be on the highest layer. // we'll also take the screen into account return ac && (ac == this || ac->screen() != screen()|| ac->allMainClients().contains(const_cast(this))); } #define BORDER(which) \ int AbstractClient::border##which() const \ { \ return isDecorated() ? decoration()->border##which() : 0; \ } BORDER(Bottom) BORDER(Left) BORDER(Right) BORDER(Top) #undef BORDER QSize AbstractClient::sizeForClientSize(const QSize &wsize, Sizemode mode, bool noframe) const { Q_UNUSED(mode) Q_UNUSED(noframe) return wsize + QSize(borderLeft() + borderRight(), borderTop() + borderBottom()); } void AbstractClient::addRepaintDuringGeometryUpdates() { const QRect deco_rect = visibleRect(); addLayerRepaint(m_visibleRectBeforeGeometryUpdate); addLayerRepaint(deco_rect); // trigger repaint of window's new location m_visibleRectBeforeGeometryUpdate = deco_rect; } QRect AbstractClient::bufferGeometryBeforeUpdateBlocking() const { return m_bufferGeometryBeforeUpdateBlocking; } QRect AbstractClient::frameGeometryBeforeUpdateBlocking() const { return m_frameGeometryBeforeUpdateBlocking; } void AbstractClient::updateGeometryBeforeUpdateBlocking() { m_bufferGeometryBeforeUpdateBlocking = bufferGeometry(); m_frameGeometryBeforeUpdateBlocking = frameGeometry(); } void AbstractClient::doMove(int, int) { } void AbstractClient::updateInitialMoveResizeGeometry() { m_moveResize.initialGeometry = frameGeometry(); m_moveResize.geometry = m_moveResize.initialGeometry; m_moveResize.startScreen = screen(); } void AbstractClient::updateCursor() { Position m = moveResizePointerMode(); if (!isResizable() || isShade()) m = PositionCenter; CursorShape c = Qt::ArrowCursor; switch(m) { case PositionTopLeft: c = KWin::ExtendedCursor::SizeNorthWest; break; case PositionBottomRight: c = KWin::ExtendedCursor::SizeSouthEast; break; case PositionBottomLeft: c = KWin::ExtendedCursor::SizeSouthWest; break; case PositionTopRight: c = KWin::ExtendedCursor::SizeNorthEast; break; case PositionTop: c = KWin::ExtendedCursor::SizeNorth; break; case PositionBottom: c = KWin::ExtendedCursor::SizeSouth; break; case PositionLeft: c = KWin::ExtendedCursor::SizeWest; break; case PositionRight: c = KWin::ExtendedCursor::SizeEast; break; default: if (isMoveResize()) c = Qt::SizeAllCursor; else c = Qt::ArrowCursor; break; } if (c == m_moveResize.cursor) return; m_moveResize.cursor = c; emit moveResizeCursorChanged(c); } void AbstractClient::leaveMoveResize() { workspace()->setMoveResizeClient(nullptr); setMoveResize(false); if (ScreenEdges::self()->isDesktopSwitchingMovingClients()) ScreenEdges::self()->reserveDesktopSwitching(false, Qt::Vertical|Qt::Horizontal); if (isElectricBorderMaximizing()) { outline()->hide(); elevate(false); } } bool AbstractClient::s_haveResizeEffect = false; void AbstractClient::updateHaveResizeEffect() { s_haveResizeEffect = effects && static_cast(effects)->provides(Effect::Resize); } bool AbstractClient::doStartMoveResize() { return true; } void AbstractClient::positionGeometryTip() { } void AbstractClient::doPerformMoveResize() { } bool AbstractClient::isWaitingForMoveResizeSync() const { return false; } void AbstractClient::doResizeSync() { } void AbstractClient::checkQuickTilingMaximizationZones(int xroot, int yroot) { QuickTileMode mode = QuickTileFlag::None; bool innerBorder = false; for (int i=0; i < screens()->count(); ++i) { if (!screens()->geometry(i).contains(QPoint(xroot, yroot))) continue; auto isInScreen = [i](const QPoint &pt) { for (int j = 0; j < screens()->count(); ++j) { if (j == i) continue; if (screens()->geometry(j).contains(pt)) { return true; } } return false; }; QRect area = workspace()->clientArea(MaximizeArea, QPoint(xroot, yroot), desktop()); if (options->electricBorderTiling()) { if (xroot <= area.x() + 20) { mode |= QuickTileFlag::Left; innerBorder = isInScreen(QPoint(area.x() - 1, yroot)); } else if (xroot >= area.x() + area.width() - 20) { mode |= QuickTileFlag::Right; innerBorder = isInScreen(QPoint(area.right() + 1, yroot)); } } if (mode != QuickTileMode(QuickTileFlag::None)) { if (yroot <= area.y() + area.height() * options->electricBorderCornerRatio()) mode |= QuickTileFlag::Top; else if (yroot >= area.y() + area.height() - area.height() * options->electricBorderCornerRatio()) mode |= QuickTileFlag::Bottom; } else if (options->electricBorderMaximize() && yroot <= area.y() + 5 && isMaximizable()) { mode = QuickTileFlag::Maximize; innerBorder = isInScreen(QPoint(xroot, area.y() - 1)); } break; // no point in checking other screens to contain this... "point"... } if (mode != electricBorderMode()) { setElectricBorderMode(mode); if (innerBorder) { if (!m_electricMaximizingDelay) { m_electricMaximizingDelay = new QTimer(this); m_electricMaximizingDelay->setInterval(250); m_electricMaximizingDelay->setSingleShot(true); connect(m_electricMaximizingDelay, &QTimer::timeout, [this]() { if (isMove()) setElectricBorderMaximizing(electricBorderMode() != QuickTileMode(QuickTileFlag::None)); }); } m_electricMaximizingDelay->start(); } else { setElectricBorderMaximizing(mode != QuickTileMode(QuickTileFlag::None)); } } } void AbstractClient::keyPressEvent(uint key_code) { if (!isMove() && !isResize()) return; bool is_control = key_code & Qt::CTRL; bool is_alt = key_code & Qt::ALT; key_code = key_code & ~Qt::KeyboardModifierMask; int delta = is_control ? 1 : is_alt ? 32 : 8; QPoint pos = Cursor::pos(); switch(key_code) { case Qt::Key_Left: pos.rx() -= delta; break; case Qt::Key_Right: pos.rx() += delta; break; case Qt::Key_Up: pos.ry() -= delta; break; case Qt::Key_Down: pos.ry() += delta; break; case Qt::Key_Space: case Qt::Key_Return: case Qt::Key_Enter: setMoveResizePointerButtonDown(false); finishMoveResize(false); updateCursor(); break; case Qt::Key_Escape: setMoveResizePointerButtonDown(false); finishMoveResize(true); updateCursor(); break; default: return; } Cursor::setPos(pos); } QSize AbstractClient::resizeIncrements() const { return QSize(1, 1); } void AbstractClient::dontMoveResize() { setMoveResizePointerButtonDown(false); stopDelayedMoveResize(); if (isMoveResize()) finishMoveResize(false); } AbstractClient::Position AbstractClient::mousePosition() const { if (isDecorated()) { switch (decoration()->sectionUnderMouse()) { case Qt::BottomLeftSection: return PositionBottomLeft; case Qt::BottomRightSection: return PositionBottomRight; case Qt::BottomSection: return PositionBottom; case Qt::LeftSection: return PositionLeft; case Qt::RightSection: return PositionRight; case Qt::TopSection: return PositionTop; case Qt::TopLeftSection: return PositionTopLeft; case Qt::TopRightSection: return PositionTopRight; default: return PositionCenter; } } return PositionCenter; } void AbstractClient::endMoveResize() { setMoveResizePointerButtonDown(false); stopDelayedMoveResize(); if (isMoveResize()) { finishMoveResize(false); setMoveResizePointerMode(mousePosition()); } updateCursor(); } void AbstractClient::destroyDecoration() { delete m_decoration.decoration; m_decoration.decoration = nullptr; } bool AbstractClient::decorationHasAlpha() const { if (!isDecorated() || decoration()->isOpaque()) { // either no decoration or decoration has alpha disabled return false; } return true; } void AbstractClient::triggerDecorationRepaint() { if (isDecorated()) { decoration()->update(); } } void AbstractClient::layoutDecorationRects(QRect &left, QRect &top, QRect &right, QRect &bottom) const { if (!isDecorated()) { return; } QRect r = decoration()->rect(); top = QRect(r.x(), r.y(), r.width(), borderTop()); bottom = QRect(r.x(), r.y() + r.height() - borderBottom(), r.width(), borderBottom()); left = QRect(r.x(), r.y() + top.height(), borderLeft(), r.height() - top.height() - bottom.height()); right = QRect(r.x() + r.width() - borderRight(), r.y() + top.height(), borderRight(), r.height() - top.height() - bottom.height()); } void AbstractClient::processDecorationMove(const QPoint &localPos, const QPoint &globalPos) { if (isMoveResizePointerButtonDown()) { handleMoveResize(localPos.x(), localPos.y(), globalPos.x(), globalPos.y()); return; } // TODO: handle modifiers Position newmode = mousePosition(); if (newmode != moveResizePointerMode()) { setMoveResizePointerMode(newmode); updateCursor(); } } bool AbstractClient::processDecorationButtonPress(QMouseEvent *event, bool ignoreMenu) { Options::MouseCommand com = Options::MouseNothing; bool active = isActive(); if (!wantsInput()) // we cannot be active, use it anyway active = true; // check whether it is a double click if (event->button() == Qt::LeftButton && titlebarPositionUnderMouse()) { if (m_decoration.doubleClickTimer.isValid()) { const qint64 interval = m_decoration.doubleClickTimer.elapsed(); m_decoration.doubleClickTimer.invalidate(); if (interval > QGuiApplication::styleHints()->mouseDoubleClickInterval()) { m_decoration.doubleClickTimer.start(); // expired -> new first click and pot. init } else { Workspace::self()->performWindowOperation(this, options->operationTitlebarDblClick()); dontMoveResize(); return false; } } else { m_decoration.doubleClickTimer.start(); // new first click and pot. init, could be invalidated by release - see below } } if (event->button() == Qt::LeftButton) com = active ? options->commandActiveTitlebar1() : options->commandInactiveTitlebar1(); else if (event->button() == Qt::MidButton) com = active ? options->commandActiveTitlebar2() : options->commandInactiveTitlebar2(); else if (event->button() == Qt::RightButton) com = active ? options->commandActiveTitlebar3() : options->commandInactiveTitlebar3(); if (event->button() == Qt::LeftButton && com != Options::MouseOperationsMenu // actions where it's not possible to get the matching && com != Options::MouseMinimize) // mouse release event { setMoveResizePointerMode(mousePosition()); setMoveResizePointerButtonDown(true); setMoveOffset(event->pos()); setInvertedMoveOffset(rect().bottomRight() - moveOffset()); setUnrestrictedMoveResize(false); startDelayedMoveResize(); updateCursor(); } // In the new API the decoration may process the menu action to display an inactive tab's menu. // If the event is unhandled then the core will create one for the active window in the group. if (!ignoreMenu || com != Options::MouseOperationsMenu) performMouseCommand(com, event->globalPos()); return !( // Return events that should be passed to the decoration in the new API com == Options::MouseRaise || com == Options::MouseOperationsMenu || com == Options::MouseActivateAndRaise || com == Options::MouseActivate || com == Options::MouseActivateRaiseAndPassClick || com == Options::MouseActivateAndPassClick || com == Options::MouseNothing); } void AbstractClient::processDecorationButtonRelease(QMouseEvent *event) { if (isDecorated()) { if (event->isAccepted() || !titlebarPositionUnderMouse()) { invalidateDecorationDoubleClickTimer(); // click was for the deco and shall not init a doubleclick } } if (event->buttons() == Qt::NoButton) { setMoveResizePointerButtonDown(false); stopDelayedMoveResize(); if (isMoveResize()) { finishMoveResize(false); setMoveResizePointerMode(mousePosition()); } updateCursor(); } } void AbstractClient::startDecorationDoubleClickTimer() { m_decoration.doubleClickTimer.start(); } void AbstractClient::invalidateDecorationDoubleClickTimer() { m_decoration.doubleClickTimer.invalidate(); } bool AbstractClient::providesContextHelp() const { return false; } void AbstractClient::showContextHelp() { } QPointer AbstractClient::decoratedClient() const { return m_decoration.client; } void AbstractClient::setDecoratedClient(QPointer< Decoration::DecoratedClientImpl > client) { m_decoration.client = client; } void AbstractClient::enterEvent(const QPoint &globalPos) { // TODO: shade hover if (options->focusPolicy() == Options::ClickToFocus || workspace()->userActionsMenu()->isShown()) return; if (options->isAutoRaise() && !isDesktop() && !isDock() && workspace()->focusChangeEnabled() && globalPos != workspace()->focusMousePosition() && workspace()->topClientOnDesktop(VirtualDesktopManager::self()->current(), options->isSeparateScreenFocus() ? screen() : -1) != this) { startAutoRaise(); } if (isDesktop() || isDock()) return; // for FocusFollowsMouse, change focus only if the mouse has actually been moved, not if the focus // change came because of window changes (e.g. closing a window) - #92290 if (options->focusPolicy() != Options::FocusFollowsMouse || globalPos != workspace()->focusMousePosition()) { workspace()->requestDelayFocus(this); } } void AbstractClient::leaveEvent() { cancelAutoRaise(); workspace()->cancelDelayFocus(); // TODO: shade hover // TODO: send hover leave to deco // TODO: handle Options::FocusStrictlyUnderMouse } QRect AbstractClient::iconGeometry() const { if (!windowManagementInterface() || !waylandServer()) { // window management interface is only available if the surface is mapped return QRect(); } int minDistance = INT_MAX; AbstractClient *candidatePanel = nullptr; QRect candidateGeom; for (auto i = windowManagementInterface()->minimizedGeometries().constBegin(), end = windowManagementInterface()->minimizedGeometries().constEnd(); i != end; ++i) { AbstractClient *client = waylandServer()->findAbstractClient(i.key()); if (!client) { continue; } const int distance = QPoint(client->pos() - pos()).manhattanLength(); if (distance < minDistance) { minDistance = distance; candidatePanel = client; candidateGeom = i.value(); } } if (!candidatePanel) { return QRect(); } return candidateGeom.translated(candidatePanel->pos()); } QRect AbstractClient::inputGeometry() const { if (isDecorated()) { return Toplevel::inputGeometry() + decoration()->resizeOnlyBorders(); } return Toplevel::inputGeometry(); } QRect AbstractClient::virtualKeyboardGeometry() const { return m_virtualKeyboardGeometry; } void AbstractClient::setVirtualKeyboardGeometry(const QRect &geo) { // No keyboard anymore if (geo.isEmpty() && !m_keyboardGeometryRestore.isEmpty()) { setFrameGeometry(m_keyboardGeometryRestore); m_keyboardGeometryRestore = QRect(); } else if (geo.isEmpty()) { return; // The keyboard has just been opened (rather than resized) save client geometry for a restore } else if (m_keyboardGeometryRestore.isEmpty()) { m_keyboardGeometryRestore = frameGeometry(); } m_virtualKeyboardGeometry = geo; // Don't resize Desktop and fullscreen windows if (isFullScreen() || isDesktop()) { return; } if (!geo.intersects(m_keyboardGeometryRestore)) { return; } const QRect availableArea = workspace()->clientArea(MaximizeArea, this); QRect newWindowGeometry = m_keyboardGeometryRestore; newWindowGeometry.moveBottom(geo.top()); newWindowGeometry.setTop(qMax(newWindowGeometry.top(), availableArea.top())); setFrameGeometry(newWindowGeometry); } bool AbstractClient::dockWantsInput() const { return false; } void AbstractClient::setDesktopFileName(QByteArray name) { name = rules()->checkDesktopFile(name).toUtf8(); if (name == m_desktopFileName) { return; } m_desktopFileName = name; updateWindowRules(Rules::DesktopFile); emit desktopFileNameChanged(); } QString AbstractClient::iconFromDesktopFile() const { if (m_desktopFileName.isEmpty()) { return QString(); } QString desktopFile = QString::fromUtf8(m_desktopFileName); if (!desktopFile.endsWith(QLatin1String(".desktop"))) { desktopFile.append(QLatin1String(".desktop")); } KDesktopFile df(desktopFile); return df.readIcon(); } bool AbstractClient::hasApplicationMenu() const { return ApplicationMenu::self()->applicationMenuEnabled() && !m_applicationMenuServiceName.isEmpty() && !m_applicationMenuObjectPath.isEmpty(); } void AbstractClient::updateApplicationMenuServiceName(const QString &serviceName) { const bool old_hasApplicationMenu = hasApplicationMenu(); m_applicationMenuServiceName = serviceName; const bool new_hasApplicationMenu = hasApplicationMenu(); if (old_hasApplicationMenu != new_hasApplicationMenu) { emit hasApplicationMenuChanged(new_hasApplicationMenu); } } void AbstractClient::updateApplicationMenuObjectPath(const QString &objectPath) { const bool old_hasApplicationMenu = hasApplicationMenu(); m_applicationMenuObjectPath = objectPath; const bool new_hasApplicationMenu = hasApplicationMenu(); if (old_hasApplicationMenu != new_hasApplicationMenu) { emit hasApplicationMenuChanged(new_hasApplicationMenu); } } void AbstractClient::setApplicationMenuActive(bool applicationMenuActive) { if (m_applicationMenuActive != applicationMenuActive) { m_applicationMenuActive = applicationMenuActive; emit applicationMenuActiveChanged(applicationMenuActive); } } void AbstractClient::showApplicationMenu(int actionId) { if (isDecorated()) { decoration()->showApplicationMenu(actionId); } else { // we don't know where the application menu button will be, show it in the top left corner instead Workspace::self()->showApplicationMenu(QRect(), this, actionId); } } bool AbstractClient::unresponsive() const { return m_unresponsive; } void AbstractClient::setUnresponsive(bool unresponsive) { if (m_unresponsive != unresponsive) { m_unresponsive = unresponsive; emit unresponsiveChanged(m_unresponsive); emit captionChanged(); } } QString AbstractClient::shortcutCaptionSuffix() const { if (shortcut().isEmpty()) { return QString(); } return QLatin1String(" {") + shortcut().toString() + QLatin1Char('}'); } AbstractClient *AbstractClient::findClientWithSameCaption() const { auto fetchNameInternalPredicate = [this](const AbstractClient *cl) { return (!cl->isSpecialWindow() || cl->isToolbar()) && cl != this && cl->captionNormal() == captionNormal() && cl->captionSuffix() == captionSuffix(); }; return workspace()->findAbstractClient(fetchNameInternalPredicate); } QString AbstractClient::caption() const { QString cap = captionNormal() + captionSuffix(); if (unresponsive()) { cap += QLatin1String(" "); cap += i18nc("Application is not responding, appended to window title", "(Not Responding)"); } return cap; } void AbstractClient::removeRule(Rules* rule) { m_rules.remove(rule); } void AbstractClient::discardTemporaryRules() { m_rules.discardTemporary(); } void AbstractClient::evaluateWindowRules() { setupWindowRules(true); applyWindowRules(); } void AbstractClient::setOnActivities(QStringList newActivitiesList) { Q_UNUSED(newActivitiesList) } void AbstractClient::checkNoBorder() { setNoBorder(false); } bool AbstractClient::groupTransient() const { return false; } const Group *AbstractClient::group() const { return nullptr; } Group *AbstractClient::group() { return nullptr; } bool AbstractClient::isInternal() const { return false; } bool AbstractClient::supportsWindowRules() const { return true; } QMargins AbstractClient::frameMargins() const { return QMargins(borderLeft(), borderTop(), borderRight(), borderBottom()); } QPoint AbstractClient::framePosToClientPos(const QPoint &point) const { return point + QPoint(borderLeft(), borderTop()); } QPoint AbstractClient::clientPosToFramePos(const QPoint &point) const { return point - QPoint(borderLeft(), borderTop()); } QSize AbstractClient::frameSizeToClientSize(const QSize &size) const { const int width = size.width() - borderLeft() - borderRight(); const int height = size.height() - borderTop() - borderBottom(); return QSize(width, height); } QSize AbstractClient::clientSizeToFrameSize(const QSize &size) const { const int width = size.width() + borderLeft() + borderRight(); const int height = size.height() + borderTop() + borderBottom(); return QSize(width, height); } QRect AbstractClient::frameRectToClientRect(const QRect &rect) const { const QPoint position = framePosToClientPos(rect.topLeft()); const QSize size = frameSizeToClientSize(rect.size()); return QRect(position, size); } QRect AbstractClient::clientRectToFrameRect(const QRect &rect) const { const QPoint position = clientPosToFramePos(rect.topLeft()); const QSize size = clientSizeToFrameSize(rect.size()); return QRect(position, size); } } diff --git a/abstract_client.h b/abstract_client.h index 61808834d..a69c63cdc 100644 --- a/abstract_client.h +++ b/abstract_client.h @@ -1,1368 +1,1368 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "cursor.h" #include #include #include namespace KWayland { namespace Server { class PlasmaWindowInterface; } } namespace KDecoration2 { class Decoration; } namespace KWin { class Group; 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 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 frameGeometry WRITE setFrameGeometry) /** * 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 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; QMargins frameMargins() const override; 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; virtual void setClientShown(bool shown); 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 asynchronous */ 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 }; virtual 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 setFrameGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) = 0; void setFrameGeometry(const QRect &rect, 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; /** * Calculates the matching client position for the given frame position @p point. */ virtual QPoint framePosToClientPos(const QPoint &point) const; /** * Calculates the matching frame position for the given client position @p point. */ virtual QPoint clientPosToFramePos(const QPoint &point) const; /** * Calculates the matching client size for the given frame size @p size. * * Notice that size constraints won't be applied. * * Default implementation returns the frame size with frame margins being excluded. */ virtual QSize frameSizeToClientSize(const QSize &size) const; /** * Calculates the matching frame size for the given client size @p size. * * Notice that size constraints won't be applied. * * Default implementation returns the client size with frame margins being included. */ virtual QSize clientSizeToFrameSize(const QSize &size) const; /** * Calculates the matching client rect for the given frame rect @p rect. * * Notice that size constraints won't be applied. */ QRect frameRectToClientRect(const QRect &rect) const; /** * Calculates the matching frame rect for the given client rect @p rect. * * Notice that size constraints won't be applied. */ QRect clientRectToFrameRect(const QRect &rect) 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); 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 bufferGeometryBeforeUpdateBlocking() const; QRect frameGeometryBeforeUpdateBlocking() const; 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(); /** * @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_bufferGeometryBeforeUpdateBlocking; QRect m_frameGeometryBeforeUpdateBlocking; 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; 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::setFrameGeometry(const QRect &rect, ForceGeometry_t force) { setFrameGeometry(rect.x(), rect.y(), rect.width(), rect.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; } } Q_DECLARE_METATYPE(KWin::AbstractClient*) Q_DECLARE_METATYPE(QList) Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::AbstractClient::SameApplicationChecks) #endif diff --git a/autotests/integration/activation_test.cpp b/autotests/integration/activation_test.cpp index dd5538633..e0e74c238 100644 --- a/autotests/integration/activation_test.cpp +++ b/autotests/integration/activation_test.cpp @@ -1,585 +1,585 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "platform.h" #include "screens.h" #include "wayland_server.h" #include "workspace.h" #include "xdgshellclient.h" #include namespace KWin { static const QString s_socketName = QStringLiteral("wayland_test_activation-0"); class ActivationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testSwitchToWindowToLeft(); void testSwitchToWindowToRight(); void testSwitchToWindowAbove(); void testSwitchToWindowBelow(); void testSwitchToWindowMaximized(); void testSwitchToWindowFullScreen(); private: void stackScreensHorizontally(); void stackScreensVertically(); }; void ActivationTest::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, 2)); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QCOMPARE(screens()->count(), 2); QCOMPARE(screens()->geometry(0), QRect(0, 0, 1280, 1024)); QCOMPARE(screens()->geometry(1), QRect(1280, 0, 1280, 1024)); waylandServer()->initWorkspace(); } void ActivationTest::init() { QVERIFY(Test::setupWaylandConnection()); screens()->setCurrent(0); Cursor::setPos(QPoint(640, 512)); } void ActivationTest::cleanup() { Test::destroyWaylandConnection(); stackScreensHorizontally(); } void ActivationTest::testSwitchToWindowToLeft() { // This test verifies that "Switch to Window to the Left" shortcut works. using namespace KWayland::Client; // Prepare the test environment. stackScreensHorizontally(); // Create several clients on the left screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); client1->move(QPoint(300, 200)); client2->move(QPoint(500, 200)); // Create several clients on the right screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(1380, 200)); client4->move(QPoint(1580, 200)); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client3->isActive()); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client2->isActive()); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client1->isActive()); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::testSwitchToWindowToRight() { // This test verifies that "Switch to Window to the Right" shortcut works. using namespace KWayland::Client; // Prepare the test environment. stackScreensHorizontally(); // Create several clients on the left screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); client1->move(QPoint(300, 200)); client2->move(QPoint(500, 200)); // Create several clients on the right screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(1380, 200)); client4->move(QPoint(1580, 200)); // Switch to window to the right. workspace()->switchWindow(Workspace::DirectionEast); QVERIFY(client1->isActive()); // Switch to window to the right. workspace()->switchWindow(Workspace::DirectionEast); QVERIFY(client2->isActive()); // Switch to window to the right. workspace()->switchWindow(Workspace::DirectionEast); QVERIFY(client3->isActive()); // Switch to window to the right. workspace()->switchWindow(Workspace::DirectionEast); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::testSwitchToWindowAbove() { // This test verifies that "Switch to Window Above" shortcut works. using namespace KWayland::Client; // Prepare the test environment. stackScreensVertically(); // Create several clients on the top screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); client1->move(QPoint(200, 300)); client2->move(QPoint(200, 500)); // Create several clients on the bottom screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(200, 1224)); client4->move(QPoint(200, 1424)); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client3->isActive()); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client2->isActive()); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client1->isActive()); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::testSwitchToWindowBelow() { // This test verifies that "Switch to Window Bottom" shortcut works. using namespace KWayland::Client; // Prepare the test environment. stackScreensVertically(); // Create several clients on the top screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); client1->move(QPoint(200, 300)); client2->move(QPoint(200, 500)); // Create several clients on the bottom screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(200, 1224)); client4->move(QPoint(200, 1424)); // Switch to window below. workspace()->switchWindow(Workspace::DirectionSouth); QVERIFY(client1->isActive()); // Switch to window below. workspace()->switchWindow(Workspace::DirectionSouth); QVERIFY(client2->isActive()); // Switch to window below. workspace()->switchWindow(Workspace::DirectionSouth); QVERIFY(client3->isActive()); // Switch to window below. workspace()->switchWindow(Workspace::DirectionSouth); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::testSwitchToWindowMaximized() { // This test verifies that we switch to the top-most maximized client, i.e. // the one that user sees at the moment. See bug 411356. using namespace KWayland::Client; // Prepare the test environment. stackScreensHorizontally(); // Create several maximized clients on the left screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QSignalSpy configureRequestedSpy1(shellSurface1.data(), &XdgShellSurface::configureRequested); QVERIFY(configureRequestedSpy1.wait()); workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy1.wait()); QSignalSpy geometryChangedSpy1(client1, &XdgShellClient::geometryChanged); QVERIFY(geometryChangedSpy1.isValid()); shellSurface1->ackConfigure(configureRequestedSpy1.last().at(2).value()); Test::render(surface1.data(), configureRequestedSpy1.last().at(0).toSize(), Qt::red); QVERIFY(geometryChangedSpy1.wait()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); QSignalSpy configureRequestedSpy2(shellSurface2.data(), &XdgShellSurface::configureRequested); QVERIFY(configureRequestedSpy2.wait()); workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy2.wait()); QSignalSpy geometryChangedSpy2(client2, &XdgShellClient::geometryChanged); QVERIFY(geometryChangedSpy2.isValid()); shellSurface2->ackConfigure(configureRequestedSpy2.last().at(2).value()); Test::render(surface2.data(), configureRequestedSpy2.last().at(0).toSize(), Qt::red); QVERIFY(geometryChangedSpy2.wait()); const QList stackingOrder = workspace()->stackingOrder(); QVERIFY(stackingOrder.indexOf(client1) < stackingOrder.indexOf(client2)); QCOMPARE(client1->maximizeMode(), MaximizeFull); QCOMPARE(client2->maximizeMode(), MaximizeFull); // Create several clients on the right screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(1380, 200)); client4->move(QPoint(1580, 200)); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client3->isActive()); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client2->isActive()); // Switch to window to the left. workspace()->switchWindow(Workspace::DirectionWest); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::testSwitchToWindowFullScreen() { // This test verifies that we switch to the top-most fullscreen client, i.e. // the one that user sees at the moment. See bug 411356. using namespace KWayland::Client; // Prepare the test environment. stackScreensVertically(); // Create several maximized clients on the top screen. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QSignalSpy configureRequestedSpy1(shellSurface1.data(), &XdgShellSurface::configureRequested); QVERIFY(configureRequestedSpy1.wait()); workspace()->slotWindowFullScreen(); QVERIFY(configureRequestedSpy1.wait()); QSignalSpy geometryChangedSpy1(client1, &XdgShellClient::geometryChanged); QVERIFY(geometryChangedSpy1.isValid()); shellSurface1->ackConfigure(configureRequestedSpy1.last().at(2).value()); Test::render(surface1.data(), configureRequestedSpy1.last().at(0).toSize(), Qt::red); QVERIFY(geometryChangedSpy1.wait()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->isActive()); QSignalSpy configureRequestedSpy2(shellSurface2.data(), &XdgShellSurface::configureRequested); QVERIFY(configureRequestedSpy2.wait()); workspace()->slotWindowFullScreen(); QVERIFY(configureRequestedSpy2.wait()); QSignalSpy geometryChangedSpy2(client2, &XdgShellClient::geometryChanged); QVERIFY(geometryChangedSpy2.isValid()); shellSurface2->ackConfigure(configureRequestedSpy2.last().at(2).value()); Test::render(surface2.data(), configureRequestedSpy2.last().at(0).toSize(), Qt::red); QVERIFY(geometryChangedSpy2.wait()); const QList stackingOrder = workspace()->stackingOrder(); QVERIFY(stackingOrder.indexOf(client1) < stackingOrder.indexOf(client2)); QVERIFY(client1->isFullScreen()); QVERIFY(client2->isFullScreen()); // Create several clients on the bottom screen. QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::blue); QVERIFY(client3); QVERIFY(client3->isActive()); QScopedPointer surface4(Test::createSurface()); QScopedPointer shellSurface4(Test::createXdgShellStableSurface(surface4.data())); XdgShellClient *client4 = Test::renderAndWaitForShown(surface4.data(), QSize(100, 50), Qt::blue); QVERIFY(client4); QVERIFY(client4->isActive()); client3->move(QPoint(200, 1224)); client4->move(QPoint(200, 1424)); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client3->isActive()); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client2->isActive()); // Switch to window above. workspace()->switchWindow(Workspace::DirectionNorth); QVERIFY(client4->isActive()); // Destroy all clients. shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface4.reset(); QVERIFY(Test::waitForWindowDestroyed(client4)); } void ActivationTest::stackScreensHorizontally() { // Process pending wl_output bind requests before destroying all outputs. QTest::qWait(1); const QVector screenGeometries { QRect(0, 0, 1280, 1024), QRect(1280, 0, 1280, 1024), }; const QVector screenScales { 1, 1, }; QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, screenGeometries.count()), Q_ARG(QVector, screenGeometries), Q_ARG(QVector, screenScales) ); } void ActivationTest::stackScreensVertically() { // Process pending wl_output bind requests before destroying all outputs. QTest::qWait(1); const QVector screenGeometries { QRect(0, 0, 1280, 1024), QRect(0, 1024, 1280, 1024), }; const QVector screenScales { 1, 1, }; QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, screenGeometries.count()), Q_ARG(QVector, screenGeometries), Q_ARG(QVector, screenScales) ); } } WAYLANDTEST_MAIN(KWin::ActivationTest) #include "activation_test.moc" diff --git a/autotests/integration/dont_crash_reinitialize_compositor.cpp b/autotests/integration/dont_crash_reinitialize_compositor.cpp index 9bae6de78..f4000487e 100644 --- a/autotests/integration/dont_crash_reinitialize_compositor.cpp +++ b/autotests/integration/dont_crash_reinitialize_compositor.cpp @@ -1,169 +1,169 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "abstract_client.h" #include "composite.h" #include "deleted.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "screens.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include namespace KWin { static const QString s_socketName = QStringLiteral("wayland_test_kwin_dont_crash_reinitialize_compositor-0"); class DontCrashReinitializeCompositorTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testReinitializeCompositor_data(); void testReinitializeCompositor(); }; void DontCrashReinitializeCompositorTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, 2)); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_COMPOSE", QByteArrayLiteral("O2")); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QCOMPARE(screens()->count(), 2); QCOMPARE(screens()->geometry(0), QRect(0, 0, 1280, 1024)); QCOMPARE(screens()->geometry(1), QRect(1280, 0, 1280, 1024)); waylandServer()->initWorkspace(); auto scene = KWin::Compositor::self()->scene(); QVERIFY(scene); QCOMPARE(scene->compositingType(), KWin::OpenGL2Compositing); } void DontCrashReinitializeCompositorTest::init() { QVERIFY(Test::setupWaylandConnection()); } void DontCrashReinitializeCompositorTest::cleanup() { // Unload all effects. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); Test::destroyWaylandConnection(); } void DontCrashReinitializeCompositorTest::testReinitializeCompositor_data() { QTest::addColumn("effectName"); QTest::newRow("Fade") << QStringLiteral("kwin4_effect_fade"); QTest::newRow("Glide") << QStringLiteral("glide"); QTest::newRow("Scale") << QStringLiteral("kwin4_effect_scale"); } void DontCrashReinitializeCompositorTest::testReinitializeCompositor() { // This test verifies that KWin doesn't crash when the compositor settings // have been changed while a scripted effect animates the disappearing of // a window. // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Create the test client. using namespace KWayland::Client; QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); // Make sure that only the test effect is loaded. QFETCH(QString, effectName); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Close the test client. QSignalSpy windowClosedSpy(client, &XdgShellClient::windowClosed); QVERIFY(windowClosedSpy.isValid()); shellSurface.reset(); surface.reset(); QVERIFY(windowClosedSpy.wait()); // The test effect should start animating the test client. Is there a better // way to verify that the test effect actually animates the test client? QVERIFY(effect->isActive()); // Re-initialize the compositor, effects will be destroyed and created again. Compositor::self()->reinitialize(); // By this time, KWin should still be alive. } } // namespace KWin WAYLANDTEST_MAIN(KWin::DontCrashReinitializeCompositorTest) #include "dont_crash_reinitialize_compositor.moc" diff --git a/autotests/integration/effects/desktop_switching_animation_test.cpp b/autotests/integration/effects/desktop_switching_animation_test.cpp index 277f3ce18..2549b043e 100644 --- a/autotests/integration/effects/desktop_switching_animation_test.cpp +++ b/autotests/integration/effects/desktop_switching_animation_test.cpp @@ -1,163 +1,163 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include "composite.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "scene.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_desktop_switching_animation-0"); class DesktopSwitchingAnimationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testSwitchDesktops_data(); void testSwitchDesktops(); }; void DesktopSwitchingAnimationTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_COMPOSE", QByteArrayLiteral("O2")); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); auto scene = Compositor::self()->scene(); QVERIFY(scene); QCOMPARE(scene->compositingType(), OpenGL2Compositing); } void DesktopSwitchingAnimationTest::init() { QVERIFY(Test::setupWaylandConnection()); } void DesktopSwitchingAnimationTest::cleanup() { auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); VirtualDesktopManager::self()->setCount(1); Test::destroyWaylandConnection(); } void DesktopSwitchingAnimationTest::testSwitchDesktops_data() { QTest::addColumn("effectName"); QTest::newRow("Desktop Cube Animation") << QStringLiteral("cubeslide"); QTest::newRow("Fade Desktop") << QStringLiteral("kwin4_effect_fadedesktop"); QTest::newRow("Slide") << QStringLiteral("slide"); } void DesktopSwitchingAnimationTest::testSwitchDesktops() { // This test verifies that virtual desktop switching animation effects actually // try to animate switching between desktops. // We need at least 2 virtual desktops for the test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->current(), 1u); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); // The Fade Desktop effect will do nothing if there are no clients to fade, // so we have to create a dummy test client. using namespace KWayland::Client; QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QCOMPARE(client->desktops().count(), 1); QCOMPARE(client->desktops().first(), VirtualDesktopManager::self()->desktops().first()); // Load effect that will be tested. QFETCH(QString, effectName); auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Switch to the second virtual desktop. VirtualDesktopManager::self()->setCurrent(2u); QCOMPARE(VirtualDesktopManager::self()->current(), 2u); QVERIFY(effect->isActive()); QCOMPARE(effects->activeFullScreenEffect(), effect); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); QTRY_COMPARE(effects->activeFullScreenEffect(), nullptr); // Destroy the test client. surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } WAYLANDTEST_MAIN(DesktopSwitchingAnimationTest) #include "desktop_switching_animation_test.moc" diff --git a/autotests/integration/effects/maximize_animation_test.cpp b/autotests/integration/effects/maximize_animation_test.cpp index a83d1aafd..bccb41198 100644 --- a/autotests/integration/effects/maximize_animation_test.cpp +++ b/autotests/integration/effects/maximize_animation_test.cpp @@ -1,212 +1,212 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include "composite.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "scene.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_maximize_animation-0"); class MaximizeAnimationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testMaximizeRestore_data(); void testMaximizeRestore(); }; void MaximizeAnimationTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); } void MaximizeAnimationTest::init() { QVERIFY(Test::setupWaylandConnection()); } void MaximizeAnimationTest::cleanup() { auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); Test::destroyWaylandConnection(); } void MaximizeAnimationTest::testMaximizeRestore_data() { QTest::addColumn("type"); QTest::newRow("xdgShellV6") << Test::XdgShellSurfaceType::XdgShellV6; QTest::newRow("xdgWmBase") << Test::XdgShellSurfaceType::XdgShellStable; } void MaximizeAnimationTest::testMaximizeRestore() { // This test verifies that the maximize effect animates a client // when it's maximized or restored. using namespace KWayland::Client; // Create the test client. QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer shellSurface(createXdgShellSurface(type, surface.data(), nullptr, Test::CreationSetup::CreateOnly)); // Wait for the initial configure event. XdgShellSurface::States states; QSignalSpy configureRequestedSpy(shellSurface.data(), &XdgShellSurface::configureRequested); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy.isValid()); QVERIFY(configureRequestedSpy.wait()); QCOMPARE(configureRequestedSpy.count(), 1); QCOMPARE(configureRequestedSpy.last().at(0).value(), QSize(0, 0)); states = configureRequestedSpy.last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Draw contents of the surface. shellSurface->ackConfigure(configureRequestedSpy.last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy.wait()); QCOMPARE(configureRequestedSpy.count(), 2); states = configureRequestedSpy.last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Load effect that will be tested. const QString effectName = QStringLiteral("kwin4_effect_maximize"); auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Maximize the client. QSignalSpy geometryChangedSpy(client, &XdgShellClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); QSignalSpy maximizeChangedSpy(client, qOverload(&XdgShellClient::clientMaximizedStateChanged)); QVERIFY(maximizeChangedSpy.isValid()); workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy.wait()); QCOMPARE(configureRequestedSpy.count(), 3); QCOMPARE(configureRequestedSpy.last().at(0).value(), QSize(1280, 1024)); states = configureRequestedSpy.last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Draw contents of the maximized client. shellSurface->ackConfigure(configureRequestedSpy.last().at(2).value()); Test::render(surface.data(), QSize(1280, 1024), Qt::red); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(geometryChangedSpy.count(), 2); QCOMPARE(maximizeChangedSpy.count(), 1); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Restore the client. workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy.wait()); QCOMPARE(configureRequestedSpy.count(), 4); QCOMPARE(configureRequestedSpy.last().at(0).value(), QSize(100, 50)); states = configureRequestedSpy.last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Draw contents of the restored client. shellSurface->ackConfigure(configureRequestedSpy.last().at(2).value()); Test::render(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(geometryChangedSpy.count(), 4); QCOMPARE(maximizeChangedSpy.count(), 2); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the test client. surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } WAYLANDTEST_MAIN(MaximizeAnimationTest) #include "maximize_animation_test.moc" diff --git a/autotests/integration/effects/minimize_animation_test.cpp b/autotests/integration/effects/minimize_animation_test.cpp index 549329b08..db39de827 100644 --- a/autotests/integration/effects/minimize_animation_test.cpp +++ b/autotests/integration/effects/minimize_animation_test.cpp @@ -1,198 +1,198 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include "composite.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "scene.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_minimize_animation-0"); class MinimizeAnimationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testMinimizeUnminimize_data(); void testMinimizeUnminimize(); }; void MinimizeAnimationTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_COMPOSE", QByteArrayLiteral("O2")); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); auto scene = Compositor::self()->scene(); QVERIFY(scene); QCOMPARE(scene->compositingType(), OpenGL2Compositing); } void MinimizeAnimationTest::init() { QVERIFY(Test::setupWaylandConnection( Test::AdditionalWaylandInterface::PlasmaShell | Test::AdditionalWaylandInterface::WindowManagement )); } void MinimizeAnimationTest::cleanup() { auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); Test::destroyWaylandConnection(); } void MinimizeAnimationTest::testMinimizeUnminimize_data() { QTest::addColumn("effectName"); QTest::newRow("Magic Lamp") << QStringLiteral("magiclamp"); QTest::newRow("Squash") << QStringLiteral("kwin4_effect_squash"); } void MinimizeAnimationTest::testMinimizeUnminimize() { // This test verifies that a minimize effect tries to animate a client // when it's minimized or unminimized. using namespace KWayland::Client; QSignalSpy plasmaWindowCreatedSpy(Test::waylandWindowManagement(), &PlasmaWindowManagement::windowCreated); QVERIFY(plasmaWindowCreatedSpy.isValid()); // Create a panel at the top of the screen. const QRect panelRect = QRect(0, 0, 1280, 36); QScopedPointer panelSurface(Test::createSurface()); QVERIFY(!panelSurface.isNull()); QScopedPointer panelShellSurface(Test::createXdgShellStableSurface(panelSurface.data())); QVERIFY(!panelShellSurface.isNull()); QScopedPointer plasmaPanelShellSurface(Test::waylandPlasmaShell()->createSurface(panelSurface.data())); QVERIFY(!plasmaPanelShellSurface.isNull()); plasmaPanelShellSurface->setRole(PlasmaShellSurface::Role::Panel); plasmaPanelShellSurface->setPosition(panelRect.topLeft()); plasmaPanelShellSurface->setPanelBehavior(PlasmaShellSurface::PanelBehavior::AlwaysVisible); XdgShellClient *panel = Test::renderAndWaitForShown(panelSurface.data(), panelRect.size(), Qt::blue); QVERIFY(panel); QVERIFY(panel->isDock()); QCOMPARE(panel->frameGeometry(), panelRect); QVERIFY(plasmaWindowCreatedSpy.wait()); QCOMPARE(plasmaWindowCreatedSpy.count(), 1); // Create the test client. QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::red); QVERIFY(client); QVERIFY(plasmaWindowCreatedSpy.wait()); QCOMPARE(plasmaWindowCreatedSpy.count(), 2); // We have to set the minimized geometry because the squash effect needs it, // otherwise it won't start animation. auto window = plasmaWindowCreatedSpy.last().first().value(); QVERIFY(window); const QRect iconRect = QRect(0, 0, 42, 36); window->setMinimizedGeometry(panelSurface.data(), iconRect); Test::flushWaylandConnection(); QTRY_COMPARE(client->iconGeometry(), iconRect.translated(panel->frameGeometry().topLeft())); // Load effect that will be tested. QFETCH(QString, effectName); auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Start the minimize animation. client->minimize(); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Start the unminimize animation. client->unminimize(); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the panel. panelSurface.reset(); QVERIFY(Test::waitForWindowDestroyed(panel)); // Destroy the test client. surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } WAYLANDTEST_MAIN(MinimizeAnimationTest) #include "minimize_animation_test.moc" diff --git a/autotests/integration/effects/popup_open_close_animation_test.cpp b/autotests/integration/effects/popup_open_close_animation_test.cpp index 3f25e5a91..349fa2dae 100644 --- a/autotests/integration/effects/popup_open_close_animation_test.cpp +++ b/autotests/integration/effects/popup_open_close_animation_test.cpp @@ -1,280 +1,280 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include "deleted.h" #include "effectloader.h" #include "effects.h" #include "internal_client.h" #include "platform.h" #include "xdgshellclient.h" #include "useractions.h" #include "wayland_server.h" #include "workspace.h" #include "decorations/decoratedclient.h" #include "effect_builtins.h" #include #include #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_popup_open_close_animation-0"); class PopupOpenCloseAnimationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testAnimatePopups(); void testAnimateUserActionsPopup(); void testAnimateDecorationTooltips(); }; void PopupOpenCloseAnimationTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); } void PopupOpenCloseAnimationTest::init() { QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::XdgDecoration)); } void PopupOpenCloseAnimationTest::cleanup() { auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); Test::destroyWaylandConnection(); } void PopupOpenCloseAnimationTest::testAnimatePopups() { // This test verifies that popup open/close animation effects try // to animate popups(e.g. popup menus, tooltips, etc). // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Create the main window. using namespace KWayland::Client; QScopedPointer mainWindowSurface(Test::createSurface()); QVERIFY(!mainWindowSurface.isNull()); QScopedPointer mainWindowShellSurface(Test::createXdgShellStableSurface(mainWindowSurface.data())); QVERIFY(!mainWindowShellSurface.isNull()); XdgShellClient *mainWindow = Test::renderAndWaitForShown(mainWindowSurface.data(), QSize(100, 50), Qt::blue); QVERIFY(mainWindow); // Load effect that will be tested. const QString effectName = QStringLiteral("kwin4_effect_fadingpopups"); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Create a popup, it should be animated. QScopedPointer popupSurface(Test::createSurface()); QVERIFY(!popupSurface.isNull()); XdgPositioner positioner(QSize(20, 20), QRect(0, 0, 10, 10)); positioner.setGravity(Qt::BottomEdge | Qt::RightEdge); positioner.setAnchorEdge(Qt::BottomEdge | Qt::LeftEdge); QScopedPointer popupShellSurface(Test::createXdgShellStablePopup(popupSurface.data(), mainWindowShellSurface.data(), positioner)); QVERIFY(!popupShellSurface.isNull()); XdgShellClient *popup = Test::renderAndWaitForShown(popupSurface.data(), positioner.initialSize(), Qt::red); QVERIFY(popup); QVERIFY(popup->isPopupWindow()); QCOMPARE(popup->transientFor(), mainWindow); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the popup, it should not be animated. QSignalSpy popupClosedSpy(popup, &XdgShellClient::windowClosed); QVERIFY(popupClosedSpy.isValid()); popupShellSurface.reset(); popupSurface.reset(); QVERIFY(popupClosedSpy.wait()); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the main window. mainWindowSurface.reset(); QVERIFY(Test::waitForWindowDestroyed(mainWindow)); } void PopupOpenCloseAnimationTest::testAnimateUserActionsPopup() { // This test verifies that popup open/close animation effects try // to animate the user actions popup. // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Create the test client. using namespace KWayland::Client; QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); // Load effect that will be tested. const QString effectName = QStringLiteral("kwin4_effect_fadingpopups"); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Show the user actions popup. workspace()->showWindowMenu(QRect(), client); auto userActionsMenu = workspace()->userActionsMenu(); QTRY_VERIFY(userActionsMenu->isShown()); QVERIFY(userActionsMenu->hasClient()); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Close the user actions popup. kwinApp()->platform()->keyboardKeyPressed(KEY_ESC, 0); kwinApp()->platform()->keyboardKeyReleased(KEY_ESC, 1); QTRY_VERIFY(!userActionsMenu->isShown()); QVERIFY(!userActionsMenu->hasClient()); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the test client. surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } void PopupOpenCloseAnimationTest::testAnimateDecorationTooltips() { // This test verifies that popup open/close animation effects try // to animate decoration tooltips. // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Create the test client. using namespace KWayland::Client; QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); QScopedPointer deco(Test::xdgDecorationManager()->getToplevelDecoration(shellSurface.data())); QVERIFY(!deco.isNull()); deco->setMode(XdgDecoration::Mode::ServerSide); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isDecorated()); // Load effect that will be tested. const QString effectName = QStringLiteral("kwin4_effect_fadingpopups"); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Show a decoration tooltip. QSignalSpy tooltipAddedSpy(workspace(), &Workspace::internalClientAdded); QVERIFY(tooltipAddedSpy.isValid()); client->decoratedClient()->requestShowToolTip(QStringLiteral("KWin rocks!")); QVERIFY(tooltipAddedSpy.wait()); InternalClient *tooltip = tooltipAddedSpy.first().first().value(); QVERIFY(tooltip->isInternal()); QVERIFY(tooltip->isPopupWindow()); QVERIFY(tooltip->internalWindow()->flags().testFlag(Qt::ToolTip)); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Hide the decoration tooltip. QSignalSpy tooltipClosedSpy(tooltip, &InternalClient::windowClosed); QVERIFY(tooltipClosedSpy.isValid()); client->decoratedClient()->requestHideToolTip(); QVERIFY(tooltipClosedSpy.wait()); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Destroy the test client. surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } WAYLANDTEST_MAIN(PopupOpenCloseAnimationTest) #include "popup_open_close_animation_test.moc" diff --git a/autotests/integration/effects/toplevel_open_close_animation_test.cpp b/autotests/integration/effects/toplevel_open_close_animation_test.cpp index 03432135e..cce83496e 100644 --- a/autotests/integration/effects/toplevel_open_close_animation_test.cpp +++ b/autotests/integration/effects/toplevel_open_close_animation_test.cpp @@ -1,224 +1,224 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "abstract_client.h" #include "composite.h" #include "deleted.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "scene.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_toplevel_open_close_animation-0"); class ToplevelOpenCloseAnimationTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testAnimateToplevels_data(); void testAnimateToplevels(); void testDontAnimatePopups_data(); void testDontAnimatePopups(); }; void ToplevelOpenCloseAnimationTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (const QString &name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("KWIN_COMPOSE", QByteArrayLiteral("O2")); qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", QByteArrayLiteral("1")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); auto scene = KWin::Compositor::self()->scene(); QVERIFY(scene); QCOMPARE(scene->compositingType(), KWin::OpenGL2Compositing); } void ToplevelOpenCloseAnimationTest::init() { QVERIFY(Test::setupWaylandConnection()); } void ToplevelOpenCloseAnimationTest::cleanup() { auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); effectsImpl->unloadAllEffects(); QVERIFY(effectsImpl->loadedEffects().isEmpty()); Test::destroyWaylandConnection(); } void ToplevelOpenCloseAnimationTest::testAnimateToplevels_data() { QTest::addColumn("effectName"); QTest::newRow("Fade") << QStringLiteral("kwin4_effect_fade"); QTest::newRow("Glide") << QStringLiteral("glide"); QTest::newRow("Scale") << QStringLiteral("kwin4_effect_scale"); } void ToplevelOpenCloseAnimationTest::testAnimateToplevels() { // This test verifies that window open/close animation effects try to // animate the appearing and the disappearing of toplevel windows. // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Load effect that will be tested. QFETCH(QString, effectName); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Create the test client. using namespace KWayland::Client; QScopedPointer surface(Test::createSurface()); QVERIFY(!surface.isNull()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QVERIFY(!shellSurface.isNull()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); // Close the test client, the effect should start animating the disappearing // of the client. QSignalSpy windowClosedSpy(client, &XdgShellClient::windowClosed); QVERIFY(windowClosedSpy.isValid()); shellSurface.reset(); surface.reset(); QVERIFY(windowClosedSpy.wait()); QVERIFY(effect->isActive()); // Eventually, the animation will be complete. QTRY_VERIFY(!effect->isActive()); } void ToplevelOpenCloseAnimationTest::testDontAnimatePopups_data() { QTest::addColumn("effectName"); QTest::newRow("Fade") << QStringLiteral("kwin4_effect_fade"); QTest::newRow("Glide") << QStringLiteral("glide"); QTest::newRow("Scale") << QStringLiteral("kwin4_effect_scale"); } void ToplevelOpenCloseAnimationTest::testDontAnimatePopups() { // This test verifies that window open/close animation effects don't try // to animate popups(e.g. popup menus, tooltips, etc). // Make sure that we have the right effects ptr. auto effectsImpl = qobject_cast(effects); QVERIFY(effectsImpl); // Create the main window. using namespace KWayland::Client; QScopedPointer mainWindowSurface(Test::createSurface()); QVERIFY(!mainWindowSurface.isNull()); QScopedPointer mainWindowShellSurface(Test::createXdgShellStableSurface(mainWindowSurface.data())); QVERIFY(!mainWindowShellSurface.isNull()); XdgShellClient *mainWindow = Test::renderAndWaitForShown(mainWindowSurface.data(), QSize(100, 50), Qt::blue); QVERIFY(mainWindow); // Load effect that will be tested. QFETCH(QString, effectName); QVERIFY(effectsImpl->loadEffect(effectName)); QCOMPARE(effectsImpl->loadedEffects().count(), 1); QCOMPARE(effectsImpl->loadedEffects().first(), effectName); Effect *effect = effectsImpl->findEffect(effectName); QVERIFY(effect); QVERIFY(!effect->isActive()); // Create a popup, it should not be animated. QScopedPointer popupSurface(Test::createSurface()); QVERIFY(!popupSurface.isNull()); XdgPositioner positioner(QSize(20, 20), QRect(0, 0, 10, 10)); positioner.setGravity(Qt::BottomEdge | Qt::RightEdge); positioner.setAnchorEdge(Qt::BottomEdge | Qt::LeftEdge); QScopedPointer popupShellSurface(Test::createXdgShellStablePopup(popupSurface.data(), mainWindowShellSurface.data(), positioner)); QVERIFY(!popupShellSurface.isNull()); XdgShellClient *popup = Test::renderAndWaitForShown(popupSurface.data(), positioner.initialSize(), Qt::red); QVERIFY(popup); QVERIFY(popup->isPopupWindow()); QCOMPARE(popup->transientFor(), mainWindow); QVERIFY(!effect->isActive()); // Destroy the popup, it should not be animated. QSignalSpy popupClosedSpy(popup, &XdgShellClient::windowClosed); QVERIFY(popupClosedSpy.isValid()); popupShellSurface.reset(); popupSurface.reset(); QVERIFY(popupClosedSpy.wait()); QVERIFY(!effect->isActive()); // Destroy the main window. mainWindowSurface.reset(); QVERIFY(Test::waitForWindowDestroyed(mainWindow)); } WAYLANDTEST_MAIN(ToplevelOpenCloseAnimationTest) #include "toplevel_open_close_animation_test.moc" diff --git a/autotests/integration/fakes/org.kde.kdecoration2/fakedecoration_with_shadows.cpp b/autotests/integration/fakes/org.kde.kdecoration2/fakedecoration_with_shadows.cpp index 7f0ff51dc..29052ab10 100644 --- a/autotests/integration/fakes/org.kde.kdecoration2/fakedecoration_with_shadows.cpp +++ b/autotests/integration/fakes/org.kde.kdecoration2/fakedecoration_with_shadows.cpp @@ -1,72 +1,72 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 #include #include class FakeDecoWithShadows : public KDecoration2::Decoration { Q_OBJECT public: explicit FakeDecoWithShadows(QObject *parent = nullptr, const QVariantList &args = QVariantList()) : Decoration(parent, args) {} ~FakeDecoWithShadows() override {} void paint(QPainter *painter, const QRect &repaintRegion) override { Q_UNUSED(painter) Q_UNUSED(repaintRegion) } public Q_SLOTS: void init() override { const int shadowSize = 128; const int offsetTop = 64; const int offsetLeft = 48; const QRect shadowRect(0, 0, 4 * shadowSize + 1, 4 * shadowSize + 1); QImage shadowTexture(shadowRect.size(), QImage::Format_ARGB32_Premultiplied); shadowTexture.fill(Qt::transparent); const QMargins padding( shadowSize - offsetLeft, shadowSize - offsetTop, shadowSize + offsetLeft, shadowSize + offsetTop); auto decoShadow = QSharedPointer::create(); decoShadow->setPadding(padding); decoShadow->setInnerShadowRect(QRect(shadowRect.center(), QSize(1, 1))); decoShadow->setShadow(shadowTexture); setShadow(decoShadow); } }; K_PLUGIN_FACTORY_WITH_JSON( FakeDecoWithShadowsFactory, "fakedecoration_with_shadows.json", registerPlugin(); ) #include "fakedecoration_with_shadows.moc" diff --git a/autotests/integration/placement_test.cpp b/autotests/integration/placement_test.cpp index 0d6611346..404023b30 100644 --- a/autotests/integration/placement_test.cpp +++ b/autotests/integration/placement_test.cpp @@ -1,361 +1,361 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2019 David Edmundson -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "cursor.h" #include "kwin_wayland_test.h" #include "platform.h" #include "screens.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include #include #include #include #include #include #include using namespace KWin; using namespace KWayland::Client; static const QString s_socketName = QStringLiteral("wayland_test_kwin_placement-0"); struct PlaceWindowResult { QSize initiallyConfiguredSize; KWayland::Client::XdgShellSurface::States initiallyConfiguredStates; QRect finalGeometry; }; class TestPlacement : public QObject { Q_OBJECT private Q_SLOTS: void init(); void cleanup(); void initTestCase(); void testPlaceSmart(); void testPlaceZeroCornered(); void testPlaceMaximized(); void testPlaceMaximizedLeavesFullscreen(); void testPlaceCentered(); void testPlaceUnderMouse(); void testPlaceCascaded(); void testPlaceRandom(); private: void setPlacementPolicy(Placement::Policy policy); /* * Create a window with the lifespan of parent and return relevant results for testing * defaultSize is the buffer size to use if the compositor returns an empty size in the first configure * event. */ PlaceWindowResult createAndPlaceWindow(const QSize &defaultSize, QObject *parent); }; void TestPlacement::init() { QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::XdgDecoration | Test::AdditionalWaylandInterface::PlasmaShell)); screens()->setCurrent(0); KWin::Cursor::setPos(QPoint(512, 512)); } void TestPlacement::cleanup() { Test::destroyWaylandConnection(); } void TestPlacement::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, 2)); kwinApp()->setConfig(KSharedConfig::openConfig(QString(), KConfig::SimpleConfig)); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QCOMPARE(screens()->count(), 2); QCOMPARE(screens()->geometry(0), QRect(0, 0, 1280, 1024)); QCOMPARE(screens()->geometry(1), QRect(1280, 0, 1280, 1024)); waylandServer()->initWorkspace(); } void TestPlacement::setPlacementPolicy(Placement::Policy policy) { auto group = kwinApp()->config()->group("Windows"); group.writeEntry("Placement", Placement::policyToString(policy)); group.sync(); Workspace::self()->slotReconfigure(); } PlaceWindowResult TestPlacement::createAndPlaceWindow(const QSize &defaultSize, QObject *parent) { PlaceWindowResult rc; // create a new window auto surface = Test::createSurface(parent); auto shellSurface = Test::createXdgShellStableSurface(surface, surface, Test::CreationSetup::CreateOnly); QSignalSpy configSpy(shellSurface, &XdgShellSurface::configureRequested); surface->commit(Surface::CommitFlag::None); configSpy.wait(); rc.initiallyConfiguredSize = configSpy[0][0].toSize(); rc.initiallyConfiguredStates = configSpy[0][1].value(); shellSurface->ackConfigure(configSpy[0][2].toUInt()); QSize size = rc.initiallyConfiguredSize; if (size.isEmpty()) { size = defaultSize; } auto c = Test::renderAndWaitForShown(surface, size, Qt::red); rc.finalGeometry = c->frameGeometry(); return rc; } void TestPlacement::testPlaceSmart() { setPlacementPolicy(Placement::Smart); QScopedPointer testParent(new QObject); //dumb QObject just for scoping surfaces to the test QRegion usedArea; for (int i = 0; i < 4; i++) { PlaceWindowResult windowPlacement = createAndPlaceWindow(QSize(600, 500), testParent.data()); // smart placement shouldn't define a size on clients QCOMPARE(windowPlacement.initiallyConfiguredSize, QSize(0, 0)); QCOMPARE(windowPlacement.finalGeometry.size(), QSize(600, 500)); // exact placement isn't a defined concept that should be tested // but the goal of smart placement is to make sure windows don't overlap until they need to // 4 windows of 600, 500 should fit without overlap QVERIFY(!usedArea.intersects(windowPlacement.finalGeometry)); usedArea += windowPlacement.finalGeometry; } } void TestPlacement::testPlaceZeroCornered() { setPlacementPolicy(Placement::ZeroCornered); QScopedPointer testParent(new QObject); for (int i = 0; i < 4; i++) { PlaceWindowResult windowPlacement = createAndPlaceWindow(QSize(600, 500), testParent.data()); // smart placement shouldn't define a size on clients QCOMPARE(windowPlacement.initiallyConfiguredSize, QSize(0, 0)); // size should match our buffer QCOMPARE(windowPlacement.finalGeometry.size(), QSize(600, 500)); //and it should be in the corner QCOMPARE(windowPlacement.finalGeometry.topLeft(), QPoint(0, 0)); } } void TestPlacement::testPlaceMaximized() { setPlacementPolicy(Placement::Maximizing); // add a top panel QScopedPointer panelSurface(Test::createSurface()); QScopedPointer panelShellSurface(Test::createXdgShellStableSurface(panelSurface.data())); QScopedPointer plasmaSurface(Test::waylandPlasmaShell()->createSurface(panelSurface.data())); plasmaSurface->setRole(PlasmaShellSurface::Role::Panel); plasmaSurface->setPosition(QPoint(0, 0)); Test::renderAndWaitForShown(panelSurface.data(), QSize(1280, 20), Qt::blue); QScopedPointer testParent(new QObject); // all windows should be initially maximized with an initial configure size sent for (int i = 0; i < 4; i++) { PlaceWindowResult windowPlacement = createAndPlaceWindow(QSize(600, 500), testParent.data()); QVERIFY(windowPlacement.initiallyConfiguredStates & XdgShellSurface::State::Maximized); QCOMPARE(windowPlacement.initiallyConfiguredSize, QSize(1280, 1024 - 20)); QCOMPARE(windowPlacement.finalGeometry, QRect(0, 20, 1280, 1024 - 20)); // under the panel } } void TestPlacement::testPlaceMaximizedLeavesFullscreen() { setPlacementPolicy(Placement::Maximizing); // add a top panel QScopedPointer panelSurface(Test::createSurface()); QScopedPointer panelShellSurface(Test::createXdgShellStableSurface(panelSurface.data())); QScopedPointer plasmaSurface(Test::waylandPlasmaShell()->createSurface(panelSurface.data())); plasmaSurface->setRole(PlasmaShellSurface::Role::Panel); plasmaSurface->setPosition(QPoint(0, 0)); Test::renderAndWaitForShown(panelSurface.data(), QSize(1280, 20), Qt::blue); QScopedPointer testParent(new QObject); // all windows should be initially fullscreen with an initial configure size sent, despite the policy for (int i = 0; i < 4; i++) { auto surface = Test::createSurface(testParent.data()); auto shellSurface = Test::createXdgShellStableSurface(surface, surface, Test::CreationSetup::CreateOnly); shellSurface->setFullscreen(true); QSignalSpy configSpy(shellSurface, &XdgShellSurface::configureRequested); surface->commit(Surface::CommitFlag::None); configSpy.wait(); auto initiallyConfiguredSize = configSpy[0][0].toSize(); auto initiallyConfiguredStates = configSpy[0][1].value(); shellSurface->ackConfigure(configSpy[0][2].toUInt()); auto c = Test::renderAndWaitForShown(surface, initiallyConfiguredSize, Qt::red); QVERIFY(initiallyConfiguredStates & XdgShellSurface::State::Fullscreen); QCOMPARE(initiallyConfiguredSize, QSize(1280, 1024 )); QCOMPARE(c->frameGeometry(), QRect(0, 0, 1280, 1024)); } } void TestPlacement::testPlaceCentered() { // This test verifies that Centered placement policy works. KConfigGroup group = kwinApp()->config()->group("Windows"); group.writeEntry("Placement", Placement::policyToString(Placement::Centered)); group.sync(); workspace()->slotReconfigure(); QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::red); QVERIFY(client); QCOMPARE(client->frameGeometry(), QRect(590, 487, 100, 50)); shellSurface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } void TestPlacement::testPlaceUnderMouse() { // This test verifies that Under Mouse placement policy works. KConfigGroup group = kwinApp()->config()->group("Windows"); group.writeEntry("Placement", Placement::policyToString(Placement::UnderMouse)); group.sync(); workspace()->slotReconfigure(); KWin::Cursor::setPos(QPoint(200, 300)); QCOMPARE(KWin::Cursor::pos(), QPoint(200, 300)); QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::red); QVERIFY(client); QCOMPARE(client->frameGeometry(), QRect(151, 276, 100, 50)); shellSurface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } void TestPlacement::testPlaceCascaded() { // This test verifies that Cascaded placement policy works. KConfigGroup group = kwinApp()->config()->group("Windows"); group.writeEntry("Placement", Placement::policyToString(Placement::Cascade)); group.sync(); workspace()->slotReconfigure(); QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::red); QVERIFY(client1); QCOMPARE(client1->pos(), QPoint(0, 0)); QCOMPARE(client1->size(), QSize(100, 50)); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QCOMPARE(client2->pos(), client1->pos() + workspace()->cascadeOffset(client2)); QCOMPARE(client2->size(), QSize(100, 50)); QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::green); QVERIFY(client3); QCOMPARE(client3->pos(), client2->pos() + workspace()->cascadeOffset(client3)); QCOMPARE(client3->size(), QSize(100, 50)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); } void TestPlacement::testPlaceRandom() { // This test verifies that Random placement policy works. KConfigGroup group = kwinApp()->config()->group("Windows"); group.writeEntry("Placement", Placement::policyToString(Placement::Random)); group.sync(); workspace()->slotReconfigure(); QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::red); QVERIFY(client1); QCOMPARE(client1->size(), QSize(100, 50)); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::blue); QVERIFY(client2); QVERIFY(client2->pos() != client1->pos()); QCOMPARE(client2->size(), QSize(100, 50)); QScopedPointer surface3(Test::createSurface()); QScopedPointer shellSurface3(Test::createXdgShellStableSurface(surface3.data())); XdgShellClient *client3 = Test::renderAndWaitForShown(surface3.data(), QSize(100, 50), Qt::green); QVERIFY(client3); QVERIFY(client3->pos() != client1->pos()); QVERIFY(client3->pos() != client2->pos()); QCOMPARE(client3->size(), QSize(100, 50)); shellSurface3.reset(); QVERIFY(Test::waitForWindowDestroyed(client3)); shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); } WAYLANDTEST_MAIN(TestPlacement) #include "placement_test.moc" diff --git a/autotests/integration/scene_opengl_shadow_test.cpp b/autotests/integration/scene_opengl_shadow_test.cpp index dd120e75f..476bb257c 100644 --- a/autotests/integration/scene_opengl_shadow_test.cpp +++ b/autotests/integration/scene_opengl_shadow_test.cpp @@ -1,864 +1,864 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kwin_wayland_test.h" #include "composite.h" #include "effect_builtins.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "shadow.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" Q_DECLARE_METATYPE(KWin::WindowQuadList); using namespace KWin; using namespace KWayland::Client; static const QString s_socketName = QStringLiteral("wayland_test_kwin_scene_opengl_shadow-0"); class SceneOpenGLShadowTest : public QObject { Q_OBJECT public: SceneOpenGLShadowTest() {} private Q_SLOTS: void initTestCase(); void cleanup(); void testShadowTileOverlaps_data(); void testShadowTileOverlaps(); void testNoCornerShadowTiles(); void testDistributeHugeCornerTiles(); }; inline bool isClose(double a, double b, double eps = 1e-5) { if (a == b) { return true; } const double diff = std::fabs(a - b); if (a == 0 || b == 0) { return diff < eps; } return diff / std::max(a, b) < eps; } inline bool compareQuads(const WindowQuad &a, const WindowQuad &b) { for (int i = 0; i < 4; i++) { if (!isClose(a[i].x(), b[i].x()) || !isClose(a[i].y(), b[i].y()) || !isClose(a[i].u(), b[i].u()) || !isClose(a[i].v(), b[i].v())) { return false; } } return true; } inline WindowQuad makeShadowQuad(const QRectF &geo, qreal tx1, qreal ty1, qreal tx2, qreal ty2) { WindowQuad quad(WindowQuadShadow); quad[0] = WindowVertex(geo.left(), geo.top(), tx1, ty1); quad[1] = WindowVertex(geo.right(), geo.top(), tx2, ty1); quad[2] = WindowVertex(geo.right(), geo.bottom(), tx2, ty2); quad[3] = WindowVertex(geo.left(), geo.bottom(), tx1, ty2); return quad; } void SceneOpenGLShadowTest::initTestCase() { // Copied from generic_scene_opengl_test.cpp qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); // disable all effects - we don't want to have it interact with the rendering auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (QString name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); qputenv("XCURSOR_THEME", QByteArrayLiteral("DMZ-White")); qputenv("XCURSOR_SIZE", QByteArrayLiteral("24")); qputenv("KWIN_COMPOSE", QByteArrayLiteral("O2")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QVERIFY(KWin::Compositor::self()); // Add directory with fake decorations to the plugin search path. QCoreApplication::addLibraryPath( QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("fakes") ); // Change decoration theme. KConfigGroup group = kwinApp()->config()->group("org.kde.kdecoration2"); group.writeEntry("library", "org.kde.test.fakedecowithshadows"); group.sync(); Workspace::self()->slotReconfigure(); auto scene = KWin::Compositor::self()->scene(); QVERIFY(scene); QCOMPARE(scene->compositingType(), KWin::OpenGL2Compositing); } void SceneOpenGLShadowTest::cleanup() { Test::destroyWaylandConnection(); } namespace { const int SHADOW_SIZE = 128; const int SHADOW_OFFSET_TOP = 64; const int SHADOW_OFFSET_LEFT = 48; // NOTE: We assume deco shadows are generated with blur so that's // why there is 4, 1 is the size of the inner shadow rect. const int SHADOW_TEXTURE_WIDTH = 4 * SHADOW_SIZE + 1; const int SHADOW_TEXTURE_HEIGHT = 4 * SHADOW_SIZE + 1; const int SHADOW_PADDING_TOP = SHADOW_SIZE - SHADOW_OFFSET_TOP; const int SHADOW_PADDING_RIGHT = SHADOW_SIZE + SHADOW_OFFSET_LEFT; const int SHADOW_PADDING_BOTTOM = SHADOW_SIZE + SHADOW_OFFSET_TOP; const int SHADOW_PADDING_LEFT = SHADOW_SIZE - SHADOW_OFFSET_LEFT; const QRectF SHADOW_INNER_RECT(2 * SHADOW_SIZE, 2 * SHADOW_SIZE, 1, 1); } void SceneOpenGLShadowTest::testShadowTileOverlaps_data() { QTest::addColumn("windowSize"); QTest::addColumn("expectedQuads"); // Precompute shadow tile geometries(in texture's space). const QRectF topLeftTile( 0, 0, SHADOW_INNER_RECT.x(), SHADOW_INNER_RECT.y()); const QRectF topRightTile( SHADOW_INNER_RECT.right(), 0, SHADOW_TEXTURE_WIDTH - SHADOW_INNER_RECT.right(), SHADOW_INNER_RECT.y()); const QRectF topTile(topLeftTile.topRight(), topRightTile.bottomLeft()); const QRectF bottomLeftTile( 0, SHADOW_INNER_RECT.bottom(), SHADOW_INNER_RECT.x(), SHADOW_TEXTURE_HEIGHT - SHADOW_INNER_RECT.bottom()); const QRectF bottomRightTile( SHADOW_INNER_RECT.right(), SHADOW_INNER_RECT.bottom(), SHADOW_TEXTURE_WIDTH - SHADOW_INNER_RECT.right(), SHADOW_TEXTURE_HEIGHT - SHADOW_INNER_RECT.bottom()); const QRectF bottomTile(bottomLeftTile.topRight(), bottomRightTile.bottomLeft()); const QRectF leftTile(topLeftTile.bottomLeft(), bottomLeftTile.topRight()); const QRectF rightTile(topRightTile.bottomLeft(), bottomRightTile.topRight()); qreal tx1 = 0; qreal ty1 = 0; qreal tx2 = 0; qreal ty2 = 0; // Explanation behind numbers: (256+1 x 256+1) is the minimum window size // which doesn't cause overlapping of shadow tiles. For example, if a window // has (256 x 256+1) size, top-left and top-right or bottom-left and // bottom-right shadow tiles overlap. // No overlaps: In this case corner tiles are rendered as they are, // and top/right/bottom/left tiles are stretched. { const QSize windowSize(256 + 1, 256 + 1); WindowQuadList shadowQuads; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); const QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); tx1 = topLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topLeftTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); const QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); tx1 = topRightTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); const QRectF top(topLeft.topRight(), topRight.bottomLeft()); tx1 = topTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(top, tx1, ty1, tx2, ty2); const QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); tx1 = bottomLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = bottomLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = bottomLeftTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); const QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); tx1 = bottomRightTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = bottomRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = bottomRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF bottom(bottomLeft.topRight(), bottomRight.bottomLeft()); tx1 = bottomTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = bottomTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = bottomTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottom, tx1, ty1, tx2, ty2); const QRectF left(topLeft.bottomLeft(), bottomLeft.topRight()); tx1 = leftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = leftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = leftTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = leftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(left, tx1, ty1, tx2, ty2); const QRectF right(topRight.bottomLeft(), bottomRight.topRight()); tx1 = rightTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = rightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = rightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = rightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(right, tx1, ty1, tx2, ty2); QTest::newRow("no overlaps") << windowSize << shadowQuads; } // Top-Left & Bottom-Left/Top-Right & Bottom-Right overlap: // In this case overlapping parts are clipped and left/right // tiles aren't rendered. const QVector> verticalOverlapTestTable { QPair { QByteArray("top-left & bottom-left/top-right & bottom-right overlap"), QSize(256 + 1, 256) }, QPair { QByteArray("top-left & bottom-left/top-right & bottom-right overlap :: pre"), QSize(256 + 1, 256 - 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : verticalOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); halfOverlap = qAbs(topLeft.bottom() - bottomLeft.top()) / 2; topLeft.setBottom(topLeft.bottom() - halfOverlap); bottomLeft.setTop(bottomLeft.top() + halfOverlap); tx1 = topLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topLeftTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topLeft.height() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = bottomLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = 1.0 - (bottomLeft.height() / SHADOW_TEXTURE_HEIGHT); tx2 = bottomLeftTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(topRight.bottom() - bottomRight.top()) / 2; topRight.setBottom(topRight.bottom() - halfOverlap); bottomRight.setTop(bottomRight.top() + halfOverlap); tx1 = topRightTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topRight.height() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); tx1 = bottomRightTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = 1.0 - (bottomRight.height() / SHADOW_TEXTURE_HEIGHT); tx2 = bottomRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF top(topLeft.topRight(), topRight.bottomLeft()); tx1 = topTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = top.height() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(top, tx1, ty1, tx2, ty2); const QRectF bottom(bottomLeft.topRight(), bottomRight.bottomLeft()); tx1 = bottomTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = 1.0 - (bottom.height() / SHADOW_TEXTURE_HEIGHT); tx2 = bottomTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottom, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // Top-Left & Top-Right/Bottom-Left & Bottom-Right overlap: // In this case overlapping parts are clipped and top/bottom // tiles aren't rendered. const QVector> horizontalOverlapTestTable { QPair { QByteArray("top-left & top-right/bottom-left & bottom-right overlap"), QSize(256, 256 + 1) }, QPair { QByteArray("top-left & top-right/bottom-left & bottom-right overlap :: pre"), QSize(256 - 1, 256 + 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : horizontalOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); halfOverlap = qAbs(topLeft.right() - topRight.left()) / 2; topLeft.setRight(topLeft.right() - halfOverlap); topRight.setLeft(topRight.left() + halfOverlap); tx1 = topLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topLeft.width() / SHADOW_TEXTURE_WIDTH; ty2 = topLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = 1.0 - (topRight.width() / SHADOW_TEXTURE_WIDTH); ty1 = topRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(bottomLeft.right() - bottomRight.left()) / 2; bottomLeft.setRight(bottomLeft.right() - halfOverlap); bottomRight.setLeft(bottomRight.left() + halfOverlap); tx1 = bottomLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = bottomLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = bottomLeft.width() / SHADOW_TEXTURE_WIDTH; ty2 = bottomLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); tx1 = 1.0 - (bottomRight.width() / SHADOW_TEXTURE_WIDTH); ty1 = bottomRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = bottomRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF left(topLeft.bottomLeft(), bottomLeft.topRight()); tx1 = leftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = leftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = left.width() / SHADOW_TEXTURE_WIDTH; ty2 = leftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(left, tx1, ty1, tx2, ty2); const QRectF right(topRight.bottomLeft(), bottomRight.topRight()); tx1 = 1.0 - (right.width() / SHADOW_TEXTURE_WIDTH); ty1 = rightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = rightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = rightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(right, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // All shadow tiles overlap: In this case all overlapping parts // are clippend and top/right/bottom/left tiles aren't rendered. const QVector> allOverlapTestTable { QPair { QByteArray("all corner tiles overlap"), QSize(256, 256) }, QPair { QByteArray("all corner tiles overlap :: pre"), QSize(256 - 1, 256 - 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : allOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(topLeft.right() - topRight.left()) / 2; topLeft.setRight(topLeft.right() - halfOverlap); topRight.setLeft(topRight.left() + halfOverlap); halfOverlap = qAbs(bottomLeft.right() - bottomRight.left()) / 2; bottomLeft.setRight(bottomLeft.right() - halfOverlap); bottomRight.setLeft(bottomRight.left() + halfOverlap); halfOverlap = qAbs(topLeft.bottom() - bottomLeft.top()) / 2; topLeft.setBottom(topLeft.bottom() - halfOverlap); bottomLeft.setTop(bottomLeft.top() + halfOverlap); halfOverlap = qAbs(topRight.bottom() - bottomRight.top()) / 2; topRight.setBottom(topRight.bottom() - halfOverlap); bottomRight.setTop(bottomRight.top() + halfOverlap); tx1 = topLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = topLeftTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topLeft.width() / SHADOW_TEXTURE_WIDTH; ty2 = topLeft.height() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = 1.0 - (topRight.width() / SHADOW_TEXTURE_WIDTH); ty1 = topRightTile.top() / SHADOW_TEXTURE_HEIGHT; tx2 = topRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = topRight.height() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); tx1 = bottomLeftTile.left() / SHADOW_TEXTURE_WIDTH; ty1 = 1.0 - (bottomLeft.height() / SHADOW_TEXTURE_HEIGHT); tx2 = bottomLeft.width() / SHADOW_TEXTURE_WIDTH; ty2 = bottomLeftTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); tx1 = 1.0 - (bottomRight.width() / SHADOW_TEXTURE_WIDTH); ty1 = 1.0 - (bottomRight.height() / SHADOW_TEXTURE_HEIGHT); tx2 = bottomRightTile.right() / SHADOW_TEXTURE_WIDTH; ty2 = bottomRightTile.bottom() / SHADOW_TEXTURE_HEIGHT; shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // Window is too small: do not render any shadow tiles. { const QSize windowSize(1, 1); const WindowQuadList shadowQuads; QTest::newRow("window is too small") << windowSize << shadowQuads; } } void SceneOpenGLShadowTest::testShadowTileOverlaps() { QFETCH(QSize, windowSize); QFETCH(WindowQuadList, expectedQuads); QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::Decoration)); // Create a decorated client. QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QScopedPointer ssd(Test::waylandServerSideDecoration()->create(surface.data())); auto *client = Test::renderAndWaitForShown(surface.data(), windowSize, Qt::blue); QSignalSpy sizeChangedSpy(shellSurface.data(), &XdgShellSurface::sizeChanged); QVERIFY(sizeChangedSpy.isValid()); // Check the client is decorated. QVERIFY(client); QVERIFY(client->isDecorated()); auto *decoration = client->decoration(); QVERIFY(decoration); // If speciefied decoration theme is not found, KWin loads a default one // so we have to check whether a client has right decoration. auto decoShadow = decoration->shadow(); QCOMPARE(decoShadow->shadow().size(), QSize(SHADOW_TEXTURE_WIDTH, SHADOW_TEXTURE_HEIGHT)); QCOMPARE(decoShadow->paddingTop(), SHADOW_PADDING_TOP); QCOMPARE(decoShadow->paddingRight(), SHADOW_PADDING_RIGHT); QCOMPARE(decoShadow->paddingBottom(), SHADOW_PADDING_BOTTOM); QCOMPARE(decoShadow->paddingLeft(), SHADOW_PADDING_LEFT); // Get shadow. QVERIFY(client->effectWindow()); QVERIFY(client->effectWindow()->sceneWindow()); QVERIFY(client->effectWindow()->sceneWindow()->shadow()); auto *shadow = client->effectWindow()->sceneWindow()->shadow(); // Validate shadow quads. const WindowQuadList &quads = shadow->shadowQuads(); QCOMPARE(quads.size(), expectedQuads.size()); QVector mask(expectedQuads.size(), false); for (const auto &q : quads) { for (int i = 0; i < expectedQuads.size(); i++) { if (!compareQuads(q, expectedQuads[i])) { continue; } if (!mask[i]) { mask[i] = true; break; } else { QFAIL("got a duplicate shadow quad"); } } } for (const auto &v : qAsConst(mask)) { if (!v) { QFAIL("missed a shadow quad"); } } } void SceneOpenGLShadowTest::testNoCornerShadowTiles() { // this test verifies that top/right/bottom/left shadow tiles are // still drawn even when corner tiles are missing QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::ShadowManager)); // Create a surface. QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); auto *client = Test::renderAndWaitForShown(surface.data(), QSize(512, 512), Qt::blue); QVERIFY(client); QVERIFY(!client->isDecorated()); // Render reference shadow texture with the following params: // - shadow size: 128 // - inner rect size: 1 // - padding: 128 QImage referenceShadowTexture(256 + 1, 256 + 1, QImage::Format_ARGB32_Premultiplied); referenceShadowTexture.fill(Qt::transparent); // We don't care about content of the shadow. // Submit the shadow to KWin. QScopedPointer clientShadow(Test::waylandShadowManager()->createShadow(surface.data())); QVERIFY(clientShadow->isValid()); auto *shmPool = Test::waylandShmPool(); Buffer::Ptr bufferTop = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128, 0, 1, 128))); clientShadow->attachTop(bufferTop); Buffer::Ptr bufferRight = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128 + 1, 128, 128, 1))); clientShadow->attachRight(bufferRight); Buffer::Ptr bufferBottom = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128, 128 + 1, 1, 128))); clientShadow->attachBottom(bufferBottom); Buffer::Ptr bufferLeft = shmPool->createBuffer( referenceShadowTexture.copy(QRect(0, 128, 128, 1))); clientShadow->attachLeft(bufferLeft); clientShadow->setOffsets(QMarginsF(128, 128, 128, 128)); QSignalSpy shadowChangedSpy(client->surface(), &KWayland::Server::SurfaceInterface::shadowChanged); QVERIFY(shadowChangedSpy.isValid()); clientShadow->commit(); surface->commit(Surface::CommitFlag::None); QVERIFY(shadowChangedSpy.wait()); // Check that we got right shadow from the client. QPointer shadowIface = client->surface()->shadow(); QVERIFY(!shadowIface.isNull()); QCOMPARE(shadowIface->offset().left(), 128.0); QCOMPARE(shadowIface->offset().top(), 128.0); QCOMPARE(shadowIface->offset().right(), 128.0); QCOMPARE(shadowIface->offset().bottom(), 128.0); QVERIFY(client->effectWindow()); QVERIFY(client->effectWindow()->sceneWindow()); KWin::Shadow *shadow = client->effectWindow()->sceneWindow()->shadow(); QVERIFY(shadow != nullptr); const WindowQuadList &quads = shadow->shadowQuads(); QCOMPARE(quads.count(), 4); // Shadow size: 128 // Padding: QMargins(128, 128, 128, 128) // Inner rect: QRect(128, 128, 1, 1) // Texture size: QSize(257, 257) // Window size: QSize(512, 512) WindowQuadList expectedQuads; expectedQuads << makeShadowQuad(QRectF( 0, -128, 512, 128), 128.0 / 257.0, 0.0, 129.0 / 257.0, 128.0 / 257.0); // top expectedQuads << makeShadowQuad(QRectF( 512, 0, 128, 512), 129.0 / 257.0, 128.0 / 257.0, 1.0, 129.0 / 257.0); // right expectedQuads << makeShadowQuad(QRectF( 0, 512, 512, 128), 128.0 / 257.0, 129.0 / 257.0, 129.0 / 257.0, 1.0); // bottom expectedQuads << makeShadowQuad(QRectF(-128, 0, 128, 512), 0.0, 128.0 / 257.0, 128.0 / 257.0, 129.0 / 257.0); // left for (const WindowQuad &expectedQuad : expectedQuads) { auto it = std::find_if(quads.constBegin(), quads.constEnd(), [&expectedQuad](const WindowQuad &quad) { return compareQuads(quad, expectedQuad); }); if (it == quads.constEnd()) { const QString message = QStringLiteral("Missing shadow quad (left: %1, top: %2, right: %3, bottom: %4)") .arg(expectedQuad.left()) .arg(expectedQuad.top()) .arg(expectedQuad.right()) .arg(expectedQuad.bottom()); const QByteArray rawMessage = message.toLocal8Bit().data(); QFAIL(rawMessage.data()); } } } void SceneOpenGLShadowTest::testDistributeHugeCornerTiles() { // this test verifies that huge corner tiles are distributed correctly QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::ShadowManager)); // Create a surface. QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); auto *client = Test::renderAndWaitForShown(surface.data(), QSize(64, 64), Qt::blue); QVERIFY(client); QVERIFY(!client->isDecorated()); // Submit the shadow to KWin. QScopedPointer clientShadow(Test::waylandShadowManager()->createShadow(surface.data())); QVERIFY(clientShadow->isValid()); QImage referenceTileTexture(512, 512, QImage::Format_ARGB32_Premultiplied); referenceTileTexture.fill(Qt::transparent); auto *shmPool = Test::waylandShmPool(); Buffer::Ptr bufferTopLeft = shmPool->createBuffer(referenceTileTexture); clientShadow->attachTopLeft(bufferTopLeft); Buffer::Ptr bufferTopRight = shmPool->createBuffer(referenceTileTexture); clientShadow->attachTopRight(bufferTopRight); clientShadow->setOffsets(QMarginsF(256, 256, 256, 0)); QSignalSpy shadowChangedSpy(client->surface(), &KWayland::Server::SurfaceInterface::shadowChanged); QVERIFY(shadowChangedSpy.isValid()); clientShadow->commit(); surface->commit(Surface::CommitFlag::None); QVERIFY(shadowChangedSpy.wait()); // Check that we got right shadow from the client. QPointer shadowIface = client->surface()->shadow(); QVERIFY(!shadowIface.isNull()); QCOMPARE(shadowIface->offset().left(), 256.0); QCOMPARE(shadowIface->offset().top(), 256.0); QCOMPARE(shadowIface->offset().right(), 256.0); QCOMPARE(shadowIface->offset().bottom(), 0.0); QVERIFY(client->effectWindow()); QVERIFY(client->effectWindow()->sceneWindow()); KWin::Shadow *shadow = client->effectWindow()->sceneWindow()->shadow(); QVERIFY(shadow != nullptr); WindowQuadList expectedQuads; // Top-left quad expectedQuads << makeShadowQuad( QRectF(-256, -256, 256 + 32, 256 + 64), 0.0, 0.0, (256.0 + 32.0) / 1024.0, (256.0 + 64.0) / 512.0); // Top-right quad expectedQuads << makeShadowQuad( QRectF(32, -256, 256 + 32, 256 + 64), 1.0 - (256.0 + 32.0) / 1024.0, 0.0, 1.0, (256.0 + 64.0) / 512.0); const WindowQuadList &quads = shadow->shadowQuads(); QCOMPARE(quads.count(), expectedQuads.count()); for (const WindowQuad &expectedQuad : expectedQuads) { auto it = std::find_if(quads.constBegin(), quads.constEnd(), [&expectedQuad](const WindowQuad &quad) { return compareQuads(quad, expectedQuad); }); if (it == quads.constEnd()) { const QString message = QStringLiteral("Missing shadow quad (left: %1, top: %2, right: %3, bottom: %4)") .arg(expectedQuad.left()) .arg(expectedQuad.top()) .arg(expectedQuad.right()) .arg(expectedQuad.bottom()); const QByteArray rawMessage = message.toLocal8Bit().data(); QFAIL(rawMessage.data()); } } } WAYLANDTEST_MAIN(SceneOpenGLShadowTest) #include "scene_opengl_shadow_test.moc" diff --git a/autotests/integration/scene_qpainter_shadow_test.cpp b/autotests/integration/scene_qpainter_shadow_test.cpp index 6e8b32b80..ecd176a1e 100644 --- a/autotests/integration/scene_qpainter_shadow_test.cpp +++ b/autotests/integration/scene_qpainter_shadow_test.cpp @@ -1,781 +1,781 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kwin_wayland_test.h" #include "composite.h" #include "effect_builtins.h" #include "effectloader.h" #include "effects.h" #include "platform.h" #include "plugins/scenes/qpainter/scene_qpainter.h" #include "shadow.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" Q_DECLARE_METATYPE(KWin::WindowQuadList) using namespace KWin; using namespace KWayland::Client; static const QString s_socketName = QStringLiteral("wayland_test_kwin_scene_qpainter_shadow-0"); class SceneQPainterShadowTest : public QObject { Q_OBJECT public: SceneQPainterShadowTest() {} private Q_SLOTS: void initTestCase(); void cleanup(); void testShadowTileOverlaps_data(); void testShadowTileOverlaps(); void testShadowTextureReconstruction(); }; inline bool isClose(double a, double b, double eps = 1e-5) { if (a == b) { return true; } const double diff = std::fabs(a - b); if (a == 0 || b == 0) { return diff < eps; } return diff / std::max(a, b) < eps; } inline bool compareQuads(const WindowQuad &a, const WindowQuad &b) { for (int i = 0; i < 4; i++) { if (!isClose(a[i].x(), b[i].x()) || !isClose(a[i].y(), b[i].y()) || !isClose(a[i].textureX(), b[i].textureX()) || !isClose(a[i].textureY(), b[i].textureY())) { return false; } } return true; } inline WindowQuad makeShadowQuad(const QRectF &geo, qreal tx1, qreal ty1, qreal tx2, qreal ty2) { WindowQuad quad(WindowQuadShadow); quad[0] = WindowVertex(geo.left(), geo.top(), tx1, ty1); quad[1] = WindowVertex(geo.right(), geo.top(), tx2, ty1); quad[2] = WindowVertex(geo.right(), geo.bottom(), tx2, ty2); quad[3] = WindowVertex(geo.left(), geo.bottom(), tx1, ty2); return quad; } void SceneQPainterShadowTest::initTestCase() { // Copied from scene_qpainter_test.cpp qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); // disable all effects - we don't want to have it interact with the rendering auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins(config, QStringLiteral("Plugins")); ScriptedEffectLoader loader; const auto builtinNames = BuiltInEffects::availableEffectNames() << loader.listOfKnownEffects(); for (QString name : builtinNames) { plugins.writeEntry(name + QStringLiteral("Enabled"), false); } config->sync(); kwinApp()->setConfig(config); if (!QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("icons/DMZ-White/index.theme")).isEmpty()) { qputenv("XCURSOR_THEME", QByteArrayLiteral("DMZ-White")); } else { // might be vanilla-dmz (e.g. Arch, FreeBSD) qputenv("XCURSOR_THEME", QByteArrayLiteral("Vanilla-DMZ")); } qputenv("XCURSOR_SIZE", QByteArrayLiteral("24")); qputenv("KWIN_COMPOSE", QByteArrayLiteral("Q")); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QVERIFY(KWin::Compositor::self()); // Add directory with fake decorations to the plugin search path. QCoreApplication::addLibraryPath( QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("fakes") ); // Change decoration theme. KConfigGroup group = kwinApp()->config()->group("org.kde.kdecoration2"); group.writeEntry("library", "org.kde.test.fakedecowithshadows"); group.sync(); Workspace::self()->slotReconfigure(); } void SceneQPainterShadowTest::cleanup() { Test::destroyWaylandConnection(); } namespace { const int SHADOW_SIZE = 128; const int SHADOW_OFFSET_TOP = 64; const int SHADOW_OFFSET_LEFT = 48; // NOTE: We assume deco shadows are generated with blur so that's // why there is 4, 1 is the size of the inner shadow rect. const int SHADOW_TEXTURE_WIDTH = 4 * SHADOW_SIZE + 1; const int SHADOW_TEXTURE_HEIGHT = 4 * SHADOW_SIZE + 1; const int SHADOW_PADDING_TOP = SHADOW_SIZE - SHADOW_OFFSET_TOP; const int SHADOW_PADDING_RIGHT = SHADOW_SIZE + SHADOW_OFFSET_LEFT; const int SHADOW_PADDING_BOTTOM = SHADOW_SIZE + SHADOW_OFFSET_TOP; const int SHADOW_PADDING_LEFT = SHADOW_SIZE - SHADOW_OFFSET_LEFT; const QRectF SHADOW_INNER_RECT(2 * SHADOW_SIZE, 2 * SHADOW_SIZE, 1, 1); } void SceneQPainterShadowTest::testShadowTileOverlaps_data() { QTest::addColumn("windowSize"); QTest::addColumn("expectedQuads"); // Precompute shadow tile geometries(in texture's space). const QRectF topLeftTile( 0, 0, SHADOW_INNER_RECT.x(), SHADOW_INNER_RECT.y()); const QRectF topRightTile( SHADOW_INNER_RECT.right(), 0, SHADOW_TEXTURE_WIDTH - SHADOW_INNER_RECT.right(), SHADOW_INNER_RECT.y()); const QRectF topTile(topLeftTile.topRight(), topRightTile.bottomLeft()); const QRectF bottomLeftTile( 0, SHADOW_INNER_RECT.bottom(), SHADOW_INNER_RECT.x(), SHADOW_TEXTURE_HEIGHT - SHADOW_INNER_RECT.bottom()); const QRectF bottomRightTile( SHADOW_INNER_RECT.right(), SHADOW_INNER_RECT.bottom(), SHADOW_TEXTURE_WIDTH - SHADOW_INNER_RECT.right(), SHADOW_TEXTURE_HEIGHT - SHADOW_INNER_RECT.bottom()); const QRectF bottomTile(bottomLeftTile.topRight(), bottomRightTile.bottomLeft()); const QRectF leftTile(topLeftTile.bottomLeft(), bottomLeftTile.topRight()); const QRectF rightTile(topRightTile.bottomLeft(), bottomRightTile.topRight()); qreal tx1 = 0; qreal ty1 = 0; qreal tx2 = 0; qreal ty2 = 0; // Explanation behind numbers: (256+1 x 256+1) is the minimum window size // which doesn't cause overlapping of shadow tiles. For example, if a window // has (256 x 256+1) size, top-left and top-right or bottom-left and // bottom-right shadow tiles overlap. // No overlaps: In this case corner tiles are rendered as they are, // and top/right/bottom/left tiles are stretched. { const QSize windowSize(256 + 1, 256 + 1); WindowQuadList shadowQuads; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); const QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); tx1 = topLeftTile.left(); ty1 = topLeftTile.top(); tx2 = topLeftTile.right(); ty2 = topLeftTile.bottom(); shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); const QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); tx1 = topRightTile.left(); ty1 = topRightTile.top(); tx2 = topRightTile.right(); ty2 = topRightTile.bottom(); shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); const QRectF top(topLeft.topRight(), topRight.bottomLeft()); tx1 = topTile.left(); ty1 = topTile.top(); tx2 = topTile.right(); ty2 = topTile.bottom(); shadowQuads << makeShadowQuad(top, tx1, ty1, tx2, ty2); const QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); tx1 = bottomLeftTile.left(); ty1 = bottomLeftTile.top(); tx2 = bottomLeftTile.right(); ty2 = bottomLeftTile.bottom(); shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); const QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); tx1 = bottomRightTile.left(); ty1 = bottomRightTile.top(); tx2 = bottomRightTile.right(); ty2 = bottomRightTile.bottom(); shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF bottom(bottomLeft.topRight(), bottomRight.bottomLeft()); tx1 = bottomTile.left(); ty1 = bottomTile.top(); tx2 = bottomTile.right(); ty2 = bottomTile.bottom(); shadowQuads << makeShadowQuad(bottom, tx1, ty1, tx2, ty2); const QRectF left(topLeft.bottomLeft(), bottomLeft.topRight()); tx1 = leftTile.left(); ty1 = leftTile.top(); tx2 = leftTile.right(); ty2 = leftTile.bottom(); shadowQuads << makeShadowQuad(left, tx1, ty1, tx2, ty2); const QRectF right(topRight.bottomLeft(), bottomRight.topRight()); tx1 = rightTile.left(); ty1 = rightTile.top(); tx2 = rightTile.right(); ty2 = rightTile.bottom(); shadowQuads << makeShadowQuad(right, tx1, ty1, tx2, ty2); QTest::newRow("no overlaps") << windowSize << shadowQuads; } // Top-Left & Bottom-Left/Top-Right & Bottom-Right overlap: // In this case overlapping parts are clipped and left/right // tiles aren't rendered. const QVector> verticalOverlapTestTable { QPair { QByteArray("top-left & bottom-left/top-right & bottom-right overlap"), QSize(256 + 1, 256) }, QPair { QByteArray("top-left & bottom-left/top-right & bottom-right overlap :: pre"), QSize(256 + 1, 256 - 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : verticalOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); halfOverlap = qAbs(topLeft.bottom() - bottomLeft.top()) / 2; topLeft.setBottom(topLeft.bottom() - std::floor(halfOverlap)); bottomLeft.setTop(bottomLeft.top() + std::ceil(halfOverlap)); tx1 = topLeftTile.left(); ty1 = topLeftTile.top(); tx2 = topLeftTile.right(); ty2 = topLeft.height(); shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = bottomLeftTile.left(); ty1 = SHADOW_TEXTURE_HEIGHT - bottomLeft.height(); tx2 = bottomLeftTile.right(); ty2 = bottomLeftTile.bottom(); shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(topRight.bottom() - bottomRight.top()) / 2; topRight.setBottom(topRight.bottom() - std::floor(halfOverlap)); bottomRight.setTop(bottomRight.top() + std::ceil(halfOverlap)); tx1 = topRightTile.left(); ty1 = topRightTile.top(); tx2 = topRightTile.right(); ty2 = topRight.height(); shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); tx1 = bottomRightTile.left(); ty1 = SHADOW_TEXTURE_HEIGHT - bottomRight.height(); tx2 = bottomRightTile.right(); ty2 = bottomRightTile.bottom(); shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF top(topLeft.topRight(), topRight.bottomLeft()); tx1 = topTile.left(); ty1 = topTile.top(); tx2 = topTile.right(); ty2 = top.height(); shadowQuads << makeShadowQuad(top, tx1, ty1, tx2, ty2); const QRectF bottom(bottomLeft.topRight(), bottomRight.bottomLeft()); tx1 = bottomTile.left(); ty1 = SHADOW_TEXTURE_HEIGHT - bottom.height(); tx2 = bottomTile.right(); ty2 = bottomTile.bottom(); shadowQuads << makeShadowQuad(bottom, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // Top-Left & Top-Right/Bottom-Left & Bottom-Right overlap: // In this case overlapping parts are clipped and top/bottom // tiles aren't rendered. const QVector> horizontalOverlapTestTable { QPair { QByteArray("top-left & top-right/bottom-left & bottom-right overlap"), QSize(256, 256 + 1) }, QPair { QByteArray("top-left & top-right/bottom-left & bottom-right overlap :: pre"), QSize(256 - 1, 256 + 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : horizontalOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); halfOverlap = qAbs(topLeft.right() - topRight.left()) / 2; topLeft.setRight(topLeft.right() - std::floor(halfOverlap)); topRight.setLeft(topRight.left() + std::ceil(halfOverlap)); tx1 = topLeftTile.left(); ty1 = topLeftTile.top(); tx2 = topLeft.width(); ty2 = topLeftTile.bottom(); shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = SHADOW_TEXTURE_WIDTH - topRight.width(); ty1 = topRightTile.top(); tx2 = topRightTile.right(); ty2 = topRightTile.bottom(); shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(bottomLeft.right() - bottomRight.left()) / 2; bottomLeft.setRight(bottomLeft.right() - std::floor(halfOverlap)); bottomRight.setLeft(bottomRight.left() + std::ceil(halfOverlap)); tx1 = bottomLeftTile.left(); ty1 = bottomLeftTile.top(); tx2 = bottomLeft.width(); ty2 = bottomLeftTile.bottom(); shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); tx1 = SHADOW_TEXTURE_WIDTH - bottomRight.width(); ty1 = bottomRightTile.top(); tx2 = bottomRightTile.right(); ty2 = bottomRightTile.bottom(); shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); const QRectF left(topLeft.bottomLeft(), bottomLeft.topRight()); tx1 = leftTile.left(); ty1 = leftTile.top(); tx2 = left.width(); ty2 = leftTile.bottom(); shadowQuads << makeShadowQuad(left, tx1, ty1, tx2, ty2); const QRectF right(topRight.bottomLeft(), bottomRight.topRight()); tx1 = SHADOW_TEXTURE_WIDTH - right.width(); ty1 = rightTile.top(); tx2 = rightTile.right(); ty2 = rightTile.bottom(); shadowQuads << makeShadowQuad(right, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // All shadow tiles overlap: In this case all overlapping parts // are clippend and top/right/bottom/left tiles aren't rendered. const QVector> allOverlapTestTable { QPair { QByteArray("all corner tiles overlap"), QSize(256, 256) }, QPair { QByteArray("all corner tiles overlap :: pre"), QSize(256 - 1, 256 - 1) } // No need to test the case when window size is QSize(256 + 1, 256 + 1). // It has been tested already (no overlaps test case). }; for (auto const &tt : allOverlapTestTable) { const char *testName = tt.first.constData(); const QSize windowSize = tt.second; WindowQuadList shadowQuads; qreal halfOverlap = 0.0; const QRectF outerRect( -SHADOW_PADDING_LEFT, -SHADOW_PADDING_TOP, windowSize.width() + SHADOW_PADDING_LEFT + SHADOW_PADDING_RIGHT, windowSize.height() + SHADOW_PADDING_TOP + SHADOW_PADDING_BOTTOM); QRectF topLeft( outerRect.left(), outerRect.top(), topLeftTile.width(), topLeftTile.height()); QRectF topRight( outerRect.right() - topRightTile.width(), outerRect.top(), topRightTile.width(), topRightTile.height()); QRectF bottomLeft( outerRect.left(), outerRect.bottom() - bottomLeftTile.height(), bottomLeftTile.width(), bottomLeftTile.height()); QRectF bottomRight( outerRect.right() - bottomRightTile.width(), outerRect.bottom() - bottomRightTile.height(), bottomRightTile.width(), bottomRightTile.height()); halfOverlap = qAbs(topLeft.right() - topRight.left()) / 2; topLeft.setRight(topLeft.right() - std::floor(halfOverlap)); topRight.setLeft(topRight.left() + std::ceil(halfOverlap)); halfOverlap = qAbs(bottomLeft.right() - bottomRight.left()) / 2; bottomLeft.setRight(bottomLeft.right() - std::floor(halfOverlap)); bottomRight.setLeft(bottomRight.left() + std::ceil(halfOverlap)); halfOverlap = qAbs(topLeft.bottom() - bottomLeft.top()) / 2; topLeft.setBottom(topLeft.bottom() - std::floor(halfOverlap)); bottomLeft.setTop(bottomLeft.top() + std::ceil(halfOverlap)); halfOverlap = qAbs(topRight.bottom() - bottomRight.top()) / 2; topRight.setBottom(topRight.bottom() - std::floor(halfOverlap)); bottomRight.setTop(bottomRight.top() + std::ceil(halfOverlap)); tx1 = topLeftTile.left(); ty1 = topLeftTile.top(); tx2 = topLeft.width(); ty2 = topLeft.height(); shadowQuads << makeShadowQuad(topLeft, tx1, ty1, tx2, ty2); tx1 = SHADOW_TEXTURE_WIDTH - topRight.width(); ty1 = topRightTile.top(); tx2 = topRightTile.right(); ty2 = topRight.height(); shadowQuads << makeShadowQuad(topRight, tx1, ty1, tx2, ty2); tx1 = bottomLeftTile.left(); ty1 = SHADOW_TEXTURE_HEIGHT - bottomLeft.height(); tx2 = bottomLeft.width(); ty2 = bottomLeftTile.bottom(); shadowQuads << makeShadowQuad(bottomLeft, tx1, ty1, tx2, ty2); tx1 = SHADOW_TEXTURE_WIDTH - bottomRight.width(); ty1 = SHADOW_TEXTURE_HEIGHT - bottomRight.height(); tx2 = bottomRightTile.right(); ty2 = bottomRightTile.bottom(); shadowQuads << makeShadowQuad(bottomRight, tx1, ty1, tx2, ty2); QTest::newRow(testName) << windowSize << shadowQuads; } // Window is too small: do not render any shadow tiles. { const QSize windowSize(1, 1); const WindowQuadList shadowQuads; QTest::newRow("window is too small") << windowSize << shadowQuads; } } void SceneQPainterShadowTest::testShadowTileOverlaps() { QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::Decoration)); QFETCH(QSize, windowSize); QFETCH(WindowQuadList, expectedQuads); // Create a decorated client. QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); QScopedPointer ssd(Test::waylandServerSideDecoration()->create(surface.data())); auto *client = Test::renderAndWaitForShown(surface.data(), windowSize, Qt::blue); QSignalSpy sizeChangedSpy(shellSurface.data(), &XdgShellSurface::sizeChanged); QVERIFY(sizeChangedSpy.isValid()); // Check the client is decorated. QVERIFY(client); QVERIFY(client->isDecorated()); auto *decoration = client->decoration(); QVERIFY(decoration); // If speciefied decoration theme is not found, KWin loads a default one // so we have to check whether a client has right decoration. auto decoShadow = decoration->shadow(); QCOMPARE(decoShadow->shadow().size(), QSize(SHADOW_TEXTURE_WIDTH, SHADOW_TEXTURE_HEIGHT)); QCOMPARE(decoShadow->paddingTop(), SHADOW_PADDING_TOP); QCOMPARE(decoShadow->paddingRight(), SHADOW_PADDING_RIGHT); QCOMPARE(decoShadow->paddingBottom(), SHADOW_PADDING_BOTTOM); QCOMPARE(decoShadow->paddingLeft(), SHADOW_PADDING_LEFT); // Get shadow. QVERIFY(client->effectWindow()); QVERIFY(client->effectWindow()->sceneWindow()); QVERIFY(client->effectWindow()->sceneWindow()->shadow()); auto *shadow = client->effectWindow()->sceneWindow()->shadow(); // Validate shadow quads. const WindowQuadList &quads = shadow->shadowQuads(); QCOMPARE(quads.size(), expectedQuads.size()); QVector mask(expectedQuads.size(), false); for (const auto &q : quads) { for (int i = 0; i < expectedQuads.size(); i++) { if (!compareQuads(q, expectedQuads[i])) { continue; } if (!mask[i]) { mask[i] = true; break; } else { QFAIL("got a duplicate shadow quad"); } } } for (const auto &v : qAsConst(mask)) { if (!v) { QFAIL("missed a shadow quad"); } } } void SceneQPainterShadowTest::testShadowTextureReconstruction() { QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::ShadowManager)); // Create a surface. QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellStableSurface(surface.data())); auto *client = Test::renderAndWaitForShown(surface.data(), QSize(512, 512), Qt::blue); QVERIFY(client); QVERIFY(!client->isDecorated()); // Render reference shadow texture with the following params: // - shadow size: 128 // - inner rect size: 1 // - padding: 128 QImage referenceShadowTexture(QSize(256 + 1, 256 + 1), QImage::Format_ARGB32_Premultiplied); referenceShadowTexture.fill(Qt::transparent); QPainter painter(&referenceShadowTexture); painter.fillRect(QRect(10, 10, 192, 200), QColor(255, 0, 0, 128)); painter.fillRect(QRect(128, 30, 10, 180), QColor(0, 0, 0, 30)); painter.fillRect(QRect(20, 140, 160, 10), QColor(0, 255, 0, 128)); painter.setCompositionMode(QPainter::CompositionMode_DestinationOut); painter.fillRect(QRect(128, 128, 1, 1), Qt::black); painter.end(); // Create shadow. QScopedPointer clientShadow(Test::waylandShadowManager()->createShadow(surface.data())); QVERIFY(clientShadow->isValid()); auto *shmPool = Test::waylandShmPool(); Buffer::Ptr bufferTopLeft = shmPool->createBuffer( referenceShadowTexture.copy(QRect(0, 0, 128, 128))); clientShadow->attachTopLeft(bufferTopLeft); Buffer::Ptr bufferTop = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128, 0, 1, 128))); clientShadow->attachTop(bufferTop); Buffer::Ptr bufferTopRight = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128 + 1, 0, 128, 128))); clientShadow->attachTopRight(bufferTopRight); Buffer::Ptr bufferRight = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128 + 1, 128, 128, 1))); clientShadow->attachRight(bufferRight); Buffer::Ptr bufferBottomRight = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128 + 1, 128 + 1, 128, 128))); clientShadow->attachBottomRight(bufferBottomRight); Buffer::Ptr bufferBottom = shmPool->createBuffer( referenceShadowTexture.copy(QRect(128, 128 + 1, 1, 128))); clientShadow->attachBottom(bufferBottom); Buffer::Ptr bufferBottomLeft = shmPool->createBuffer( referenceShadowTexture.copy(QRect(0, 128 + 1, 128, 128))); clientShadow->attachBottomLeft(bufferBottomLeft); Buffer::Ptr bufferLeft = shmPool->createBuffer( referenceShadowTexture.copy(QRect(0, 128, 128, 1))); clientShadow->attachLeft(bufferLeft); clientShadow->setOffsets(QMarginsF(128, 128, 128, 128)); // Commit shadow. QSignalSpy shadowChangedSpy(client->surface(), &KWayland::Server::SurfaceInterface::shadowChanged); QVERIFY(shadowChangedSpy.isValid()); clientShadow->commit(); surface->commit(Surface::CommitFlag::None); QVERIFY(shadowChangedSpy.wait()); // Check whether we've got right shadow. auto shadowIface = client->surface()->shadow(); QVERIFY(!shadowIface.isNull()); QCOMPARE(shadowIface->offset().left(), 128.0); QCOMPARE(shadowIface->offset().top(), 128.0); QCOMPARE(shadowIface->offset().right(), 128.0); QCOMPARE(shadowIface->offset().bottom(), 128.0); // Get SceneQPainterShadow's texture. QVERIFY(client->effectWindow()); QVERIFY(client->effectWindow()->sceneWindow()); QVERIFY(client->effectWindow()->sceneWindow()->shadow()); auto &shadowTexture = static_cast(client->effectWindow()->sceneWindow()->shadow())->shadowTexture(); QCOMPARE(shadowTexture, referenceShadowTexture); } WAYLANDTEST_MAIN(SceneQPainterShadowTest) #include "scene_qpainter_shadow_test.moc" diff --git a/autotests/integration/scripting/minimizeall_test.cpp b/autotests/integration/scripting/minimizeall_test.cpp index 0f6716872..914f4cb94 100644 --- a/autotests/integration/scripting/minimizeall_test.cpp +++ b/autotests/integration/scripting/minimizeall_test.cpp @@ -1,170 +1,170 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "platform.h" #include "screens.h" #include "scripting/scripting.h" #include "wayland_server.h" #include "workspace.h" #include "xdgshellclient.h" #include #include #include namespace KWin { static const QString s_socketName = QStringLiteral("wayland_test_minimizeall-0"); static const QString s_scriptName = QStringLiteral("minimizeall"); class MinimizeAllScriptTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testMinimizeUnminimize(); }; void MinimizeAllScriptTest::initTestCase() { qputenv("XDG_DATA_DIRS", QCoreApplication::applicationDirPath().toUtf8()); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, 2)); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QCOMPARE(screens()->count(), 2); QCOMPARE(screens()->geometry(0), QRect(0, 0, 1280, 1024)); QCOMPARE(screens()->geometry(1), QRect(1280, 0, 1280, 1024)); waylandServer()->initWorkspace(); } static QString locateMainScript(const QString &pluginName) { const QList offers = KPackage::PackageLoader::self()->findPackages( QStringLiteral("KWin/Script"), QStringLiteral("kwin/scripts"), [&](const KPluginMetaData &metaData) { return metaData.pluginId() == pluginName; } ); if (offers.isEmpty()) { return QString(); } const KPluginMetaData &metaData = offers.first(); const QString mainScriptFileName = metaData.value(QStringLiteral("X-Plasma-MainScript")); const QFileInfo metaDataFileInfo(metaData.fileName()); return metaDataFileInfo.path() + QLatin1String("/contents/") + mainScriptFileName; } void MinimizeAllScriptTest::init() { QVERIFY(Test::setupWaylandConnection()); Scripting::self()->loadScript(locateMainScript(s_scriptName), s_scriptName); QTRY_VERIFY(Scripting::self()->isScriptLoaded(s_scriptName)); AbstractScript *script = Scripting::self()->findScript(s_scriptName); QVERIFY(script); QSignalSpy runningChangedSpy(script, &AbstractScript::runningChanged); QVERIFY(runningChangedSpy.isValid()); script->run(); QTRY_COMPARE(runningChangedSpy.count(), 1); } void MinimizeAllScriptTest::cleanup() { Test::destroyWaylandConnection(); Scripting::self()->unloadScript(s_scriptName); QTRY_VERIFY(!Scripting::self()->isScriptLoaded(s_scriptName)); } void MinimizeAllScriptTest::testMinimizeUnminimize() { // This test verifies that all windows are minimized when Meta+Shift+D // is pressed, and unminimized when the shortcut is pressed once again. using namespace KWayland::Client; // Create a couple of test clients. QScopedPointer surface1(Test::createSurface()); QScopedPointer shellSurface1(Test::createXdgShellStableSurface(surface1.data())); XdgShellClient *client1 = Test::renderAndWaitForShown(surface1.data(), QSize(100, 50), Qt::blue); QVERIFY(client1); QVERIFY(client1->isActive()); QVERIFY(client1->isMinimizable()); QScopedPointer surface2(Test::createSurface()); QScopedPointer shellSurface2(Test::createXdgShellStableSurface(surface2.data())); XdgShellClient *client2 = Test::renderAndWaitForShown(surface2.data(), QSize(100, 50), Qt::red); QVERIFY(client2); QVERIFY(client2->isActive()); QVERIFY(client2->isMinimizable()); // Minimize the windows. quint32 timestamp = 1; kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTMETA, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTSHIFT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_D, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_D, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTSHIFT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTMETA, timestamp++); QTRY_VERIFY(client1->isMinimized()); QTRY_VERIFY(client2->isMinimized()); // Unminimize the windows. kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTMETA, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTSHIFT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_D, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_D, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTSHIFT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTMETA, timestamp++); QTRY_VERIFY(!client1->isMinimized()); QTRY_VERIFY(!client2->isMinimized()); // Destroy test clients. shellSurface2.reset(); QVERIFY(Test::waitForWindowDestroyed(client2)); shellSurface1.reset(); QVERIFY(Test::waitForWindowDestroyed(client1)); } } WAYLANDTEST_MAIN(KWin::MinimizeAllScriptTest) #include "minimizeall_test.moc" diff --git a/autotests/integration/stacking_order_test.cpp b/autotests/integration/stacking_order_test.cpp index bdefb4064..a8eb3b2f3 100644 --- a/autotests/integration/stacking_order_test.cpp +++ b/autotests/integration/stacking_order_test.cpp @@ -1,910 +1,910 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "abstract_client.h" #include "atoms.h" #include "x11client.h" #include "deleted.h" #include "main.h" #include "platform.h" #include "xdgshellclient.h" #include "wayland_server.h" #include "workspace.h" #include #include #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_kwin_stacking_order-0"); class StackingOrderTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testTransientIsAboveParent(); void testRaiseTransient(); void testDeletedTransient(); void testGroupTransientIsAboveWindowGroup(); void testRaiseGroupTransient(); void testDeletedGroupTransient(); void testDontKeepAboveNonModalDialogGroupTransients(); void testKeepAbove(); void testKeepBelow(); }; void StackingOrderTest::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); kwinApp()->setConfig(KSharedConfig::openConfig(QString(), KConfig::SimpleConfig)); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); waylandServer()->initWorkspace(); } void StackingOrderTest::init() { QVERIFY(Test::setupWaylandConnection()); } void StackingOrderTest::cleanup() { Test::destroyWaylandConnection(); } void StackingOrderTest::testTransientIsAboveParent() { // This test verifies that transients are always above their parents. // Create the parent. KWayland::Client::Surface *parentSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(parentSurface); KWayland::Client::XdgShellSurface *parentShellSurface = Test::createXdgShellStableSurface(parentSurface, parentSurface); QVERIFY(parentShellSurface); XdgShellClient *parent = Test::renderAndWaitForShown(parentSurface, QSize(256, 256), Qt::blue); QVERIFY(parent); QVERIFY(parent->isActive()); QVERIFY(!parent->isTransient()); // Initially, the stacking order should contain only the parent window. QCOMPARE(workspace()->stackingOrder(), (QList{parent})); // Create the transient. KWayland::Client::Surface *transientSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(transientSurface); KWayland::Client::XdgShellSurface *transientShellSurface = Test::createXdgShellStableSurface(transientSurface, transientSurface); QVERIFY(transientShellSurface); transientShellSurface->setTransientFor(parentShellSurface); XdgShellClient *transient = Test::renderAndWaitForShown( transientSurface, QSize(128, 128), Qt::red); QVERIFY(transient); QVERIFY(transient->isActive()); QVERIFY(transient->isTransient()); // The transient should be above the parent. QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient})); // The transient still stays above the parent if we activate the latter. workspace()->activateClient(parent); QTRY_VERIFY(parent->isActive()); QTRY_VERIFY(!transient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient})); } void StackingOrderTest::testRaiseTransient() { // This test verifies that both the parent and the transient will be // raised if either one of them is activated. // Create the parent. KWayland::Client::Surface *parentSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(parentSurface); KWayland::Client::XdgShellSurface *parentShellSurface = Test::createXdgShellStableSurface(parentSurface, parentSurface); QVERIFY(parentShellSurface); XdgShellClient *parent = Test::renderAndWaitForShown(parentSurface, QSize(256, 256), Qt::blue); QVERIFY(parent); QVERIFY(parent->isActive()); QVERIFY(!parent->isTransient()); // Initially, the stacking order should contain only the parent window. QCOMPARE(workspace()->stackingOrder(), (QList{parent})); // Create the transient. KWayland::Client::Surface *transientSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(transientSurface); KWayland::Client::XdgShellSurface *transientShellSurface = Test::createXdgShellStableSurface(transientSurface, transientSurface); QVERIFY(transientShellSurface); transientShellSurface->setTransientFor(parentShellSurface); XdgShellClient *transient = Test::renderAndWaitForShown( transientSurface, QSize(128, 128), Qt::red); QVERIFY(transient); QTRY_VERIFY(transient->isActive()); QVERIFY(transient->isTransient()); // The transient should be above the parent. QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient})); // Create a window that doesn't have any relationship to the parent or the transient. KWayland::Client::Surface *anotherSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(anotherSurface); KWayland::Client::XdgShellSurface *anotherShellSurface = Test::createXdgShellStableSurface(anotherSurface, anotherSurface); QVERIFY(anotherShellSurface); XdgShellClient *anotherClient = Test::renderAndWaitForShown(anotherSurface, QSize(128, 128), Qt::green); QVERIFY(anotherClient); QVERIFY(anotherClient->isActive()); QVERIFY(!anotherClient->isTransient()); // The newly created surface has to be above both the parent and the transient. QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient, anotherClient})); // If we activate the parent, the transient should be raised too. workspace()->activateClient(parent); QTRY_VERIFY(parent->isActive()); QTRY_VERIFY(!transient->isActive()); QTRY_VERIFY(!anotherClient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{anotherClient, parent, transient})); // Go back to the initial setup. workspace()->activateClient(anotherClient); QTRY_VERIFY(!parent->isActive()); QTRY_VERIFY(!transient->isActive()); QTRY_VERIFY(anotherClient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient, anotherClient})); // If we activate the transient, the parent should be raised too. workspace()->activateClient(transient); QTRY_VERIFY(!parent->isActive()); QTRY_VERIFY(transient->isActive()); QTRY_VERIFY(!anotherClient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{anotherClient, parent, transient})); } struct WindowUnrefDeleter { static inline void cleanup(Deleted *d) { if (d != nullptr) { d->unrefWindow(); } } }; void StackingOrderTest::testDeletedTransient() { // This test verifies that deleted transients are kept above their // old parents. // Create the parent. KWayland::Client::Surface *parentSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(parentSurface); KWayland::Client::XdgShellSurface *parentShellSurface = Test::createXdgShellStableSurface(parentSurface, parentSurface); QVERIFY(parentShellSurface); XdgShellClient *parent = Test::renderAndWaitForShown(parentSurface, QSize(256, 256), Qt::blue); QVERIFY(parent); QVERIFY(parent->isActive()); QVERIFY(!parent->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{parent})); // Create the first transient. KWayland::Client::Surface *transient1Surface = Test::createSurface(Test::waylandCompositor()); QVERIFY(transient1Surface); KWayland::Client::XdgShellSurface *transient1ShellSurface = Test::createXdgShellStableSurface(transient1Surface, transient1Surface); QVERIFY(transient1ShellSurface); transient1ShellSurface->setTransientFor(parentShellSurface); XdgShellClient *transient1 = Test::renderAndWaitForShown( transient1Surface, QSize(128, 128), Qt::red); QVERIFY(transient1); QTRY_VERIFY(transient1->isActive()); QVERIFY(transient1->isTransient()); QCOMPARE(transient1->transientFor(), parent); QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient1})); // Create the second transient. KWayland::Client::Surface *transient2Surface = Test::createSurface(Test::waylandCompositor()); QVERIFY(transient2Surface); KWayland::Client::XdgShellSurface *transient2ShellSurface = Test::createXdgShellStableSurface(transient2Surface, transient2Surface); QVERIFY(transient2ShellSurface); transient2ShellSurface->setTransientFor(transient1ShellSurface); XdgShellClient *transient2 = Test::renderAndWaitForShown( transient2Surface, QSize(128, 128), Qt::red); QVERIFY(transient2); QTRY_VERIFY(transient2->isActive()); QVERIFY(transient2->isTransient()); QCOMPARE(transient2->transientFor(), transient1); QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient1, transient2})); // Activate the parent, both transients have to be above it. workspace()->activateClient(parent); QTRY_VERIFY(parent->isActive()); QTRY_VERIFY(!transient1->isActive()); QTRY_VERIFY(!transient2->isActive()); // Close the top-most transient. connect(transient2, &XdgShellClient::windowClosed, this, [](Toplevel *toplevel, Deleted *deleted) { Q_UNUSED(toplevel) deleted->refWindow(); } ); QSignalSpy windowClosedSpy(transient2, &XdgShellClient::windowClosed); QVERIFY(windowClosedSpy.isValid()); delete transient2ShellSurface; delete transient2Surface; QVERIFY(windowClosedSpy.wait()); QScopedPointer deletedTransient( windowClosedSpy.first().at(1).value()); QVERIFY(deletedTransient.data()); // The deleted transient still has to be above its old parent (transient1). QTRY_VERIFY(parent->isActive()); QTRY_VERIFY(!transient1->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{parent, transient1, deletedTransient.data()})); } static xcb_window_t createGroupWindow(xcb_connection_t *conn, const QRect &geometry, xcb_window_t leaderWid = XCB_WINDOW_NONE) { xcb_window_t wid = xcb_generate_id(conn); xcb_create_window( conn, // c XCB_COPY_FROM_PARENT, // depth wid, // wid rootWindow(), // parent geometry.x(), // x geometry.y(), // y geometry.width(), // width geometry.height(), // height 0, // border_width XCB_WINDOW_CLASS_INPUT_OUTPUT, // _class XCB_COPY_FROM_PARENT, // visual 0, // value_mask nullptr // value_list ); xcb_size_hints_t sizeHints = {}; xcb_icccm_size_hints_set_position(&sizeHints, 1, geometry.x(), geometry.y()); xcb_icccm_size_hints_set_size(&sizeHints, 1, geometry.width(), geometry.height()); xcb_icccm_set_wm_normal_hints(conn, wid, &sizeHints); if (leaderWid == XCB_WINDOW_NONE) { leaderWid = wid; } xcb_change_property( conn, // c XCB_PROP_MODE_REPLACE, // mode wid, // window atoms->wm_client_leader, // property XCB_ATOM_WINDOW, // type 32, // format 1, // data_len &leaderWid // data ); return wid; } struct XcbConnectionDeleter { static inline void cleanup(xcb_connection_t *c) { xcb_disconnect(c); } }; void StackingOrderTest::testGroupTransientIsAboveWindowGroup() { // This test verifies that group transients are always above other // window group members. const QRect geometry = QRect(0, 0, 128, 128); QScopedPointer conn( xcb_connect(nullptr, nullptr)); QSignalSpy windowCreatedSpy(workspace(), &Workspace::clientAdded); QVERIFY(windowCreatedSpy.isValid()); // Create the group leader. xcb_window_t leaderWid = createGroupWindow(conn.data(), geometry); xcb_map_window(conn.data(), leaderWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *leader = windowCreatedSpy.first().first().value(); QVERIFY(leader); QVERIFY(leader->isActive()); QCOMPARE(leader->windowId(), leaderWid); QVERIFY(!leader->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader})); // Create another group member. windowCreatedSpy.clear(); xcb_window_t member1Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member1Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member1 = windowCreatedSpy.first().first().value(); QVERIFY(member1); QVERIFY(member1->isActive()); QCOMPARE(member1->windowId(), member1Wid); QCOMPARE(member1->group(), leader->group()); QVERIFY(!member1->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1})); // Create yet another group member. windowCreatedSpy.clear(); xcb_window_t member2Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member2Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member2 = windowCreatedSpy.first().first().value(); QVERIFY(member2); QVERIFY(member2->isActive()); QCOMPARE(member2->windowId(), member2Wid); QCOMPARE(member2->group(), leader->group()); QVERIFY(!member2->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2})); // Create a group transient. windowCreatedSpy.clear(); xcb_window_t transientWid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_icccm_set_wm_transient_for(conn.data(), transientWid, rootWindow()); // Currently, we have some weird bug workaround: if a group transient // is a non-modal dialog, then it won't be kept above its window group. // We need to explicitly specify window type, otherwise the window type // will be deduced to _NET_WM_WINDOW_TYPE_DIALOG because we set transient // for before (the EWMH spec says to do that). xcb_atom_t net_wm_window_type = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE"), false, conn.data()); xcb_atom_t net_wm_window_type_normal = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NORMAL"), false, conn.data()); xcb_change_property( conn.data(), // c XCB_PROP_MODE_REPLACE, // mode transientWid, // window net_wm_window_type, // property XCB_ATOM_ATOM, // type 32, // format 1, // data_len &net_wm_window_type_normal // data ); xcb_map_window(conn.data(), transientWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *transient = windowCreatedSpy.first().first().value(); QVERIFY(transient); QVERIFY(transient->isActive()); QCOMPARE(transient->windowId(), transientWid); QCOMPARE(transient->group(), leader->group()); QVERIFY(transient->isTransient()); QVERIFY(transient->groupTransient()); QVERIFY(!transient->isDialog()); // See above why QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); // If we activate any member of the window group, the transient will be above it. workspace()->activateClient(leader); QTRY_VERIFY(leader->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, member2, leader, transient})); workspace()->activateClient(member1); QTRY_VERIFY(member1->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member2, leader, member1, transient})); workspace()->activateClient(member2); QTRY_VERIFY(member2->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); workspace()->activateClient(transient); QTRY_VERIFY(transient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); } void StackingOrderTest::testRaiseGroupTransient() { const QRect geometry = QRect(0, 0, 128, 128); QScopedPointer conn( xcb_connect(nullptr, nullptr)); QSignalSpy windowCreatedSpy(workspace(), &Workspace::clientAdded); QVERIFY(windowCreatedSpy.isValid()); // Create the group leader. xcb_window_t leaderWid = createGroupWindow(conn.data(), geometry); xcb_map_window(conn.data(), leaderWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *leader = windowCreatedSpy.first().first().value(); QVERIFY(leader); QVERIFY(leader->isActive()); QCOMPARE(leader->windowId(), leaderWid); QVERIFY(!leader->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader})); // Create another group member. windowCreatedSpy.clear(); xcb_window_t member1Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member1Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member1 = windowCreatedSpy.first().first().value(); QVERIFY(member1); QVERIFY(member1->isActive()); QCOMPARE(member1->windowId(), member1Wid); QCOMPARE(member1->group(), leader->group()); QVERIFY(!member1->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1})); // Create yet another group member. windowCreatedSpy.clear(); xcb_window_t member2Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member2Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member2 = windowCreatedSpy.first().first().value(); QVERIFY(member2); QVERIFY(member2->isActive()); QCOMPARE(member2->windowId(), member2Wid); QCOMPARE(member2->group(), leader->group()); QVERIFY(!member2->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2})); // Create a group transient. windowCreatedSpy.clear(); xcb_window_t transientWid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_icccm_set_wm_transient_for(conn.data(), transientWid, rootWindow()); // Currently, we have some weird bug workaround: if a group transient // is a non-modal dialog, then it won't be kept above its window group. // We need to explicitly specify window type, otherwise the window type // will be deduced to _NET_WM_WINDOW_TYPE_DIALOG because we set transient // for before (the EWMH spec says to do that). xcb_atom_t net_wm_window_type = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE"), false, conn.data()); xcb_atom_t net_wm_window_type_normal = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NORMAL"), false, conn.data()); xcb_change_property( conn.data(), // c XCB_PROP_MODE_REPLACE, // mode transientWid, // window net_wm_window_type, // property XCB_ATOM_ATOM, // type 32, // format 1, // data_len &net_wm_window_type_normal // data ); xcb_map_window(conn.data(), transientWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *transient = windowCreatedSpy.first().first().value(); QVERIFY(transient); QVERIFY(transient->isActive()); QCOMPARE(transient->windowId(), transientWid); QCOMPARE(transient->group(), leader->group()); QVERIFY(transient->isTransient()); QVERIFY(transient->groupTransient()); QVERIFY(!transient->isDialog()); // See above why QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); // Create a Wayland client that is not a member of the window group. KWayland::Client::Surface *anotherSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(anotherSurface); KWayland::Client::XdgShellSurface *anotherShellSurface = Test::createXdgShellStableSurface(anotherSurface, anotherSurface); QVERIFY(anotherShellSurface); XdgShellClient *anotherClient = Test::renderAndWaitForShown(anotherSurface, QSize(128, 128), Qt::green); QVERIFY(anotherClient); QVERIFY(anotherClient->isActive()); QVERIFY(!anotherClient->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient, anotherClient})); // If we activate the leader, then only it and the transient have to be raised. workspace()->activateClient(leader); QTRY_VERIFY(leader->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, member2, anotherClient, leader, transient})); // If another member of the window group is activated, then the transient will // be above that member and the leader. workspace()->activateClient(member2); QTRY_VERIFY(member2->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, anotherClient, leader, member2, transient})); // FIXME: If we activate the transient, only it will be raised. workspace()->activateClient(anotherClient); QTRY_VERIFY(anotherClient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, leader, member2, transient, anotherClient})); workspace()->activateClient(transient); QTRY_VERIFY(transient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, leader, member2, anotherClient, transient})); } void StackingOrderTest::testDeletedGroupTransient() { // This test verifies that deleted group transients are kept above their // old window groups. const QRect geometry = QRect(0, 0, 128, 128); QScopedPointer conn( xcb_connect(nullptr, nullptr)); QSignalSpy windowCreatedSpy(workspace(), &Workspace::clientAdded); QVERIFY(windowCreatedSpy.isValid()); // Create the group leader. xcb_window_t leaderWid = createGroupWindow(conn.data(), geometry); xcb_map_window(conn.data(), leaderWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *leader = windowCreatedSpy.first().first().value(); QVERIFY(leader); QVERIFY(leader->isActive()); QCOMPARE(leader->windowId(), leaderWid); QVERIFY(!leader->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader})); // Create another group member. windowCreatedSpy.clear(); xcb_window_t member1Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member1Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member1 = windowCreatedSpy.first().first().value(); QVERIFY(member1); QVERIFY(member1->isActive()); QCOMPARE(member1->windowId(), member1Wid); QCOMPARE(member1->group(), leader->group()); QVERIFY(!member1->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1})); // Create yet another group member. windowCreatedSpy.clear(); xcb_window_t member2Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member2Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member2 = windowCreatedSpy.first().first().value(); QVERIFY(member2); QVERIFY(member2->isActive()); QCOMPARE(member2->windowId(), member2Wid); QCOMPARE(member2->group(), leader->group()); QVERIFY(!member2->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2})); // Create a group transient. windowCreatedSpy.clear(); xcb_window_t transientWid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_icccm_set_wm_transient_for(conn.data(), transientWid, rootWindow()); // Currently, we have some weird bug workaround: if a group transient // is a non-modal dialog, then it won't be kept above its window group. // We need to explicitly specify window type, otherwise the window type // will be deduced to _NET_WM_WINDOW_TYPE_DIALOG because we set transient // for before (the EWMH spec says to do that). xcb_atom_t net_wm_window_type = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE"), false, conn.data()); xcb_atom_t net_wm_window_type_normal = Xcb::Atom( QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NORMAL"), false, conn.data()); xcb_change_property( conn.data(), // c XCB_PROP_MODE_REPLACE, // mode transientWid, // window net_wm_window_type, // property XCB_ATOM_ATOM, // type 32, // format 1, // data_len &net_wm_window_type_normal // data ); xcb_map_window(conn.data(), transientWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *transient = windowCreatedSpy.first().first().value(); QVERIFY(transient); QVERIFY(transient->isActive()); QCOMPARE(transient->windowId(), transientWid); QCOMPARE(transient->group(), leader->group()); QVERIFY(transient->isTransient()); QVERIFY(transient->groupTransient()); QVERIFY(!transient->isDialog()); // See above why QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); // Unmap the transient. connect(transient, &X11Client::windowClosed, this, [](Toplevel *toplevel, Deleted *deleted) { Q_UNUSED(toplevel) deleted->refWindow(); } ); QSignalSpy windowClosedSpy(transient, &X11Client::windowClosed); QVERIFY(windowClosedSpy.isValid()); xcb_unmap_window(conn.data(), transientWid); xcb_flush(conn.data()); QVERIFY(windowClosedSpy.wait()); QScopedPointer deletedTransient( windowClosedSpy.first().at(1).value()); QVERIFY(deletedTransient.data()); // The transient has to be above each member of the window group. QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, deletedTransient.data()})); } void StackingOrderTest::testDontKeepAboveNonModalDialogGroupTransients() { // Bug 76026 const QRect geometry = QRect(0, 0, 128, 128); QScopedPointer conn( xcb_connect(nullptr, nullptr)); QSignalSpy windowCreatedSpy(workspace(), &Workspace::clientAdded); QVERIFY(windowCreatedSpy.isValid()); // Create the group leader. xcb_window_t leaderWid = createGroupWindow(conn.data(), geometry); xcb_map_window(conn.data(), leaderWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *leader = windowCreatedSpy.first().first().value(); QVERIFY(leader); QVERIFY(leader->isActive()); QCOMPARE(leader->windowId(), leaderWid); QVERIFY(!leader->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader})); // Create another group member. windowCreatedSpy.clear(); xcb_window_t member1Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member1Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member1 = windowCreatedSpy.first().first().value(); QVERIFY(member1); QVERIFY(member1->isActive()); QCOMPARE(member1->windowId(), member1Wid); QCOMPARE(member1->group(), leader->group()); QVERIFY(!member1->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1})); // Create yet another group member. windowCreatedSpy.clear(); xcb_window_t member2Wid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_map_window(conn.data(), member2Wid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *member2 = windowCreatedSpy.first().first().value(); QVERIFY(member2); QVERIFY(member2->isActive()); QCOMPARE(member2->windowId(), member2Wid); QCOMPARE(member2->group(), leader->group()); QVERIFY(!member2->isTransient()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2})); // Create a group transient. windowCreatedSpy.clear(); xcb_window_t transientWid = createGroupWindow(conn.data(), geometry, leaderWid); xcb_icccm_set_wm_transient_for(conn.data(), transientWid, rootWindow()); xcb_map_window(conn.data(), transientWid); xcb_flush(conn.data()); QVERIFY(windowCreatedSpy.wait()); X11Client *transient = windowCreatedSpy.first().first().value(); QVERIFY(transient); QVERIFY(transient->isActive()); QCOMPARE(transient->windowId(), transientWid); QCOMPARE(transient->group(), leader->group()); QVERIFY(transient->isTransient()); QVERIFY(transient->groupTransient()); QVERIFY(transient->isDialog()); QVERIFY(!transient->isModal()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); workspace()->activateClient(leader); QTRY_VERIFY(leader->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member1, member2, transient, leader})); workspace()->activateClient(member1); QTRY_VERIFY(member1->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{member2, transient, leader, member1})); workspace()->activateClient(member2); QTRY_VERIFY(member2->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{transient, leader, member1, member2})); workspace()->activateClient(transient); QTRY_VERIFY(transient->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{leader, member1, member2, transient})); } void StackingOrderTest::testKeepAbove() { // This test verifies that "keep-above" windows are kept above other windows. // Create the first client. KWayland::Client::Surface *clientASurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(clientASurface); KWayland::Client::XdgShellSurface *clientAShellSurface = Test::createXdgShellStableSurface(clientASurface, clientASurface); QVERIFY(clientAShellSurface); XdgShellClient *clientA = Test::renderAndWaitForShown(clientASurface, QSize(128, 128), Qt::green); QVERIFY(clientA); QVERIFY(clientA->isActive()); QVERIFY(!clientA->keepAbove()); QCOMPARE(workspace()->stackingOrder(), (QList{clientA})); // Create the second client. KWayland::Client::Surface *clientBSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(clientBSurface); KWayland::Client::XdgShellSurface *clientBShellSurface = Test::createXdgShellStableSurface(clientBSurface, clientBSurface); QVERIFY(clientBShellSurface); XdgShellClient *clientB = Test::renderAndWaitForShown(clientBSurface, QSize(128, 128), Qt::green); QVERIFY(clientB); QVERIFY(clientB->isActive()); QVERIFY(!clientB->keepAbove()); QCOMPARE(workspace()->stackingOrder(), (QList{clientA, clientB})); // Go to the initial test position. workspace()->activateClient(clientA); QTRY_VERIFY(clientA->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{clientB, clientA})); // Set the "keep-above" flag on the client B, it should go above other clients. { StackingUpdatesBlocker blocker(workspace()); clientB->setKeepAbove(true); } QVERIFY(clientB->keepAbove()); QVERIFY(!clientB->isActive()); QCOMPARE(workspace()->stackingOrder(), (QList{clientA, clientB})); } void StackingOrderTest::testKeepBelow() { // This test verifies that "keep-below" windows are kept below other windows. // Create the first client. KWayland::Client::Surface *clientASurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(clientASurface); KWayland::Client::XdgShellSurface *clientAShellSurface = Test::createXdgShellStableSurface(clientASurface, clientASurface); QVERIFY(clientAShellSurface); XdgShellClient *clientA = Test::renderAndWaitForShown(clientASurface, QSize(128, 128), Qt::green); QVERIFY(clientA); QVERIFY(clientA->isActive()); QVERIFY(!clientA->keepBelow()); QCOMPARE(workspace()->stackingOrder(), (QList{clientA})); // Create the second client. KWayland::Client::Surface *clientBSurface = Test::createSurface(Test::waylandCompositor()); QVERIFY(clientBSurface); KWayland::Client::XdgShellSurface *clientBShellSurface = Test::createXdgShellStableSurface(clientBSurface, clientBSurface); QVERIFY(clientBShellSurface); XdgShellClient *clientB = Test::renderAndWaitForShown(clientBSurface, QSize(128, 128), Qt::green); QVERIFY(clientB); QVERIFY(clientB->isActive()); QVERIFY(!clientB->keepBelow()); QCOMPARE(workspace()->stackingOrder(), (QList{clientA, clientB})); // Set the "keep-below" flag on the client B, it should go below other clients. { StackingUpdatesBlocker blocker(workspace()); clientB->setKeepBelow(true); } QVERIFY(clientB->isActive()); QVERIFY(clientB->keepBelow()); QCOMPARE(workspace()->stackingOrder(), (QList{clientB, clientA})); } WAYLANDTEST_MAIN(StackingOrderTest) #include "stacking_order_test.moc" diff --git a/autotests/integration/xdgshellclient_rules_test.cpp b/autotests/integration/xdgshellclient_rules_test.cpp index fd7308ff5..52bd1c4ad 100644 --- a/autotests/integration/xdgshellclient_rules_test.cpp +++ b/autotests/integration/xdgshellclient_rules_test.cpp @@ -1,4544 +1,4544 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 Martin Flöser -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "platform.h" #include "rules.h" #include "screens.h" #include "xdgshellclient.h" #include "virtualdesktops.h" #include "wayland_server.h" #include "workspace.h" #include #include #include using namespace KWin; using namespace KWayland::Client; static const QString s_socketName = QStringLiteral("wayland_test_kwin_xdgshellclient_rules-0"); class TestXdgShellClientRules : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testPositionDontAffect_data(); void testPositionDontAffect(); void testPositionApply_data(); void testPositionApply(); void testPositionRemember_data(); void testPositionRemember(); void testPositionForce_data(); void testPositionForce(); void testPositionApplyNow_data(); void testPositionApplyNow(); void testPositionForceTemporarily_data(); void testPositionForceTemporarily(); void testSizeDontAffect_data(); void testSizeDontAffect(); void testSizeApply_data(); void testSizeApply(); void testSizeRemember_data(); void testSizeRemember(); void testSizeForce_data(); void testSizeForce(); void testSizeApplyNow_data(); void testSizeApplyNow(); void testSizeForceTemporarily_data(); void testSizeForceTemporarily(); void testMaximizeDontAffect_data(); void testMaximizeDontAffect(); void testMaximizeApply_data(); void testMaximizeApply(); void testMaximizeRemember_data(); void testMaximizeRemember(); void testMaximizeForce_data(); void testMaximizeForce(); void testMaximizeApplyNow_data(); void testMaximizeApplyNow(); void testMaximizeForceTemporarily_data(); void testMaximizeForceTemporarily(); void testDesktopDontAffect_data(); void testDesktopDontAffect(); void testDesktopApply_data(); void testDesktopApply(); void testDesktopRemember_data(); void testDesktopRemember(); void testDesktopForce_data(); void testDesktopForce(); void testDesktopApplyNow_data(); void testDesktopApplyNow(); void testDesktopForceTemporarily_data(); void testDesktopForceTemporarily(); void testMinimizeDontAffect_data(); void testMinimizeDontAffect(); void testMinimizeApply_data(); void testMinimizeApply(); void testMinimizeRemember_data(); void testMinimizeRemember(); void testMinimizeForce_data(); void testMinimizeForce(); void testMinimizeApplyNow_data(); void testMinimizeApplyNow(); void testMinimizeForceTemporarily_data(); void testMinimizeForceTemporarily(); void testSkipTaskbarDontAffect_data(); void testSkipTaskbarDontAffect(); void testSkipTaskbarApply_data(); void testSkipTaskbarApply(); void testSkipTaskbarRemember_data(); void testSkipTaskbarRemember(); void testSkipTaskbarForce_data(); void testSkipTaskbarForce(); void testSkipTaskbarApplyNow_data(); void testSkipTaskbarApplyNow(); void testSkipTaskbarForceTemporarily_data(); void testSkipTaskbarForceTemporarily(); void testSkipPagerDontAffect_data(); void testSkipPagerDontAffect(); void testSkipPagerApply_data(); void testSkipPagerApply(); void testSkipPagerRemember_data(); void testSkipPagerRemember(); void testSkipPagerForce_data(); void testSkipPagerForce(); void testSkipPagerApplyNow_data(); void testSkipPagerApplyNow(); void testSkipPagerForceTemporarily_data(); void testSkipPagerForceTemporarily(); void testSkipSwitcherDontAffect_data(); void testSkipSwitcherDontAffect(); void testSkipSwitcherApply_data(); void testSkipSwitcherApply(); void testSkipSwitcherRemember_data(); void testSkipSwitcherRemember(); void testSkipSwitcherForce_data(); void testSkipSwitcherForce(); void testSkipSwitcherApplyNow_data(); void testSkipSwitcherApplyNow(); void testSkipSwitcherForceTemporarily_data(); void testSkipSwitcherForceTemporarily(); void testKeepAboveDontAffect_data(); void testKeepAboveDontAffect(); void testKeepAboveApply_data(); void testKeepAboveApply(); void testKeepAboveRemember_data(); void testKeepAboveRemember(); void testKeepAboveForce_data(); void testKeepAboveForce(); void testKeepAboveApplyNow_data(); void testKeepAboveApplyNow(); void testKeepAboveForceTemporarily_data(); void testKeepAboveForceTemporarily(); void testKeepBelowDontAffect_data(); void testKeepBelowDontAffect(); void testKeepBelowApply_data(); void testKeepBelowApply(); void testKeepBelowRemember_data(); void testKeepBelowRemember(); void testKeepBelowForce_data(); void testKeepBelowForce(); void testKeepBelowApplyNow_data(); void testKeepBelowApplyNow(); void testKeepBelowForceTemporarily_data(); void testKeepBelowForceTemporarily(); void testShortcutDontAffect_data(); void testShortcutDontAffect(); void testShortcutApply_data(); void testShortcutApply(); void testShortcutRemember_data(); void testShortcutRemember(); void testShortcutForce_data(); void testShortcutForce(); void testShortcutApplyNow_data(); void testShortcutApplyNow(); void testShortcutForceTemporarily_data(); void testShortcutForceTemporarily(); void testDesktopFileDontAffect_data(); void testDesktopFileDontAffect(); void testDesktopFileApply_data(); void testDesktopFileApply(); void testDesktopFileRemember_data(); void testDesktopFileRemember(); void testDesktopFileForce_data(); void testDesktopFileForce(); void testDesktopFileApplyNow_data(); void testDesktopFileApplyNow(); void testDesktopFileForceTemporarily_data(); void testDesktopFileForceTemporarily(); void testActiveOpacityDontAffect_data(); void testActiveOpacityDontAffect(); void testActiveOpacityForce_data(); void testActiveOpacityForce(); void testActiveOpacityForceTemporarily_data(); void testActiveOpacityForceTemporarily(); void testInactiveOpacityDontAffect_data(); void testInactiveOpacityDontAffect(); void testInactiveOpacityForce_data(); void testInactiveOpacityForce(); void testInactiveOpacityForceTemporarily_data(); void testInactiveOpacityForceTemporarily(); void testMatchAfterNameChange(); }; void TestXdgShellClientRules::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); QSignalSpy workspaceCreatedSpy(kwinApp(), &Application::workspaceCreated); QVERIFY(workspaceCreatedSpy.isValid()); kwinApp()->platform()->setInitialWindowSize(QSize(1280, 1024)); QVERIFY(waylandServer()->init(s_socketName.toLocal8Bit())); QMetaObject::invokeMethod(kwinApp()->platform(), "setVirtualOutputs", Qt::DirectConnection, Q_ARG(int, 2)); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QCOMPARE(screens()->count(), 2); QCOMPARE(screens()->geometry(0), QRect(0, 0, 1280, 1024)); QCOMPARE(screens()->geometry(1), QRect(1280, 0, 1280, 1024)); waylandServer()->initWorkspace(); } void TestXdgShellClientRules::init() { VirtualDesktopManager::self()->setCurrent(VirtualDesktopManager::self()->desktops().first()); QVERIFY(Test::setupWaylandConnection(Test::AdditionalWaylandInterface::Decoration)); screens()->setCurrent(0); } void TestXdgShellClientRules::cleanup() { Test::destroyWaylandConnection(); // Unreference the previous config. RuleBook::self()->setConfig({}); workspace()->slotReconfigure(); // Restore virtual desktops to the initial state. VirtualDesktopManager::self()->setCount(1); QCOMPARE(VirtualDesktopManager::self()->count(), 1u); } #define TEST_DATA(name) \ void TestXdgShellClientRules::name##_data() \ { \ QTest::addColumn("type"); \ QTest::newRow("XdgShellV6") << Test::XdgShellSurfaceType::XdgShellV6; \ QTest::newRow("XdgWmBase") << Test::XdgShellSurfaceType::XdgShellStable; \ } std::tuple createWindow(Test::XdgShellSurfaceType type, const QByteArray &appId) { // Create an xdg surface. Surface *surface = Test::createSurface(); XdgShellSurface *shellSurface = Test::createXdgShellSurface(type, surface, surface, Test::CreationSetup::CreateOnly); // Assign the desired app id. shellSurface->setAppId(appId); // Wait for the initial configure event. QSignalSpy configureRequestedSpy(shellSurface, &XdgShellSurface::configureRequested); surface->commit(Surface::CommitFlag::None); configureRequestedSpy.wait(); // Draw content of the surface. shellSurface->ackConfigure(configureRequestedSpy.last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface, QSize(100, 50), Qt::blue); return {client, surface, shellSurface}; } TEST_DATA(testPositionDontAffect) void TestXdgShellClientRules::testPositionDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The position of the client should not be affected by the rule. The default // placement policy will put the client in the top-left corner of the screen. QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(0, 0)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testPositionApply) void TestXdgShellClientRules::testPositionApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The client should be moved to the position specified by the rule. QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // One should still be able to move the client around. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QSignalSpy clientStepUserMovedResizedSpy(client, &AbstractClient::clientStepUserMovedResized); QVERIFY(clientStepUserMovedResizedSpy.isValid()); QSignalSpy clientFinishUserMovedResizedSpy(client, &AbstractClient::clientFinishUserMovedResized); QVERIFY(clientFinishUserMovedResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowMove(); QCOMPARE(workspace()->moveResizeClient(), client); QCOMPARE(clientStartMoveResizedSpy.count(), 1); QVERIFY(client->isMove()); QVERIFY(!client->isResize()); const QPoint cursorPos = KWin::Cursor::pos(); client->keyPressEvent(Qt::Key_Right); client->updateMoveResize(KWin::Cursor::pos()); QCOMPARE(KWin::Cursor::pos(), cursorPos + QPoint(8, 0)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 1); QCOMPARE(client->pos(), QPoint(50, 42)); client->keyPressEvent(Qt::Key_Enter); QCOMPARE(clientFinishUserMovedResizedSpy.count(), 1); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QCOMPARE(client->pos(), QPoint(50, 42)); // The rule should be applied again if the client appears after it's been closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testPositionRemember) void TestXdgShellClientRules::testPositionRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The client should be moved to the position specified by the rule. QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // One should still be able to move the client around. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QSignalSpy clientStepUserMovedResizedSpy(client, &AbstractClient::clientStepUserMovedResized); QVERIFY(clientStepUserMovedResizedSpy.isValid()); QSignalSpy clientFinishUserMovedResizedSpy(client, &AbstractClient::clientFinishUserMovedResized); QVERIFY(clientFinishUserMovedResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowMove(); QCOMPARE(workspace()->moveResizeClient(), client); QCOMPARE(clientStartMoveResizedSpy.count(), 1); QVERIFY(client->isMove()); QVERIFY(!client->isResize()); const QPoint cursorPos = KWin::Cursor::pos(); client->keyPressEvent(Qt::Key_Right); client->updateMoveResize(KWin::Cursor::pos()); QCOMPARE(KWin::Cursor::pos(), cursorPos + QPoint(8, 0)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 1); QCOMPARE(client->pos(), QPoint(50, 42)); client->keyPressEvent(Qt::Key_Enter); QCOMPARE(clientFinishUserMovedResizedSpy.count(), 1); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QCOMPARE(client->pos(), QPoint(50, 42)); // The client should be placed at the last know position if we reopen it. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(50, 42)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testPositionForce) void TestXdgShellClientRules::testPositionForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The client should be moved to the position specified by the rule. QVERIFY(!client->isMovable()); QVERIFY(!client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // User should not be able to move the client. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowMove(); QCOMPARE(workspace()->moveResizeClient(), nullptr); QCOMPARE(clientStartMoveResizedSpy.count(), 0); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); // The position should still be forced if we reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isMovable()); QVERIFY(!client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testPositionApplyNow) void TestXdgShellClientRules::testPositionApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; QObject *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The position of the client isn't set by any rule, thus the default placement // policy will try to put the client in the top-left corner of the screen. QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(0, 0)); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); // The client should be moved to the position specified by the rule. QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); workspace()->slotReconfigure(); QCOMPARE(geometryChangedSpy.count(), 1); QCOMPARE(client->pos(), QPoint(42, 42)); // We still have to be able to move the client around. QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QSignalSpy clientStepUserMovedResizedSpy(client, &AbstractClient::clientStepUserMovedResized); QVERIFY(clientStepUserMovedResizedSpy.isValid()); QSignalSpy clientFinishUserMovedResizedSpy(client, &AbstractClient::clientFinishUserMovedResized); QVERIFY(clientFinishUserMovedResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowMove(); QCOMPARE(workspace()->moveResizeClient(), client); QCOMPARE(clientStartMoveResizedSpy.count(), 1); QVERIFY(client->isMove()); QVERIFY(!client->isResize()); const QPoint cursorPos = KWin::Cursor::pos(); client->keyPressEvent(Qt::Key_Right); client->updateMoveResize(KWin::Cursor::pos()); QCOMPARE(KWin::Cursor::pos(), cursorPos + QPoint(8, 0)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 1); QCOMPARE(client->pos(), QPoint(50, 42)); client->keyPressEvent(Qt::Key_Enter); QCOMPARE(clientFinishUserMovedResizedSpy.count(), 1); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QCOMPARE(client->pos(), QPoint(50, 42)); // The rule should not be applied again. client->evaluateWindowRules(); QCOMPARE(client->pos(), QPoint(50, 42)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testPositionForceTemporarily) void TestXdgShellClientRules::testPositionForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("position", QPoint(42, 42)); group.writeEntry("positionrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The client should be moved to the position specified by the rule. QVERIFY(!client->isMovable()); QVERIFY(!client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(42, 42)); // User should not be able to move the client. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowMove(); QCOMPARE(workspace()->moveResizeClient(), nullptr); QCOMPARE(clientStartMoveResizedSpy.count(), 0); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); // The rule should be discarded if we close the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMovable()); QVERIFY(client->isMovableAcrossScreens()); QCOMPARE(client->pos(), QPoint(0, 0)); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeDontAffect) void TestXdgShellClientRules::testSizeDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The window size shouldn't be enforced by the rule. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(0, 0)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(100, 50)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeApply) void TestXdgShellClientRules::testSizeApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The initial configure event should contain size hint set by the rule. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(480, 640)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Resizing)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Resizing)); // One still should be able to resize the client. QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QSignalSpy clientStepUserMovedResizedSpy(client, &AbstractClient::clientStepUserMovedResized); QVERIFY(clientStepUserMovedResizedSpy.isValid()); QSignalSpy clientFinishUserMovedResizedSpy(client, &AbstractClient::clientFinishUserMovedResized); QVERIFY(clientFinishUserMovedResizedSpy.isValid()); QSignalSpy surfaceSizeChangedSpy(shellSurface.data(), &XdgShellSurface::sizeChanged); QVERIFY(surfaceSizeChangedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowResize(); QCOMPARE(workspace()->moveResizeClient(), client); QCOMPARE(clientStartMoveResizedSpy.count(), 1); QVERIFY(!client->isMove()); QVERIFY(client->isResize()); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Resizing)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); const QPoint cursorPos = KWin::Cursor::pos(); client->keyPressEvent(Qt::Key_Right); client->updateMoveResize(KWin::Cursor::pos()); QCOMPARE(KWin::Cursor::pos(), cursorPos + QPoint(8, 0)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 4); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Resizing)); QCOMPARE(surfaceSizeChangedSpy.count(), 1); QCOMPARE(surfaceSizeChangedSpy.last().first().toSize(), QSize(488, 640)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 0); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(488, 640), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(488, 640)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 1); client->keyPressEvent(Qt::Key_Enter); QCOMPARE(clientFinishUserMovedResizedSpy.count(), 1); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QEXPECT_FAIL("", "Interactive resize is not spec-compliant", Continue); QVERIFY(configureRequestedSpy->wait(10)); QEXPECT_FAIL("", "Interactive resize is not spec-compliant", Continue); QCOMPARE(configureRequestedSpy->count(), 5); // The rule should be applied again if the client appears after it's been closed. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeRemember) void TestXdgShellClientRules::testSizeRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The initial configure event should contain size hint set by the rule. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Resizing)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Resizing)); // One should still be able to resize the client. QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QSignalSpy clientStepUserMovedResizedSpy(client, &AbstractClient::clientStepUserMovedResized); QVERIFY(clientStepUserMovedResizedSpy.isValid()); QSignalSpy clientFinishUserMovedResizedSpy(client, &AbstractClient::clientFinishUserMovedResized); QVERIFY(clientFinishUserMovedResizedSpy.isValid()); QSignalSpy surfaceSizeChangedSpy(shellSurface.data(), &XdgShellSurface::sizeChanged); QVERIFY(surfaceSizeChangedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowResize(); QCOMPARE(workspace()->moveResizeClient(), client); QCOMPARE(clientStartMoveResizedSpy.count(), 1); QVERIFY(!client->isMove()); QVERIFY(client->isResize()); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Resizing)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); const QPoint cursorPos = KWin::Cursor::pos(); client->keyPressEvent(Qt::Key_Right); client->updateMoveResize(KWin::Cursor::pos()); QCOMPARE(KWin::Cursor::pos(), cursorPos + QPoint(8, 0)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 4); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Resizing)); QCOMPARE(surfaceSizeChangedSpy.count(), 1); QCOMPARE(surfaceSizeChangedSpy.last().first().toSize(), QSize(488, 640)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 0); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(488, 640), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(488, 640)); QCOMPARE(clientStepUserMovedResizedSpy.count(), 1); client->keyPressEvent(Qt::Key_Enter); QCOMPARE(clientFinishUserMovedResizedSpy.count(), 1); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QEXPECT_FAIL("", "Interactive resize is not spec-compliant", Continue); QVERIFY(configureRequestedSpy->wait(10)); QEXPECT_FAIL("", "Interactive resize is not spec-compliant", Continue); QCOMPARE(configureRequestedSpy->count(), 5); // If the client appears again, it should have the last known size. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(488, 640)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(488, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(488, 640)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeForce) void TestXdgShellClientRules::testSizeForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The initial configure event should contain size hint set by the rule. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Any attempt to resize the client should not succeed. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowResize(); QCOMPARE(workspace()->moveResizeClient(), nullptr); QCOMPARE(clientStartMoveResizedSpy.count(), 0); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QVERIFY(!configureRequestedSpy->wait(100)); // If the client appears again, the size should still be forced. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeApplyNow) void TestXdgShellClientRules::testSizeApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The expected surface dimensions should be set by the rule. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(0, 0)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(100, 50)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The compositor should send a configure event with a new size. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); // Draw the surface with the new size. QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(480, 640)); QVERIFY(!configureRequestedSpy->wait(100)); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!configureRequestedSpy->wait(100)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSizeForceTemporarily) void TestXdgShellClientRules::testSizeForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("size", QSize(480, 640)); group.writeEntry("sizerule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // The initial configure event should contain size hint set by the rule. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(480, 640)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(480, 640), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isResizable()); QCOMPARE(client->size(), QSize(480, 640)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Any attempt to resize the client should not succeed. QSignalSpy clientStartMoveResizedSpy(client, &AbstractClient::clientStartUserMovedResized); QVERIFY(clientStartMoveResizedSpy.isValid()); QCOMPARE(workspace()->moveResizeClient(), nullptr); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); workspace()->slotWindowResize(); QCOMPARE(workspace()->moveResizeClient(), nullptr); QCOMPARE(clientStartMoveResizedSpy.count(), 0); QVERIFY(!client->isMove()); QVERIFY(!client->isResize()); QVERIFY(!configureRequestedSpy->wait(100)); // The rule should be discarded when the client is closed. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().first().toSize(), QSize(0, 0)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isResizable()); QCOMPARE(client->size(), QSize(100, 50)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeDontAffect) void TestXdgShellClientRules::testMaximizeDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::DontAffect)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->size(), QSize(100, 50)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeApply) void TestXdgShellClientRules::testMaximizeApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::Apply)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // One should still be able to change the maximized state of the client. workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(100, 50)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); // If we create the client again, it should be initially maximized. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeRemember) void TestXdgShellClientRules::testMaximizeRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::Remember)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // One should still be able to change the maximized state of the client. workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(100, 50)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); // If we create the client again, it should not be maximized (because last time it wasn't). shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->size(), QSize(100, 50)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeForce) void TestXdgShellClientRules::testMaximizeForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::Force)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Any attempt to change the maximized state should not succeed. const QRect oldGeometry = client->frameGeometry(); workspace()->slotWindowMaximize(); QVERIFY(!configureRequestedSpy->wait(100)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->frameGeometry(), oldGeometry); // If we create the client again, the maximized state should still be forced. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeApplyNow) void TestXdgShellClientRules::testMaximizeApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->size(), QSize(100, 50)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::ApplyNow)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We should receive a configure event with a new surface size. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 3); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Draw contents of the maximized client. QSignalSpy geometryChangedSpy(client, &AbstractClient::geometryChanged); QVERIFY(geometryChangedSpy.isValid()); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(1280, 1024)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); // The client still has to be maximizeable. QVERIFY(client->isMaximizable()); // Restore the client. workspace()->slotWindowMaximize(); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 4); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(100, 50)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); Test::render(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(geometryChangedSpy.wait()); QCOMPARE(client->size(), QSize(100, 50)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); // The rule should be discarded after it's been applied. const QRect oldGeometry = client->frameGeometry(); client->evaluateWindowRules(); QVERIFY(!configureRequestedSpy->wait(100)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->frameGeometry(), oldGeometry); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMaximizeForceTemporarily) void TestXdgShellClientRules::testMaximizeForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("maximizehoriz", true); group.writeEntry("maximizehorizrule", int(Rules::ForceTemporarily)); group.writeEntry("maximizevert", true); group.writeEntry("maximizevertrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); QScopedPointer surface; surface.reset(Test::createSurface()); QScopedPointer shellSurface; shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); QScopedPointer configureRequestedSpy; configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); // Wait for the initial configure event. XdgShellSurface::States states; QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(1280, 1024)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Map the client. shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); XdgShellClient *client = Test::renderAndWaitForShown(surface.data(), QSize(1280, 1024), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(!client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->size(), QSize(1280, 1024)); // We should receive a configure event when the client becomes active. QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(states.testFlag(XdgShellSurface::State::Maximized)); // Any attempt to change the maximized state should not succeed. const QRect oldGeometry = client->frameGeometry(); workspace()->slotWindowMaximize(); QVERIFY(!configureRequestedSpy->wait(100)); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeFull); QCOMPARE(client->frameGeometry(), oldGeometry); // The rule should be discarded if we close the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); surface.reset(Test::createSurface()); shellSurface.reset(createXdgShellSurface(type, surface.data(), surface.data(), Test::CreationSetup::CreateOnly)); configureRequestedSpy.reset(new QSignalSpy(shellSurface.data(), &XdgShellSurface::configureRequested)); shellSurface->setAppId("org.kde.foo"); surface->commit(Surface::CommitFlag::None); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 1); QCOMPARE(configureRequestedSpy->last().at(0).toSize(), QSize(0, 0)); states = configureRequestedSpy->last().at(1).value(); QVERIFY(!states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); shellSurface->ackConfigure(configureRequestedSpy->last().at(2).value()); client = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(client); QVERIFY(client->isActive()); QVERIFY(client->isMaximizable()); QCOMPARE(client->maximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->requestedMaximizeMode(), MaximizeMode::MaximizeRestore); QCOMPARE(client->size(), QSize(100, 50)); QVERIFY(configureRequestedSpy->wait()); QCOMPARE(configureRequestedSpy->count(), 2); states = configureRequestedSpy->last().at(1).value(); QVERIFY(states.testFlag(XdgShellSurface::State::Activated)); QVERIFY(!states.testFlag(XdgShellSurface::State::Maximized)); // Destroy the client. shellSurface.reset(); surface.reset(); QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopDontAffect) void TestXdgShellClientRules::testDesktopDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should appear on the current virtual desktop. QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopApply) void TestXdgShellClientRules::testDesktopApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should appear on the second virtual desktop. QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // We still should be able to move the client between desktops. workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // If we re-open the client, it should appear on the second virtual desktop again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopRemember) void TestXdgShellClientRules::testDesktopRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // Move the client to the first virtual desktop. workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // If we create the client again, it should appear on the first virtual desktop. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopForce) void TestXdgShellClientRules::testDesktopForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should appear on the second virtual desktop. QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // Any attempt to move the client to another virtual desktop should fail. workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // If we re-open the client, it should appear on the second virtual desktop again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopApplyNow) void TestXdgShellClientRules::testDesktopApplyNow() { // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should have been moved to the second virtual desktop. QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // One should still be able to move the client between desktops. workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // The rule should not be applied again. client->evaluateWindowRules(); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopForceTemporarily) void TestXdgShellClientRules::testDesktopForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("desktop", 2); group.writeEntry("desktoprule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // We need at least two virtual desktop for this test. VirtualDesktopManager::self()->setCount(2); QCOMPARE(VirtualDesktopManager::self()->count(), 2u); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should appear on the second virtual desktop. QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // Any attempt to move the client to another virtual desktop should fail. workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 2); // The rule should be discarded when the client is withdrawn. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); VirtualDesktopManager::self()->setCurrent(1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // One should be able to move the client between desktops. workspace()->sendClientToDesktop(client, 2, true); QCOMPARE(client->desktop(), 2); QCOMPARE(VirtualDesktopManager::self()->current(), 1); workspace()->sendClientToDesktop(client, 1, true); QCOMPARE(client->desktop(), 1); QCOMPARE(VirtualDesktopManager::self()->current(), 1); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeDontAffect) void TestXdgShellClientRules::testMinimizeDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", true); group.writeEntry("minimizerule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); // The client should not be minimized. QVERIFY(!client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeApply) void TestXdgShellClientRules::testMinimizeApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", true); group.writeEntry("minimizerule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); // The client should be minimized. QVERIFY(client->isMinimized()); // We should still be able to unminimize the client. client->unminimize(); QVERIFY(!client->isMinimized()); // If we re-open the client, it should be minimized back again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); QVERIFY(client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeRemember) void TestXdgShellClientRules::testMinimizeRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", false); group.writeEntry("minimizerule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); QVERIFY(!client->isMinimized()); // Minimize the client. client->minimize(); QVERIFY(client->isMinimized()); // If we open the client again, it should be minimized. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); QVERIFY(client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeForce) void TestXdgShellClientRules::testMinimizeForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", false); group.writeEntry("minimizerule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->isMinimizable()); QVERIFY(!client->isMinimized()); // Any attempt to minimize the client should fail. client->minimize(); QVERIFY(!client->isMinimized()); // If we re-open the client, the minimized state should still be forced. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->isMinimizable()); QVERIFY(!client->isMinimized()); client->minimize(); QVERIFY(!client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeApplyNow) void TestXdgShellClientRules::testMinimizeApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); QVERIFY(!client->isMinimized()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", true); group.writeEntry("minimizerule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should be minimized now. QVERIFY(client->isMinimizable()); QVERIFY(client->isMinimized()); // One is still able to unminimize the client. client->unminimize(); QVERIFY(!client->isMinimized()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(client->isMinimizable()); QVERIFY(!client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testMinimizeForceTemporarily) void TestXdgShellClientRules::testMinimizeForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("minimize", false); group.writeEntry("minimizerule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->isMinimizable()); QVERIFY(!client->isMinimized()); // Any attempt to minimize the client should fail until the client is closed. client->minimize(); QVERIFY(!client->isMinimized()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isMinimizable()); QVERIFY(!client->isMinimized()); client->minimize(); QVERIFY(client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarDontAffect) void TestXdgShellClientRules::testSkipTaskbarDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be affected by the rule. QVERIFY(!client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarApply) void TestXdgShellClientRules::testSkipTaskbarApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a taskbar. QVERIFY(client->skipTaskbar()); // Though one can change that. client->setOriginalSkipTaskbar(false); QVERIFY(!client->skipTaskbar()); // Reopen the client, the rule should be applied again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarRemember) void TestXdgShellClientRules::testSkipTaskbarRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a taskbar. QVERIFY(client->skipTaskbar()); // Change the skip-taskbar state. client->setOriginalSkipTaskbar(false); QVERIFY(!client->skipTaskbar()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be included on a taskbar. QVERIFY(!client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarForce) void TestXdgShellClientRules::testSkipTaskbarForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a taskbar. QVERIFY(client->skipTaskbar()); // Any attempt to change the skip-taskbar state should not succeed. client->setOriginalSkipTaskbar(false); QVERIFY(client->skipTaskbar()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The skip-taskbar state should be still forced. QVERIFY(client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarApplyNow) void TestXdgShellClientRules::testSkipTaskbarApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipTaskbar()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should not be on a taskbar now. QVERIFY(client->skipTaskbar()); // Also, one change the skip-taskbar state. client->setOriginalSkipTaskbar(false); QVERIFY(!client->skipTaskbar()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipTaskbarForceTemporarily) void TestXdgShellClientRules::testSkipTaskbarForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skiptaskbar", true); group.writeEntry("skiptaskbarrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a taskbar. QVERIFY(client->skipTaskbar()); // Any attempt to change the skip-taskbar state should not succeed. client->setOriginalSkipTaskbar(false); QVERIFY(client->skipTaskbar()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipTaskbar()); // The skip-taskbar state is no longer forced. client->setOriginalSkipTaskbar(true); QVERIFY(client->skipTaskbar()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerDontAffect) void TestXdgShellClientRules::testSkipPagerDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be affected by the rule. QVERIFY(!client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerApply) void TestXdgShellClientRules::testSkipPagerApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a pager. QVERIFY(client->skipPager()); // Though one can change that. client->setSkipPager(false); QVERIFY(!client->skipPager()); // Reopen the client, the rule should be applied again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerRemember) void TestXdgShellClientRules::testSkipPagerRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a pager. QVERIFY(client->skipPager()); // Change the skip-pager state. client->setSkipPager(false); QVERIFY(!client->skipPager()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be included on a pager. QVERIFY(!client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerForce) void TestXdgShellClientRules::testSkipPagerForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a pager. QVERIFY(client->skipPager()); // Any attempt to change the skip-pager state should not succeed. client->setSkipPager(false); QVERIFY(client->skipPager()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The skip-pager state should be still forced. QVERIFY(client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerApplyNow) void TestXdgShellClientRules::testSkipPagerApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipPager()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should not be on a pager now. QVERIFY(client->skipPager()); // Also, one change the skip-pager state. client->setSkipPager(false); QVERIFY(!client->skipPager()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipPagerForceTemporarily) void TestXdgShellClientRules::testSkipPagerForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skippager", true); group.writeEntry("skippagerrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be included on a pager. QVERIFY(client->skipPager()); // Any attempt to change the skip-pager state should not succeed. client->setSkipPager(false); QVERIFY(client->skipPager()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipPager()); // The skip-pager state is no longer forced. client->setSkipPager(true); QVERIFY(client->skipPager()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherDontAffect) void TestXdgShellClientRules::testSkipSwitcherDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should not be affected by the rule. QVERIFY(!client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherApply) void TestXdgShellClientRules::testSkipSwitcherApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be excluded from window switching effects. QVERIFY(client->skipSwitcher()); // Though one can change that. client->setSkipSwitcher(false); QVERIFY(!client->skipSwitcher()); // Reopen the client, the rule should be applied again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherRemember) void TestXdgShellClientRules::testSkipSwitcherRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be excluded from window switching effects. QVERIFY(client->skipSwitcher()); // Change the skip-switcher state. client->setSkipSwitcher(false); QVERIFY(!client->skipSwitcher()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be included in window switching effects. QVERIFY(!client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherForce) void TestXdgShellClientRules::testSkipSwitcherForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be excluded from window switching effects. QVERIFY(client->skipSwitcher()); // Any attempt to change the skip-switcher state should not succeed. client->setSkipSwitcher(false); QVERIFY(client->skipSwitcher()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The skip-switcher state should be still forced. QVERIFY(client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherApplyNow) void TestXdgShellClientRules::testSkipSwitcherApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipSwitcher()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should be excluded from window switching effects now. QVERIFY(client->skipSwitcher()); // Also, one change the skip-switcher state. client->setSkipSwitcher(false); QVERIFY(!client->skipSwitcher()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testSkipSwitcherForceTemporarily) void TestXdgShellClientRules::testSkipSwitcherForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("skipswitcher", true); group.writeEntry("skipswitcherrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The client should be excluded from window switching effects. QVERIFY(client->skipSwitcher()); // Any attempt to change the skip-switcher state should not succeed. client->setSkipSwitcher(false); QVERIFY(client->skipSwitcher()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->skipSwitcher()); // The skip-switcher state is no longer forced. client->setSkipSwitcher(true); QVERIFY(client->skipSwitcher()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveDontAffect) void TestXdgShellClientRules::testKeepAboveDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The keep-above state of the client should not be affected by the rule. QVERIFY(!client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveApply) void TestXdgShellClientRules::testKeepAboveApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept above. QVERIFY(client->keepAbove()); // One should also be able to alter the keep-above state. client->setKeepAbove(false); QVERIFY(!client->keepAbove()); // If one re-opens the client, it should be kept above back again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveRemember) void TestXdgShellClientRules::testKeepAboveRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept above. QVERIFY(client->keepAbove()); // Unset the keep-above state. client->setKeepAbove(false); QVERIFY(!client->keepAbove()); delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); // Re-open the client, it should not be kept above. std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveForce) void TestXdgShellClientRules::testKeepAboveForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept above. QVERIFY(client->keepAbove()); // Any attemt to unset the keep-above should not succeed. client->setKeepAbove(false); QVERIFY(client->keepAbove()); // If we re-open the client, it should still be kept above. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveApplyNow) void TestXdgShellClientRules::testKeepAboveApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepAbove()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should now be kept above other clients. QVERIFY(client->keepAbove()); // One is still able to change the keep-above state of the client. client->setKeepAbove(false); QVERIFY(!client->keepAbove()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepAboveForceTemporarily) void TestXdgShellClientRules::testKeepAboveForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept above. QVERIFY(client->keepAbove()); // Any attempt to alter the keep-above state should not succeed. client->setKeepAbove(false); QVERIFY(client->keepAbove()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepAbove()); // The keep-above state is no longer forced. client->setKeepAbove(true); QVERIFY(client->keepAbove()); client->setKeepAbove(false); QVERIFY(!client->keepAbove()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowDontAffect) void TestXdgShellClientRules::testKeepBelowDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The keep-below state of the client should not be affected by the rule. QVERIFY(!client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowApply) void TestXdgShellClientRules::testKeepBelowApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept below. QVERIFY(client->keepBelow()); // One should also be able to alter the keep-below state. client->setKeepBelow(false); QVERIFY(!client->keepBelow()); // If one re-opens the client, it should be kept above back again. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowRemember) void TestXdgShellClientRules::testKeepBelowRemember() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept below. QVERIFY(client->keepBelow()); // Unset the keep-below state. client->setKeepBelow(false); QVERIFY(!client->keepBelow()); delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); // Re-open the client, it should not be kept below. std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowForce) void TestXdgShellClientRules::testKeepBelowForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept below. QVERIFY(client->keepBelow()); // Any attemt to unset the keep-below should not succeed. client->setKeepBelow(false); QVERIFY(client->keepBelow()); // If we re-open the client, it should still be kept below. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowApplyNow) void TestXdgShellClientRules::testKeepBelowApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepBelow()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should now be kept below other clients. QVERIFY(client->keepBelow()); // One is still able to change the keep-below state of the client. client->setKeepBelow(false); QVERIFY(!client->keepBelow()); // The rule should not be applied again. client->evaluateWindowRules(); QVERIFY(!client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testKeepBelowForceTemporarily) void TestXdgShellClientRules::testKeepBelowForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("below", true); group.writeEntry("belowrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // Initially, the client should be kept below. QVERIFY(client->keepBelow()); // Any attempt to alter the keep-below state should not succeed. client->setKeepBelow(false); QVERIFY(client->keepBelow()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(!client->keepBelow()); // The keep-below state is no longer forced. client->setKeepBelow(true); QVERIFY(client->keepBelow()); client->setKeepBelow(false); QVERIFY(!client->keepBelow()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutDontAffect) void TestXdgShellClientRules::testShortcutDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QCOMPARE(client->shortcut(), QKeySequence()); client->minimize(); QVERIFY(client->isMinimized()); // If we press the window shortcut, nothing should happen. QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(!clientUnminimizedSpy.wait(100)); QVERIFY(client->isMinimized()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutApply) void TestXdgShellClientRules::testShortcutApply() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::Apply)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // If we press the window shortcut, the window should be brought back to user. QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // One can also change the shortcut. client->setShortcut(QStringLiteral("Ctrl+Alt+2")); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_2})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // The old shortcut should do nothing. client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(!clientUnminimizedSpy.wait(100)); QVERIFY(client->isMinimized()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The window shortcut should be set back to Ctrl+Alt+1. QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutRemember) void TestXdgShellClientRules::testShortcutRemember() { QSKIP("KWin core doesn't try to save the last used window shortcut"); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::Remember)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // If we press the window shortcut, the window should be brought back to user. QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // Change the window shortcut to Ctrl+Alt+2. client->setShortcut(QStringLiteral("Ctrl+Alt+2")); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_2})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The window shortcut should be set to the last known value. QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_2})); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutForce) void TestXdgShellClientRules::testShortcutForce() { QSKIP("KWin core can't release forced window shortcuts"); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // If we press the window shortcut, the window should be brought back to user. QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // Any attempt to change the window shortcut should not succeed. client->setShortcut(QStringLiteral("Ctrl+Alt+2")); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(!clientUnminimizedSpy.wait(100)); QVERIFY(client->isMinimized()); // Reopen the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // The window shortcut should still be forced. QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutApplyNow) void TestXdgShellClientRules::testShortcutApplyNow() { // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->shortcut().isEmpty()); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::ApplyNow)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // The client should now have a window shortcut assigned. QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // Assign a different shortcut. client->setShortcut(QStringLiteral("Ctrl+Alt+2")); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_2})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // The rule should not be applied again. client->evaluateWindowRules(); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_2})); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testShortcutForceTemporarily) void TestXdgShellClientRules::testShortcutForceTemporarily() { QSKIP("KWin core can't release forced window shortcuts"); // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("shortcut", "Ctrl+Alt+1"); group.writeEntry("shortcutrule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); // If we press the window shortcut, the window should be brought back to user. QSignalSpy clientUnminimizedSpy(client, &AbstractClient::clientUnminimized); QVERIFY(clientUnminimizedSpy.isValid()); quint32 timestamp = 1; QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_1, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(clientUnminimizedSpy.wait()); QVERIFY(!client->isMinimized()); // Any attempt to change the window shortcut should not succeed. client->setShortcut(QStringLiteral("Ctrl+Alt+2")); QCOMPARE(client->shortcut(), (QKeySequence{Qt::CTRL + Qt::ALT + Qt::Key_1})); client->minimize(); QVERIFY(client->isMinimized()); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTCTRL, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyPressed(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_2, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTALT, timestamp++); kwinApp()->platform()->keyboardKeyReleased(KEY_LEFTCTRL, timestamp++); QVERIFY(!clientUnminimizedSpy.wait(100)); QVERIFY(client->isMinimized()); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->shortcut().isEmpty()); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testDesktopFileDontAffect) void TestXdgShellClientRules::testDesktopFileDontAffect() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testDesktopFileApply) void TestXdgShellClientRules::testDesktopFileApply() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testDesktopFileRemember) void TestXdgShellClientRules::testDesktopFileRemember() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testDesktopFileForce) void TestXdgShellClientRules::testDesktopFileForce() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testDesktopFileApplyNow) void TestXdgShellClientRules::testDesktopFileApplyNow() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testDesktopFileForceTemporarily) void TestXdgShellClientRules::testDesktopFileForceTemporarily() { // Currently, the desktop file name is derived from the app id. If the app id is // changed, then the old rules will be lost. Either setDesktopFileName should // be exposed or the desktop file name rule should be removed for wayland clients. QSKIP("Needs changes in KWin core to pass"); } TEST_DATA(testActiveOpacityDontAffect) void TestXdgShellClientRules::testActiveOpacityDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityactive", 90); group.writeEntry("opacityactiverule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // The opacity should not be affected by the rule. QCOMPARE(client->opacity(), 1.0); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testActiveOpacityForce) void TestXdgShellClientRules::testActiveOpacityForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityactive", 90); group.writeEntry("opacityactiverule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 0.9); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testActiveOpacityForceTemporarily) void TestXdgShellClientRules::testActiveOpacityForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityactive", 90); group.writeEntry("opacityactiverule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 0.9); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 1.0); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testInactiveOpacityDontAffect) void TestXdgShellClientRules::testInactiveOpacityDontAffect() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityinactive", 80); group.writeEntry("opacityinactiverule", int(Rules::DontAffect)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); // Make the client inactive. workspace()->setActiveClient(nullptr); QVERIFY(!client->isActive()); // The opacity of the client should not be affected by the rule. QCOMPARE(client->opacity(), 1.0); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testInactiveOpacityForce) void TestXdgShellClientRules::testInactiveOpacityForce() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityinactive", 80); group.writeEntry("opacityinactiverule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 1.0); // Make the client inactive. workspace()->setActiveClient(nullptr); QVERIFY(!client->isActive()); // The opacity should be forced by the rule. QCOMPARE(client->opacity(), 0.8); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } TEST_DATA(testInactiveOpacityForceTemporarily) void TestXdgShellClientRules::testInactiveOpacityForceTemporarily() { // Initialize RuleBook with the test rule. auto config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("opacityinactive", 80); group.writeEntry("opacityinactiverule", int(Rules::ForceTemporarily)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); // Create the test client. QFETCH(Test::XdgShellSurfaceType, type); XdgShellClient *client; Surface *surface; XdgShellSurface *shellSurface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 1.0); // Make the client inactive. workspace()->setActiveClient(nullptr); QVERIFY(!client->isActive()); // The opacity should be forced by the rule. QCOMPARE(client->opacity(), 0.8); // The rule should be discarded when the client is closed. delete shellSurface; delete surface; std::tie(client, surface, shellSurface) = createWindow(type, "org.kde.foo"); QVERIFY(client); QVERIFY(client->isActive()); QCOMPARE(client->opacity(), 1.0); workspace()->setActiveClient(nullptr); QVERIFY(!client->isActive()); QCOMPARE(client->opacity(), 1.0); // Destroy the client. delete shellSurface; delete surface; QVERIFY(Test::waitForWindowDestroyed(client)); } void TestXdgShellClientRules::testMatchAfterNameChange() { KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); config->group("General").writeEntry("count", 1); KConfigGroup group = config->group("1"); group.writeEntry("above", true); group.writeEntry("aboverule", int(Rules::Force)); group.writeEntry("wmclass", "org.kde.foo"); group.writeEntry("wmclasscomplete", false); group.writeEntry("wmclassmatch", int(Rules::ExactMatch)); group.sync(); RuleBook::self()->setConfig(config); workspace()->slotReconfigure(); QScopedPointer surface(Test::createSurface()); QScopedPointer shellSurface(Test::createXdgShellV6Surface(surface.data())); auto c = Test::renderAndWaitForShown(surface.data(), QSize(100, 50), Qt::blue); QVERIFY(c); QVERIFY(c->isActive()); QCOMPARE(c->keepAbove(), false); QSignalSpy desktopFileNameSpy(c, &AbstractClient::desktopFileNameChanged); QVERIFY(desktopFileNameSpy.isValid()); shellSurface->setAppId(QByteArrayLiteral("org.kde.foo")); QVERIFY(desktopFileNameSpy.wait()); QCOMPARE(c->keepAbove(), true); } WAYLANDTEST_MAIN(TestXdgShellClientRules) #include "xdgshellclient_rules_test.moc" diff --git a/autotests/libkwineffects/timelinetest.cpp b/autotests/libkwineffects/timelinetest.cpp index 260c22462..8f8e3e2a0 100644 --- a/autotests/libkwineffects/timelinetest.cpp +++ b/autotests/libkwineffects/timelinetest.cpp @@ -1,414 +1,414 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 #include using namespace std::chrono_literals; // FIXME: Delete it in the future. Q_DECLARE_METATYPE(std::chrono::milliseconds) class TimeLineTest : public QObject { Q_OBJECT private Q_SLOTS: void testUpdateForward(); void testUpdateBackward(); void testUpdateFinished(); void testToggleDirection(); void testReset(); void testSetElapsed_data(); void testSetElapsed(); void testSetDuration(); void testSetDurationRetargeting(); void testSetDurationRetargetingSmallDuration(); void testRunning(); void testStrictRedirectSourceMode_data(); void testStrictRedirectSourceMode(); void testRelaxedRedirectSourceMode_data(); void testRelaxedRedirectSourceMode(); void testStrictRedirectTargetMode_data(); void testStrictRedirectTargetMode(); void testRelaxedRedirectTargetMode_data(); void testRelaxedRedirectTargetMode(); }; void TimeLineTest::testUpdateForward() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); // 0/1000 QCOMPARE(timeLine.value(), 0.0); QVERIFY(!timeLine.done()); // 100/1000 timeLine.update(100ms); QCOMPARE(timeLine.value(), 0.1); QVERIFY(!timeLine.done()); // 400/1000 timeLine.update(300ms); QCOMPARE(timeLine.value(), 0.4); QVERIFY(!timeLine.done()); // 900/1000 timeLine.update(500ms); QCOMPARE(timeLine.value(), 0.9); QVERIFY(!timeLine.done()); // 1000/1000 timeLine.update(3000ms); QCOMPARE(timeLine.value(), 1.0); QVERIFY(timeLine.done()); } void TimeLineTest::testUpdateBackward() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Backward); timeLine.setEasingCurve(QEasingCurve::Linear); // 0/1000 QCOMPARE(timeLine.value(), 1.0); QVERIFY(!timeLine.done()); // 100/1000 timeLine.update(100ms); QCOMPARE(timeLine.value(), 0.9); QVERIFY(!timeLine.done()); // 400/1000 timeLine.update(300ms); QCOMPARE(timeLine.value(), 0.6); QVERIFY(!timeLine.done()); // 900/1000 timeLine.update(500ms); QCOMPARE(timeLine.value(), 0.1); QVERIFY(!timeLine.done()); // 1000/1000 timeLine.update(3000ms); QCOMPARE(timeLine.value(), 0.0); QVERIFY(timeLine.done()); } void TimeLineTest::testUpdateFinished() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.update(1000ms); QCOMPARE(timeLine.value(), 1.0); QVERIFY(timeLine.done()); timeLine.update(42ms); QCOMPARE(timeLine.value(), 1.0); QVERIFY(timeLine.done()); } void TimeLineTest::testToggleDirection() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); QCOMPARE(timeLine.value(), 0.0); QVERIFY(!timeLine.done()); timeLine.update(600ms); QCOMPARE(timeLine.value(), 0.6); QVERIFY(!timeLine.done()); timeLine.toggleDirection(); QCOMPARE(timeLine.value(), 0.6); QVERIFY(!timeLine.done()); timeLine.update(200ms); QCOMPARE(timeLine.value(), 0.4); QVERIFY(!timeLine.done()); timeLine.update(3000ms); QCOMPARE(timeLine.value(), 0.0); QVERIFY(timeLine.done()); } void TimeLineTest::testReset() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.update(1000ms); QCOMPARE(timeLine.value(), 1.0); QVERIFY(timeLine.done()); timeLine.reset(); QCOMPARE(timeLine.value(), 0.0); QVERIFY(!timeLine.done()); } void TimeLineTest::testSetElapsed_data() { QTest::addColumn("duration"); QTest::addColumn("elapsed"); QTest::addColumn("expectedElapsed"); QTest::addColumn("expectedDone"); QTest::addColumn("initiallyDone"); QTest::newRow("Less than duration, not finished") << 1000ms << 300ms << 300ms << false << false; QTest::newRow("Less than duration, finished") << 1000ms << 300ms << 300ms << false << true; QTest::newRow("Greater than duration, not finished") << 1000ms << 3000ms << 1000ms << true << false; QTest::newRow("Greater than duration, finished") << 1000ms << 3000ms << 1000ms << true << true; QTest::newRow("Equal to duration, not finished") << 1000ms << 1000ms << 1000ms << true << false; QTest::newRow("Equal to duration, finished") << 1000ms << 1000ms << 1000ms << true << true; } void TimeLineTest::testSetElapsed() { QFETCH(std::chrono::milliseconds, duration); QFETCH(std::chrono::milliseconds, elapsed); QFETCH(std::chrono::milliseconds, expectedElapsed); QFETCH(bool, expectedDone); QFETCH(bool, initiallyDone); KWin::TimeLine timeLine(duration, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); if (initiallyDone) { timeLine.update(duration); QVERIFY(timeLine.done()); } timeLine.setElapsed(elapsed); QCOMPARE(timeLine.elapsed(), expectedElapsed); QCOMPARE(timeLine.done(), expectedDone); } void TimeLineTest::testSetDuration() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); QCOMPARE(timeLine.duration(), 1000ms); timeLine.setDuration(3000ms); QCOMPARE(timeLine.duration(), 3000ms); } void TimeLineTest::testSetDurationRetargeting() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.update(500ms); QCOMPARE(timeLine.value(), 0.5); QVERIFY(!timeLine.done()); timeLine.setDuration(3000ms); QCOMPARE(timeLine.value(), 0.5); QVERIFY(!timeLine.done()); } void TimeLineTest::testSetDurationRetargetingSmallDuration() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.update(999ms); QCOMPARE(timeLine.value(), 0.999); QVERIFY(!timeLine.done()); timeLine.setDuration(3ms); QCOMPARE(timeLine.value(), 1.0); QVERIFY(timeLine.done()); } void TimeLineTest::testRunning() { KWin::TimeLine timeLine(1000ms, KWin::TimeLine::Forward); timeLine.setEasingCurve(QEasingCurve::Linear); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); timeLine.update(100ms); QVERIFY(timeLine.running()); QVERIFY(!timeLine.done()); timeLine.update(900ms); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); } void TimeLineTest::testStrictRedirectSourceMode_data() { QTest::addColumn("initialDirection"); QTest::addColumn("initialValue"); QTest::addColumn("finalDirection"); QTest::addColumn("finalValue"); QTest::newRow("forward -> backward") << KWin::TimeLine::Forward << 0.0 << KWin::TimeLine::Backward << 0.0; QTest::newRow("backward -> forward") << KWin::TimeLine::Backward << 1.0 << KWin::TimeLine::Forward << 1.0; } void TimeLineTest::testStrictRedirectSourceMode() { QFETCH(KWin::TimeLine::Direction, initialDirection); KWin::TimeLine timeLine(1000ms, initialDirection); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.setSourceRedirectMode(KWin::TimeLine::RedirectMode::Strict); QTEST(timeLine.direction(), "initialDirection"); QTEST(timeLine.value(), "initialValue"); QCOMPARE(timeLine.sourceRedirectMode(), KWin::TimeLine::RedirectMode::Strict); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); QFETCH(KWin::TimeLine::Direction, finalDirection); timeLine.setDirection(finalDirection); QTEST(timeLine.direction(), "finalDirection"); QTEST(timeLine.value(), "finalValue"); QCOMPARE(timeLine.sourceRedirectMode(), KWin::TimeLine::RedirectMode::Strict); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); } void TimeLineTest::testRelaxedRedirectSourceMode_data() { QTest::addColumn("initialDirection"); QTest::addColumn("initialValue"); QTest::addColumn("finalDirection"); QTest::addColumn("finalValue"); QTest::newRow("forward -> backward") << KWin::TimeLine::Forward << 0.0 << KWin::TimeLine::Backward << 1.0; QTest::newRow("backward -> forward") << KWin::TimeLine::Backward << 1.0 << KWin::TimeLine::Forward << 0.0; } void TimeLineTest::testRelaxedRedirectSourceMode() { QFETCH(KWin::TimeLine::Direction, initialDirection); KWin::TimeLine timeLine(1000ms, initialDirection); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.setSourceRedirectMode(KWin::TimeLine::RedirectMode::Relaxed); QTEST(timeLine.direction(), "initialDirection"); QTEST(timeLine.value(), "initialValue"); QCOMPARE(timeLine.sourceRedirectMode(), KWin::TimeLine::RedirectMode::Relaxed); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); QFETCH(KWin::TimeLine::Direction, finalDirection); timeLine.setDirection(finalDirection); QTEST(timeLine.direction(), "finalDirection"); QTEST(timeLine.value(), "finalValue"); QCOMPARE(timeLine.sourceRedirectMode(), KWin::TimeLine::RedirectMode::Relaxed); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); } void TimeLineTest::testStrictRedirectTargetMode_data() { QTest::addColumn("initialDirection"); QTest::addColumn("initialValue"); QTest::addColumn("finalDirection"); QTest::addColumn("finalValue"); QTest::newRow("forward -> backward") << KWin::TimeLine::Forward << 0.0 << KWin::TimeLine::Backward << 1.0; QTest::newRow("backward -> forward") << KWin::TimeLine::Backward << 1.0 << KWin::TimeLine::Forward << 0.0; } void TimeLineTest::testStrictRedirectTargetMode() { QFETCH(KWin::TimeLine::Direction, initialDirection); KWin::TimeLine timeLine(1000ms, initialDirection); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.setTargetRedirectMode(KWin::TimeLine::RedirectMode::Strict); QTEST(timeLine.direction(), "initialDirection"); QTEST(timeLine.value(), "initialValue"); QCOMPARE(timeLine.targetRedirectMode(), KWin::TimeLine::RedirectMode::Strict); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); timeLine.update(1000ms); QTEST(timeLine.value(), "finalValue"); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); QFETCH(KWin::TimeLine::Direction, finalDirection); timeLine.setDirection(finalDirection); QTEST(timeLine.direction(), "finalDirection"); QTEST(timeLine.value(), "finalValue"); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); } void TimeLineTest::testRelaxedRedirectTargetMode_data() { QTest::addColumn("initialDirection"); QTest::addColumn("initialValue"); QTest::addColumn("finalDirection"); QTest::addColumn("finalValue"); QTest::newRow("forward -> backward") << KWin::TimeLine::Forward << 0.0 << KWin::TimeLine::Backward << 1.0; QTest::newRow("backward -> forward") << KWin::TimeLine::Backward << 1.0 << KWin::TimeLine::Forward << 0.0; } void TimeLineTest::testRelaxedRedirectTargetMode() { QFETCH(KWin::TimeLine::Direction, initialDirection); KWin::TimeLine timeLine(1000ms, initialDirection); timeLine.setEasingCurve(QEasingCurve::Linear); timeLine.setTargetRedirectMode(KWin::TimeLine::RedirectMode::Relaxed); QTEST(timeLine.direction(), "initialDirection"); QTEST(timeLine.value(), "initialValue"); QCOMPARE(timeLine.targetRedirectMode(), KWin::TimeLine::RedirectMode::Relaxed); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); timeLine.update(1000ms); QTEST(timeLine.value(), "finalValue"); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); QFETCH(KWin::TimeLine::Direction, finalDirection); timeLine.setDirection(finalDirection); QTEST(timeLine.direction(), "finalDirection"); QTEST(timeLine.value(), "finalValue"); QVERIFY(!timeLine.running()); QVERIFY(!timeLine.done()); timeLine.update(1000ms); QTEST(timeLine.direction(), "finalDirection"); QTEST(timeLine.value(), "initialValue"); QVERIFY(!timeLine.running()); QVERIFY(timeLine.done()); } QTEST_MAIN(TimeLineTest) #include "timelinetest.moc" diff --git a/colorcorrection/clockskewnotifier.cpp b/colorcorrection/clockskewnotifier.cpp index b47baeb50..b24ecc854 100644 --- a/colorcorrection/clockskewnotifier.cpp +++ b/colorcorrection/clockskewnotifier.cpp @@ -1,90 +1,90 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #include "clockskewnotifier.h" #include "clockskewnotifierengine_p.h" namespace KWin { class ClockSkewNotifier::Private { public: void loadNotifierEngine(); void unloadNotifierEngine(); ClockSkewNotifier *notifier = nullptr; ClockSkewNotifierEngine *engine = nullptr; bool isActive = false; }; void ClockSkewNotifier::Private::loadNotifierEngine() { engine = ClockSkewNotifierEngine::create(notifier); if (engine) { QObject::connect(engine, &ClockSkewNotifierEngine::clockSkewed, notifier, &ClockSkewNotifier::clockSkewed); } } void ClockSkewNotifier::Private::unloadNotifierEngine() { if (!engine) { return; } QObject::disconnect(engine, &ClockSkewNotifierEngine::clockSkewed, notifier, &ClockSkewNotifier::clockSkewed); engine->deleteLater(); engine = nullptr; } ClockSkewNotifier::ClockSkewNotifier(QObject *parent) : QObject(parent) , d(new Private) { d->notifier = this; } ClockSkewNotifier::~ClockSkewNotifier() { } bool ClockSkewNotifier::isActive() const { return d->isActive; } void ClockSkewNotifier::setActive(bool set) { if (d->isActive == set) { return; } d->isActive = set; if (d->isActive) { d->loadNotifierEngine(); } else { d->unloadNotifierEngine(); } emit activeChanged(); } } // namespace KWin diff --git a/colorcorrection/clockskewnotifier.h b/colorcorrection/clockskewnotifier.h index bbaa86530..02f9155d8 100644 --- a/colorcorrection/clockskewnotifier.h +++ b/colorcorrection/clockskewnotifier.h @@ -1,74 +1,74 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #pragma once #include namespace KWin { /** * The ClockSkewNotifier class provides a way for monitoring system clock changes. * * The ClockSkewNotifier class makes it possible to detect discontinuous changes to * the system clock. Such changes are usually initiated by the user adjusting values * in the Date and Time KCM or calls made to functions like settimeofday(). */ class ClockSkewNotifier : public QObject { Q_OBJECT Q_PROPERTY(bool active READ isActive WRITE setActive NOTIFY activeChanged) public: explicit ClockSkewNotifier(QObject *parent = nullptr); ~ClockSkewNotifier() override; /** * Returns @c true if the notifier is active; otherwise returns @c false. */ bool isActive() const; /** * Sets the active status of the clock skew notifier to @p active. * * clockSkewed() signal won't be emitted while the notifier is inactive. * * The notifier is inactive by default. * * @see activeChanged */ void setActive(bool active); signals: /** * This signal is emitted whenever the active property is changed. */ void activeChanged(); /** * This signal is emitted whenever the system clock is changed. */ void clockSkewed(); private: class Private; QScopedPointer d; }; } // namespace KWin diff --git a/colorcorrection/clockskewnotifierengine.cpp b/colorcorrection/clockskewnotifierengine.cpp index 0c1f40f52..2b5fdc8b6 100644 --- a/colorcorrection/clockskewnotifierengine.cpp +++ b/colorcorrection/clockskewnotifierengine.cpp @@ -1,41 +1,41 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #include "clockskewnotifierengine_p.h" #if defined(Q_OS_LINUX) #include "clockskewnotifierengine_linux.h" #endif namespace KWin { ClockSkewNotifierEngine *ClockSkewNotifierEngine::create(QObject *parent) { #if defined(Q_OS_LINUX) return LinuxClockSkewNotifierEngine::create(parent); #else return nullptr; #endif } ClockSkewNotifierEngine::ClockSkewNotifierEngine(QObject *parent) : QObject(parent) { } } // namespace KWin diff --git a/colorcorrection/clockskewnotifierengine_linux.cpp b/colorcorrection/clockskewnotifierengine_linux.cpp index 08cf1cfd5..22b805771 100644 --- a/colorcorrection/clockskewnotifierengine_linux.cpp +++ b/colorcorrection/clockskewnotifierengine_linux.cpp @@ -1,74 +1,74 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #include "clockskewnotifierengine_linux.h" #include #include #include #include #ifndef TFD_TIMER_CANCEL_ON_SET // only available in newer glib #define TFD_TIMER_CANCEL_ON_SET (1 << 1) #endif namespace KWin { LinuxClockSkewNotifierEngine *LinuxClockSkewNotifierEngine::create(QObject *parent) { const int fd = timerfd_create(CLOCK_REALTIME, O_CLOEXEC | O_NONBLOCK); if (fd == -1) { qWarning("Couldn't create clock skew notifier engine: %s", strerror(errno)); return nullptr; } const itimerspec spec = {}; const int ret = timerfd_settime(fd, TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &spec, nullptr); if (ret == -1) { qWarning("Couldn't create clock skew notifier engine: %s", strerror(errno)); close(fd); return nullptr; } return new LinuxClockSkewNotifierEngine(fd, parent); } LinuxClockSkewNotifierEngine::LinuxClockSkewNotifierEngine(int fd, QObject *parent) : ClockSkewNotifierEngine(parent) , m_fd(fd) { const QSocketNotifier *notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this); connect(notifier, &QSocketNotifier::activated, this, &LinuxClockSkewNotifierEngine::handleTimerCancelled); } LinuxClockSkewNotifierEngine::~LinuxClockSkewNotifierEngine() { close(m_fd); } void LinuxClockSkewNotifierEngine::handleTimerCancelled() { uint64_t expirationCount; read(m_fd, &expirationCount, sizeof(expirationCount)); emit clockSkewed(); } } // namespace KWin diff --git a/colorcorrection/clockskewnotifierengine_linux.h b/colorcorrection/clockskewnotifierengine_linux.h index 6bc0828be..78870e28a 100644 --- a/colorcorrection/clockskewnotifierengine_linux.h +++ b/colorcorrection/clockskewnotifierengine_linux.h @@ -1,44 +1,44 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #pragma once #include "clockskewnotifierengine_p.h" namespace KWin { class LinuxClockSkewNotifierEngine : public ClockSkewNotifierEngine { Q_OBJECT public: ~LinuxClockSkewNotifierEngine() override; static LinuxClockSkewNotifierEngine *create(QObject *parent); private Q_SLOTS: void handleTimerCancelled(); private: LinuxClockSkewNotifierEngine(int fd, QObject *parent); int m_fd; }; } // namespace KWin diff --git a/colorcorrection/clockskewnotifierengine_p.h b/colorcorrection/clockskewnotifierengine_p.h index 3d303275a..94a808b06 100644 --- a/colorcorrection/clockskewnotifierengine_p.h +++ b/colorcorrection/clockskewnotifierengine_p.h @@ -1,40 +1,40 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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. */ #pragma once #include namespace KWin { class ClockSkewNotifierEngine : public QObject { Q_OBJECT public: static ClockSkewNotifierEngine *create(QObject *parent); protected: explicit ClockSkewNotifierEngine(QObject *parent); Q_SIGNALS: void clockSkewed(); }; } // namespace KWin diff --git a/effects/dialogparent/package/contents/code/main.js b/effects/dialogparent/package/contents/code/main.js index 5eb812f1d..a91d68989 100644 --- a/effects/dialogparent/package/contents/code/main.js +++ b/effects/dialogparent/package/contents/code/main.js @@ -1,164 +1,164 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin - Copyright (C) 2018 Vlad Zahorodnii + Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ /*global effect, effects, animate, cancel, set, animationTime, Effect, QEasingCurve */ /*jslint continue: true */ var dialogParentEffect = { duration: animationTime(300), windowAdded: function (window) { "use strict"; if (window.modal) { dialogParentEffect.dialogGotModality(window); } }, dialogGotModality: function (window) { "use strict"; var mainWindows = window.mainWindows(); for (var i = 0; i < mainWindows.length; ++i) { dialogParentEffect.startAnimation(mainWindows[i]); } }, startAnimation: function (window) { "use strict"; if (window.visible === false) { return; } if (window.dialogParentAnimation) { if (redirect(window.dialogParentAnimation, Effect.Forward)) { return; } cancel(window.dialogParentAnimation); } window.dialogParentAnimation = set({ window: window, duration: dialogParentEffect.duration, keepAlive: false, animations: [{ type: Effect.Saturation, to: 0.4 }, { type: Effect.Brightness, to: 0.6 }] }); }, windowClosed: function (window) { "use strict"; if (window.modal) { dialogParentEffect.dialogLostModality(window); } }, dialogLostModality: function (window) { "use strict"; var mainWindows = window.mainWindows(); for (var i = 0; i < mainWindows.length; ++i) { dialogParentEffect.cancelAnimationSmooth(mainWindows[i]); } }, cancelAnimationInstant: function (window) { "use strict"; if (window.dialogParentAnimation) { cancel(window.dialogParentAnimation); delete window.dialogParentAnimation; } }, cancelAnimationSmooth: function (window) { "use strict"; if (!window.dialogParentAnimation) { return; } if (redirect(window.dialogParentAnimation, Effect.Backward)) { return; } cancel(window.dialogParentAnimation); delete window.dialogParentEffect; }, desktopChanged: function () { "use strict"; // If there is an active full screen effect, then try smoothly dim/brighten // the main windows. Keep in mind that in order for this to work properly, this // effect has to come after the full screen effect in the effect chain, // otherwise this slot will be invoked before the full screen effect can mark // itself as a full screen effect. if (effects.hasActiveFullScreenEffect) { return; } var windows = effects.stackingOrder; for (var i = 0; i < windows.length; ++i) { var window = windows[i]; dialogParentEffect.cancelAnimationInstant(window); dialogParentEffect.restartAnimation(window); } }, modalDialogChanged: function(dialog) { "use strict"; if (dialog.modal === false) dialogParentEffect.dialogLostModality(dialog); else if (dialog.modal === true) dialogParentEffect.dialogGotModality(dialog); }, restartAnimation: function (window) { "use strict"; if (window === null || window.findModal() === null) { return; } dialogParentEffect.startAnimation(window); if (window.dialogParentAnimation) { complete(window.dialogParentAnimation); } }, activeFullScreenEffectChanged: function () { "use strict"; var windows = effects.stackingOrder; for (var i = 0; i < windows.length; ++i) { var dialog = windows[i]; if (!dialog.modal) { continue; } if (effects.hasActiveFullScreenEffect) { dialogParentEffect.dialogLostModality(dialog); } else { dialogParentEffect.dialogGotModality(dialog); } } }, init: function () { "use strict"; var i, windows; effects.windowAdded.connect(dialogParentEffect.windowAdded); effects.windowClosed.connect(dialogParentEffect.windowClosed); effects.windowMinimized.connect(dialogParentEffect.cancelAnimationInstant); effects.windowUnminimized.connect(dialogParentEffect.restartAnimation); effects.windowModalityChanged.connect(dialogParentEffect.modalDialogChanged) effects['desktopChanged(int,int)'].connect(dialogParentEffect.desktopChanged); effects.desktopPresenceChanged.connect(dialogParentEffect.cancelAnimationInstant); effects.desktopPresenceChanged.connect(dialogParentEffect.restartAnimation); effects.activeFullScreenEffectChanged.connect( dialogParentEffect.activeFullScreenEffectChanged); // start animation windows = effects.stackingOrder; for (i = 0; i < windows.length; i += 1) { dialogParentEffect.restartAnimation(windows[i]); } } }; dialogParentEffect.init(); diff --git a/effects/diminactive/diminactive.cpp b/effects/diminactive/diminactive.cpp index dbf41236a..18c0073e0 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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/diminactive/diminactive.h b/effects/diminactive/diminactive.h index 72aebcf04..f6fdb0df1 100644 --- a/effects/diminactive/diminactive.h +++ b/effects/diminactive/diminactive.h @@ -1,140 +1,140 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_DIMINACTIVE_H #define KWIN_DIMINACTIVE_H // kwineffects #include namespace KWin { class DimInactiveEffect : public Effect { Q_OBJECT Q_PROPERTY(int dimStrength READ dimStrength) Q_PROPERTY(bool dimPanels READ dimPanels) Q_PROPERTY(bool dimDesktop READ dimDesktop) Q_PROPERTY(bool dimKeepAbove READ dimKeepAbove) Q_PROPERTY(bool dimByGroup READ dimByGroup) Q_PROPERTY(bool dimFullScreen READ dimFullScreen) public: DimInactiveEffect(); ~DimInactiveEffect() override; void reconfigure(ReconfigureFlags flags) override; void prePaintScreen(ScreenPrePaintData &data, int time) override; void paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) override; void postPaintScreen() override; int requestedEffectChainPosition() const override; bool isActive() const override; int dimStrength() const; bool dimPanels() const; bool dimDesktop() const; bool dimKeepAbove() const; bool dimByGroup() const; bool dimFullScreen() const; private Q_SLOTS: void windowActivated(EffectWindow *w); void windowClosed(EffectWindow *w); void windowDeleted(EffectWindow *w); void activeFullScreenEffectChanged(); void updateActiveWindow(EffectWindow *w); private: void dimWindow(WindowPaintData &data, qreal strength); bool canDimWindow(const EffectWindow *w) const; void scheduleInTransition(EffectWindow *w); void scheduleGroupInTransition(EffectWindow *w); void scheduleOutTransition(EffectWindow *w); void scheduleGroupOutTransition(EffectWindow *w); void scheduleRepaint(EffectWindow *w); private: qreal m_dimStrength; bool m_dimPanels; bool m_dimDesktop; bool m_dimKeepAbove; bool m_dimByGroup; bool m_dimFullScreen; EffectWindow *m_activeWindow = nullptr; const EffectWindowGroup *m_activeWindowGroup; QHash m_transitions; QHash m_forceDim; struct { bool active = false; TimeLine timeLine; } m_fullScreenTransition; }; inline int DimInactiveEffect::requestedEffectChainPosition() const { return 50; } inline bool DimInactiveEffect::isActive() const { return true; } inline int DimInactiveEffect::dimStrength() const { return qRound(m_dimStrength * 100.0); } inline bool DimInactiveEffect::dimPanels() const { return m_dimPanels; } inline bool DimInactiveEffect::dimDesktop() const { return m_dimDesktop; } inline bool DimInactiveEffect::dimKeepAbove() const { return m_dimKeepAbove; } inline bool DimInactiveEffect::dimByGroup() const { return m_dimByGroup; } inline bool DimInactiveEffect::dimFullScreen() const { return m_dimFullScreen; } } // namespace KWin #endif diff --git a/effects/diminactive/diminactive_config.cpp b/effects/diminactive/diminactive_config.cpp index 5b19ec289..b5dc45a39 100644 --- a/effects/diminactive/diminactive_config.cpp +++ b/effects/diminactive/diminactive_config.cpp @@ -1,65 +1,65 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Christian Nitschkowski -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "diminactive_config.h" // KConfigSkeleton #include "diminactiveconfig.h" #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(DimInactiveEffectConfigFactory, "diminactive_config.json", registerPlugin();) namespace KWin { DimInactiveEffectConfig::DimInactiveEffectConfig(QWidget *parent, const QVariantList &args) : KCModule(KAboutData::pluginData(QStringLiteral("diminactive")), parent, args) { m_ui.setupUi(this); DimInactiveConfig::instance(KWIN_CONFIG); addConfig(DimInactiveConfig::self(), this); load(); } DimInactiveEffectConfig::~DimInactiveEffectConfig() { } void DimInactiveEffectConfig::save() { KCModule::save(); OrgKdeKwinEffectsInterface interface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QDBusConnection::sessionBus()); interface.reconfigureEffect(QStringLiteral("diminactive")); } } // namespace KWin #include "diminactive_config.moc" diff --git a/effects/diminactive/diminactive_config.h b/effects/diminactive/diminactive_config.h index b074045c0..1c01d8c1d 100644 --- a/effects/diminactive/diminactive_config.h +++ b/effects/diminactive/diminactive_config.h @@ -1,48 +1,48 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Christian Nitschkowski -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_DIMINACTIVE_CONFIG_H #define KWIN_DIMINACTIVE_CONFIG_H #include #include "ui_diminactive_config.h" namespace KWin { class DimInactiveEffectConfig : public KCModule { Q_OBJECT public: explicit DimInactiveEffectConfig(QWidget *parent = nullptr, const QVariantList &args = QVariantList()); ~DimInactiveEffectConfig() override; void save() override; private: ::Ui::DimInactiveEffectConfig m_ui; }; } // namespace KWin #endif diff --git a/effects/dimscreen/package/contents/code/main.js b/effects/dimscreen/package/contents/code/main.js index 1a8a1a22b..fc3364f10 100644 --- a/effects/dimscreen/package/contents/code/main.js +++ b/effects/dimscreen/package/contents/code/main.js @@ -1,238 +1,238 @@ /******************************************************************** This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ "use strict"; var authenticationAgents = [ "kdesu kdesu", "kdesudo kdesudo", "pinentry pinentry", "polkit-kde-authentication-agent-1 polkit-kde-authentication-agent-1", "polkit-kde-manager polkit-kde-manager", // On Wayland, the resource name is filename of executable. It's empty for // authentication agents because KWayland can't get their executable paths. " org.kde.kdesu", " org.kde.polkit-kde-authentication-agent-1" ]; function activeAuthenticationAgent() { var activeWindow = effects.activeWindow; if (!activeWindow) { return null; } if (authenticationAgents.indexOf(activeWindow.windowClass) == -1) { return null; } return activeWindow; } var dimScreenEffect = { loadConfig: function () { dimScreenEffect.duration = animationTime(250); dimScreenEffect.brightness = 0.67; dimScreenEffect.saturation = 0.67; }, startAnimation: function (window) { if (!window.visible) { return; } if (window.popupWindow) { return; } if (window.x11Client && !window.managed) { return; } if (window.dimAnimation) { if (redirect(window.dimAnimation, Effect.Forward)) { return; } cancel(window.dimAnimation); } window.dimAnimation = set({ window: window, curve: QEasingCurve.InOutSine, duration: dimScreenEffect.duration, keepAlive: false, animations: [ { type: Effect.Saturation, to: dimScreenEffect.saturation }, { type: Effect.Brightness, to: dimScreenEffect.brightness } ] }); }, startAnimationSmooth: function (window) { dimScreenEffect.startAnimation(window); }, startAnimationInstant: function (window) { dimScreenEffect.startAnimation(window); if (window.dimAnimation) { complete(window.dimAnimation); } }, cancelAnimationSmooth: function (window) { if (!window.dimAnimation) { return; } if (redirect(window.dimAnimation, Effect.Backward)) { return; } cancel(window.dimAnimation); delete window.dimAnimation; }, cancelAnimationInstant: function (window) { if (window.dimAnimation) { cancel(window.dimAnimation); delete window.dimAnimation; } }, dimScreen: function (agent, animationFunc, cancelFunc) { // Keep track of currently active authentication agent so we don't have // to re-scan the stacking order in brightenScreen each time when some // window is activated. dimScreenEffect.authenticationAgent = agent; var windows = effects.stackingOrder; for (var i = 0; i < windows.length; ++i) { var window = windows[i]; if (window == agent) { // The agent might have been dimmed before (because there are // several authentication agents on the screen), so we need to // cancel previous animations for it if there are any. cancelFunc(agent); continue; } animationFunc(window); } }, dimScreenSmooth: function (agent) { dimScreenEffect.dimScreen( agent, dimScreenEffect.startAnimationSmooth, dimScreenEffect.cancelAnimationSmooth ); }, dimScreenInstant: function (agent) { dimScreenEffect.dimScreen( agent, dimScreenEffect.startAnimationInstant, dimScreenEffect.cancelAnimationInstant ); }, brightenScreen: function (cancelFunc) { if (!dimScreenEffect.authenticationAgent) { return; } dimScreenEffect.authenticationAgent = null; var windows = effects.stackingOrder; for (var i = 0; i < windows.length; ++i) { cancelFunc(windows[i]); } }, brightenScreenSmooth: function () { dimScreenEffect.brightenScreen(dimScreenEffect.cancelAnimationSmooth); }, brightenScreenInstant: function () { dimScreenEffect.brightenScreen(dimScreenEffect.cancelAnimationInstant); }, slotWindowActivated: function (window) { if (!window) { return; } if (authenticationAgents.indexOf(window.windowClass) != -1) { dimScreenEffect.dimScreenSmooth(window); } else { dimScreenEffect.brightenScreenSmooth(); } }, slotWindowAdded: function (window) { // Don't dim authentication agents that just opened. var agent = activeAuthenticationAgent(); if (agent == window) { return; } // If a window appeared while the screen is dimmed, dim the window too. if (agent) { dimScreenEffect.startAnimationInstant(window); } }, slotActiveFullScreenEffectChanged: function () { // If some full screen effect has been activated, for example the desktop // cube effect, then brighten screen back. We need to do that because the // full screen effect can dim windows on its own. if (effects.hasActiveFullScreenEffect) { dimScreenEffect.brightenScreenSmooth(); return; } // If user left the full screen effect, try to dim screen back. var agent = activeAuthenticationAgent(); if (agent) { dimScreenEffect.dimScreenSmooth(agent); } }, slotDesktopChanged: function () { // If there is an active full screen effect, then try smoothly dim/brighten // the screen. Keep in mind that in order for this to work properly, this // effect has to come after the full screen effect in the effect chain, // otherwise this slot will be invoked before the full screen effect can mark // itself as a full screen effect. if (effects.hasActiveFullScreenEffect) { return; } // Try to brighten windows on the previous virtual desktop. dimScreenEffect.brightenScreenInstant(); // Try to dim windows on the current virtual desktop. var agent = activeAuthenticationAgent(); if (agent) { dimScreenEffect.dimScreenInstant(agent); } }, restartAnimation: function (window) { if (activeAuthenticationAgent()) { dimScreenEffect.startAnimationInstant(window); } }, init: function () { dimScreenEffect.loadConfig(); effect.configChanged.connect(dimScreenEffect.loadConfig); effects.windowActivated.connect(dimScreenEffect.slotWindowActivated); effects.windowAdded.connect(dimScreenEffect.slotWindowAdded); effects.windowMinimized.connect(dimScreenEffect.cancelAnimationInstant); effects.windowUnminimized.connect(dimScreenEffect.restartAnimation); effects.activeFullScreenEffectChanged.connect( dimScreenEffect.slotActiveFullScreenEffectChanged); effects['desktopChanged(int,int)'].connect(dimScreenEffect.slotDesktopChanged); } }; dimScreenEffect.init(); diff --git a/effects/dimscreen/package/metadata.desktop b/effects/dimscreen/package/metadata.desktop index 9571b4c19..cd52b0deb 100644 --- a/effects/dimscreen/package/metadata.desktop +++ b/effects/dimscreen/package/metadata.desktop @@ -1,143 +1,143 @@ [Desktop Entry] Comment=Darkens the entire screen when requesting root privileges Comment[ar]=يعتم كامل الشاشة عند طلب صلاحيات الجذر Comment[bg]=Екранът затъмнява при необходимост от администраторски права Comment[ca]=Enfosqueix tota la pantalla en demanar privilegis d'administrador Comment[ca@valencia]=Enfosqueix tota la pantalla en demanar privilegis d'administrador Comment[cs]=Ztmaví obrazovku, pokud jsou vyžadována oprávnění administrátora systému Comment[da]=Gør hele skærmen mørkere når der bedes om root-privilegier Comment[de]=Dunkelt den gesamten Bildschirm ab, wenn nach dem Systemverwalter-Passwort gefragt wird. Comment[el]=Σκίαση ολόκληρης της οθόνης όταν απαιτούνται διακαιώματα ριζικού χρήστη root Comment[en_GB]=Darkens the entire screen when requesting root privileges Comment[eo]=Malheligi la tutan ekranon kiam ĉefuzantaj permesoj estas petitaj. Comment[es]=Oscurece la pantalla completa cuando se requieran privilegios de root Comment[et]=Tumendab administraatori õiguste nõudmisel kogu ekraani Comment[eu]=Pantaila osoa iluntzen du root-aren pribilegioak eskatzean Comment[fi]=Tummentaa koko näytön pääkäyttäjäoikeuksia kysyttäessä Comment[fr]=Noircit la totalité du bureau quand les privilèges administrateurs sont nécessaires Comment[fy]=It gehiele skerm donker meitsje as der om root-rjochten frege wurdt Comment[ga]=Dorchaigh an scáileán iomlán nuair atáthar ag iarraidh ceadanna an fhorúsáideora a fháil Comment[gl]=Escurece toda a pantalla cando se piden os privilexios de root Comment[gu]=જ્યારે રૂટ હક્ક માંગવામાં આવે ત્યારે આખા સ્ક્રિનને ઘેરો બનાવે છે Comment[hi]=जब रूट विशेषाधिकार हेतु निवेदन किया जाए तो संपूर्ण स्क्रीन को गाढ़ा करता है Comment[hne]=जब रूट प्रिविलेज बर निवेदन करही तब पूरा स्क्रीन ल धुंधला कर देही Comment[hr]=Zatamni cijeli ekran kad se zahtijevaju administratorske povlastice Comment[hu]=Elsötétíti a képernyőt rendszergazdai jogosultság kérésekor Comment[ia]=Il obscura le schermo integre quando il demanda privileges de super-usator (root) Comment[id]=Pergelap seluruh layar ketika meminta hak akses root Comment[is]=Skyggir allan skjáinn þegar beðið er um lykilorð kerfisstjóra Comment[it]=Scurisce tutto lo schermo quando si richiedono i privilegi di root Comment[ja]=root 権限が要求されるとスクリーン全体を暗くします Comment[kk]=root құқығын сұрағанда бүкіл экранды күңгірттеу Comment[km]=ធ្វើ​ឲ្យ​អេក្រង់ទាំងមូល​ងងឹត​នៅពេល​បង្ហាញ​សិទ្ធិជា​ root Comment[kn]=ನಿರ್ವಾಹಕ ಸವಲತ್ತುಗಳನ್ನು ಕೇಳುವಾಗ ಇಡೀ ತೆರೆಯನ್ನು ಮಂಕಾಗಿಸುತ್ತದೆ Comment[ko]=루트 권한이 필요할 때 화면을 어둡게 합니다 Comment[lt]=Užtemdo visą ekraną, kai reikalaujama pagrindinio naudotojo (root) teisių Comment[lv]=Aptumšina visu ekrānu, kad pieprasa root privilēģijas Comment[mk]=Го затемнува целиот екран при побарување администраторски привилегии Comment[ml]=മൂല (റൂട്ട്) വിശേഷാധികാരം അഭ്യര്‍ത്തിക്കുംബോള്‍ സ്ക്രീന്‍ കറുപ്പിക്കുന്നു Comment[mr]=प्रशासकीय अधिकारांची विनंती करताना पूर्ण स्क्रीन गडद करा Comment[nds]=Maakt den helen Schirm düüsterer, wenn na Systeempleger-Verlöven fraagt warrt Comment[nl]=Maakt het volledige scherm donker wanneer er om root-privileges wordt verzocht Comment[nn]=Gjer heile skjermen mørkare når det vert spurt om rottilgang Comment[pa]=ਜਦੋਂ ਰੂਟ ਅਧਿਕਾਰਾਂ ਦੀ ਲੋੜ ਹੋਵੇ ਤਾਂ ਪੂਰੀ ਸਕਰੀਨ ਲਈ ਗੂੜ੍ਹਾ ਕਰੋ Comment[pl]=Przyciemnia ekran przy żądaniu praw administratora Comment[pt]=Escurece o ecrã inteiro ao pedir privilégios de administrador Comment[pt_BR]=Escurece a tela inteira ao solicitar privilégios de superusuário (root) Comment[ro]=Întunecă întregul ecran la cererea privilegiilor de root Comment[ru]=Затемнение всего экрана при запросе привилегий суперпользователя Comment[si]=රූට් බලතල ඉල්ලා සිටින විට සම්පූර්ණ තිරය අඳුරු කරන්න Comment[sk]=Stmaví celú obrazovku, keď sú vyžadované rootovské oprávnenia Comment[sl]=Potemni celoten zaslon, ko se zahteva skrbniška dovoljenja Comment[sv]=Gör hela skärmen mörkare när administratörsrättigheter begärs Comment[ta]=Darkens the entire screen when requesting root privileges Comment[te]=రూట్ అనుమతులను అభ్యర్ధిస్తున్నప్పుడు మొత్తం తెరను చీకటిచేస్తుంది. Comment[th]=ทำทั้งหน้าจอให้ดูมืดขึ้น เมื่อมีการร้องขอใช้สิทธิ์ของผู้บริหารระบบ (root) Comment[tr]=Yönetici hakları isteğinde bulunulduğunda ekranı koyulaştırır Comment[ug]=root ھوقۇقىنى ئىلتىماس قىلغاندا پۈتكۈل ئېكراننى خىرەلەشتۈرىدۇ Comment[uk]=Притлумлює кольори усього екрана, коли працюємо з доступом root Comment[vi]=Làm tối toàn màn hình khi yêu cầu quyền quản trị Comment[wa]=Fwait pus noer li waitroûle etire cwand on dmande les droets da root Comment[x-test]=xxDarkens the entire screen when requesting root privilegesxx Comment[zh_CN]=在请求 root 权限时暗化整个屏幕 Comment[zh_TW]=當要求 root 權限時將整個螢幕變暗 Icon=preferences-system-windows-effect-dimscreen Name=Dim Screen for Administrator Mode Name[af]=Verdof vir Administrateurmodus Name[ar]=يعتم الشاشة لنمط المدير Name[bg]=Затъмняване на екрана в администраторски режим Name[ca]=Enfosqueix la pantalla pel mode administrador Name[ca@valencia]=Enfosqueix la pantalla per al mode d'administrador Name[cs]=Ztmavit obrazovku v administrátorském režimu Name[da]=Dæmp skærmen til administratortilstand Name[de]=Bildschirm für Systemverwaltungsmodus abdunkeln Name[el]=Σκίαση οθόνης σε λειτουργία διαχειριστή Name[en_GB]=Dim Screen for Administrator Mode Name[eo]=Malheligi la ekranon en administra reĝimo Name[es]=Oscurecer la pantalla en el modo administrador Name[et]=Tuhm ekraan administraatori režiimis Name[eu]=Ilundu leihoa administratzaile modurako Name[fi]=Himmennä näyttö pääkäyttäjätilassa Name[fr]=Assombrir l'écran pour le mode administrateur Name[fy]=Yn administratormodus it skerm dimme Name[ga]=Doiléirigh an Scáileán i Mód an Riarthóra Name[gl]=Escurecer a pantalla no modo de administración Name[gu]=સંચાલક સ્થિતિ માટે ઝાંખો સ્ક્રિન Name[hi]=प्रबंधक मोड के लिए स्क्रीन मंद करें Name[hne]=प्रसासक मोड बर स्क्रीन ल धुंधला कर देव Name[hr]=Priguši zaslon za administrativni način Name[hu]=Halványított képernyő rendszergazdai módban Name[ia]=Schermo Dim pro modo de administrator Name[id]=Pergelap Layar untuk Mode Administrator Name[is]=Dimma skjá fyrir kerfisstjóraham Name[it]=Scurisci lo schermo in modalità amministrativa Name[ja]=管理者モードでスクリーンを暗く Name[kk]=Әкімші режімде экранды күңгірттеп көрсету Name[km]=បន្ថយ​ពន្លឺ​អេក្រង់ សម្រាប់​របៀប​ជា​អ្នក​គ្រប់គ្រង Name[kn]=ನಿರ್ವಾಹಕ ವಿಧಾನದಲ್ಲಿ (ಅ ಡ್ಮಿನಿಸ್ಟ್ರೇಟರ್ ಮೋಡ್) ತೆರೆಯನ್ನು ಮಂಕಾಗಿಸು Name[ko]=관리자 모드에서 화면 어둡게 하기 Name[lt]=Ekrano pritemdymas administratoriaus veiksenoje Name[lv]=Aptumšināt ekrānu, pieprasot administratora tiesības Name[mk]=Го затемнува екранот за администраторски режим Name[ml]=അഡ്മിനിസ്ട്രേറ്റര്‍ മോഡില്‍ സ്ക്രീന്‍ തെളിച്ചം കുറയ്ക്കല്‍ Name[mr]=प्रशासक पद्धती करिता गडद स्क्रीन Name[nds]=In Systeemplegerbedrief Schirm bedüüstern Name[nl]=Scherm dimmen voor administratormodus Name[nn]=Mørklegg skjermen i administratormodus Name[pa]=ਪਰਸ਼ਾਸ਼ਕੀ ਮੋਡ ਵਿੱਚ ਸਕਰੀਨ ਡਿਮ ਕਰੋ Name[pl]=Przyciemnienie ekranu dla trybu administratora Name[pt]=Escurecer o Ecrã no Modo de Administrador Name[pt_BR]=Escurecer a tela no modo administrador Name[ro]=Împăienjenește ecranul pentru Regimul administrator Name[ru]=Затемнение экрана при административной задаче Name[si]=පරිපාලක ප්‍රකාරයේදී තිර දීප්තිය අඩු කරන්න Name[sk]=Stmaviť obrazovku v administrátorskom režime Name[sl]=Potemnitev za način skrbnika Name[sv]=Dämpa skärmen vid administratörsläge Name[ta]=Dim Screen for Administrator Mode Name[te]=నిర్వాహక రీతికొరకు తెరను డిమ్ చేస్తుంది Name[th]=ทำให้หน้าจอมืดลงสำหรับใช้ในโหมดผู้บริหารระบบ Name[tr]=Yönetici Kipinde Ekranı Dondur Name[ug]=باشقۇرغۇچى ھالىتىدە ئېكراننى تۇتۇقلاشتۇر Name[uk]=Притлумлення кольорів у режимі адміністратора Name[vi]=Làm tối màn hình cho chế độ quản trị Name[wa]=Fé pus noere li waitroûle pol môde Manaedjeu Name[x-test]=xxDim Screen for Administrator Modexx Name[zh_CN]=进入管理员模式时暗淡屏幕 Name[zh_TW]=為管理員模式暗化螢幕 Type=Service X-KDE-ParentApp= X-KDE-PluginInfo-Author=Martin Flöser, Vlad Zahorodnii X-KDE-PluginInfo-Category=Focus -X-KDE-PluginInfo-Email=mgraesslin@kde.org, vladzzag@gmail.com +X-KDE-PluginInfo-Email=mgraesslin@kde.org, vlad.zahorodnii@kde.org X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-Name=kwin4_effect_dimscreen X-KDE-PluginInfo-Version=1 X-KDE-PluginInfo-Website= X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-EnabledByDefault=false X-KDE-Ordering=60 X-Plasma-API=javascript X-Plasma-MainScript=code/main.js X-KWin-Video-Url=https://files.kde.org/plasma/kwin/effect-videos/dim_administration.mp4 diff --git a/effects/fadedesktop/package/contents/code/main.js b/effects/fadedesktop/package/contents/code/main.js index 59534dd95..ba00f4f28 100644 --- a/effects/fadedesktop/package/contents/code/main.js +++ b/effects/fadedesktop/package/contents/code/main.js @@ -1,136 +1,136 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Lucas Murray Copyright (C) 2012 Martin Gräßlin - Copyright (C) 2018 Vlad Zahorodnii + Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ "use strict"; var fadeDesktopEffect = { duration: animationTime(250), loadConfig: function () { fadeDesktopEffect.duration = animationTime(250); }, fadeInWindow: function (window) { if (window.fadeOutAnimation) { if (redirect(window.fadeOutAnimation, Effect.Backward)) { return; } cancel(window.fadeOutAnimation); delete window.fadeOutAnimation; } if (window.fadeInAnimation) { if (redirect(window.fadeInAnimation, Effect.Forward)) { return; } cancel(window.fadeInAnimation); } window.fadeInAnimation = animate({ window: window, curve: QEasingCurve.Linear, duration: fadeDesktopEffect.duration, fullScreen: true, keepAlive: false, type: Effect.Opacity, from: 0.0, to: 1.0 }); }, fadeOutWindow: function (window) { if (window.fadeInAnimation) { if (redirect(window.fadeInAnimation, Effect.Backward)) { return; } cancel(window.fadeInAnimation); delete window.fadeInAnimation; } if (window.fadeOutAnimation) { if (redirect(window.fadeOutAnimation, Effect.Forward)) { return; } cancel(window.fadeOutAnimation); } window.fadeOutAnimation = animate({ window: window, curve: QEasingCurve.Linear, duration: fadeDesktopEffect.duration, fullScreen: true, keepAlive: false, type: Effect.Opacity, from: 1.0, to: 0.0 }); }, slotDesktopChanged: function (oldDesktop, newDesktop, movingWindow) { if (effects.hasActiveFullScreenEffect && !effect.isActiveFullScreenEffect) { return; } var stackingOrder = effects.stackingOrder; for (var i = 0; i < stackingOrder.length; ++i) { var w = stackingOrder[i]; // Don't animate windows that have been moved to the current // desktop, i.e. newDesktop. if (w == movingWindow) { continue; } // If the window is not on the old and the new desktop or it's // on both of them, then don't animate it. var onOldDesktop = w.isOnDesktop(oldDesktop); var onNewDesktop = w.isOnDesktop(newDesktop); if (onOldDesktop == onNewDesktop) { continue; } if (w.minimized) { continue; } if (!w.isOnActivity(effects.currentActivity)){ continue; } if (onOldDesktop) { fadeDesktopEffect.fadeOutWindow(w); } else { fadeDesktopEffect.fadeInWindow(w); } } }, slotIsActiveFullScreenEffectChanged: function () { var isActiveFullScreen = effect.isActiveFullScreenEffect; var stackingOrder = effects.stackingOrder; for (var i = 0; i < stackingOrder.length; ++i) { var w = stackingOrder[i]; w.setData(Effect.WindowForceBlurRole, isActiveFullScreen); w.setData(Effect.WindowForceBackgroundContrastRole, isActiveFullScreen); } }, init: function () { effect.configChanged.connect(fadeDesktopEffect.loadConfig); effect.isActiveFullScreenEffectChanged.connect( fadeDesktopEffect.slotIsActiveFullScreenEffectChanged); effects['desktopChanged(int,int,KWin::EffectWindow*)'].connect( fadeDesktopEffect.slotDesktopChanged); } }; fadeDesktopEffect.init(); diff --git a/effects/fadingpopups/package/contents/code/main.js b/effects/fadingpopups/package/contents/code/main.js index 17743be17..0d0233ecb 100644 --- a/effects/fadingpopups/package/contents/code/main.js +++ b/effects/fadingpopups/package/contents/code/main.js @@ -1,151 +1,151 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ "use strict"; var blacklist = [ // The logout screen has to be animated only by the logout effect. "ksmserver ksmserver", "ksmserver-logout-greeter ksmserver-logout-greeter", // KDE Plasma splash screen has to be animated only by the login effect. "ksplashqml ksplashqml", "ksplashsimple ksplashsimple", "ksplashx ksplashx" ]; function isPopupWindow(window) { // If the window is blacklisted, don't animate it. if (blacklist.indexOf(window.windowClass) != -1) { return false; } // Animate combo box popups, tooltips, popup menus, etc. if (window.popupWindow) { return true; } // Maybe the outline deserves its own effect. if (window.outline) { return true; } // Override-redirect windows are usually used for user interface // concepts that are expected to be animated by this effect, e.g. // popups that contain window thumbnails on X11, etc. if (window.x11Client && !window.managed) { // Some utility windows can look like popup windows (e.g. the // address bar dropdown in Firefox), but we don't want to fade // them because the fade effect didn't do that. if (window.utility) { return false; } return true; } // Previously, there was a "monolithic" fade effect, which tried to // animate almost every window that was shown or hidden. Then it was // split into two effects: one that animates toplevel windows and // this one. In addition to popups, this effect also animates some // special windows(e.g. notifications) because the monolithic version // was doing that. if (window.dock || window.splash || window.toolbar || window.notification || window.onScreenDisplay || window.criticalNotification) { return true; } return false; } var fadingPopupsEffect = { loadConfig: function () { fadingPopupsEffect.fadeInDuration = animationTime(150); fadingPopupsEffect.fadeOutDuration = animationTime(150) * 4; }, slotWindowAdded: function (window) { if (effects.hasActiveFullScreenEffect) { return; } if (!isPopupWindow(window)) { return; } if (!window.visible) { return; } if (!effect.grab(window, Effect.WindowAddedGrabRole)) { return; } window.fadeInAnimation = animate({ window: window, curve: QEasingCurve.Linear, duration: fadingPopupsEffect.fadeInDuration, type: Effect.Opacity, from: 0.0, to: 1.0 }); }, slotWindowClosed: function (window) { if (effects.hasActiveFullScreenEffect) { return; } if (!isPopupWindow(window)) { return; } if (!window.visible) { return; } if (!effect.grab(window, Effect.WindowClosedGrabRole)) { return; } window.fadeOutAnimation = animate({ window: window, curve: QEasingCurve.OutQuart, duration: fadingPopupsEffect.fadeOutDuration, type: Effect.Opacity, from: 1.0, to: 0.0 }); }, slotWindowDataChanged: function (window, role) { if (role == Effect.WindowAddedGrabRole) { if (window.fadeInAnimation && effect.isGrabbed(window, role)) { cancel(window.fadeInAnimation); delete window.fadeInAnimation; } } else if (role == Effect.WindowClosedGrabRole) { if (window.fadeOutAnimation && effect.isGrabbed(window, role)) { cancel(window.fadeOutAnimation); delete window.fadeOutAnimation; } } }, init: function () { fadingPopupsEffect.loadConfig(); effect.configChanged.connect(fadingPopupsEffect.loadConfig); effects.windowAdded.connect(fadingPopupsEffect.slotWindowAdded); effects.windowClosed.connect(fadingPopupsEffect.slotWindowClosed); effects.windowDataChanged.connect(fadingPopupsEffect.slotWindowDataChanged); } }; fadingPopupsEffect.init(); diff --git a/effects/fadingpopups/package/metadata.desktop b/effects/fadingpopups/package/metadata.desktop index 139893661..05bbbe689 100644 --- a/effects/fadingpopups/package/metadata.desktop +++ b/effects/fadingpopups/package/metadata.desktop @@ -1,78 +1,78 @@ [Desktop Entry] Name=Fading Popups Name[ca]=Missatges emergents esvaïts Name[ca@valencia]=Missatges emergents que es fonen Name[cs]=Mizející vyskakovací okna Name[da]=Pop-op'er udtoner Name[de]=Überblendete Aufklappfenster Name[en_GB]=Fading Popups Name[es]=Desvanecer ventanas emergentes Name[et]=Hääbuvad hüpikdialoogid Name[eu]=Itzaleztatzen diren gainerakorrak Name[fi]=Hiipuvat ponnahdusikkunat Name[fr]=Fondu des boites de dialogue Name[gl]=Xanelas emerxentes que esvaen Name[hu]=Halványodó felugró ablakok Name[ia]=Popups dissolvente Name[id]=Sembulan Melesap Name[it]=Finestre a comparsa che si dissolvono Name[ko]=페이드 팝업 Name[lt]=Pamažu atsirandantys/išnykstantys iškylantieji langai Name[nl]=Vervagende pop-ups Name[nn]=Inn- og uttoning av sprettoppvindauge Name[pl]=Zanikanie okien wysuwnych Name[pt]=Mensagens Desvanecentes Name[pt_BR]=Desvanecer mensagens Name[ru]=Растворяющиеся всплывающие окна Name[sk]=Miznúce vyskakovacie okná Name[sv]=Borttonande meddelanderutor Name[uk]=Інтерактивні контекстні панелі Name[x-test]=xxFading Popupsxx Name[zh_CN]=气泡通知渐隐渐现 Name[zh_TW]=淡化彈出視窗 Icon=preferences-system-windows-effect-fadingpopups Comment=Make popups smoothly fade in and out when they are shown or hidden Comment[ca]=Fa que els missatges emergents s'encenguin o s'apaguin de manera gradual quan es mostren o s'oculten Comment[ca@valencia]=Fa que els missatges emergents s'encenguen o s'apaguen de manera gradual quan es mostren o s'oculten Comment[cs]=Nechá vyskakovací okna plynule zmizet/objevit se, pokud jsou zobrazeny resp. skryty Comment[da]=Få pop-op'er til at tone ud og ind når de vises eller skjules Comment[de]=Blendet Aufklappfenster beim Öffnen/Schließen langsam ein bzw. aus Comment[en_GB]=Make popups smoothly fade in and out when they are shown or hidden Comment[es]=Hace que las ventanas emergentes aparezcan o se desvanezcan suavemente al mostrarlas u ocultarlas Comment[et]=Paneb hüpikaknad sujuvalt hääbuma või tugevnema, kui need peidetakse või nähtavale tuuakse Comment[eu]=Gainerakorrak emeki agertzen eta desagertzen ditu haiek erakustean edo ezkutatzean Comment[fi]=Ponnahdusikkunat tulevat näkyviin tai poistuvat näkyvistä pehmeästi häivyttäen Comment[fr]=Estompe ou fait apparaître en fondu les boites de dialogue lorsqu'elles sont affichées ou cachées Comment[gl]=Esvae e fai opacas as xanelas emerxentes con suavidade ao mostralas ou agochadas Comment[hu]=A felugró folyamatosan áttűnő módon lesznek elrejtve és megjelenítve Comment[ia]=Face que fenestras pote dulcemente pallidir intra e foras quando illos es monstrate o celate Comment[id]=Buat sembulan secara halus lesap-muncul dan lesap-hilang ketika ia ditampilkan atau disembunyikan Comment[it]=Fai dissolvere e comparire gradualmente le finestre a comparsa quando vengono mostrate o nascoste Comment[ko]=팝업이 보여지거나 감춰질 때 부드러운 페이드 인/아웃을 사용합니다 Comment[lt]=Sukuria efektą, kai iškylantieji langai, juos parodant ar paslepiant, glotniai pamažu atsiranda/išnyksta Comment[nl]=Laat pop-ups vloeiend opkomen/vervagen als ze worden weergegeven of verborgen Comment[nn]=Ton sprettoppvindauge gradvis inn og ut når dei vert viste eller gøymde Comment[pl]=Okna wysuwne gładko wyłaniają się przy otwieraniu i zanikają przy zamykaniu Comment[pt]=Fazer com que as janelas apareçam/desapareçam suavemente quando aparecem ou ficam escondidas Comment[pt_BR]=Faz as mensagens aparecerem/desaparecerem suavemente quando são exibidas ou ocultadas Comment[ru]=Всплывающие окна при закрытии будут становиться всё более прозрачными, а потом совсем исчезать Comment[sk]=Okná sa plynule objavia/zmiznú pri ich zobrazení alebo skrytí Comment[sv]=Gör att meddelanderutor mjukt tonas in eller ut när de visas eller döljs Comment[uk]=Поступова поява або зникнення контекстних вікон вікон при відкритті чи закритті Comment[x-test]=xxMake popups smoothly fade in and out when they are shown or hiddenxx Comment[zh_CN]=当弹窗被显示或者隐藏时,使窗口平滑地淡入淡出 Comment[zh_TW]=當彈出視窗出現或消失時,讓彈出視窗滑順的淡入和淡出 Type=Service X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-Author=Vlad Zahorodnii -X-KDE-PluginInfo-Email=vladzzag@gmail.com +X-KDE-PluginInfo-Email=vlad.zahorodnii@kde.org X-KDE-PluginInfo-Name=kwin4_effect_fadingpopups X-KDE-PluginInfo-Version=1.0 X-KDE-PluginInfo-Category=Appearance X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true X-KDE-Ordering=60 X-Plasma-API=javascript X-Plasma-MainScript=code/main.js diff --git a/effects/glide/glide.cpp b/effects/glide/glide.cpp index a023bf686..00c221990 100644 --- a/effects/glide/glide.cpp +++ b/effects/glide/glide.cpp @@ -1,337 +1,337 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Philip Falkner Copyright (C) 2009 Martin Gräßlin Copyright (C) 2010 Alexandre Pereira -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "glide.h" // KConfigSkeleton #include "glideconfig.h" // Qt #include #include namespace KWin { static const QSet s_blacklist { QStringLiteral("ksmserver ksmserver"), QStringLiteral("ksmserver-logout-greeter ksmserver-logout-greeter"), QStringLiteral("ksplashqml ksplashqml"), QStringLiteral("ksplashsimple ksplashsimple"), QStringLiteral("ksplashx ksplashx") }; GlideEffect::GlideEffect() { initConfig(); reconfigure(ReconfigureAll); connect(effects, &EffectsHandler::windowAdded, this, &GlideEffect::windowAdded); connect(effects, &EffectsHandler::windowClosed, this, &GlideEffect::windowClosed); connect(effects, &EffectsHandler::windowDeleted, this, &GlideEffect::windowDeleted); connect(effects, &EffectsHandler::windowDataChanged, this, &GlideEffect::windowDataChanged); } GlideEffect::~GlideEffect() = default; void GlideEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) GlideConfig::self()->read(); m_duration = std::chrono::milliseconds(animationTime(160)); m_inParams.edge = static_cast(GlideConfig::inRotationEdge()); m_inParams.angle.from = GlideConfig::inRotationAngle(); m_inParams.angle.to = 0.0; m_inParams.distance.from = GlideConfig::inDistance(); m_inParams.distance.to = 0.0; m_inParams.opacity.from = GlideConfig::inOpacity(); m_inParams.opacity.to = 1.0; m_outParams.edge = static_cast(GlideConfig::outRotationEdge()); m_outParams.angle.from = 0.0; m_outParams.angle.to = GlideConfig::outRotationAngle(); m_outParams.distance.from = 0.0; m_outParams.distance.to = GlideConfig::outDistance(); m_outParams.opacity.from = 1.0; m_outParams.opacity.to = GlideConfig::outOpacity(); } void GlideEffect::prePaintScreen(ScreenPrePaintData &data, int time) { const std::chrono::milliseconds delta(time); auto animationIt = m_animations.begin(); while (animationIt != m_animations.end()) { (*animationIt).update(delta); ++animationIt; } data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); } void GlideEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { if (m_animations.contains(w)) { data.setTransformed(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } effects->prePaintWindow(w, data, time); } void GlideEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { auto animationIt = m_animations.constFind(w); if (animationIt == m_animations.constEnd()) { effects->paintWindow(w, mask, region, data); return; } // Perspective projection distorts objects near edges // of the viewport. This is critical because distortions // near edges of the viewport are not desired with this effect. // To fix this, the center of the window will be moved to the origin, // after applying perspective projection, the center is moved back // to its "original" projected position. Overall, this is how the window // will be transformed: // [move to the origin] -> [rotate] -> [translate] -> // -> [perspective projection] -> [reverse "move to the origin"] const QMatrix4x4 oldProjMatrix = data.screenProjectionMatrix(); const QRectF windowGeo = w->geometry(); const QVector3D invOffset = oldProjMatrix.map(QVector3D(windowGeo.center())); QMatrix4x4 invOffsetMatrix; invOffsetMatrix.translate(invOffset.x(), invOffset.y()); data.setProjectionMatrix(invOffsetMatrix * oldProjMatrix); // Move the center of the window to the origin. const QRectF screenGeo = effects->virtualScreenGeometry(); const QPointF offset = screenGeo.center() - windowGeo.center(); data.translate(offset.x(), offset.y()); const GlideParams params = w->isDeleted() ? m_outParams : m_inParams; const qreal t = (*animationIt).value(); switch (params.edge) { case RotationEdge::Top: data.setRotationAxis(Qt::XAxis); data.setRotationOrigin(QVector3D(0, 0, 0)); data.setRotationAngle(-interpolate(params.angle.from, params.angle.to, t)); break; case RotationEdge::Right: data.setRotationAxis(Qt::YAxis); data.setRotationOrigin(QVector3D(w->width(), 0, 0)); data.setRotationAngle(-interpolate(params.angle.from, params.angle.to, t)); break; case RotationEdge::Bottom: data.setRotationAxis(Qt::XAxis); data.setRotationOrigin(QVector3D(0, w->height(), 0)); data.setRotationAngle(interpolate(params.angle.from, params.angle.to, t)); break; case RotationEdge::Left: data.setRotationAxis(Qt::YAxis); data.setRotationOrigin(QVector3D(0, 0, 0)); data.setRotationAngle(interpolate(params.angle.from, params.angle.to, t)); break; default: // Fallback to Top. data.setRotationAxis(Qt::XAxis); data.setRotationOrigin(QVector3D(0, 0, 0)); data.setRotationAngle(-interpolate(params.angle.from, params.angle.to, t)); break; } data.setZTranslation(-interpolate(params.distance.from, params.distance.to, t)); data.multiplyOpacity(interpolate(params.opacity.from, params.opacity.to, t)); effects->paintWindow(w, mask, region, data); } void GlideEffect::postPaintScreen() { auto animationIt = m_animations.begin(); while (animationIt != m_animations.end()) { if ((*animationIt).done()) { EffectWindow *w = animationIt.key(); if (w->isDeleted()) { w->unrefWindow(); } animationIt = m_animations.erase(animationIt); } else { ++animationIt; } } effects->addRepaintFull(); effects->postPaintScreen(); } bool GlideEffect::isActive() const { return !m_animations.isEmpty(); } bool GlideEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void GlideEffect::windowAdded(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!isGlideWindow(w)) { return; } if (!w->isVisible()) { return; } const void *addGrab = w->data(WindowAddedGrabRole).value(); if (addGrab && addGrab != this) { return; } w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); TimeLine &timeLine = m_animations[w]; timeLine.reset(); timeLine.setDirection(TimeLine::Forward); timeLine.setDuration(m_duration); timeLine.setEasingCurve(QEasingCurve::InCurve); effects->addRepaintFull(); } void GlideEffect::windowClosed(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!isGlideWindow(w)) { return; } if (!w->isVisible()) { return; } const void *closeGrab = w->data(WindowClosedGrabRole).value(); if (closeGrab && closeGrab != this) { return; } w->refWindow(); w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); TimeLine &timeLine = m_animations[w]; timeLine.reset(); timeLine.setDirection(TimeLine::Forward); timeLine.setDuration(m_duration); timeLine.setEasingCurve(QEasingCurve::OutCurve); effects->addRepaintFull(); } void GlideEffect::windowDeleted(EffectWindow *w) { m_animations.remove(w); } void GlideEffect::windowDataChanged(EffectWindow *w, int role) { if (role != WindowAddedGrabRole && role != WindowClosedGrabRole) { return; } if (w->data(role).value() == this) { return; } auto animationIt = m_animations.find(w); if (animationIt == m_animations.end()) { return; } if (w->isDeleted() && role == WindowClosedGrabRole) { w->unrefWindow(); } m_animations.erase(animationIt); } bool GlideEffect::isGlideWindow(EffectWindow *w) const { // We don't want to animate most of plasmashell's windows, yet, some // of them we want to, for example, Task Manager Settings window. // The problem is that all those window share single window class. // So, the only way to decide whether a window should be animated is // to use a heuristic: if a window has decoration, then it's most // likely a dialog or a settings window so we have to animate it. if (w->windowClass() == QLatin1String("plasmashell plasmashell") || w->windowClass() == QLatin1String("plasmashell org.kde.plasmashell")) { return w->hasDecoration(); } if (s_blacklist.contains(w->windowClass())) { return false; } if (w->hasDecoration()) { return true; } // Don't animate combobox popups, tooltips, popup menus, etc. if (w->isPopupWindow()) { return false; } // Don't animate the outline because it looks very sick. if (w->isOutline()) { return false; } // Override-redirect windows are usually used for user interface // concepts that are not expected to be animated by this effect. if (w->isX11Client() && !w->isManaged()) { return false; } return w->isNormalWindow() || w->isDialog(); } } // namespace KWin diff --git a/effects/glide/glide.h b/effects/glide/glide.h index fa57f2b70..c470f2f8c 100644 --- a/effects/glide/glide.h +++ b/effects/glide/glide.h @@ -1,156 +1,156 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Philip Falkner Copyright (C) 2009 Martin Gräßlin Copyright (C) 2010 Alexandre Pereira -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_GLIDE_H #define KWIN_GLIDE_H // kwineffects #include namespace KWin { class GlideEffect : public Effect { Q_OBJECT Q_PROPERTY(int duration READ duration) Q_PROPERTY(RotationEdge inRotationEdge READ inRotationEdge) Q_PROPERTY(qreal inRotationAngle READ inRotationAngle) Q_PROPERTY(qreal inDistance READ inDistance) Q_PROPERTY(qreal inOpacity READ inOpacity) Q_PROPERTY(RotationEdge outRotationEdge READ outRotationEdge) Q_PROPERTY(qreal outRotationAngle READ outRotationAngle) Q_PROPERTY(qreal outDistance READ outDistance) Q_PROPERTY(qreal outOpacity READ outOpacity) public: GlideEffect(); ~GlideEffect() override; void reconfigure(ReconfigureFlags flags) 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; static bool supported(); enum RotationEdge { Top = 0, Right = 1, Bottom = 2, Left = 3 }; Q_ENUM(RotationEdge) int duration() const; RotationEdge inRotationEdge() const; qreal inRotationAngle() const; qreal inDistance() const; qreal inOpacity() const; RotationEdge outRotationEdge() const; qreal outRotationAngle() const; qreal outDistance() const; qreal outOpacity() const; private Q_SLOTS: void windowAdded(EffectWindow *w); void windowClosed(EffectWindow *w); void windowDeleted(EffectWindow *w); void windowDataChanged(EffectWindow *w, int role); private: bool isGlideWindow(EffectWindow *w) const; std::chrono::milliseconds m_duration; QHash m_animations; struct GlideParams { RotationEdge edge; struct { qreal from; qreal to; } angle, distance, opacity; }; GlideParams m_inParams; GlideParams m_outParams; }; inline int GlideEffect::requestedEffectChainPosition() const { return 50; } inline int GlideEffect::duration() const { return m_duration.count(); } inline GlideEffect::RotationEdge GlideEffect::inRotationEdge() const { return m_inParams.edge; } inline qreal GlideEffect::inRotationAngle() const { return m_inParams.angle.from; } inline qreal GlideEffect::inDistance() const { return m_inParams.distance.from; } inline qreal GlideEffect::inOpacity() const { return m_inParams.opacity.from; } inline GlideEffect::RotationEdge GlideEffect::outRotationEdge() const { return m_outParams.edge; } inline qreal GlideEffect::outRotationAngle() const { return m_outParams.angle.to; } inline qreal GlideEffect::outDistance() const { return m_outParams.distance.to; } inline qreal GlideEffect::outOpacity() const { return m_outParams.opacity.to; } } // namespace KWin #endif diff --git a/effects/scale/package/contents/code/main.js b/effects/scale/package/contents/code/main.js index 1988ca0fa..24d9641f2 100644 --- a/effects/scale/package/contents/code/main.js +++ b/effects/scale/package/contents/code/main.js @@ -1,180 +1,180 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. - Copyright (C) 2018 Vlad Zahorodnii + Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ "use strict"; var blacklist = [ // The logout screen has to be animated only by the logout effect. "ksmserver ksmserver", "ksmserver-logout-greeter ksmserver-logout-greeter", // KDE Plasma splash screen has to be animated only by the login effect. "ksplashqml ksplashqml", "ksplashsimple ksplashsimple", "ksplashx ksplashx" ]; var scaleEffect = { loadConfig: function (window) { var defaultDuration = 160; var duration = effect.readConfig("Duration", defaultDuration) || defaultDuration; scaleEffect.duration = animationTime(duration); scaleEffect.inScale = effect.readConfig("InScale", 0.96); scaleEffect.inOpacity = effect.readConfig("InOpacity", 0.4); scaleEffect.outScale = effect.readConfig("OutScale", 0.96); scaleEffect.outOpacity = effect.readConfig("OutOpacity", 0.0); }, isScaleWindow: function (window) { // We don't want to animate most of plasmashell's windows, yet, some // of them we want to, for example, Task Manager Settings window. // The problem is that all those window share single window class. // So, the only way to decide whether a window should be animated is // to use a heuristic: if a window has decoration, then it's most // likely a dialog or a settings window so we have to animate it. if (window.windowClass == "plasmashell plasmashell" || window.windowClass == "plasmashell org.kde.plasmashell") { return window.hasDecoration; } if (blacklist.indexOf(window.windowClass) != -1) { return false; } if (window.hasDecoration) { return true; } // Don't animate combobox popups, tooltips, popup menus, etc. if (window.popupWindow) { return false; } // Dont't animate the outline because it looks very sick. if (window.outline) { return false; } // Override-redirect windows are usually used for user interface // concepts that are not expected to be animated by this effect. if (window.x11Client && !window.managed) { return false; } return window.normalWindow || window.dialog; }, setupForcedRoles: function (window) { window.setData(Effect.WindowForceBackgroundContrastRole, true); window.setData(Effect.WindowForceBlurRole, true); }, cleanupForcedRoles: function (window) { window.setData(Effect.WindowForceBackgroundContrastRole, null); window.setData(Effect.WindowForceBlurRole, null); }, slotWindowAdded: function (window) { if (effects.hasActiveFullScreenEffect) { return; } if (!scaleEffect.isScaleWindow(window)) { return; } if (!window.visible) { return; } if (!effect.grab(window, Effect.WindowAddedGrabRole)) { return; } scaleEffect.setupForcedRoles(window); window.scaleInAnimation = animate({ window: window, curve: QEasingCurve.InOutSine, duration: scaleEffect.duration, animations: [ { type: Effect.Scale, from: scaleEffect.inScale }, { type: Effect.Opacity, from: scaleEffect.inOpacity } ] }); }, slotWindowClosed: function (window) { if (effects.hasActiveFullScreenEffect) { return; } if (!scaleEffect.isScaleWindow(window)) { return; } if (!window.visible) { return; } if (!effect.grab(window, Effect.WindowClosedGrabRole)) { return; } if (window.scaleInAnimation) { cancel(window.scaleInAnimation); delete window.scaleInAnimation; } scaleEffect.setupForcedRoles(window); window.scaleOutAnimation = animate({ window: window, curve: QEasingCurve.InOutSine, duration: scaleEffect.duration, animations: [ { type: Effect.Scale, to: scaleEffect.outScale }, { type: Effect.Opacity, to: scaleEffect.outOpacity } ] }); }, slotWindowDataChanged: function (window, role) { if (role == Effect.WindowAddedGrabRole) { if (window.scaleInAnimation && effect.isGrabbed(window, role)) { cancel(window.scaleInAnimation); delete window.scaleInAnimation; scaleEffect.cleanupForcedRoles(window); } } else if (role == Effect.WindowClosedGrabRole) { if (window.scaleOutAnimation && effect.isGrabbed(window, role)) { cancel(window.scaleOutAnimation); delete window.scaleOutAnimation; scaleEffect.cleanupForcedRoles(window); } } }, init: function () { scaleEffect.loadConfig(); effect.configChanged.connect(scaleEffect.loadConfig); effect.animationEnded.connect(scaleEffect.cleanupForcedRoles); effects.windowAdded.connect(scaleEffect.slotWindowAdded); effects.windowClosed.connect(scaleEffect.slotWindowClosed); effects.windowDataChanged.connect(scaleEffect.slotWindowDataChanged); } }; scaleEffect.init(); diff --git a/effects/scale/package/metadata.desktop b/effects/scale/package/metadata.desktop index 49597d15d..5d8823a03 100644 --- a/effects/scale/package/metadata.desktop +++ b/effects/scale/package/metadata.desktop @@ -1,83 +1,83 @@ [Desktop Entry] Name=Scale Name[ca]=Escala Name[ca@valencia]=Escala Name[cs]=Měřítko Name[da]=Skalér Name[de]=Skalieren Name[el]=Κλιμάκωση Name[en_GB]=Scale Name[es]=Escalar Name[et]=Skaleerimine Name[eu]=Eskalatu Name[fi]=Skaalaa Name[fr]=Échelle Name[gl]=Cambiar as dimensións Name[hu]=Nagyítás Name[ia]=Scala Name[id]=Skala Name[it]=Scala Name[ko]=크기 조정 Name[lt]=Mastelio keitimas Name[nl]=Schalen Name[nn]=Skalering Name[pl]=Skalowanie Name[pt]=Escala Name[pt_BR]=Escala Name[ru]=Масштабирование Name[sk]=Škálovať Name[sv]=Skala Name[uk]=Масштабування Name[x-test]=xxScalexx Name[zh_CN]=比例 Name[zh_TW]=縮放 Icon=preferences-system-windows-effect-scale Comment=Make windows smoothly scale in and out when they are shown or hidden Comment[ca]=Fa que les finestres entrin o surtin volant quan es mostren o s'oculten Comment[ca@valencia]=Fa que les finestres entrin o isquen volant quan es mostren o s'oculten Comment[cs]=Nechá okna plynule zvětšit/zmenšit se, pokud jsou zobrazeny resp. skryty Comment[da]=Få vinduer til at skalere blidt ud og ind når de vises eller skjules Comment[de]=Ändert die Fenstergröße langsam beim Ein- oder Ausblenden Comment[en_GB]=Make windows smoothly scale in and out when they are shown or hidden Comment[es]=Hace que las ventanas se agranden o se encojan suavemente al mostrarlas u ocultarlas Comment[et]=Skaleerib aknaid sujuvalt, kui need peidetakse või nähtavale tuuakse Comment[eu]=Leihoak emeki eskalatu barrura eta kanpora haiek erakutsi edo ezkutatzean Comment[fi]=Ikkunat ilmestyvät näkyviin tai poistuvat näkyvistä hiljalleen Comment[fr]=Échelonne les fenêtres lorsqu'elles sont affichées ou cachées Comment[gl]=Facer que as xanelas crezan ou decrezan suavemente cando se mostran ou agochan Comment[ia]=Face que fenestras pote dulcemente scalar intra e foras quando illos es monstrate o celate Comment[id]=Buat window menskala besar atau kecil secara mulus ketika ia ditampilkan atau disembunyikan Comment[it]=Ridimensiona le finestre dolcemente quando sono mostrate o nascoste Comment[ko]=창이 보여지거나 감춰질 때 부드러운 크기 조정을 사용합니다 Comment[lt]=Glotniai didinti ar mažinti langų mastelį, juos parodant ar paslepiant Comment[nl]=Laat vensters vloeiend kleiner en groter schalen als ze worden getoond of verborgen Comment[nn]=Skaler vindauge jamt inn og ut når dei vert viste eller gøymde Comment[pl]=Okna gładko pomniejszają się przy otwieraniu i powiększają przy zamykaniu Comment[pt]=Fazer com que as janelas apareçam/desapareçam suavemente quando aparecem ou ficam escondidas Comment[pt_BR]=Faz com que as janelas aumentem ou reduzam o seu tamanho de forma suave ao serem exibidas ou ocultadas Comment[ru]=Плавное увеличение или уменьшение окон при их появлении и скрытии Comment[sk]=Okná sa plynule objavia/zmiznú pri ich zobrazení alebo skrytí Comment[sv]=Gör att fönster mjukt skalas in eller ut när de visas eller döljs Comment[uk]=Плавне масштабування вікон при появі або приховуванні Comment[x-test]=xxMake windows smoothly scale in and out when they are shown or hiddenxx Comment[zh_CN]=窗口显示或隐藏时平滑缩放 Comment[zh_TW]=顯示或隱藏視窗時以平順的比例縮放方式呈現。 Type=Service X-KDE-ServiceTypes=KWin/Effect,KCModule X-KDE-PluginInfo-Author=Vlad Zahorodnii -X-KDE-PluginInfo-Email=vladzzag@gmail.com +X-KDE-PluginInfo-Email=vlad.zahorodnii@kde.org X-KDE-PluginInfo-Name=kwin4_effect_scale X-KDE-PluginInfo-Version=1 X-KDE-PluginInfo-Category=Window Open/Close Animation X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false X-KDE-Ordering=60 X-Plasma-API=javascript X-Plasma-MainScript=code/main.js X-KDE-PluginKeyword=kwin4_effect_scale X-KDE-Library=kcm_kwin4_genericscripted X-KDE-ParentComponents=kwin4_effect_scale X-KWin-Config-TranslationDomain=kwin_effects X-KWin-Exclusive-Category=toplevel-open-close-animation diff --git a/effects/sheet/sheet.cpp b/effects/sheet/sheet.cpp index 179949794..8a2279b91 100644 --- a/effects/sheet/sheet.cpp +++ b/effects/sheet/sheet.cpp @@ -1,230 +1,230 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Philip Falkner Copyright (C) 2009 Martin Gräßlin -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "sheet.h" // KConfigSkeleton #include "sheetconfig.h" // Qt #include namespace KWin { SheetEffect::SheetEffect() { initConfig(); reconfigure(ReconfigureAll); connect(effects, &EffectsHandler::windowAdded, this, &SheetEffect::slotWindowAdded); connect(effects, &EffectsHandler::windowClosed, this, &SheetEffect::slotWindowClosed); connect(effects, &EffectsHandler::windowDeleted, this, &SheetEffect::slotWindowDeleted); } void SheetEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) SheetConfig::self()->read(); // TODO: Rename AnimationTime config key to Duration. const int d = animationTime(SheetConfig::animationTime() != 0 ? SheetConfig::animationTime() : 300); m_duration = std::chrono::milliseconds(static_cast(d)); } void SheetEffect::prePaintScreen(ScreenPrePaintData &data, int time) { const std::chrono::milliseconds delta(time); auto animationIt = m_animations.begin(); while (animationIt != m_animations.end()) { (*animationIt).timeLine.update(delta); ++animationIt; } data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); } void SheetEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { if (m_animations.contains(w)) { data.setTransformed(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } effects->prePaintWindow(w, data, time); } void SheetEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { auto animationIt = m_animations.constFind(w); if (animationIt == m_animations.constEnd()) { effects->paintWindow(w, mask, region, data); return; } // Perspective projection distorts objects near edges of the viewport // in undesired way. To fix this, the center of the window will be // moved to the origin, after applying perspective projection, the // center is moved back to its "original" projected position. Overall, // this is how the window will be transformed: // [move to the origin] -> [scale] -> [rotate] -> [translate] -> // -> [perspective projection] -> [reverse "move to the origin"] const QMatrix4x4 oldProjMatrix = data.screenProjectionMatrix(); const QRectF windowGeo = w->geometry(); const QVector3D invOffset = oldProjMatrix.map(QVector3D(windowGeo.center())); QMatrix4x4 invOffsetMatrix; invOffsetMatrix.translate(invOffset.x(), invOffset.y()); data.setProjectionMatrix(invOffsetMatrix * oldProjMatrix); // Move the center of the window to the origin. const QRectF screenGeo = effects->virtualScreenGeometry(); const QPointF offset = screenGeo.center() - windowGeo.center(); data.translate(offset.x(), offset.y()); const qreal t = (*animationIt).timeLine.value(); data.setRotationAxis(Qt::XAxis); data.setRotationAngle(interpolate(60.0, 0.0, t)); data *= QVector3D(1.0, t, t); data.translate(0.0, -interpolate(w->y() - (*animationIt).parentY, 0.0, t)); data.multiplyOpacity(t); effects->paintWindow(w, mask, region, data); } void SheetEffect::postPaintWindow(EffectWindow *w) { auto animationIt = m_animations.begin(); while (animationIt != m_animations.end()) { EffectWindow *w = animationIt.key(); w->addRepaintFull(); if ((*animationIt).timeLine.done()) { if (w->isDeleted()) { w->unrefWindow(); } animationIt = m_animations.erase(animationIt); } else { ++animationIt; } } if (m_animations.isEmpty()) { effects->addRepaintFull(); } effects->postPaintWindow(w); } bool SheetEffect::isActive() const { return !m_animations.isEmpty(); } bool SheetEffect::supported() { return effects->isOpenGLCompositing() && effects->animationsSupported(); } void SheetEffect::slotWindowAdded(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!isSheetWindow(w)) { return; } Animation &animation = m_animations[w]; animation.parentY = 0; animation.timeLine.reset(); animation.timeLine.setDuration(m_duration); animation.timeLine.setDirection(TimeLine::Forward); animation.timeLine.setEasingCurve(QEasingCurve::Linear); const auto windows = effects->stackingOrder(); auto parentIt = std::find_if(windows.constBegin(), windows.constEnd(), [w](EffectWindow *p) { return p->findModal() == w; }); if (parentIt != windows.constEnd()) { animation.parentY = (*parentIt)->y(); } w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); w->addRepaintFull(); } void SheetEffect::slotWindowClosed(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!isSheetWindow(w)) { return; } w->refWindow(); Animation &animation = m_animations[w]; animation.timeLine.reset(); animation.parentY = 0; animation.timeLine.setDuration(m_duration); animation.timeLine.setDirection(TimeLine::Backward); animation.timeLine.setEasingCurve(QEasingCurve::Linear); const auto windows = effects->stackingOrder(); auto parentIt = std::find_if(windows.constBegin(), windows.constEnd(), [w](EffectWindow *p) { return p->findModal() == w; }); if (parentIt != windows.constEnd()) { animation.parentY = (*parentIt)->y(); } w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); w->addRepaintFull(); } void SheetEffect::slotWindowDeleted(EffectWindow *w) { m_animations.remove(w); } bool SheetEffect::isSheetWindow(EffectWindow *w) const { return w->isModal(); } } // namespace KWin diff --git a/effects/sheet/sheet.h b/effects/sheet/sheet.h index e81ccf000..9c05d1ed4 100644 --- a/effects/sheet/sheet.h +++ b/effects/sheet/sheet.h @@ -1,85 +1,85 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Philip Falkner Copyright (C) 2009 Martin Gräßlin -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_SHEET_H #define KWIN_SHEET_H // kwineffects #include namespace KWin { class SheetEffect : public Effect { Q_OBJECT Q_PROPERTY(int duration READ duration) public: SheetEffect(); void reconfigure(ReconfigureFlags flags) 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 postPaintWindow(EffectWindow *w) override; bool isActive() const override; int requestedEffectChainPosition() const override; static bool supported(); int duration() const; private Q_SLOTS: void slotWindowAdded(EffectWindow *w); void slotWindowClosed(EffectWindow *w); void slotWindowDeleted(EffectWindow *w); private: bool isSheetWindow(EffectWindow *w) const; private: std::chrono::milliseconds m_duration; struct Animation { TimeLine timeLine; int parentY; }; QHash m_animations; }; inline int SheetEffect::requestedEffectChainPosition() const { return 60; } inline int SheetEffect::duration() const { return m_duration.count(); } } // namespace KWin #endif diff --git a/effects/showpaint/showpaint_config.cpp b/effects/showpaint/showpaint_config.cpp index 4bbf1ef25..db45a161f 100644 --- a/effects/showpaint/showpaint_config.cpp +++ b/effects/showpaint/showpaint_config.cpp @@ -1,87 +1,87 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "showpaint_config.h" #include #include #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(ShowPaintEffectConfigFactory, "showpaint_config.json", registerPlugin();) namespace KWin { ShowPaintEffectConfig::ShowPaintEffectConfig(QWidget *parent, const QVariantList &args) : KCModule(KAboutData::pluginData(QStringLiteral("showpaint")), parent, args) , m_ui(new Ui::ShowPaintEffectConfig) { m_ui->setupUi(this); auto *actionCollection = new KActionCollection(this, QStringLiteral("kwin")); actionCollection->setComponentDisplayName(i18n("KWin")); actionCollection->setConfigGroup(QStringLiteral("ShowPaint")); actionCollection->setConfigGlobal(true); QAction *toggleAction = actionCollection->addAction(QStringLiteral("Toggle")); toggleAction->setText(i18n("Toggle Show Paint")); toggleAction->setProperty("isConfigurationAction", true); KGlobalAccel::self()->setDefaultShortcut(toggleAction, {}); KGlobalAccel::self()->setShortcut(toggleAction, {}); m_ui->shortcutsEditor->addCollection(actionCollection); connect(m_ui->shortcutsEditor, &KShortcutsEditor::keyChange, this, qOverload<>(&ShowPaintEffectConfig::changed)); load(); } ShowPaintEffectConfig::~ShowPaintEffectConfig() { // If save() is called, undoChanges() has no effect. m_ui->shortcutsEditor->undoChanges(); delete m_ui; } void ShowPaintEffectConfig::save() { KCModule::save(); m_ui->shortcutsEditor->save(); } void ShowPaintEffectConfig::defaults() { m_ui->shortcutsEditor->allDefault(); KCModule::defaults(); } } // namespace KWin #include "showpaint_config.moc" diff --git a/effects/showpaint/showpaint_config.h b/effects/showpaint/showpaint_config.h index 5cb6c3e21..0523370d5 100644 --- a/effects/showpaint/showpaint_config.h +++ b/effects/showpaint/showpaint_config.h @@ -1,46 +1,46 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "ui_showpaint_config.h" namespace KWin { class ShowPaintEffectConfig : public KCModule { Q_OBJECT public: explicit ShowPaintEffectConfig(QWidget *parent = nullptr, const QVariantList &args = {}); ~ShowPaintEffectConfig() override; public Q_SLOTS: void save() override; void defaults() override; private: Ui::ShowPaintEffectConfig *m_ui; }; } // namespace KWin diff --git a/effects/slide/slide.cpp b/effects/slide/slide.cpp index 78b523164..34becbf6a 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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, const QRegion ®ion, 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/slide/slide.h b/effects/slide/slide.h index ecc43d0f5..563d26c3e 100644 --- a/effects/slide/slide.h +++ b/effects/slide/slide.h @@ -1,142 +1,142 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_SLIDE_H #define KWIN_SLIDE_H // kwineffects #include namespace KWin { class SlideEffect : public Effect { Q_OBJECT Q_PROPERTY(int duration READ duration) Q_PROPERTY(int horizontalGap READ horizontalGap) Q_PROPERTY(int verticalGap READ verticalGap) Q_PROPERTY(bool slideDocks READ slideDocks) Q_PROPERTY(bool slideBackground READ slideBackground) public: SlideEffect(); ~SlideEffect() override; void reconfigure(ReconfigureFlags) override; void prePaintScreen(ScreenPrePaintData &data, int time) override; void paintScreen(int mask, const QRegion ®ion, 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; bool isActive() const override { return m_active; } int requestedEffectChainPosition() const override { return 50; } static bool supported(); int duration() const; int horizontalGap() const; int verticalGap() const; bool slideDocks() const; bool slideBackground() const; private Q_SLOTS: void desktopChanged(int old, int current, EffectWindow *with); void windowAdded(EffectWindow *w); void windowDeleted(EffectWindow *w); void numberDesktopsChanged(uint old); void numberScreensChanged(); private: QPoint desktopCoords(int id) const; QRect desktopGeometry(int id) const; int workspaceWidth() const; int workspaceHeight() const; bool isTranslated(const EffectWindow *w) const; bool isPainted(const EffectWindow *w) const; bool shouldElevate(const EffectWindow *w) const; void start(int old, int current, EffectWindow *movingWindow = nullptr); void stop(); private: int m_hGap; int m_vGap; bool m_slideDocks; bool m_slideBackground; bool m_active = false; TimeLine m_timeLine; QPoint m_startPos; QPoint m_diff; EffectWindow *m_movingWindow = nullptr; struct { int desktop; bool firstPass; bool lastPass; QPoint translation; EffectWindowList fullscreenWindows; } m_paintCtx; EffectWindowList m_elevatedWindows; }; inline int SlideEffect::duration() const { return m_timeLine.duration().count(); } inline int SlideEffect::horizontalGap() const { return m_hGap; } inline int SlideEffect::verticalGap() const { return m_vGap; } inline bool SlideEffect::slideDocks() const { return m_slideDocks; } inline bool SlideEffect::slideBackground() const { return m_slideBackground; } } // namespace KWin #endif diff --git a/effects/slide/slide_config.cpp b/effects/slide/slide_config.cpp index 19f6af751..32510202c 100644 --- a/effects/slide/slide_config.cpp +++ b/effects/slide/slide_config.cpp @@ -1,63 +1,63 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2017, 2018 Vlad Zahorodnii +Copyright (C) 2017, 2018 Vlad Zahorodnii 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 "slide_config.h" // KConfigSkeleton #include "slideconfig.h" #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(SlideEffectConfigFactory, "slide_config.json", registerPlugin();) namespace KWin { SlideEffectConfig::SlideEffectConfig(QWidget *parent, const QVariantList &args) : KCModule(KAboutData::pluginData(QStringLiteral("slide")), parent, args) { m_ui.setupUi(this); SlideConfig::instance(KWIN_CONFIG); addConfig(SlideConfig::self(), this); load(); } SlideEffectConfig::~SlideEffectConfig() { } void SlideEffectConfig::save() { KCModule::save(); OrgKdeKwinEffectsInterface interface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QDBusConnection::sessionBus()); interface.reconfigureEffect(QStringLiteral("slide")); } } // namespace KWin #include "slide_config.moc" diff --git a/effects/slide/slide_config.h b/effects/slide/slide_config.h index 992ca9761..473faf208 100644 --- a/effects/slide/slide_config.h +++ b/effects/slide/slide_config.h @@ -1,47 +1,47 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2017, 2018 Vlad Zahorodnii +Copyright (C) 2017, 2018 Vlad Zahorodnii 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 SLIDE_CONFIG_H #define SLIDE_CONFIG_H #include #include "ui_slide_config.h" namespace KWin { class SlideEffectConfig : public KCModule { Q_OBJECT public: explicit SlideEffectConfig(QWidget *parent = nullptr, const QVariantList &args = QVariantList()); ~SlideEffectConfig() override; void save() override; private: ::Ui::SlideEffectConfig m_ui; }; } // namespace KWin #endif diff --git a/effects/slidingpopups/slidingpopups.cpp b/effects/slidingpopups/slidingpopups.cpp index 7316145e9..ccc53470f 100644 --- a/effects/slidingpopups/slidingpopups.cpp +++ b/effects/slidingpopups/slidingpopups.cpp @@ -1,544 +1,544 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Marco Martin notmart@gmail.com -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "slidingpopups.h" #include "slidingpopupsconfig.h" #include #include #include #include #include #include #include Q_DECLARE_METATYPE(KWindowEffects::SlideFromLocation) namespace KWin { SlidingPopupsEffect::SlidingPopupsEffect() { initConfig(); KWayland::Server::Display *display = effects->waylandDisplay(); if (display) { display->createSlideManager(this)->create(); } m_slideLength = QFontMetrics(qApp->font()).height() * 8; m_atom = effects->announceSupportProperty("_KDE_SLIDE", this); connect(effects, &EffectsHandler::windowAdded, this, &SlidingPopupsEffect::slotWindowAdded); connect(effects, &EffectsHandler::windowClosed, this, &SlidingPopupsEffect::slideOut); connect(effects, &EffectsHandler::windowDeleted, this, &SlidingPopupsEffect::slotWindowDeleted); connect(effects, &EffectsHandler::propertyNotify, this, &SlidingPopupsEffect::slotPropertyNotify); connect(effects, &EffectsHandler::windowShown, this, &SlidingPopupsEffect::slideIn); connect(effects, &EffectsHandler::windowHidden, this, &SlidingPopupsEffect::slideOut); connect(effects, &EffectsHandler::xcbConnectionChanged, this, [this] { m_atom = effects->announceSupportProperty(QByteArrayLiteral("_KDE_SLIDE"), this); } ); connect(effects, qOverload(&EffectsHandler::desktopChanged), this, &SlidingPopupsEffect::stopAnimations); connect(effects, &EffectsHandler::activeFullScreenEffectChanged, this, &SlidingPopupsEffect::stopAnimations); reconfigure(ReconfigureAll); } SlidingPopupsEffect::~SlidingPopupsEffect() { } bool SlidingPopupsEffect::supported() { return effects->animationsSupported(); } void SlidingPopupsEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) SlidingPopupsConfig::self()->read(); m_slideInDuration = std::chrono::milliseconds( static_cast(animationTime(SlidingPopupsConfig::slideInTime() != 0 ? SlidingPopupsConfig::slideInTime() : 150))); m_slideOutDuration = std::chrono::milliseconds( static_cast(animationTime(SlidingPopupsConfig::slideOutTime() != 0 ? SlidingPopupsConfig::slideOutTime() : 250))); auto animationIt = m_animations.begin(); while (animationIt != m_animations.end()) { const auto duration = ((*animationIt).kind == AnimationKind::In) ? m_slideInDuration : m_slideOutDuration; (*animationIt).timeLine.setDuration(duration); ++animationIt; } auto dataIt = m_animationsData.begin(); while (dataIt != m_animationsData.end()) { (*dataIt).slideInDuration = m_slideInDuration; (*dataIt).slideOutDuration = m_slideOutDuration; ++dataIt; } } void SlidingPopupsEffect::prePaintWindow(EffectWindow *w, WindowPrePaintData &data, int time) { auto animationIt = m_animations.find(w); if (animationIt == m_animations.end()) { effects->prePaintWindow(w, data, time); return; } (*animationIt).timeLine.update(std::chrono::milliseconds(time)); data.setTransformed(); w->enablePainting(EffectWindow::PAINT_DISABLED | EffectWindow::PAINT_DISABLED_BY_DELETE); effects->prePaintWindow(w, data, time); } void SlidingPopupsEffect::paintWindow(EffectWindow *w, int mask, QRegion region, WindowPaintData &data) { auto animationIt = m_animations.constFind(w); if (animationIt == m_animations.constEnd()) { effects->paintWindow(w, mask, region, data); return; } const AnimationData &animData = m_animationsData[w]; const int slideLength = (animData.slideLength > 0) ? animData.slideLength : m_slideLength; const QRect screenRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); int splitPoint = 0; const QRect geo = w->expandedGeometry(); const qreal t = (*animationIt).timeLine.value(); switch (animData.location) { case Location::Left: if (slideLength < geo.width()) { data.multiplyOpacity(t); } data.translate(-interpolate(qMin(geo.width(), slideLength), 0.0, t)); splitPoint = geo.width() - (geo.x() + geo.width() - screenRect.x() - animData.offset); region = QRegion(geo.x() + splitPoint, geo.y(), geo.width() - splitPoint, geo.height()); break; case Location::Top: if (slideLength < geo.height()) { data.multiplyOpacity(t); } data.translate(0.0, -interpolate(qMin(geo.height(), slideLength), 0.0, t)); splitPoint = geo.height() - (geo.y() + geo.height() - screenRect.y() - animData.offset); region = QRegion(geo.x(), geo.y() + splitPoint, geo.width(), geo.height() - splitPoint); break; case Location::Right: if (slideLength < geo.width()) { data.multiplyOpacity(t); } data.translate(interpolate(qMin(geo.width(), slideLength), 0.0, t)); splitPoint = screenRect.x() + screenRect.width() - geo.x() - animData.offset; region = QRegion(geo.x(), geo.y(), splitPoint, geo.height()); break; case Location::Bottom: default: if (slideLength < geo.height()) { data.multiplyOpacity(t); } data.translate(0.0, interpolate(qMin(geo.height(), slideLength), 0.0, t)); splitPoint = screenRect.y() + screenRect.height() - geo.y() - animData.offset; region = QRegion(geo.x(), geo.y(), geo.width(), splitPoint); } effects->paintWindow(w, mask, region, data); } void SlidingPopupsEffect::postPaintWindow(EffectWindow *w) { auto animationIt = m_animations.find(w); if (animationIt != m_animations.end()) { if ((*animationIt).timeLine.done()) { if (w->isDeleted()) { w->unrefWindow(); } else { w->setData(WindowForceBackgroundContrastRole, QVariant()); w->setData(WindowForceBlurRole, QVariant()); } m_animations.erase(animationIt); } w->addRepaintFull(); } effects->postPaintWindow(w); } void SlidingPopupsEffect::slotWindowAdded(EffectWindow *w) { //X11 if (m_atom != XCB_ATOM_NONE) { slotPropertyNotify(w, m_atom); } //Wayland if (auto surf = w->surface()) { slotWaylandSlideOnShowChanged(w); connect(surf, &KWayland::Server::SurfaceInterface::slideOnShowHideChanged, this, [this, surf] { slotWaylandSlideOnShowChanged(effects->findWindow(surf)); }); } if (auto internal = w->internalWindow()) { internal->installEventFilter(this); setupInternalWindowSlide(w); } slideIn(w); } void SlidingPopupsEffect::slotWindowDeleted(EffectWindow *w) { m_animations.remove(w); m_animationsData.remove(w); } void SlidingPopupsEffect::slotPropertyNotify(EffectWindow *w, long atom) { if (!w || atom != m_atom || m_atom == XCB_ATOM_NONE) { return; } // _KDE_SLIDE atom format(each field is an uint32_t): // [] [] [] // // If offset is equal to -1, this effect will decide what offset to use // given edge of the screen, from which the window has to slide. // // If slide in duration is equal to 0 milliseconds, the default slide in // duration will be used. Same with the slide out duration. // // NOTE: If only slide in duration has been provided, then it will be // also used as slide out duration. I.e. if you provided only slide in // duration, then slide in duration == slide out duration. const QByteArray rawAtomData = w->readProperty(m_atom, m_atom, 32); if (rawAtomData.isEmpty()) { // Property was removed, thus also remove the effect for window if (w->data(WindowClosedGrabRole).value() == this) { w->setData(WindowClosedGrabRole, QVariant()); } m_animations.remove(w); m_animationsData.remove(w); return; } // Offset and location are required. if (static_cast(rawAtomData.size()) < sizeof(uint32_t) * 2) { return; } const auto *atomData = reinterpret_cast(rawAtomData.data()); AnimationData &animData = m_animationsData[w]; animData.offset = atomData[0]; switch (atomData[1]) { case 0: // West animData.location = Location::Left; break; case 1: // North animData.location = Location::Top; break; case 2: // East animData.location = Location::Right; break; case 3: // South default: animData.location = Location::Bottom; break; } if (static_cast(rawAtomData.size()) >= sizeof(uint32_t) * 3) { animData.slideInDuration = std::chrono::milliseconds(atomData[2]); if (static_cast(rawAtomData.size()) >= sizeof(uint32_t) * 4) { animData.slideOutDuration = std::chrono::milliseconds(atomData[3]); } else { animData.slideOutDuration = animData.slideInDuration; } } else { animData.slideInDuration = m_slideInDuration; animData.slideOutDuration = m_slideOutDuration; } if (static_cast(rawAtomData.size()) >= sizeof(uint32_t) * 5) { animData.slideLength = atomData[4]; } else { animData.slideLength = 0; } setupAnimData(w); } void SlidingPopupsEffect::setupAnimData(EffectWindow *w) { const QRect screenRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); const QRect windowGeo = w->geometry(); AnimationData &animData = m_animationsData[w]; if (animData.offset == -1) { switch (animData.location) { case Location::Left: animData.offset = qMax(windowGeo.left() - screenRect.left(), 0); break; case Location::Top: animData.offset = qMax(windowGeo.top() - screenRect.top(), 0); break; case Location::Right: animData.offset = qMax(screenRect.right() - windowGeo.right(), 0); break; case Location::Bottom: default: animData.offset = qMax(screenRect.bottom() - windowGeo.bottom(), 0); break; } } // sanitize switch (animData.location) { case Location::Left: animData.offset = qMax(windowGeo.left() - screenRect.left(), animData.offset); break; case Location::Top: animData.offset = qMax(windowGeo.top() - screenRect.top(), animData.offset); break; case Location::Right: animData.offset = qMax(screenRect.right() - windowGeo.right(), animData.offset); break; case Location::Bottom: default: animData.offset = qMax(screenRect.bottom() - windowGeo.bottom(), animData.offset); break; } animData.slideInDuration = (animData.slideInDuration.count() != 0) ? animData.slideInDuration : m_slideInDuration; animData.slideOutDuration = (animData.slideOutDuration.count() != 0) ? animData.slideOutDuration : m_slideOutDuration; // Grab the window, so other windowClosed effects will ignore it w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); } void SlidingPopupsEffect::slotWaylandSlideOnShowChanged(EffectWindow* w) { if (!w) { return; } KWayland::Server::SurfaceInterface *surf = w->surface(); if (!surf) { return; } if (surf->slideOnShowHide()) { AnimationData &animData = m_animationsData[w]; animData.offset = surf->slideOnShowHide()->offset(); switch (surf->slideOnShowHide()->location()) { case KWayland::Server::SlideInterface::Location::Top: animData.location = Location::Top; break; case KWayland::Server::SlideInterface::Location::Left: animData.location = Location::Left; break; case KWayland::Server::SlideInterface::Location::Right: animData.location = Location::Right; break; case KWayland::Server::SlideInterface::Location::Bottom: default: animData.location = Location::Bottom; break; } animData.slideLength = 0; animData.slideInDuration = m_slideInDuration; animData.slideOutDuration = m_slideOutDuration; setupAnimData(w); } } void SlidingPopupsEffect::setupInternalWindowSlide(EffectWindow *w) { if (!w) { return; } auto internal = w->internalWindow(); if (!internal) { return; } const QVariant slideProperty = internal->property("kwin_slide"); if (!slideProperty.isValid()) { return; } Location location; switch (slideProperty.value()) { case KWindowEffects::BottomEdge: location = Location::Bottom; break; case KWindowEffects::TopEdge: location = Location::Top; break; case KWindowEffects::RightEdge: location = Location::Right; break; case KWindowEffects::LeftEdge: location = Location::Left; break; default: return; } AnimationData &animData = m_animationsData[w]; animData.location = location; bool intOk = false; animData.offset = internal->property("kwin_slide_offset").toInt(&intOk); if (!intOk) { animData.offset = -1; } animData.slideLength = 0; animData.slideInDuration = m_slideInDuration; animData.slideOutDuration = m_slideOutDuration; setupAnimData(w); } bool SlidingPopupsEffect::eventFilter(QObject *watched, QEvent *event) { auto internal = qobject_cast(watched); if (internal && event->type() == QEvent::DynamicPropertyChange) { QDynamicPropertyChangeEvent *pe = static_cast(event); if (pe->propertyName() == "kwin_slide" || pe->propertyName() == "kwin_slide_offset") { if (auto w = effects->findWindow(internal)) { setupInternalWindowSlide(w); } } } return false; } void SlidingPopupsEffect::slideIn(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!w->isVisible()) { return; } auto dataIt = m_animationsData.constFind(w); if (dataIt == m_animationsData.constEnd()) { return; } Animation &animation = m_animations[w]; animation.kind = AnimationKind::In; animation.timeLine.setDirection(TimeLine::Forward); animation.timeLine.setDuration((*dataIt).slideInDuration); animation.timeLine.setEasingCurve(QEasingCurve::OutQuad); // If the opposite animation (Out) was active and it had shorter duration, // at this point, the timeline can end up in the "done" state. Thus, we have // to reset it. if (animation.timeLine.done()) { animation.timeLine.reset(); } w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); w->setData(WindowForceBackgroundContrastRole, QVariant(true)); w->setData(WindowForceBlurRole, QVariant(true)); w->addRepaintFull(); } void SlidingPopupsEffect::slideOut(EffectWindow *w) { if (effects->activeFullScreenEffect()) { return; } if (!w->isVisible()) { return; } auto dataIt = m_animationsData.constFind(w); if (dataIt == m_animationsData.constEnd()) { return; } if (w->isDeleted()) { w->refWindow(); } Animation &animation = m_animations[w]; animation.kind = AnimationKind::Out; animation.timeLine.setDirection(TimeLine::Backward); animation.timeLine.setDuration((*dataIt).slideOutDuration); // this is effectively InQuad because the direction is reversed animation.timeLine.setEasingCurve(QEasingCurve::OutQuad); // If the opposite animation (In) was active and it had shorter duration, // at this point, the timeline can end up in the "done" state. Thus, we have // to reset it. if (animation.timeLine.done()) { animation.timeLine.reset(); } w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); w->setData(WindowForceBackgroundContrastRole, QVariant(true)); w->setData(WindowForceBlurRole, QVariant(true)); w->addRepaintFull(); } void SlidingPopupsEffect::stopAnimations() { for (auto it = m_animations.constBegin(); it != m_animations.constEnd(); ++it) { EffectWindow *w = it.key(); if (w->isDeleted()) { w->unrefWindow(); } else { w->setData(WindowForceBackgroundContrastRole, QVariant()); w->setData(WindowForceBlurRole, QVariant()); } } m_animations.clear(); } bool SlidingPopupsEffect::isActive() const { return !m_animations.isEmpty(); } } // namespace diff --git a/effects/slidingpopups/slidingpopups.h b/effects/slidingpopups/slidingpopups.h index d40c850f6..940ee604e 100644 --- a/effects/slidingpopups/slidingpopups.h +++ b/effects/slidingpopups/slidingpopups.h @@ -1,118 +1,118 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Marco Martin notmart@gmail.com -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_SLIDINGPOPUPS_H #define KWIN_SLIDINGPOPUPS_H // Include with base class for effects. #include namespace KWin { class SlidingPopupsEffect : public Effect { Q_OBJECT Q_PROPERTY(int slideInDuration READ slideInDuration) Q_PROPERTY(int slideOutDuration READ slideOutDuration) public: SlidingPopupsEffect(); ~SlidingPopupsEffect() 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 reconfigure(ReconfigureFlags flags) override; bool isActive() const override; int requestedEffectChainPosition() const override { return 40; } static bool supported(); int slideInDuration() const; int slideOutDuration() const; bool eventFilter(QObject *watched, QEvent *event) override; private Q_SLOTS: void slotWindowAdded(EffectWindow *w); void slotWindowDeleted(EffectWindow *w); void slotPropertyNotify(EffectWindow *w, long atom); void slotWaylandSlideOnShowChanged(EffectWindow *w); void slideIn(EffectWindow *w); void slideOut(EffectWindow *w); void stopAnimations(); private: void setupAnimData(EffectWindow *w); void setupInternalWindowSlide(EffectWindow *w); long m_atom; int m_slideLength; std::chrono::milliseconds m_slideInDuration; std::chrono::milliseconds m_slideOutDuration; enum class AnimationKind { In, Out }; struct Animation { AnimationKind kind; TimeLine timeLine; }; QHash m_animations; enum class Location { Left, Top, Right, Bottom }; struct AnimationData { int offset; Location location; std::chrono::milliseconds slideInDuration; std::chrono::milliseconds slideOutDuration; int slideLength; }; QHash m_animationsData; }; inline int SlidingPopupsEffect::slideInDuration() const { return m_slideInDuration.count(); } inline int SlidingPopupsEffect::slideOutDuration() const { return m_slideOutDuration.count(); } } // namespace #endif diff --git a/effects/snaphelper/snaphelper.cpp b/effects/snaphelper/snaphelper.cpp index 05cd2dc31..39b7e76b0 100644 --- a/effects/snaphelper/snaphelper.cpp +++ b/effects/snaphelper/snaphelper.cpp @@ -1,335 +1,335 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Lucas Murray -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "snaphelper.h" #include #ifdef KWIN_HAVE_XRENDER_COMPOSITING #include #include #endif #include namespace KWin { static const int s_lineWidth = 4; static const QColor s_lineColor = QColor(128, 128, 128, 128); static QRegion computeDirtyRegion(const QRect &windowRect) { const QMargins outlineMargins( s_lineWidth / 2, s_lineWidth / 2, s_lineWidth / 2, s_lineWidth / 2 ); QRegion dirtyRegion; for (int i = 0; i < effects->numScreens(); ++i) { const QRect screenRect = effects->clientArea(ScreenArea, i, 0); QRect screenWindowRect = windowRect; screenWindowRect.moveCenter(screenRect.center()); QRect verticalBarRect(0, 0, s_lineWidth, screenRect.height()); verticalBarRect.moveCenter(screenRect.center()); verticalBarRect.adjust(-1, -1, 1, 1); dirtyRegion += verticalBarRect; QRect horizontalBarRect(0, 0, screenRect.width(), s_lineWidth); horizontalBarRect.moveCenter(screenRect.center()); horizontalBarRect.adjust(-1, -1, 1, 1); dirtyRegion += horizontalBarRect; const QRect outlineOuterRect = screenWindowRect .marginsAdded(outlineMargins) .adjusted(-1, -1, 1, 1); const QRect outlineInnerRect = screenWindowRect .marginsRemoved(outlineMargins) .adjusted(1, 1, -1, -1); dirtyRegion += QRegion(outlineOuterRect) - QRegion(outlineInnerRect); } return dirtyRegion; } SnapHelperEffect::SnapHelperEffect() { reconfigure(ReconfigureAll); connect(effects, &EffectsHandler::windowClosed, this, &SnapHelperEffect::slotWindowClosed); connect(effects, &EffectsHandler::windowStartUserMovedResized, this, &SnapHelperEffect::slotWindowStartUserMovedResized); connect(effects, &EffectsHandler::windowFinishUserMovedResized, this, &SnapHelperEffect::slotWindowFinishUserMovedResized); connect(effects, &EffectsHandler::windowGeometryShapeChanged, this, &SnapHelperEffect::slotWindowGeometryShapeChanged); } SnapHelperEffect::~SnapHelperEffect() { } void SnapHelperEffect::reconfigure(ReconfigureFlags flags) { Q_UNUSED(flags) m_animation.timeLine.setDuration( std::chrono::milliseconds(static_cast(animationTime(250)))); } void SnapHelperEffect::prePaintScreen(ScreenPrePaintData &data, int time) { if (m_animation.active) { m_animation.timeLine.update(std::chrono::milliseconds(time)); } effects->prePaintScreen(data, time); } void SnapHelperEffect::paintScreen(int mask, const QRegion ®ion, ScreenPaintData &data) { effects->paintScreen(mask, region, data); const qreal opacityFactor = m_animation.active ? m_animation.timeLine.value() : 1.0; // Display the guide if (effects->isOpenGLCompositing()) { GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setUseColor(true); ShaderBinder binder(ShaderTrait::UniformColor); binder.shader()->setUniform(GLShader::ModelViewProjectionMatrix, data.projectionMatrix()); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); QColor color = s_lineColor; color.setAlphaF(color.alphaF() * opacityFactor); vbo->setColor(color); glLineWidth(s_lineWidth); QVector verts; verts.reserve(effects->numScreens() * 24); for (int i = 0; i < effects->numScreens(); ++i) { const QRect rect = effects->clientArea(ScreenArea, i, 0); const int midX = rect.x() + rect.width() / 2; const int midY = rect.y() + rect.height() / 2 ; const int halfWidth = m_geometry.width() / 2; const int halfHeight = m_geometry.height() / 2; // Center vertical line. verts << rect.x() + rect.width() / 2 << rect.y(); verts << rect.x() + rect.width() / 2 << rect.y() + rect.height(); // Center horizontal line. verts << rect.x() << rect.y() + rect.height() / 2; verts << rect.x() + rect.width() << rect.y() + rect.height() / 2; // Top edge of the window outline. verts << midX - halfWidth - s_lineWidth / 2 << midY - halfHeight; verts << midX + halfWidth + s_lineWidth / 2 << midY - halfHeight; // Right edge of the window outline. verts << midX + halfWidth << midY - halfHeight + s_lineWidth / 2; verts << midX + halfWidth << midY + halfHeight - s_lineWidth / 2; // Bottom edge of the window outline. verts << midX + halfWidth + s_lineWidth / 2 << midY + halfHeight; verts << midX - halfWidth - s_lineWidth / 2 << midY + halfHeight; // Left edge of the window outline. verts << midX - halfWidth << midY + halfHeight - s_lineWidth / 2; verts << midX - halfWidth << midY - halfHeight + s_lineWidth / 2; } vbo->setData(verts.count() / 2, 2, verts.data(), nullptr); vbo->render(GL_LINES); glDisable(GL_BLEND); glLineWidth(1.0); } if (effects->compositingType() == XRenderCompositing) { #ifdef KWIN_HAVE_XRENDER_COMPOSITING for (int i = 0; i < effects->numScreens(); ++i) { const QRect rect = effects->clientArea(ScreenArea, i, 0); const int midX = rect.x() + rect.width() / 2; const int midY = rect.y() + rect.height() / 2 ; const int halfWidth = m_geometry.width() / 2; const int halfHeight = m_geometry.height() / 2; xcb_rectangle_t rects[6]; // Center vertical line. rects[0].x = rect.x() + rect.width() / 2 - s_lineWidth / 2; rects[0].y = rect.y(); rects[0].width = s_lineWidth; rects[0].height = rect.height(); // Center horizontal line. rects[1].x = rect.x(); rects[1].y = rect.y() + rect.height() / 2 - s_lineWidth / 2; rects[1].width = rect.width(); rects[1].height = s_lineWidth; // Top edge of the window outline. rects[2].x = midX - halfWidth - s_lineWidth / 2; rects[2].y = midY - halfHeight - s_lineWidth / 2; rects[2].width = 2 * halfWidth + s_lineWidth; rects[2].height = s_lineWidth; // Right edge of the window outline. rects[3].x = midX + halfWidth - s_lineWidth / 2; rects[3].y = midY - halfHeight + s_lineWidth / 2; rects[3].width = s_lineWidth; rects[3].height = 2 * halfHeight - s_lineWidth; // Bottom edge of the window outline. rects[4].x = midX - halfWidth - s_lineWidth / 2; rects[4].y = midY + halfHeight - s_lineWidth / 2; rects[4].width = 2 * halfWidth + s_lineWidth; rects[4].height = s_lineWidth; // Left edge of the window outline. rects[5].x = midX - halfWidth - s_lineWidth / 2; rects[5].y = midY - halfHeight + s_lineWidth / 2; rects[5].width = s_lineWidth; rects[5].height = 2 * halfHeight - s_lineWidth; QColor color = s_lineColor; color.setAlphaF(color.alphaF() * opacityFactor); xcb_render_fill_rectangles(xcbConnection(), XCB_RENDER_PICT_OP_OVER, effects->xrenderBufferPicture(), preMultiply(color), 6, rects); } #endif } if (effects->compositingType() == QPainterCompositing) { QPainter *painter = effects->scenePainter(); painter->save(); QColor color = s_lineColor; color.setAlphaF(color.alphaF() * opacityFactor); QPen pen(color); pen.setWidth(s_lineWidth); painter->setPen(pen); painter->setBrush(Qt::NoBrush); for (int i = 0; i < effects->numScreens(); ++i) { const QRect rect = effects->clientArea(ScreenArea, i, 0); // Center lines. painter->drawLine(rect.center().x(), rect.y(), rect.center().x(), rect.y() + rect.height()); painter->drawLine(rect.x(), rect.center().y(), rect.x() + rect.width(), rect.center().y()); // Window outline. QRect outlineRect(0, 0, m_geometry.width(), m_geometry.height()); outlineRect.moveCenter(rect.center()); painter->drawRect(outlineRect); } painter->restore(); } } void SnapHelperEffect::postPaintScreen() { if (m_animation.active) { effects->addRepaint(computeDirtyRegion(m_geometry)); } if (m_animation.timeLine.done()) { m_animation.active = false; } effects->postPaintScreen(); } void SnapHelperEffect::slotWindowClosed(EffectWindow *w) { if (w != m_window) { return; } m_window = nullptr; m_animation.active = true; m_animation.timeLine.setDirection(TimeLine::Backward); if (m_animation.timeLine.done()) { m_animation.timeLine.reset(); } effects->addRepaint(computeDirtyRegion(m_geometry)); } void SnapHelperEffect::slotWindowStartUserMovedResized(EffectWindow *w) { if (!w->isMovable()) { return; } m_window = w; m_geometry = w->geometry(); m_animation.active = true; m_animation.timeLine.setDirection(TimeLine::Forward); if (m_animation.timeLine.done()) { m_animation.timeLine.reset(); } effects->addRepaint(computeDirtyRegion(m_geometry)); } void SnapHelperEffect::slotWindowFinishUserMovedResized(EffectWindow *w) { if (w != m_window) { return; } m_window = nullptr; m_geometry = w->geometry(); m_animation.active = true; m_animation.timeLine.setDirection(TimeLine::Backward); if (m_animation.timeLine.done()) { m_animation.timeLine.reset(); } effects->addRepaint(computeDirtyRegion(m_geometry)); } void SnapHelperEffect::slotWindowGeometryShapeChanged(EffectWindow *w, const QRect &old) { if (w != m_window) { return; } m_geometry = w->geometry(); effects->addRepaint(computeDirtyRegion(old)); } bool SnapHelperEffect::isActive() const { return m_window != nullptr || m_animation.active; } } // namespace KWin diff --git a/effects/snaphelper/snaphelper.h b/effects/snaphelper/snaphelper.h index 011480730..c67af96ce 100644 --- a/effects/snaphelper/snaphelper.h +++ b/effects/snaphelper/snaphelper.h @@ -1,66 +1,66 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Lucas Murray -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_SNAPHELPER_H #define KWIN_SNAPHELPER_H #include namespace KWin { class SnapHelperEffect : public Effect { Q_OBJECT public: SnapHelperEffect(); ~SnapHelperEffect() override; void reconfigure(ReconfigureFlags flags) override; void prePaintScreen(ScreenPrePaintData &data, int time) override; void paintScreen(int mask, const QRegion ®ion, ScreenPaintData &data) override; void postPaintScreen() override; bool isActive() const override; private Q_SLOTS: void slotWindowClosed(EffectWindow *w); void slotWindowStartUserMovedResized(EffectWindow *w); void slotWindowFinishUserMovedResized(EffectWindow *w); void slotWindowGeometryShapeChanged(EffectWindow *w, const QRect &old); private: QRect m_geometry; EffectWindow *m_window = nullptr; struct Animation { bool active = false; TimeLine timeLine; }; Animation m_animation; }; } // namespace KWin #endif diff --git a/effects/squash/package/contents/code/main.js b/effects/squash/package/contents/code/main.js index 393a6fe21..d48a4fa03 100644 --- a/effects/squash/package/contents/code/main.js +++ b/effects/squash/package/contents/code/main.js @@ -1,166 +1,166 @@ /******************************************************************** This file is part of the KDE project. - Copyright (C) 2018 Vlad Zahorodnii + Copyright (C) 2018 Vlad Zahorodnii 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 . *********************************************************************/ "use strict"; var squashEffect = { duration: animationTime(250), loadConfig: function () { squashEffect.duration = animationTime(250); }, slotWindowMinimized: function (window) { if (effects.hasActiveFullScreenEffect) { return; } // If the window doesn't have an icon in the task manager, // don't animate it. var iconRect = window.iconGeometry; if (iconRect.width == 0 || iconRect.height == 0) { return; } if (window.unminimizeAnimation) { if (redirect(window.unminimizeAnimation, Effect.Backward)) { return; } cancel(window.unminimizeAnimation); delete window.unminimizeAnimation; } if (window.minimizeAnimation) { if (redirect(window.minimizeAnimation, Effect.Forward)) { return; } cancel(window.minimizeAnimation); } var windowRect = window.geometry; window.minimizeAnimation = animate({ window: window, curve: QEasingCurve.InOutSine, duration: squashEffect.duration, animations: [ { type: Effect.Size, from: { value1: windowRect.width, value2: windowRect.height }, to: { value1: iconRect.width, value2: iconRect.height } }, { type: Effect.Translation, from: { value1: 0.0, value2: 0.0 }, to: { value1: iconRect.x - windowRect.x - (windowRect.width - iconRect.width) / 2, value2: iconRect.y - windowRect.y - (windowRect.height - iconRect.height) / 2, } }, { type: Effect.Opacity, from: 1.0, to: 0.0 } ] }); }, slotWindowUnminimized: function (window) { if (effects.hasActiveFullScreenEffect) { return; } // If the window doesn't have an icon in the task manager, // don't animate it. var iconRect = window.iconGeometry; if (iconRect.width == 0 || iconRect.height == 0) { return; } if (window.minimizeAnimation) { if (redirect(window.minimizeAnimation, Effect.Backward)) { return; } cancel(window.minimizeAnimation); delete window.minimizeAnimation; } if (window.unminimizeAnimation) { if (redirect(window.unminimizeAnimation, Effect.Forward)) { return; } cancel(window.unminimizeAnimation); } var windowRect = window.geometry; window.unminimizeAnimation = animate({ window: window, curve: QEasingCurve.InOutSine, duration: squashEffect.duration, animations: [ { type: Effect.Size, from: { value1: iconRect.width, value2: iconRect.height }, to: { value1: windowRect.width, value2: windowRect.height } }, { type: Effect.Translation, from: { value1: iconRect.x - windowRect.x - (windowRect.width - iconRect.width) / 2, value2: iconRect.y - windowRect.y - (windowRect.height - iconRect.height) / 2, }, to: { value1: 0.0, value2: 0.0 } }, { type: Effect.Opacity, from: 0.0, to: 1.0 } ] }); }, init: function () { effect.configChanged.connect(squashEffect.loadConfig); effects.windowMinimized.connect(squashEffect.slotWindowMinimized); effects.windowUnminimized.connect(squashEffect.slotWindowUnminimized); } }; squashEffect.init(); diff --git a/effects/squash/package/metadata.desktop b/effects/squash/package/metadata.desktop index 18d4bcdf1..1206087c9 100644 --- a/effects/squash/package/metadata.desktop +++ b/effects/squash/package/metadata.desktop @@ -1,76 +1,76 @@ [Desktop Entry] Comment=Squash windows when they are minimized Comment[ca]=Amuntega les finestres quan estan minimitzades Comment[ca@valencia]=Amuntega les finestres quan estan minimitzades Comment[da]=Mas vinduer når de minimeres Comment[de]=Quetscht Fenster beim Minimieren zusammen Comment[en_GB]=Squash windows when they are minimised Comment[es]=Aplastar las ventanas al minimizarlas Comment[et]=Minimeeritud akende taas üleshüpitamine Comment[eu]=Zanpatu leihoak haiek ikonotzean Comment[fi]=Litistä ikkunat, kun ne pienennetään Comment[fr]=Écrase les fenêtres lorsqu'elles sont minimisées Comment[gl]=Xuntar as xanelas cando estean minimizadas Comment[ia]=Deforma fenestras durante que illes es minimisate Comment[id]=Sesakkan window ketika mereka diminimalkan Comment[it]=Schiaccia le finestre quando vengono minimizzate Comment[ko]=창을 최소화할 때 압축시킵니다 Comment[lt]=Sutraiškyti langus, juos suskleidžiant Comment[nl]=Krimp vensters wanneer ze geminimaliseerd zijn Comment[nn]=Skvis vindauge når dei vert minimerte Comment[pl]=Ściąga okna przy ich minimalizacji Comment[pt]=Esmagar as janelas quando são minimizadas Comment[pt_BR]=Achatar as janelas quando são minimizadas Comment[ru]=Сжатие окна при сворачивании Comment[sk]=Deformuje okná pri ich minimalizovaní Comment[sv]=Kläm fönster när de minimeras Comment[uk]=Складує вікна, якщо їх мінімізовано Comment[x-test]=xxSquash windows when they are minimizedxx Comment[zh_CN]=最小化时压扁窗口 Comment[zh_TW]=壓縮最小化的視窗 Icon=preferences-system-windows-effect-squash Name=Squash Name[ca]=Amuntega Name[ca@valencia]=Amuntega Name[da]=Mas Name[de]=Quetschen Name[en_GB]=Squash Name[es]=Aplastar Name[et]=Üleshüpe Name[eu]=Zanpatu Name[fi]=Litistä Name[fr]=Écraser Name[gl]=Xuntar Name[id]=Sesakkan Name[it]=Schiaccia Name[ko]=압축 Name[lt]=Sutraiškymas Name[nl]=Krimpen Name[nn]=Skvis Name[pl]=Ściąganie Name[pt]=Esmagar Name[pt_BR]=Achatar Name[ru]=Сжатие Name[sk]=Rozpučiť Name[sv]=Kläm Name[uk]=Складування Name[x-test]=xxSquashxx Name[zh_CN]=压扁 Name[zh_TW]=壓縮 Type=Service X-KDE-ParentApp= X-KDE-PluginInfo-Author=Rivo Laks, Vlad Zahorodnii X-KDE-PluginInfo-Category=Appearance -X-KDE-PluginInfo-Email=rivolaks@hot.ee, vladzzag@gmail.com +X-KDE-PluginInfo-Email=rivolaks@hot.ee, vlad.zahorodnii@kde.org X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-Name=kwin4_effect_squash X-KDE-PluginInfo-Version=1 X-KDE-PluginInfo-Website= X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-EnabledByDefault=true X-KDE-Ordering=60 X-Plasma-API=javascript X-Plasma-MainScript=code/main.js X-KWin-Exclusive-Category=minimize X-KWin-Video-Url=https://files.kde.org/plasma/kwin/effect-videos/minimize.ogv diff --git a/effects/trackmouse/trackmouse.cpp b/effects/trackmouse/trackmouse.cpp index 71df0a65f..d38f0a403 100644 --- a/effects/trackmouse/trackmouse.cpp +++ b/effects/trackmouse/trackmouse.cpp @@ -1,312 +1,312 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2010 Jorge Mata -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "trackmouse.h" // KConfigSkeleton #include "trackmouseconfig.h" #include #include #include #include #include #include #include #include #include #include namespace KWin { TrackMouseEffect::TrackMouseEffect() : m_angle(0) { initConfig(); m_texture[0] = m_texture[1] = nullptr; #ifdef KWIN_HAVE_XRENDER_COMPOSITING m_picture[0] = m_picture[1] = nullptr; if ( effects->compositingType() == XRenderCompositing) m_angleBase = 1.57079632679489661923; // Pi/2 #endif if ( effects->isOpenGLCompositing() || effects->compositingType() == QPainterCompositing) m_angleBase = 90.0; m_mousePolling = false; m_action = new QAction(this); m_action->setObjectName(QStringLiteral("TrackMouse")); m_action->setText(i18n("Track mouse")); KGlobalAccel::self()->setDefaultShortcut(m_action, QList()); KGlobalAccel::self()->setShortcut(m_action, QList()); effects->registerGlobalShortcut(QKeySequence(), m_action); connect(m_action, &QAction::triggered, this, &TrackMouseEffect::toggle); connect(effects, &EffectsHandler::mouseChanged, this, &TrackMouseEffect::slotMouseChanged); reconfigure(ReconfigureAll); } TrackMouseEffect::~TrackMouseEffect() { if (m_mousePolling) effects->stopMousePolling(); for (int i = 0; i < 2; ++i) { delete m_texture[i]; m_texture[i] = nullptr; #ifdef KWIN_HAVE_XRENDER_COMPOSITING delete m_picture[i]; m_picture[i] = nullptr; #endif } } void TrackMouseEffect::reconfigure(ReconfigureFlags) { m_modifiers = Qt::KeyboardModifiers(); TrackMouseConfig::self()->read(); if (TrackMouseConfig::shift()) m_modifiers |= Qt::ShiftModifier; if (TrackMouseConfig::alt()) m_modifiers |= Qt::AltModifier; if (TrackMouseConfig::control()) m_modifiers |= Qt::ControlModifier; if (TrackMouseConfig::meta()) m_modifiers |= Qt::MetaModifier; if (m_modifiers) { if (!m_mousePolling) effects->startMousePolling(); m_mousePolling = true; } else if (m_mousePolling) { effects->stopMousePolling(); m_mousePolling = false; } } void TrackMouseEffect::prePaintScreen(ScreenPrePaintData& data, int time) { QTime t = QTime::currentTime(); m_angle = ((t.second() % 4) * m_angleBase) + (t.msec() / 1000.0 * m_angleBase); m_lastRect[0].moveCenter(cursorPos()); m_lastRect[1].moveCenter(cursorPos()); data.paint |= m_lastRect[0].adjusted(-1,-1,1,1); effects->prePaintScreen(data, time); } void TrackMouseEffect::paintScreen(int mask, const QRegion ®ion, ScreenPaintData& data) { effects->paintScreen(mask, region, data); // paint normal screen if ( effects->isOpenGLCompositing() && m_texture[0] && m_texture[1]) { ShaderBinder binder(ShaderTrait::MapTexture); GLShader *shader(binder.shader()); if (!shader) { return; } glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); QMatrix4x4 matrix(data.projectionMatrix()); const QPointF p = m_lastRect[0].topLeft() + QPoint(m_lastRect[0].width()/2.0, m_lastRect[0].height()/2.0); const float x = p.x()*data.xScale() + data.xTranslation(); const float y = p.y()*data.yScale() + data.yTranslation(); for (int i = 0; i < 2; ++i) { matrix.translate(x, y, 0.0); matrix.rotate(i ? -2*m_angle : m_angle, 0, 0, 1.0); matrix.translate(-x, -y, 0.0); QMatrix4x4 mvp(matrix); mvp.translate(m_lastRect[i].x(), m_lastRect[i].y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_texture[i]->bind(); m_texture[i]->render(region, m_lastRect[i]); m_texture[i]->unbind(); } glDisable(GL_BLEND); } #ifdef KWIN_HAVE_XRENDER_COMPOSITING if ( effects->compositingType() == XRenderCompositing && m_picture[0] && m_picture[1]) { float sine = sin(m_angle); const float cosine = cos(m_angle); for (int i = 0; i < 2; ++i) { if (i) sine = -sine; const float dx = m_size[i].width()/2.0; const float dy = m_size[i].height()/2.0; const xcb_render_picture_t picture = *m_picture[i]; #define DOUBLE_TO_FIXED(d) ((xcb_render_fixed_t) ((d) * 65536)) xcb_render_transform_t xform = { DOUBLE_TO_FIXED( cosine ), DOUBLE_TO_FIXED( -sine ), DOUBLE_TO_FIXED( dx - cosine*dx + sine*dy ), DOUBLE_TO_FIXED( sine ), DOUBLE_TO_FIXED( cosine ), DOUBLE_TO_FIXED( dy - sine*dx - cosine*dy ), DOUBLE_TO_FIXED( 0.0 ), DOUBLE_TO_FIXED( 0.0 ), DOUBLE_TO_FIXED( 1.0 ) }; #undef DOUBLE_TO_FIXED xcb_render_set_picture_transform(xcbConnection(), picture, xform); xcb_render_set_picture_filter(xcbConnection(), picture, 8, "bilinear", 0, nullptr); const QRect &rect = m_lastRect[i]; xcb_render_composite(xcbConnection(), XCB_RENDER_PICT_OP_OVER, picture, XCB_RENDER_PICTURE_NONE, effects->xrenderBufferPicture(), 0, 0, 0, 0, qRound((rect.x()+rect.width()/2.0)*data.xScale() - rect.width()/2.0 + data.xTranslation()), qRound((rect.y()+rect.height()/2.0)*data.yScale() - rect.height()/2.0 + data.yTranslation()), rect.width(), rect.height()); } } #endif if (effects->compositingType() == QPainterCompositing && !m_image[0].isNull() && !m_image[1].isNull()) { QPainter *painter = effects->scenePainter(); const QPointF p = m_lastRect[0].topLeft() + QPoint(m_lastRect[0].width()/2.0, m_lastRect[0].height()/2.0); for (int i = 0; i < 2; ++i) { painter->save(); painter->translate(p.x(), p.y()); painter->rotate(i ? -2*m_angle : m_angle); painter->translate(-p.x(), -p.y()); painter->drawImage(m_lastRect[i], m_image[i]); painter->restore(); } } } void TrackMouseEffect::postPaintScreen() { effects->addRepaint(m_lastRect[0].adjusted(-1,-1,1,1)); effects->postPaintScreen(); } bool TrackMouseEffect::init() { effects->makeOpenGLContextCurrent(); #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (!(m_texture[0] || m_picture[0] || !m_image[0].isNull())) { loadTexture(); if (!(m_texture[0] || m_picture[0] || !m_image[0].isNull())) return false; } #else if (!m_texture[0] || m_image[0].isNull()) { loadTexture(); if (!m_texture[0] || m_image[0].isNull()) return false; } #endif m_lastRect[0].moveCenter(cursorPos()); m_lastRect[1].moveCenter(cursorPos()); m_angle = 0; return true; } void TrackMouseEffect::toggle() { switch (m_state) { case State::ActivatedByModifiers: m_state = State::ActivatedByShortcut; break; case State::ActivatedByShortcut: m_state = State::Inactive; break; case State::Inactive: if (!init()) { return; } m_state = State::ActivatedByShortcut; break; default: Q_UNREACHABLE(); break; } effects->addRepaint(m_lastRect[0].adjusted(-1, -1, 1, 1)); } void TrackMouseEffect::slotMouseChanged(const QPoint&, const QPoint&, Qt::MouseButtons, Qt::MouseButtons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers) { if (!m_mousePolling) { // we didn't ask for it but maybe someone else did... return; } switch (m_state) { case State::ActivatedByModifiers: if (modifiers == m_modifiers) { return; } m_state = State::Inactive; break; case State::ActivatedByShortcut: return; case State::Inactive: if (modifiers != m_modifiers) { return; } if (!init()) { return; } m_state = State::ActivatedByModifiers; break; default: Q_UNREACHABLE(); break; } effects->addRepaint(m_lastRect[0].adjusted(-1, -1, 1, 1)); } void TrackMouseEffect::loadTexture() { QString f[2] = {QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("tm_outer.png")), QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("tm_inner.png"))}; if (f[0].isEmpty() || f[1].isEmpty()) return; for (int i = 0; i < 2; ++i) { if ( effects->isOpenGLCompositing()) { QImage img(f[i]); m_texture[i] = new GLTexture(img); m_lastRect[i].setSize(img.size()); } #ifdef KWIN_HAVE_XRENDER_COMPOSITING if ( effects->compositingType() == XRenderCompositing) { QImage pixmap(f[i]); m_picture[i] = new XRenderPicture(pixmap); m_size[i] = pixmap.size(); m_lastRect[i].setSize(pixmap.size()); } #endif if (effects->compositingType() == QPainterCompositing) { m_image[i] = QImage(f[i]); m_lastRect[i].setSize(m_image[i].size()); } } } bool TrackMouseEffect::isActive() const { return m_state != State::Inactive; } } // namespace diff --git a/effects/trackmouse/trackmouse.h b/effects/trackmouse/trackmouse.h index 6bad2ebb0..49e0b916a 100644 --- a/effects/trackmouse/trackmouse.h +++ b/effects/trackmouse/trackmouse.h @@ -1,87 +1,87 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2010 Jorge Mata -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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_TRACKMOUSE_H #define KWIN_TRACKMOUSE_H #include class QAction; namespace KWin { class GLTexture; class TrackMouseEffect : public Effect { Q_OBJECT Q_PROPERTY(Qt::KeyboardModifiers modifiers READ modifiers) Q_PROPERTY(bool mousePolling READ isMousePolling) public: TrackMouseEffect(); ~TrackMouseEffect() override; void prePaintScreen(ScreenPrePaintData& data, int time) override; void paintScreen(int mask, const QRegion ®ion, ScreenPaintData& data) override; void postPaintScreen() override; void reconfigure(ReconfigureFlags) override; bool isActive() const override; // for properties Qt::KeyboardModifiers modifiers() const { return m_modifiers; } bool isMousePolling() const { return m_mousePolling; } private Q_SLOTS: void toggle(); void slotMouseChanged(const QPoint& pos, const QPoint& old, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); private: bool init(); void loadTexture(); QRect m_lastRect[2]; bool m_mousePolling; float m_angle; float m_angleBase; GLTexture* m_texture[2]; #ifdef KWIN_HAVE_XRENDER_COMPOSITING QSize m_size[2]; XRenderPicture *m_picture[2]; #endif QAction* m_action; QImage m_image[2]; Qt::KeyboardModifiers m_modifiers; enum class State { ActivatedByModifiers, ActivatedByShortcut, Inactive }; State m_state = State::Inactive; }; } // namespace #endif diff --git a/idle_inhibition.cpp b/idle_inhibition.cpp index ddb843997..fc662af64 100644 --- a/idle_inhibition.cpp +++ b/idle_inhibition.cpp @@ -1,121 +1,121 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 Martin Flöser -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "idle_inhibition.h" #include "deleted.h" #include "xdgshellclient.h" #include "workspace.h" #include #include #include #include using KWayland::Server::SurfaceInterface; namespace KWin { IdleInhibition::IdleInhibition(IdleInterface *idle) : QObject(idle) , m_idle(idle) { // Workspace is created after the wayland server is initialized. connect(kwinApp(), &Application::workspaceCreated, this, &IdleInhibition::slotWorkspaceCreated); } IdleInhibition::~IdleInhibition() = default; void IdleInhibition::registerXdgShellClient(XdgShellClient *client) { auto updateInhibit = [this, client] { update(client); }; m_connections[client] = connect(client->surface(), &SurfaceInterface::inhibitsIdleChanged, this, updateInhibit); connect(client, &XdgShellClient::desktopChanged, this, updateInhibit); connect(client, &XdgShellClient::clientMinimized, this, updateInhibit); connect(client, &XdgShellClient::clientUnminimized, this, updateInhibit); connect(client, &XdgShellClient::windowHidden, this, updateInhibit); connect(client, &XdgShellClient::windowShown, this, updateInhibit); connect(client, &XdgShellClient::windowClosed, this, [this, client] { uninhibit(client); auto it = m_connections.find(client); if (it != m_connections.end()) { disconnect(it.value()); m_connections.erase(it); } } ); updateInhibit(); } void IdleInhibition::inhibit(AbstractClient *client) { if (isInhibited(client)) { // already inhibited return; } m_idleInhibitors << client; m_idle->inhibit(); // TODO: notify powerdevil? } void IdleInhibition::uninhibit(AbstractClient *client) { auto it = std::find(m_idleInhibitors.begin(), m_idleInhibitors.end(), client); if (it == m_idleInhibitors.end()) { // not inhibited return; } m_idleInhibitors.erase(it); m_idle->uninhibit(); } void IdleInhibition::update(AbstractClient *client) { if (client->isInternal()) { return; } // TODO: Don't honor the idle inhibitor object if the shell client is not // on the current activity (currently, activities are not supported). const bool visible = client->isShown(true) && client->isOnCurrentDesktop(); if (visible && client->surface()->inhibitsIdle()) { inhibit(client); } else { uninhibit(client); } } void IdleInhibition::slotWorkspaceCreated() { connect(workspace(), &Workspace::currentDesktopChanged, this, &IdleInhibition::slotDesktopChanged); } void IdleInhibition::slotDesktopChanged() { workspace()->forEachAbstractClient([this] (AbstractClient *c) { update(c); }); } } diff --git a/idle_inhibition.h b/idle_inhibition.h index 1f29281b7..8a1efc824 100644 --- a/idle_inhibition.h +++ b/idle_inhibition.h @@ -1,71 +1,71 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2017 Martin Flöser -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 namespace KWayland { namespace Server { class IdleInterface; } } using KWayland::Server::IdleInterface; namespace KWin { class AbstractClient; class XdgShellClient; class IdleInhibition : public QObject { Q_OBJECT public: explicit IdleInhibition(IdleInterface *idle); ~IdleInhibition() override; void registerXdgShellClient(XdgShellClient *client); bool isInhibited() const { return !m_idleInhibitors.isEmpty(); } bool isInhibited(AbstractClient *client) const { return m_idleInhibitors.contains(client); } private Q_SLOTS: void slotWorkspaceCreated(); void slotDesktopChanged(); private: void inhibit(AbstractClient *client); void uninhibit(AbstractClient *client); void update(AbstractClient *client); IdleInterface *m_idle; QVector m_idleInhibitors; QMap m_connections; }; } diff --git a/input.cpp b/input.cpp index 107db696b..c552cb28e 100644 --- a/input.cpp +++ b/input.cpp @@ -1,2537 +1,2537 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "effects.h" #include "gestures.h" #include "globalshortcuts.h" #include "input_event.h" #include "input_event_spy.h" #include "keyboard_input.h" #include "logind.h" #include "main.h" #include "pointer_input.h" #include "tablet_input.h" #include "touch_hide_cursor_spy.h" #include "touch_input.h" #include "x11client.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 "xdgshellclient.h" #include "wayland_server.h" #include "xwl/xwayland_interface.h" #include "internal_client.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(qint32 id, const QPointF &point, quint32 time) { Q_UNUSED(id) Q_UNUSED(point) Q_UNUSED(time) return false; } bool InputEventFilter::touchMotion(qint32 id, const QPointF &point, quint32 time) { Q_UNUSED(id) Q_UNUSED(point) Q_UNUSED(time) return false; } bool InputEventFilter::touchUp(qint32 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; } bool InputEventFilter::tabletToolEvent(QTabletEvent *event) { Q_UNUSED(event) return false; } bool InputEventFilter::tabletToolButtonEvent(const QSet &pressedButtons) { Q_UNUSED(pressedButtons) return false; } bool InputEventFilter::tabletPadButtonEvent(const QSet &pressedButtons) { Q_UNUSED(pressedButtons) return false; } bool InputEventFilter::tabletPadStripEvent(int number, int position, bool isFinger) { Q_UNUSED(number) Q_UNUSED(position) Q_UNUSED(isFinger) return false; } bool InputEventFilter::tabletPadRingEvent(int number, int position, bool isFinger) { Q_UNUSED(number) Q_UNUSED(position) Q_UNUSED(isFinger) 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(qint32 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(qint32 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(qint32 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 wheelEvent(QWheelEvent *event) override { 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(qint32 id, const QPointF &pos, quint32 time) override { if (!effects) { return false; } return static_cast< EffectsHandlerImpl* >(effects)->touchDown(id, pos, time); } bool touchMotion(qint32 id, const QPointF &pos, quint32 time) override { if (!effects) { return false; } return static_cast< EffectsHandlerImpl* >(effects)->touchMotion(id, pos, time); } bool touchUp(qint32 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(qint32 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(qint32 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(qint32 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: qint32 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(qint32 id, const QPointF &pos, quint32 time) override { Q_UNUSED(time) if (!isActive()) { return false; } m_touchPoints.insert(id, pos); return true; } bool touchMotion(qint32 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(qint32 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 = qobject_cast(workspace()->findInternal(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 = qobject_cast(workspace()->findInternal(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 QList &internalClients = workspace()->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(qint32 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(qint32 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(qint32 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(qint32 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(qint32 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(qint32 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(qint32 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(qint32 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(qint32 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; qint32 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(qint32 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(qint32 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(qint32 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(qint32 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; } }; /** * Useful when there's no proper tablet support on the clients */ class FakeTabletInputFilter : public InputEventFilter { public: FakeTabletInputFilter() { } bool tabletToolEvent(QTabletEvent *event) override { if (!workspace()) { return false; } switch (event->type()) { case QEvent::TabletMove: case QEvent::TabletEnterProximity: input()->pointer()->processMotion(event->globalPosF(), event->timestamp()); break; case QEvent::TabletPress: input()->pointer()->processButton(KWin::qtMouseButtonToButton(Qt::LeftButton), InputRedirection::PointerButtonPressed, event->timestamp()); break; case QEvent::TabletRelease: input()->pointer()->processButton(KWin::qtMouseButtonToButton(Qt::LeftButton), InputRedirection::PointerButtonReleased, event->timestamp()); break; case QEvent::TabletLeaveProximity: break; default: qCWarning(KWIN_CORE) << "Unexpected tablet event type" << event; break; } waylandServer()->simulateUserActivity(); 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(qint32 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(qint32 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(qint32 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_tablet(new TabletInputRedirection(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 = nullptr; 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] (qint32 id, const QPointF &pos) { // TODO: Fix time m_touch->processDown(id, pos, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchMotionRequested, this, [this] (qint32 id, const QPointF &pos) { // TODO: Fix time m_touch->processMotion(id, pos, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::touchUpRequested, this, [this] (qint32 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(device, &FakeInputDevice::keyboardKeyPressRequested, this, [this] (quint32 button) { // TODO: Fix time m_keyboard->processKey(button, InputRedirection::KeyboardKeyPressed, 0); waylandServer()->simulateUserActivity(); } ); connect(device, &FakeInputDevice::keyboardKeyReleaseRequested, this, [this] (quint32 button) { // TODO: Fix time m_keyboard->processKey(button, InputRedirection::KeyboardKeyReleased, 0); waylandServer()->simulateUserActivity(); } ); } ); connect(workspace(), &Workspace::configChanged, this, &InputRedirection::reconfigure); m_keyboard->init(); m_pointer->init(); m_touch->init(); m_tablet->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); installInputEventFilter(new FakeTabletInputFilter); } } 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)); connect(conn, &LibInput::Connection::tabletToolEvent, m_tablet, &TabletInputRedirection::tabletToolEvent); connect(conn, &LibInput::Connection::tabletToolButtonEvent, m_tablet, &TabletInputRedirection::tabletToolButtonEvent); connect(conn, &LibInput::Connection::tabletPadButtonEvent, m_tablet, &TabletInputRedirection::tabletPadButtonEvent); connect(conn, &LibInput::Connection::tabletPadRingEvent, m_tablet, &TabletInputRedirection::tabletPadRingEvent); connect(conn, &LibInput::Connection::tabletPadStripEvent, m_tablet, &TabletInputRedirection::tabletPadStripEvent); 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 QList &unmanaged = Workspace::self()->unmanagedList(); foreach (Unmanaged *u, unmanaged) { if (u->inputGeometry().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 QList &stacking = Workspace::self()->stackingOrder(); if (stacking.isEmpty()) { return nullptr; } 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->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 nullptr; } 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 = workspace()->findInternal(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 QList &internalClients = workspace()->internalClients(); if (internalClients.isEmpty()) { return nullptr; } auto it = internalClients.end(); do { --it; QWindow *w = (*it)->internalWindow(); if (!w || !w->isVisible()) { continue; } if (!(*it)->frameGeometry().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 a7c6b2fec..3e983d476 100644 --- a/input.h +++ b/input.h @@ -1,514 +1,514 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 #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 TabletInputRedirection; class TouchInputRedirection; class WindowSelectorFilter; class SwitchEvent; namespace Decoration { class DecoratedClientImpl; } namespace LibInput { class Connection; class Device; } /** * @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 }; enum TabletEventType { Axis, Proximity, Tip }; ~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; } TabletInputRedirection *tablet() const { return m_tablet; } 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; TabletInputRedirection *m_tablet; 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(qint32 id, const QPointF &pos, quint32 time); virtual bool touchMotion(qint32 id, const QPointF &pos, quint32 time); virtual bool touchUp(qint32 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); virtual bool tabletToolEvent(QTabletEvent *event); virtual bool tabletToolButtonEvent(const QSet &buttons); virtual bool tabletPadButtonEvent(const QSet &buttons); virtual bool tabletPadStripEvent(int number, int position, bool isFinger); virtual bool tabletPadRingEvent(int number, int position, bool isFinger); 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/internal_client.cpp b/internal_client.cpp index cf787bc6a..b3dee3b1a 100644 --- a/internal_client.cpp +++ b/internal_client.cpp @@ -1,677 +1,677 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2019 Martin Flöser -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "internal_client.h" #include "decorations/decorationbridge.h" #include "deleted.h" #include "workspace.h" #include #include #include Q_DECLARE_METATYPE(NET::WindowType) static const QByteArray s_skipClosePropertyName = QByteArrayLiteral("KWIN_SKIP_CLOSE_ANIMATION"); namespace KWin { InternalClient::InternalClient(QWindow *window) : m_internalWindow(window) , m_clientSize(window->size()) , m_windowId(window->winId()) , m_internalWindowFlags(window->flags()) { connect(m_internalWindow, &QWindow::xChanged, this, &InternalClient::updateInternalWindowGeometry); connect(m_internalWindow, &QWindow::yChanged, this, &InternalClient::updateInternalWindowGeometry); connect(m_internalWindow, &QWindow::widthChanged, this, &InternalClient::updateInternalWindowGeometry); connect(m_internalWindow, &QWindow::heightChanged, this, &InternalClient::updateInternalWindowGeometry); connect(m_internalWindow, &QWindow::windowTitleChanged, this, &InternalClient::setCaption); connect(m_internalWindow, &QWindow::opacityChanged, this, &InternalClient::setOpacity); connect(m_internalWindow, &QWindow::destroyed, this, &InternalClient::destroyClient); connect(this, &InternalClient::opacityChanged, this, &InternalClient::addRepaintFull); const QVariant windowType = m_internalWindow->property("kwin_windowType"); if (!windowType.isNull()) { m_windowType = windowType.value(); } setCaption(m_internalWindow->title()); setIcon(QIcon::fromTheme(QStringLiteral("kwin"))); setOnAllDesktops(true); setOpacity(m_internalWindow->opacity()); setSkipCloseAnimation(m_internalWindow->property(s_skipClosePropertyName).toBool()); setupCompositing(); updateColorScheme(); blockGeometryUpdates(true); commitGeometry(m_internalWindow->geometry()); updateDecoration(true); setFrameGeometry(clientRectToFrameRect(m_internalWindow->geometry())); setGeometryRestore(frameGeometry()); blockGeometryUpdates(false); m_internalWindow->installEventFilter(this); } InternalClient::~InternalClient() { } bool InternalClient::eventFilter(QObject *watched, QEvent *event) { if (watched == m_internalWindow && event->type() == QEvent::DynamicPropertyChange) { QDynamicPropertyChangeEvent *pe = static_cast(event); if (pe->propertyName() == s_skipClosePropertyName) { setSkipCloseAnimation(m_internalWindow->property(s_skipClosePropertyName).toBool()); } if (pe->propertyName() == "kwin_windowType") { m_windowType = m_internalWindow->property("kwin_windowType").value(); workspace()->updateClientArea(); } } return false; } QRect InternalClient::bufferGeometry() const { return frameGeometry() - frameMargins(); } QStringList InternalClient::activities() const { return QStringList(); } void InternalClient::blockActivityUpdates(bool b) { Q_UNUSED(b) // Internal clients do not support activities. } qreal InternalClient::bufferScale() const { if (m_internalWindow) { return m_internalWindow->devicePixelRatio(); } return 1; } QString InternalClient::captionNormal() const { return m_captionNormal; } QString InternalClient::captionSuffix() const { return m_captionSuffix; } QPoint InternalClient::clientContentPos() const { return -1 * clientPos(); } QSize InternalClient::clientSize() const { return m_clientSize; } void InternalClient::debug(QDebug &stream) const { stream.nospace() << "\'InternalClient:" << m_internalWindow << "\'"; } QRect InternalClient::transparentRect() const { return QRect(); } NET::WindowType InternalClient::windowType(bool direct, int supported_types) const { Q_UNUSED(direct) Q_UNUSED(supported_types) return m_windowType; } double InternalClient::opacity() const { return m_opacity; } void InternalClient::setOpacity(double opacity) { if (m_opacity == opacity) { return; } const double oldOpacity = m_opacity; m_opacity = opacity; emit opacityChanged(this, oldOpacity); } void InternalClient::killWindow() { // We don't kill our internal windows. } bool InternalClient::isPopupWindow() const { if (AbstractClient::isPopupWindow()) { return true; } return m_internalWindowFlags.testFlag(Qt::Popup); } QByteArray InternalClient::windowRole() const { return QByteArray(); } void InternalClient::closeWindow() { if (m_internalWindow) { m_internalWindow->hide(); } } bool InternalClient::isCloseable() const { return true; } bool InternalClient::isFullScreenable() const { return false; } bool InternalClient::isFullScreen() const { return false; } bool InternalClient::isMaximizable() const { return false; } bool InternalClient::isMinimizable() const { return false; } bool InternalClient::isMovable() const { return true; } bool InternalClient::isMovableAcrossScreens() const { return true; } bool InternalClient::isResizable() const { return true; } bool InternalClient::noBorder() const { return m_userNoBorder || m_internalWindowFlags.testFlag(Qt::FramelessWindowHint) || m_internalWindowFlags.testFlag(Qt::Popup); } bool InternalClient::userCanSetNoBorder() const { return !m_internalWindowFlags.testFlag(Qt::FramelessWindowHint) || m_internalWindowFlags.testFlag(Qt::Popup); } bool InternalClient::wantsInput() const { return false; } bool InternalClient::isInternal() const { return true; } bool InternalClient::isLockScreen() const { if (m_internalWindow) { return m_internalWindow->property("org_kde_ksld_emergency").toBool(); } return false; } bool InternalClient::isInputMethod() const { if (m_internalWindow) { return m_internalWindow->property("__kwin_input_method").toBool(); } return false; } bool InternalClient::isOutline() const { if (m_internalWindow) { return m_internalWindow->property("__kwin_outline").toBool(); } return false; } quint32 InternalClient::windowId() const { return m_windowId; } MaximizeMode InternalClient::maximizeMode() const { return MaximizeRestore; } QRect InternalClient::geometryRestore() const { return m_maximizeRestoreGeometry; } bool InternalClient::isShown(bool shaded_is_shown) const { Q_UNUSED(shaded_is_shown) return readyForPainting(); } bool InternalClient::isHiddenInternal() const { return false; } void InternalClient::hideClient(bool hide) { Q_UNUSED(hide) } void InternalClient::resizeWithChecks(int w, int h, ForceGeometry_t force) { Q_UNUSED(force) if (!m_internalWindow) { return; } 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(); } setFrameGeometry(QRect(x(), y(), w, h)); } void InternalClient::setFrameGeometry(int x, int y, int w, int h, ForceGeometry_t force) { const QRect rect(x, y, w, h); if (areGeometryUpdatesBlocked()) { m_frameGeometry = rect; if (pendingGeometryUpdate() == PendingGeometryForced) { // Maximum, nothing needed. } else if (force == ForceGeometrySet) { setPendingGeometryUpdate(PendingGeometryForced); } else { setPendingGeometryUpdate(PendingGeometryNormal); } return; } if (pendingGeometryUpdate() != PendingGeometryNone) { // Reset geometry to the one before blocking, so that we can compare properly. m_frameGeometry = frameGeometryBeforeUpdateBlocking(); } if (m_frameGeometry == rect) { return; } const QRect newClientGeometry = frameRectToClientRect(rect); if (m_clientSize == newClientGeometry.size()) { commitGeometry(rect); } else { requestGeometry(rect); } } void InternalClient::setGeometryRestore(const QRect &rect) { m_maximizeRestoreGeometry = rect; } bool InternalClient::supportsWindowRules() const { return false; } AbstractClient *InternalClient::findModal(bool allow_itself) { Q_UNUSED(allow_itself) return nullptr; } void InternalClient::setOnAllActivities(bool set) { Q_UNUSED(set) // Internal clients do not support activities. } void InternalClient::takeFocus() { } bool InternalClient::userCanSetFullScreen() const { return false; } void InternalClient::setFullScreen(bool set, bool user) { Q_UNUSED(set) Q_UNUSED(user) } void InternalClient::setNoBorder(bool set) { if (!userCanSetNoBorder()) { return; } if (m_userNoBorder == set) { return; } m_userNoBorder = set; updateDecoration(true); } void InternalClient::updateDecoration(bool check_workspace_pos, bool force) { if (!force && isDecorated() == !noBorder()) { return; } const QRect oldFrameGeometry = frameGeometry(); const QRect oldClientGeometry = oldFrameGeometry - frameMargins(); GeometryUpdatesBlocker blocker(this); if (force) { destroyDecoration(); } if (!noBorder()) { createDecoration(oldClientGeometry); } else { destroyDecoration(); } updateShadow(); if (check_workspace_pos) { checkWorkspacePosition(oldFrameGeometry, -2, oldClientGeometry); } } void InternalClient::updateColorScheme() { AbstractClient::updateColorScheme(QString()); } void InternalClient::showOnScreenEdge() { } void InternalClient::destroyClient() { if (isMoveResize()) { leaveMoveResize(); } Deleted *deleted = Deleted::create(this); emit windowClosed(this, deleted); destroyDecoration(); workspace()->removeInternalClient(this); deleted->unrefWindow(); m_internalWindow = nullptr; delete this; } void InternalClient::present(const QSharedPointer fbo) { Q_ASSERT(m_internalImage.isNull()); const QSize bufferSize = fbo->size() / bufferScale(); commitGeometry(QRect(pos(), sizeForClientSize(bufferSize))); markAsMapped(); if (m_internalFBO != fbo) { discardWindowPixmap(); m_internalFBO = fbo; } setDepth(32); addDamageFull(); addRepaintFull(); } void InternalClient::present(const QImage &image, const QRegion &damage) { Q_ASSERT(m_internalFBO.isNull()); const QSize bufferSize = image.size() / bufferScale(); commitGeometry(QRect(pos(), sizeForClientSize(bufferSize))); markAsMapped(); if (m_internalImage.size() != image.size()) { discardWindowPixmap(); } m_internalImage = image; setDepth(32); addDamage(damage); addRepaint(damage.translated(borderLeft(), borderTop())); } QWindow *InternalClient::internalWindow() const { return m_internalWindow; } bool InternalClient::acceptsFocus() const { return false; } bool InternalClient::belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const { Q_UNUSED(checks) return qobject_cast(other) != nullptr; } void InternalClient::changeMaximize(bool horizontal, bool vertical, bool adjust) { Q_UNUSED(horizontal) Q_UNUSED(vertical) Q_UNUSED(adjust) // Internal clients are not maximizable. } void InternalClient::destroyDecoration() { if (!isDecorated()) { return; } const QRect clientGeometry = frameRectToClientRect(frameGeometry()); AbstractClient::destroyDecoration(); setFrameGeometry(clientGeometry); } void InternalClient::doMove(int x, int y) { Q_UNUSED(x) Q_UNUSED(y) syncGeometryToInternalWindow(); } void InternalClient::doResizeSync() { requestGeometry(moveResizeGeometry()); } void InternalClient::updateCaption() { const QString oldSuffix = m_captionSuffix; const auto shortcut = shortcutCaptionSuffix(); m_captionSuffix = shortcut; if ((!isSpecialWindow() || isToolbar()) && findClientWithSameCaption()) { int i = 2; do { m_captionSuffix = shortcut + QLatin1String(" <") + QString::number(i) + QLatin1Char('>'); i++; } while (findClientWithSameCaption()); } if (m_captionSuffix != oldSuffix) { emit captionChanged(); } } void InternalClient::createDecoration(const QRect &rect) { KDecoration2::Decoration *decoration = Decoration::DecorationBridge::self()->createDecoration(this); if (decoration) { QMetaObject::invokeMethod(decoration, "update", Qt::QueuedConnection); connect(decoration, &KDecoration2::Decoration::shadowChanged, this, &Toplevel::updateShadow); connect(decoration, &KDecoration2::Decoration::bordersChanged, this, [this]() { GeometryUpdatesBlocker blocker(this); const QRect oldGeometry = frameGeometry(); if (!isShade()) { checkWorkspacePosition(oldGeometry); } emit geometryShapeChanged(this, oldGeometry); } ); } const QRect oldFrameGeometry = frameGeometry(); setDecoration(decoration); setFrameGeometry(clientRectToFrameRect(rect)); emit geometryShapeChanged(this, oldFrameGeometry); } void InternalClient::requestGeometry(const QRect &rect) { if (m_internalWindow) { m_internalWindow->setGeometry(frameRectToClientRect(rect)); } } void InternalClient::commitGeometry(const QRect &rect) { if (m_frameGeometry == rect && pendingGeometryUpdate() == PendingGeometryNone) { return; } m_frameGeometry = rect; m_clientSize = frameRectToClientRect(frameGeometry()).size(); addWorkspaceRepaint(visibleRect()); syncGeometryToInternalWindow(); const QRect oldGeometry = frameGeometryBeforeUpdateBlocking(); updateGeometryBeforeUpdateBlocking(); emit geometryShapeChanged(this, oldGeometry); if (isResize()) { performMoveResize(); } } void InternalClient::setCaption(const QString &caption) { if (m_captionNormal == caption) { return; } m_captionNormal = caption; const QString oldCaptionSuffix = m_captionSuffix; updateCaption(); if (m_captionSuffix == oldCaptionSuffix) { emit captionChanged(); } } void InternalClient::markAsMapped() { if (!ready_for_painting) { setReadyForPainting(); workspace()->addInternalClient(this); } } void InternalClient::syncGeometryToInternalWindow() { if (m_internalWindow->geometry() == frameRectToClientRect(frameGeometry())) { return; } QTimer::singleShot(0, this, [this] { requestGeometry(frameGeometry()); }); } void InternalClient::updateInternalWindowGeometry() { if (isMoveResize()) { return; } commitGeometry(clientRectToFrameRect(m_internalWindow->geometry())); } } diff --git a/internal_client.h b/internal_client.h index 62e1ede80..140e87d69 100644 --- a/internal_client.h +++ b/internal_client.h @@ -1,129 +1,129 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2019 Martin Flöser -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" namespace KWin { class KWIN_EXPORT InternalClient : public AbstractClient { Q_OBJECT public: explicit InternalClient(QWindow *window); ~InternalClient() override; bool eventFilter(QObject *watched, QEvent *event) override; QRect bufferGeometry() const override; QStringList activities() const override; void blockActivityUpdates(bool b = true) override; qreal bufferScale() const override; QString captionNormal() const override; QString captionSuffix() const override; QPoint clientContentPos() const override; QSize clientSize() const override; void debug(QDebug &stream) const override; QRect transparentRect() const override; NET::WindowType windowType(bool direct = false, int supported_types = 0) const override; double opacity() const override; void setOpacity(double opacity) override; void killWindow() override; bool isPopupWindow() const override; QByteArray windowRole() const override; void closeWindow() 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 noBorder() const override; bool userCanSetNoBorder() const override; bool wantsInput() const override; bool isInternal() const override; bool isLockScreen() const override; bool isInputMethod() const override; bool isOutline() const override; quint32 windowId() const override; MaximizeMode maximizeMode() const override; QRect geometryRestore() const override; bool isShown(bool shaded_is_shown) const override; bool isHiddenInternal() const override; void hideClient(bool hide) override; using AbstractClient::resizeWithChecks; void resizeWithChecks(int w, int h, ForceGeometry_t force = NormalGeometrySet) override; using AbstractClient::setFrameGeometry; void setFrameGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) override; void setGeometryRestore(const QRect &rect) override; bool supportsWindowRules() const override; AbstractClient *findModal(bool allow_itself = false) override; void setOnAllActivities(bool set) override; void takeFocus() override; bool userCanSetFullScreen() 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 updateColorScheme() override; void showOnScreenEdge() override; void destroyClient(); void present(const QSharedPointer fbo); void present(const QImage &image, const QRegion &damage); QWindow *internalWindow() const; protected: bool acceptsFocus() const override; bool belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const override; void changeMaximize(bool horizontal, bool vertical, bool adjust) override; void destroyDecoration() override; void doMove(int x, int y) override; void doResizeSync() override; void updateCaption() override; private: void createDecoration(const QRect &rect); void requestGeometry(const QRect &rect); void commitGeometry(const QRect &rect); void setCaption(const QString &caption); void markAsMapped(); void syncGeometryToInternalWindow(); void updateInternalWindowGeometry(); QWindow *m_internalWindow = nullptr; QRect m_maximizeRestoreGeometry; QSize m_clientSize = QSize(0, 0); QString m_captionNormal; QString m_captionSuffix; double m_opacity = 1.0; NET::WindowType m_windowType = NET::Normal; quint32 m_windowId = 0; Qt::WindowFlags m_internalWindowFlags = Qt::WindowFlags(); bool m_userNoBorder = false; Q_DISABLE_COPY(InternalClient) }; } diff --git a/kcmkwin/common/effectsmodel.cpp b/kcmkwin/common/effectsmodel.cpp index b3a9d1125..47c264f16 100644 --- a/kcmkwin/common/effectsmodel.cpp +++ b/kcmkwin/common/effectsmodel.cpp @@ -1,684 +1,684 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Antonis Tsiapaliokas -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "effectsmodel.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KWin { static QString translatedCategory(const QString &category) { static const QVector knownCategories = { QStringLiteral("Accessibility"), QStringLiteral("Appearance"), QStringLiteral("Candy"), QStringLiteral("Focus"), QStringLiteral("Show Desktop Animation"), QStringLiteral("Tools"), QStringLiteral("Virtual Desktop Switching Animation"), QStringLiteral("Window Management"), QStringLiteral("Window Open/Close Animation") }; static const QVector translatedCategories = { i18nc("Category of Desktop Effects, used as section header", "Accessibility"), i18nc("Category of Desktop Effects, used as section header", "Appearance"), i18nc("Category of Desktop Effects, used as section header", "Candy"), i18nc("Category of Desktop Effects, used as section header", "Focus"), i18nc("Category of Desktop Effects, used as section header", "Show Desktop Animation"), i18nc("Category of Desktop Effects, used as section header", "Tools"), i18nc("Category of Desktop Effects, used as section header", "Virtual Desktop Switching Animation"), i18nc("Category of Desktop Effects, used as section header", "Window Management"), i18nc("Category of Desktop Effects, used as section header", "Window Open/Close Animation") }; const int index = knownCategories.indexOf(category); if (index == -1) { qDebug() << "Unknown category '" << category << "' and thus not translated"; return category; } return translatedCategories[index]; } static EffectsModel::Status effectStatus(bool enabled) { return enabled ? EffectsModel::Status::Enabled : EffectsModel::Status::Disabled; } EffectsModel::EffectsModel(QObject *parent) : QAbstractItemModel(parent) { } QHash EffectsModel::roleNames() const { QHash roleNames; roleNames[NameRole] = "NameRole"; roleNames[DescriptionRole] = "DescriptionRole"; roleNames[AuthorNameRole] = "AuthorNameRole"; roleNames[AuthorEmailRole] = "AuthorEmailRole"; roleNames[LicenseRole] = "LicenseRole"; roleNames[VersionRole] = "VersionRole"; roleNames[CategoryRole] = "CategoryRole"; roleNames[ServiceNameRole] = "ServiceNameRole"; roleNames[IconNameRole] = "IconNameRole"; roleNames[StatusRole] = "StatusRole"; roleNames[VideoRole] = "VideoRole"; roleNames[WebsiteRole] = "WebsiteRole"; roleNames[SupportedRole] = "SupportedRole"; roleNames[ExclusiveRole] = "ExclusiveRole"; roleNames[ConfigurableRole] = "ConfigurableRole"; roleNames[ScriptedRole] = QByteArrayLiteral("ScriptedRole"); roleNames[EnabledByDefaultRole] = "EnabledByDefaultRole"; return roleNames; } QModelIndex EffectsModel::index(int row, int column, const QModelIndex &parent) const { if (parent.isValid() || column > 0 || column < 0 || row < 0 || row >= m_effects.count()) { return {}; } return createIndex(row, column); } QModelIndex EffectsModel::parent(const QModelIndex &child) const { Q_UNUSED(child) return {}; } int EffectsModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return 1; } int EffectsModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return m_effects.count(); } QVariant EffectsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return {}; } const EffectData effect = m_effects.at(index.row()); switch (role) { case Qt::DisplayRole: case NameRole: return effect.name; case DescriptionRole: return effect.description; case AuthorNameRole: return effect.authorName; case AuthorEmailRole: return effect.authorEmail; case LicenseRole: return effect.license; case VersionRole: return effect.version; case CategoryRole: return effect.category; case ServiceNameRole: return effect.serviceName; case IconNameRole: return effect.iconName; case StatusRole: return static_cast(effect.status); case VideoRole: return effect.video; case WebsiteRole: return effect.website; case SupportedRole: return effect.supported; case ExclusiveRole: return effect.exclusiveGroup; case InternalRole: return effect.internal; case ConfigurableRole: return effect.configurable; case ScriptedRole: return effect.kind == Kind::Scripted; case EnabledByDefaultRole: return effect.enabledByDefault; default: return {}; } } bool EffectsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) { return QAbstractItemModel::setData(index, value, role); } if (role == StatusRole) { // note: whenever the StatusRole is modified (even to the same value) the entry // gets marked as changed and will get saved to the config file. This means the // config file could get polluted EffectData &data = m_effects[index.row()]; data.status = Status(value.toInt()); data.changed = data.status != data.originalStatus; emit dataChanged(index, index); if (data.status == Status::Enabled && !data.exclusiveGroup.isEmpty()) { // need to disable all other exclusive effects in the same category for (int i = 0; i < m_effects.size(); ++i) { if (i == index.row()) { continue; } EffectData &otherData = m_effects[i]; if (otherData.exclusiveGroup == data.exclusiveGroup) { otherData.status = Status::Disabled; otherData.changed = otherData.status != otherData.originalStatus; emit dataChanged(this->index(i, 0), this->index(i, 0)); } } } return true; } return QAbstractItemModel::setData(index, value, role); } void EffectsModel::loadBuiltInEffects(const KConfigGroup &kwinConfig, const KPluginInfo::List &configs) { const auto builtins = BuiltInEffects::availableEffects(); for (auto builtin : builtins) { const BuiltInEffects::EffectData &data = BuiltInEffects::effectData(builtin); EffectData effect; effect.name = data.displayName; effect.description = data.comment; effect.authorName = i18n("KWin development team"); effect.authorEmail = QString(); // not used at all effect.license = QStringLiteral("GPL"); effect.version = QStringLiteral(KWIN_VERSION_STRING); effect.untranslatedCategory = data.category; effect.category = translatedCategory(data.category); effect.serviceName = data.name; effect.iconName = QStringLiteral("preferences-system-windows"); effect.enabledByDefault = data.enabled; effect.enabledByDefaultFunction = (data.enabledFunction != nullptr); const QString enabledKey = QStringLiteral("%1Enabled").arg(effect.serviceName); if (kwinConfig.hasKey(enabledKey)) { effect.status = effectStatus(kwinConfig.readEntry(effect.serviceName + "Enabled", effect.enabledByDefault)); } else if (data.enabledFunction != nullptr) { effect.status = Status::EnabledUndeterminded; } else { effect.status = effectStatus(effect.enabledByDefault); } effect.originalStatus = effect.status; effect.video = data.video; effect.website = QUrl(); effect.supported = true; effect.exclusiveGroup = data.exclusiveCategory; effect.internal = data.internal; effect.kind = Kind::BuiltIn; effect.configurable = std::any_of(configs.constBegin(), configs.constEnd(), [data](const KPluginInfo &info) { return info.property(QStringLiteral("X-KDE-ParentComponents")).toString() == data.name; } ); if (shouldStore(effect)) { m_pendingEffects << effect; } } } void EffectsModel::loadJavascriptEffects(const KConfigGroup &kwinConfig) { const auto plugins = KPackage::PackageLoader::self()->listPackages( QStringLiteral("KWin/Effect"), QStringLiteral("kwin/effects") ); for (const KPluginMetaData &metaData : plugins) { KPluginInfo plugin(metaData); EffectData effect; effect.name = plugin.name(); effect.description = plugin.comment(); effect.authorName = plugin.author(); effect.authorEmail = plugin.email(); effect.license = plugin.license(); effect.version = plugin.version(); effect.untranslatedCategory = plugin.category(); effect.category = translatedCategory(plugin.category()); effect.serviceName = plugin.pluginName(); effect.iconName = plugin.icon(); effect.status = effectStatus(kwinConfig.readEntry(effect.serviceName + "Enabled", plugin.isPluginEnabledByDefault())); effect.originalStatus = effect.status; effect.enabledByDefault = plugin.isPluginEnabledByDefault(); effect.enabledByDefaultFunction = false; effect.video = plugin.property(QStringLiteral("X-KWin-Video-Url")).toUrl(); effect.website = QUrl(plugin.website()); effect.supported = true; effect.exclusiveGroup = plugin.property(QStringLiteral("X-KWin-Exclusive-Category")).toString(); effect.internal = plugin.property(QStringLiteral("X-KWin-Internal")).toBool(); effect.kind = Kind::Scripted; const QString pluginKeyword = plugin.property(QStringLiteral("X-KDE-PluginKeyword")).toString(); if (!pluginKeyword.isEmpty()) { // scripted effects have their pluginName() as the keyword effect.configurable = plugin.property(QStringLiteral("X-KDE-ParentComponents")).toString() == pluginKeyword; } else { effect.configurable = false; } if (shouldStore(effect)) { m_pendingEffects << effect; } } } void EffectsModel::loadPluginEffects(const KConfigGroup &kwinConfig, const KPluginInfo::List &configs) { const auto pluginEffects = KPluginLoader::findPlugins( QStringLiteral("kwin/effects/plugins/"), [](const KPluginMetaData &data) { return data.serviceTypes().contains(QStringLiteral("KWin/Effect")); } ); for (const KPluginMetaData &pluginEffect : pluginEffects) { if (!pluginEffect.isValid()) { continue; } EffectData effect; effect.name = pluginEffect.name(); effect.description = pluginEffect.description(); effect.license = pluginEffect.license(); effect.version = pluginEffect.version(); effect.untranslatedCategory = pluginEffect.category(); effect.category = translatedCategory(pluginEffect.category()); effect.serviceName = pluginEffect.pluginId(); effect.iconName = pluginEffect.iconName(); effect.enabledByDefault = pluginEffect.isEnabledByDefault(); effect.supported = true; effect.enabledByDefaultFunction = false; effect.internal = false; effect.kind = Kind::Binary; for (int i = 0; i < pluginEffect.authors().count(); ++i) { effect.authorName.append(pluginEffect.authors().at(i).name()); effect.authorEmail.append(pluginEffect.authors().at(i).emailAddress()); if (i+1 < pluginEffect.authors().count()) { effect.authorName.append(", "); effect.authorEmail.append(", "); } } if (pluginEffect.rawData().contains("org.kde.kwin.effect")) { const QJsonObject d(pluginEffect.rawData().value("org.kde.kwin.effect").toObject()); effect.exclusiveGroup = d.value("exclusiveGroup").toString(); effect.video = QUrl::fromUserInput(d.value("video").toString()); effect.enabledByDefaultFunction = d.value("enabledByDefaultMethod").toBool(); } effect.website = QUrl(pluginEffect.website()); const QString enabledKey = QStringLiteral("%1Enabled").arg(effect.serviceName); if (kwinConfig.hasKey(enabledKey)) { effect.status = effectStatus(kwinConfig.readEntry(effect.serviceName + "Enabled", effect.enabledByDefault)); } else if (effect.enabledByDefaultFunction) { effect.status = Status::EnabledUndeterminded; } else { effect.status = effectStatus(effect.enabledByDefault); } effect.originalStatus = effect.status; effect.configurable = std::any_of(configs.constBegin(), configs.constEnd(), [pluginEffect](const KPluginInfo &info) { return info.property(QStringLiteral("X-KDE-ParentComponents")).toString() == pluginEffect.pluginId(); } ); if (shouldStore(effect)) { m_pendingEffects << effect; } } } void EffectsModel::load(LoadOptions options) { KConfigGroup kwinConfig(KSharedConfig::openConfig("kwinrc"), "Plugins"); m_pendingEffects.clear(); const KPluginInfo::List configs = KPluginTrader::self()->query(QStringLiteral("kwin/effects/configs/")); loadBuiltInEffects(kwinConfig, configs); loadJavascriptEffects(kwinConfig); loadPluginEffects(kwinConfig, configs); std::sort(m_pendingEffects.begin(), m_pendingEffects.end(), [](const EffectData &a, const EffectData &b) { if (a.category == b.category) { if (a.exclusiveGroup == b.exclusiveGroup) { return a.name < b.name; } return a.exclusiveGroup < b.exclusiveGroup; } return a.category < b.category; } ); auto commit = [this, options] { if (options == LoadOptions::KeepDirty) { for (const EffectData &oldEffect : m_effects) { if (!oldEffect.changed) { continue; } auto effectIt = std::find_if(m_pendingEffects.begin(), m_pendingEffects.end(), [oldEffect](const EffectData &data) { return data.serviceName == oldEffect.serviceName; } ); if (effectIt == m_pendingEffects.end()) { continue; } effectIt->status = oldEffect.status; effectIt->changed = effectIt->status != effectIt->originalStatus; } } beginResetModel(); m_effects = m_pendingEffects; m_pendingEffects.clear(); endResetModel(); emit loaded(); }; OrgKdeKwinEffectsInterface interface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QDBusConnection::sessionBus()); if (interface.isValid()) { QStringList effectNames; effectNames.reserve(m_pendingEffects.count()); for (const EffectData &data : m_pendingEffects) { effectNames.append(data.serviceName); } const int serial = ++m_lastSerial; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(interface.areEffectsSupported(effectNames), this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *self) { self->deleteLater(); if (m_lastSerial != serial) { return; } const QDBusPendingReply > reply = *self; if (reply.isError()) { commit(); return; } const QList supportedValues = reply.value(); if (supportedValues.count() != effectNames.count()) { return; } for (int i = 0; i < effectNames.size(); ++i) { const bool supported = supportedValues.at(i); const QString effectName = effectNames.at(i); auto it = std::find_if(m_pendingEffects.begin(), m_pendingEffects.end(), [effectName](const EffectData &data) { return data.serviceName == effectName; } ); if (it == m_pendingEffects.end()) { continue; } if ((*it).supported != supported) { (*it).supported = supported; } } commit(); } ); } else { commit(); } } void EffectsModel::updateEffectStatus(const QModelIndex &rowIndex, Status effectState) { setData(rowIndex, static_cast(effectState), StatusRole); } void EffectsModel::save() { KConfigGroup kwinConfig(KSharedConfig::openConfig("kwinrc"), "Plugins"); QVector dirtyEffects; for (EffectData &effect : m_effects) { if (!effect.changed) { continue; } effect.changed = false; effect.originalStatus = effect.status; const QString key = effect.serviceName + QStringLiteral("Enabled"); const bool shouldEnable = (effect.status != Status::Disabled); const bool restoreToDefault = effect.enabledByDefaultFunction ? effect.status == Status::EnabledUndeterminded : shouldEnable == effect.enabledByDefault; if (restoreToDefault) { kwinConfig.deleteEntry(key); } else { kwinConfig.writeEntry(key, shouldEnable); } dirtyEffects.append(effect); } if (dirtyEffects.isEmpty()) { return; } kwinConfig.sync(); OrgKdeKwinEffectsInterface interface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QDBusConnection::sessionBus()); if (!interface.isValid()) { return; } for (const EffectData &effect : dirtyEffects) { if (effect.status != Status::Disabled) { interface.loadEffect(effect.serviceName); } else { interface.unloadEffect(effect.serviceName); } } } void EffectsModel::defaults() { for (int i = 0; i < m_effects.count(); ++i) { const auto &effect = m_effects.at(i); if (effect.enabledByDefaultFunction && effect.status != Status::EnabledUndeterminded) { updateEffectStatus(index(i, 0), Status::EnabledUndeterminded); } else if (static_cast(effect.status) != effect.enabledByDefault) { updateEffectStatus(index(i, 0), effect.enabledByDefault ? Status::Enabled : Status::Disabled); } } } bool EffectsModel::isDefaults() const { return std::all_of(m_effects.constBegin(), m_effects.constEnd(), [](const EffectData &effect) { if (effect.enabledByDefaultFunction && effect.status != Status::EnabledUndeterminded) { return false; } if (static_cast(effect.status) != effect.enabledByDefault) { return false; } return true; }); } bool EffectsModel::needsSave() const { return std::any_of(m_effects.constBegin(), m_effects.constEnd(), [](const EffectData &data) { return data.changed; } ); } QModelIndex EffectsModel::findByPluginId(const QString &pluginId) const { auto it = std::find_if(m_effects.constBegin(), m_effects.constEnd(), [pluginId](const EffectData &data) { return data.serviceName == pluginId; } ); if (it == m_effects.constEnd()) { return {}; } return index(std::distance(m_effects.constBegin(), it), 0); } static KCModule *findBinaryConfig(const QString &pluginId, QObject *parent) { return KPluginTrader::createInstanceFromQuery( QStringLiteral("kwin/effects/configs/"), QString(), QStringLiteral("'%1' in [X-KDE-ParentComponents]").arg(pluginId), parent ); } static KCModule *findScriptedConfig(const QString &pluginId, QObject *parent) { const auto offers = KPluginTrader::self()->query( QStringLiteral("kwin/effects/configs/"), QString(), QStringLiteral("[X-KDE-Library] == 'kcm_kwin4_genericscripted'") ); if (offers.isEmpty()) { return nullptr; } const KPluginInfo &generic = offers.first(); KPluginLoader loader(generic.libraryPath()); KPluginFactory *factory = loader.factory(); if (!factory) { return nullptr; } return factory->create(pluginId, parent); } void EffectsModel::requestConfigure(const QModelIndex &index, QWindow *transientParent) { if (!index.isValid()) { return; } QPointer dialog = new QDialog(); KCModule *module = index.data(ScriptedRole).toBool() ? findScriptedConfig(index.data(ServiceNameRole).toString(), dialog) : findBinaryConfig(index.data(ServiceNameRole).toString(), dialog); if (!module) { delete dialog; return; } dialog->setWindowTitle(index.data(NameRole).toString()); dialog->winId(); dialog->windowHandle()->setTransientParent(transientParent); auto buttons = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults, dialog ); connect(buttons, &QDialogButtonBox::accepted, dialog, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject); connect(buttons->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, module, &KCModule::defaults); connect(module, &KCModule::defaulted, this, [=](bool defaulted) { buttons->button(QDialogButtonBox::RestoreDefaults)->setEnabled(!defaulted); }); auto layout = new QVBoxLayout(dialog); layout->addWidget(module); layout->addWidget(buttons); if (dialog->exec() == QDialog::Accepted) { module->save(); } delete dialog; } bool EffectsModel::shouldStore(const EffectData &data) const { Q_UNUSED(data) return true; } } diff --git a/kcmkwin/common/effectsmodel.h b/kcmkwin/common/effectsmodel.h index b49754ac9..8d00b568c 100644 --- a/kcmkwin/common/effectsmodel.h +++ b/kcmkwin/common/effectsmodel.h @@ -1,275 +1,275 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Antonis Tsiapaliokas -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 status of each effect is its default state. */ bool isDefaults() const; /** * 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/animationsmodel.cpp b/kcmkwin/kwindesktop/animationsmodel.cpp index f80a64c53..b888de83c 100644 --- a/kcmkwin/kwindesktop/animationsmodel.cpp +++ b/kcmkwin/kwindesktop/animationsmodel.cpp @@ -1,165 +1,165 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "animationsmodel.h" namespace KWin { AnimationsModel::AnimationsModel(QObject *parent) : EffectsModel(parent) { connect(this, &EffectsModel::loaded, this, [this] { setEnabled(modelCurrentEnabled()); setCurrentIndex(modelCurrentIndex()); } ); connect(this, &AnimationsModel::currentIndexChanged, this, [this] { const QModelIndex index_ = index(m_currentIndex, 0); if (!index_.isValid()) { return; } const bool configurable = index_.data(ConfigurableRole).toBool(); if (configurable != m_currentConfigurable) { m_currentConfigurable = configurable; emit currentConfigurableChanged(); } } ); } bool AnimationsModel::enabled() const { return m_enabled; } void AnimationsModel::setEnabled(bool enabled) { if (m_enabled != enabled) { m_enabled = enabled; emit enabledChanged(); } } int AnimationsModel::currentIndex() const { return m_currentIndex; } void AnimationsModel::setCurrentIndex(int index) { if (m_currentIndex != index) { m_currentIndex = index; emit currentIndexChanged(); } } bool AnimationsModel::currentConfigurable() const { return m_currentConfigurable; } bool AnimationsModel::shouldStore(const EffectData &data) const { return data.untranslatedCategory.contains( QStringLiteral("Virtual Desktop Switching Animation"), Qt::CaseInsensitive); } EffectsModel::Status AnimationsModel::status(int row) const { return Status(data(index(row, 0), static_cast(StatusRole)).toInt()); } bool AnimationsModel::modelCurrentEnabled() const { for (int i = 0; i < rowCount(); ++i) { if (status(i) != Status::Disabled) { return true; } } return false; } int AnimationsModel::modelCurrentIndex() const { for (int i = 0; i < rowCount(); ++i) { if (status(i) != Status::Disabled) { return i; } } return 0; } void AnimationsModel::load() { EffectsModel::load(); } void AnimationsModel::save() { for (int i = 0; i < rowCount(); ++i) { const auto status = (m_enabled && i == m_currentIndex) ? EffectsModel::Status::Enabled : EffectsModel::Status::Disabled; updateEffectStatus(index(i, 0), status); } EffectsModel::save(); } void AnimationsModel::defaults() { EffectsModel::defaults(); setEnabled(modelCurrentEnabled()); setCurrentIndex(modelCurrentIndex()); } bool AnimationsModel::isDefaults() const { // effect at m_currentIndex index may not be the current saved selected effect const bool enabledByDefault = index(m_currentIndex, 0).data(EnabledByDefaultRole).toBool(); return enabledByDefault; } bool AnimationsModel::needsSave() const { KConfigGroup kwinConfig(KSharedConfig::openConfig("kwinrc"), "Plugins"); for (int i = 0; i < rowCount(); ++i) { const QModelIndex index_ = index(i, 0); const bool enabledConfig = kwinConfig.readEntry( index_.data(ServiceNameRole).toString() + QLatin1String("Enabled"), index_.data(EnabledByDefaultRole).toBool() ); const bool enabled = (m_enabled && i == m_currentIndex); if (enabled != enabledConfig) { return true; } } return false; } } diff --git a/kcmkwin/kwindesktop/animationsmodel.h b/kcmkwin/kwindesktop/animationsmodel.h index f05d9feec..2c6855b82 100644 --- a/kcmkwin/kwindesktop/animationsmodel.h +++ b/kcmkwin/kwindesktop/animationsmodel.h @@ -1,72 +1,72 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "effectsmodel.h" namespace KWin { class AnimationsModel : public EffectsModel { Q_OBJECT Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged) Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) Q_PROPERTY(bool currentConfigurable READ currentConfigurable NOTIFY currentConfigurableChanged) public: explicit AnimationsModel(QObject *parent = nullptr); bool enabled() const; void setEnabled(bool enabled); int currentIndex() const; void setCurrentIndex(int index); bool currentConfigurable() const; void load(); void save(); void defaults(); bool isDefaults() const; bool needsSave() const; Q_SIGNALS: void enabledChanged(); void currentIndexChanged(); void currentConfigurableChanged(); protected: bool shouldStore(const EffectData &data) const override; private: Status status(int row) const; bool modelCurrentEnabled() const; int modelCurrentIndex() const; bool m_enabled = false; int m_currentIndex = -1; bool m_currentConfigurable = false; Q_DISABLE_COPY(AnimationsModel) }; } diff --git a/kcmkwin/kwindesktop/virtualdesktops.cpp b/kcmkwin/kwindesktop/virtualdesktops.cpp index 5a433f4e3..2a4aa0e16 100644 --- a/kcmkwin/kwindesktop/virtualdesktops.cpp +++ b/kcmkwin/kwindesktop/virtualdesktops.cpp @@ -1,175 +1,175 @@ /* * Copyright (C) 2018 Eike Hein - * Copyright (C) 2018 Vlad Zahorodnii + * Copyright (C) 2018 Vlad Zahorodnii * * 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 "virtualdesktops.h" #include "animationsmodel.h" #include "desktopsmodel.h" #include "virtualdesktopssettings.h" #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(VirtualDesktopsFactory, "kcm_kwin_virtualdesktops.json", registerPlugin();) namespace KWin { VirtualDesktops::VirtualDesktops(QObject *parent, const QVariantList &args) : KQuickAddons::ManagedConfigModule(parent, args) , m_settings(new VirtualDesktopsSettings(this)) , m_desktopsModel(new KWin::DesktopsModel(this)) , m_animationsModel(new AnimationsModel(this)) { KAboutData *about = new KAboutData(QStringLiteral("kcm_kwin_virtualdesktops"), i18n("Virtual Desktops"), QStringLiteral("2.0"), QString(), KAboutLicense::GPL); setAboutData(about); qmlRegisterType(); setButtons(Apply | Default); QObject::connect(m_desktopsModel, &KWin::DesktopsModel::userModifiedChanged, this, &VirtualDesktops::settingsChanged); connect(m_animationsModel, &AnimationsModel::enabledChanged, this, &VirtualDesktops::settingsChanged); connect(m_animationsModel, &AnimationsModel::currentIndexChanged, this, &VirtualDesktops::settingsChanged); } VirtualDesktops::~VirtualDesktops() { } QAbstractItemModel *VirtualDesktops::desktopsModel() const { return m_desktopsModel; } QAbstractItemModel *VirtualDesktops::animationsModel() const { return m_animationsModel; } VirtualDesktopsSettings *VirtualDesktops::virtualDesktopsSettings() const { return m_settings; } void VirtualDesktops::load() { ManagedConfigModule::load(); m_desktopsModel->load(); m_animationsModel->load(); } void VirtualDesktops::save() { ManagedConfigModule::save(); m_desktopsModel->syncWithServer(); m_animationsModel->save(); QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KWin"), QStringLiteral("org.kde.KWin"), QStringLiteral("reloadConfig")); QDBusConnection::sessionBus().send(message); } void VirtualDesktops::defaults() { ManagedConfigModule::defaults(); m_desktopsModel->defaults(); m_animationsModel->defaults(); } bool VirtualDesktops::isDefaults() const { return m_animationsModel->isDefaults() && m_desktopsModel->isDefaults(); } void VirtualDesktops::configureAnimation() { const QModelIndex index = m_animationsModel->index(m_animationsModel->currentIndex(), 0); if (!index.isValid()) { return; } m_animationsModel->requestConfigure(index, nullptr); } void VirtualDesktops::showAboutAnimation() { const QModelIndex index = m_animationsModel->index(m_animationsModel->currentIndex(), 0); if (!index.isValid()) { return; } const QString name = index.data(AnimationsModel::NameRole).toString(); const QString comment = index.data(AnimationsModel::DescriptionRole).toString(); const QString author = index.data(AnimationsModel::AuthorNameRole).toString(); const QString email = index.data(AnimationsModel::AuthorEmailRole).toString(); const QString website = index.data(AnimationsModel::WebsiteRole).toString(); const QString version = index.data(AnimationsModel::VersionRole).toString(); const QString license = index.data(AnimationsModel::LicenseRole).toString(); const QString icon = index.data(AnimationsModel::IconNameRole).toString(); const KAboutLicense::LicenseKey licenseType = KAboutLicense::byKeyword(license).key(); KAboutData aboutData( name, // Plugin name name, // Display name version, // Version comment, // Short description licenseType, // License QString(), // Copyright statement QString(), // Other text website.toLatin1() // Home page ); aboutData.setProgramLogo(icon); const QStringList authors = author.split(','); const QStringList emails = email.split(','); if (authors.count() == emails.count()) { int i = 0; for (const QString &author : authors) { if (!author.isEmpty()) { aboutData.addAuthor(i18n(author.toUtf8()), QString(), emails[i]); } i++; } } QPointer aboutPlugin = new KAboutApplicationDialog(aboutData); aboutPlugin->exec(); delete aboutPlugin; } bool VirtualDesktops::isSaveNeeded() const { return m_animationsModel->needsSave() || m_desktopsModel->needsSave(); } } #include "virtualdesktops.moc" diff --git a/kcmkwin/kwindesktop/virtualdesktops.h b/kcmkwin/kwindesktop/virtualdesktops.h index 9b486da9c..296875790 100644 --- a/kcmkwin/kwindesktop/virtualdesktops.h +++ b/kcmkwin/kwindesktop/virtualdesktops.h @@ -1,70 +1,70 @@ /* * Copyright (C) 2018 Eike Hein - * Copyright (C) 2018 Vlad Zahorodnii + * Copyright (C) 2018 Vlad Zahorodnii * * 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 VIRTUALDESKTOPS_H #define VIRTUALDESKTOPS_H #include #include class VirtualDesktopsSettings; namespace KWin { class AnimationsModel; class DesktopsModel; class VirtualDesktops : public KQuickAddons::ManagedConfigModule { Q_OBJECT Q_PROPERTY(QAbstractItemModel* desktopsModel READ desktopsModel CONSTANT) Q_PROPERTY(QAbstractItemModel *animationsModel READ animationsModel CONSTANT) Q_PROPERTY(VirtualDesktopsSettings *virtualDesktopsSettings READ virtualDesktopsSettings CONSTANT) public: explicit VirtualDesktops(QObject *parent = nullptr, const QVariantList &list = QVariantList()); ~VirtualDesktops() override; QAbstractItemModel *desktopsModel() const; QAbstractItemModel *animationsModel() const; VirtualDesktopsSettings *virtualDesktopsSettings() const; bool isDefaults() const override; bool isSaveNeeded() const override; public Q_SLOTS: void load() override; void save() override; void defaults() override; void configureAnimation(); void showAboutAnimation(); private: VirtualDesktopsSettings *m_settings; DesktopsModel *m_desktopsModel; AnimationsModel *m_animationsModel; }; } #endif diff --git a/kcmkwin/kwineffects/effectsfilterproxymodel.cpp b/kcmkwin/kwineffects/effectsfilterproxymodel.cpp index c11b1fc7b..e9a173f62 100644 --- a/kcmkwin/kwineffects/effectsfilterproxymodel.cpp +++ b/kcmkwin/kwineffects/effectsfilterproxymodel.cpp @@ -1,104 +1,104 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 "effectsfilterproxymodel.h" #include "effectsmodel.h" namespace KWin { EffectsFilterProxyModel::EffectsFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { } EffectsFilterProxyModel::~EffectsFilterProxyModel() { } QString EffectsFilterProxyModel::query() const { return m_query; } void EffectsFilterProxyModel::setQuery(const QString &query) { if (m_query != query) { m_query = query; emit queryChanged(); invalidateFilter(); } } bool EffectsFilterProxyModel::excludeInternal() const { return m_excludeInternal; } void EffectsFilterProxyModel::setExcludeInternal(bool exclude) { if (m_excludeInternal != exclude) { m_excludeInternal = exclude; emit excludeInternalChanged(); invalidateFilter(); } } bool EffectsFilterProxyModel::excludeUnsupported() const { return m_excludeUnsupported; } void EffectsFilterProxyModel::setExcludeUnsupported(bool exclude) { if (m_excludeUnsupported != exclude) { m_excludeUnsupported = exclude; emit excludeUnsupportedChanged(); invalidateFilter(); } } bool EffectsFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { const QModelIndex idx = sourceModel()->index(sourceRow, 0, sourceParent); if (!m_query.isEmpty()) { const bool matches = idx.data(EffectsModel::NameRole).toString().contains(m_query, Qt::CaseInsensitive) || idx.data(EffectsModel::DescriptionRole).toString().contains(m_query, Qt::CaseInsensitive) || idx.data(EffectsModel::CategoryRole).toString().contains(m_query, Qt::CaseInsensitive); if (!matches) { return false; } } if (m_excludeInternal) { if (idx.data(EffectsModel::InternalRole).toBool()) { return false; } } if (m_excludeUnsupported) { if (!idx.data(EffectsModel::SupportedRole).toBool()) { return false; } } return true; } } // namespace KWin diff --git a/kcmkwin/kwineffects/effectsfilterproxymodel.h b/kcmkwin/kwineffects/effectsfilterproxymodel.h index 57a843cba..a329ad3bc 100644 --- a/kcmkwin/kwineffects/effectsfilterproxymodel.h +++ b/kcmkwin/kwineffects/effectsfilterproxymodel.h @@ -1,62 +1,62 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 namespace KWin { class EffectsFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel *sourceModel READ sourceModel WRITE setSourceModel) Q_PROPERTY(QString query READ query WRITE setQuery NOTIFY queryChanged) Q_PROPERTY(bool excludeInternal READ excludeInternal WRITE setExcludeInternal NOTIFY excludeInternalChanged) Q_PROPERTY(bool excludeUnsupported READ excludeUnsupported WRITE setExcludeUnsupported NOTIFY excludeUnsupportedChanged) public: explicit EffectsFilterProxyModel(QObject *parent = nullptr); ~EffectsFilterProxyModel() override; QString query() const; void setQuery(const QString &query); bool excludeInternal() const; void setExcludeInternal(bool exclude); bool excludeUnsupported() const; void setExcludeUnsupported(bool exclude); Q_SIGNALS: void queryChanged(); void excludeInternalChanged(); void excludeUnsupportedChanged(); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; private: QString m_query; bool m_excludeInternal = true; bool m_excludeUnsupported = true; Q_DISABLE_COPY(EffectsFilterProxyModel) }; } // namespace KWin diff --git a/kcmkwin/kwineffects/kcm.cpp b/kcmkwin/kwineffects/kcm.cpp index f9cc4370d..898ec5ccd 100644 --- a/kcmkwin/kwineffects/kcm.cpp +++ b/kcmkwin/kwineffects/kcm.cpp @@ -1,124 +1,124 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 "kcm.h" #include "effectsfilterproxymodel.h" #include "effectsmodel.h" #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(DesktopEffectsKCMFactory, "kcm_kwin_effects.json", registerPlugin();) namespace KWin { DesktopEffectsKCM::DesktopEffectsKCM(QObject *parent, const QVariantList &args) : KQuickAddons::ConfigModule(parent, args) , m_model(new EffectsModel(this)) { qmlRegisterType("org.kde.private.kcms.kwin.effects", 1, 0, "EffectsFilterProxyModel"); auto about = new KAboutData( QStringLiteral("kcm_kwin_effects"), i18n("Desktop Effects"), QStringLiteral("2.0"), QString(), KAboutLicense::GPL ); - about->addAuthor(i18n("Vlad Zahorodnii"), QString(), QStringLiteral("vladzzag@gmail.com")); + about->addAuthor(i18n("Vlad Zahorodnii"), QString(), QStringLiteral("vlad.zahorodnii@kde.org")); setAboutData(about); setButtons(Apply | Default); connect(m_model, &EffectsModel::dataChanged, this, &DesktopEffectsKCM::updateNeedsSave); connect(m_model, &EffectsModel::loaded, this, &DesktopEffectsKCM::updateNeedsSave); } DesktopEffectsKCM::~DesktopEffectsKCM() { } QAbstractItemModel *DesktopEffectsKCM::effectsModel() const { return m_model; } void DesktopEffectsKCM::load() { m_model->load(); setNeedsSave(false); } void DesktopEffectsKCM::save() { m_model->save(); setNeedsSave(false); } void DesktopEffectsKCM::defaults() { m_model->defaults(); updateNeedsSave(); } void DesktopEffectsKCM::openGHNS(QQuickItem *context) { QPointer dialog = new KNS3::DownloadDialog(QStringLiteral("kwineffect.knsrc")); dialog->setWindowTitle(i18n("Download New Desktop Effects")); dialog->winId(); if (context && context->window()) { dialog->windowHandle()->setTransientParent(context->window()); } if (dialog->exec() == QDialog::Accepted) { if (!dialog->changedEntries().isEmpty()) { m_model->load(EffectsModel::LoadOptions::KeepDirty); } } delete dialog; } void DesktopEffectsKCM::configure(const QString &pluginId, QQuickItem *context) { const QModelIndex index = m_model->findByPluginId(pluginId); QWindow *transientParent = nullptr; if (context && context->window()) { transientParent = context->window(); } m_model->requestConfigure(index, transientParent); } void DesktopEffectsKCM::updateNeedsSave() { setNeedsSave(m_model->needsSave()); setRepresentsDefaults(m_model->isDefaults()); } } // namespace KWin #include "kcm.moc" diff --git a/kcmkwin/kwineffects/kcm.h b/kcmkwin/kwineffects/kcm.h index 2dbb662fe..7d55d5712 100644 --- a/kcmkwin/kwineffects/kcm.h +++ b/kcmkwin/kwineffects/kcm.h @@ -1,58 +1,58 @@ /* - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 namespace KWin { class EffectsModel; class DesktopEffectsKCM : public KQuickAddons::ConfigModule { Q_OBJECT Q_PROPERTY(QAbstractItemModel *effectsModel READ effectsModel CONSTANT) public: explicit DesktopEffectsKCM(QObject *parent = nullptr, const QVariantList &list = {}); ~DesktopEffectsKCM() override; QAbstractItemModel *effectsModel() const; public Q_SLOTS: void load() override; void save() override; void defaults() override; void openGHNS(QQuickItem *context); void configure(const QString &pluginId, QQuickItem *context); private Q_SLOTS: void updateNeedsSave(); private: EffectsModel *m_model; Q_DISABLE_COPY(DesktopEffectsKCM) }; } // namespace KWin diff --git a/kcmkwin/kwineffects/package/contents/ui/Effect.qml b/kcmkwin/kwineffects/package/contents/ui/Effect.qml index 66566281f..e9e8b1d21 100644 --- a/kcmkwin/kwineffects/package/contents/ui/Effect.qml +++ b/kcmkwin/kwineffects/package/contents/ui/Effect.qml @@ -1,128 +1,128 @@ /* * Copyright (C) 2013 Antonis Tsiapaliokas - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 . * */ import QtQuick 2.5 import QtQuick.Controls 2.5 as QQC2 import QtQuick.Layouts 1.1 import org.kde.kirigami 2.5 as Kirigami Kirigami.SwipeListItem { id: listItem hoverEnabled: true onClicked: { view.currentIndex = index; } contentItem: RowLayout { id: row QQC2.RadioButton { property bool _exclusive: model.ExclusiveRole != "" property bool _toggled: false checked: model.StatusRole visible: _exclusive QQC2.ButtonGroup.group: _exclusive ? effectsList.findButtonGroup(model.ExclusiveRole) : null onToggled: { model.StatusRole = checked ? Qt.Checked : Qt.Unchecked; _toggled = true; } onClicked: { // Uncheck the radio button if it's clicked. if (checked && !_toggled) { model.StatusRole = Qt.Unchecked; } _toggled = false; } } QQC2.CheckBox { checkState: model.StatusRole visible: model.ExclusiveRole == "" onToggled: model.StatusRole = checkState } ColumnLayout { Layout.topMargin: Kirigami.Units.smallSpacing Layout.bottomMargin: Kirigami.Units.smallSpacing spacing: 0 Kirigami.Heading { Layout.fillWidth: true level: 5 text: model.NameRole wrapMode: Text.Wrap } QQC2.Label { Layout.fillWidth: true text: model.DescriptionRole opacity: listItem.hovered ? 0.8 : 0.6 wrapMode: Text.Wrap } QQC2.Label { id: aboutItem Layout.fillWidth: true text: i18n("Author: %1\nLicense: %2", model.AuthorNameRole, model.LicenseRole) opacity: listItem.hovered ? 0.8 : 0.6 visible: view.currentIndex === index wrapMode: Text.Wrap } Loader { id: videoItem active: false source: "Video.qml" visible: false function showHide() { if (!videoItem.active) { videoItem.active = true; videoItem.visible = true; } else { videoItem.active = false; videoItem.visible = false; } } } } } actions: [ Kirigami.Action { visible: model.VideoRole.toString() !== "" icon.name: "videoclip-amarok" tooltip: i18nc("@info:tooltip", "Show/Hide Video") onTriggered: videoItem.showHide() }, Kirigami.Action { visible: model.ConfigurableRole enabled: model.StatusRole != Qt.Unchecked icon.name: "configure" tooltip: i18nc("@info:tooltip", "Configure...") onTriggered: kcm.configure(model.ServiceNameRole, this) } ] } diff --git a/kcmkwin/kwineffects/package/contents/ui/main.qml b/kcmkwin/kwineffects/package/contents/ui/main.qml index 68e0ccf6d..03967cc23 100644 --- a/kcmkwin/kwineffects/package/contents/ui/main.qml +++ b/kcmkwin/kwineffects/package/contents/ui/main.qml @@ -1,140 +1,140 @@ /* * Copyright (C) 2013 Antonis Tsiapaliokas - * Copyright (C) 2019 Vlad Zahorodnii + * Copyright (C) 2019 Vlad Zahorodnii * * 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 . */ import QtQuick 2.5 import QtQuick.Controls 2.5 as QQC2 import QtQuick.Layouts 1.1 import org.kde.kcm 1.2 import org.kde.kconfig 1.0 import org.kde.kirigami 2.10 as Kirigami import org.kde.private.kcms.kwin.effects 1.0 as Private ScrollViewKCM { ConfigModule.quickHelp: i18n("This module lets you configure desktop effects.") header: ColumnLayout { QQC2.Label { Layout.fillWidth: true elide: Text.ElideRight text: i18n("Hint: To find out or configure how to activate an effect, look at the effect's settings.") } RowLayout { Kirigami.SearchField { id: searchField Layout.fillWidth: true } QQC2.ToolButton { id: filterButton icon.name: "view-filter" checkable: true checked: menu.opened onClicked: menu.popup(filterButton, filterButton.width - menu.width, filterButton.height) QQC2.ToolTip { text: i18n("Configure Filter") } } QQC2.Menu { id: menu modal: true QQC2.MenuItem { checkable: true checked: searchModel.excludeUnsupported text: i18n("Exclude unsupported effects") onToggled: searchModel.excludeUnsupported = checked } QQC2.MenuItem { checkable: true checked: searchModel.excludeInternal text: i18n("Exclude internal effects") onToggled: searchModel.excludeInternal = checked } } } } view: ListView { id: effectsList property var _buttonGroups: [] model: Private.EffectsFilterProxyModel { id: searchModel query: searchField.text sourceModel: kcm.effectsModel } delegate: Effect { width: effectsList.width } section.property: "CategoryRole" section.delegate: Kirigami.ListSectionHeader { width: effectsList.width text: section } function findButtonGroup(name) { for (let item of effectsList._buttonGroups) { if (item.name == name) { return item.group; } } let group = Qt.createQmlObject( 'import QtQuick 2.5;' + 'import QtQuick.Controls 2.5;' + 'ButtonGroup {}', effectsList, "dynamicButtonGroup" + effectsList._buttonGroups.length ); effectsList._buttonGroups.push({ name, group }); return group; } } footer: ColumnLayout { RowLayout { Layout.alignment: Qt.AlignRight QQC2.Button { icon.name: "get-hot-new-stuff" text: i18n("Get New Desktop Effects...") visible: KAuthorized.authorize("ghns") onClicked: kcm.openGHNS(this) } } } } diff --git a/libkwineffects/anidata.cpp b/libkwineffects/anidata.cpp index 4823cb371..32965d18a 100644 --- a/libkwineffects/anidata.cpp +++ b/libkwineffects/anidata.cpp @@ -1,133 +1,133 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Thomas Lübking -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "anidata_p.h" #include "logging_p.h" QDebug operator<<(QDebug dbg, const KWin::AniData &a) { dbg.nospace() << a.debugInfo(); return dbg.space(); } using namespace KWin; FullScreenEffectLock::FullScreenEffectLock(Effect *effect) { effects->setActiveFullScreenEffect(effect); } FullScreenEffectLock::~FullScreenEffectLock() { effects->setActiveFullScreenEffect(nullptr); } KeepAliveLock::KeepAliveLock(EffectWindow *w) : m_window(w) { m_window->refWindow(); } KeepAliveLock::~KeepAliveLock() { m_window->unrefWindow(); } PreviousWindowPixmapLock::PreviousWindowPixmapLock(EffectWindow *w) : m_window(w) { m_window->referencePreviousWindowPixmap(); } PreviousWindowPixmapLock::~PreviousWindowPixmapLock() { m_window->unreferencePreviousWindowPixmap(); // Add synthetic repaint to prevent glitches after cross-fading // translucent windows. effects->addRepaint(m_window->expandedGeometry()); } AniData::AniData() : attribute(AnimationEffect::Opacity) , customCurve(0) // Linear , meta(0) , startTime(0) , waitAtSource(false) , keepAlive(true) { } AniData::AniData(AnimationEffect::Attribute a, int meta_, const FPx2 &to_, int delay, const FPx2 &from_, bool waitAtSource_, FullScreenEffectLockPtr fullScreenEffectLock_, bool keepAlive, PreviousWindowPixmapLockPtr previousWindowPixmapLock_) : attribute(a) , from(from_) , to(to_) , meta(meta_) , startTime(AnimationEffect::clock() + delay) , fullScreenEffectLock(std::move(fullScreenEffectLock_)) , waitAtSource(waitAtSource_) , keepAlive(keepAlive) , previousWindowPixmapLock(std::move(previousWindowPixmapLock_)) { } bool AniData::isActive() const { if (!timeLine.done()) { return true; } if (timeLine.direction() == TimeLine::Backward) { return !(terminationFlags & AnimationEffect::TerminateAtSource); } return !(terminationFlags & AnimationEffect::TerminateAtTarget); } static QString attributeString(KWin::AnimationEffect::Attribute attribute) { switch (attribute) { case KWin::AnimationEffect::Opacity: return QStringLiteral("Opacity"); case KWin::AnimationEffect::Brightness: return QStringLiteral("Brightness"); case KWin::AnimationEffect::Saturation: return QStringLiteral("Saturation"); case KWin::AnimationEffect::Scale: return QStringLiteral("Scale"); case KWin::AnimationEffect::Translation: return QStringLiteral("Translation"); case KWin::AnimationEffect::Rotation: return QStringLiteral("Rotation"); case KWin::AnimationEffect::Position: return QStringLiteral("Position"); case KWin::AnimationEffect::Size: return QStringLiteral("Size"); case KWin::AnimationEffect::Clip: return QStringLiteral("Clip"); default: return QStringLiteral(" "); } } QString AniData::debugInfo() const { return QLatin1String("Animation: ") + attributeString(attribute) + QLatin1String("\n From: ") + from.toString() + QLatin1String("\n To: ") + to.toString() + QLatin1String("\n Started: ") + QString::number(AnimationEffect::clock() - startTime) + QLatin1String("ms ago\n") + QLatin1String( " Duration: ") + QString::number(timeLine.duration().count()) + QLatin1String("ms\n") + QLatin1String( " Passed: ") + QString::number(timeLine.elapsed().count()) + QLatin1String("ms\n"); } diff --git a/libkwineffects/anidata_p.h b/libkwineffects/anidata_p.h index 96d0abaa2..e343cd5d2 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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.cpp b/libkwineffects/kwinanimationeffect.cpp index 421716322..b43a8028a 100644 --- a/libkwineffects/kwinanimationeffect.cpp +++ b/libkwineffects/kwinanimationeffect.cpp @@ -1,1057 +1,1057 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Thomas Lübking -Copyright (C) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "kwinanimationeffect.h" #include "anidata_p.h" #include #include #include #include QDebug operator<<(QDebug dbg, const KWin::FPx2 &fpx2) { dbg.nospace() << fpx2[0] << "," << fpx2[1] << QString(fpx2.isValid() ? QStringLiteral(" (valid)") : QStringLiteral(" (invalid)")); return dbg.space(); } namespace KWin { QElapsedTimer AnimationEffect::s_clock; class AnimationEffectPrivate { public: AnimationEffectPrivate() { m_animated = m_damageDirty = m_animationsTouched = m_isInitialized = false; m_justEndedAnimation = 0; } AnimationEffect::AniMap m_animations; static quint64 m_animCounter; quint64 m_justEndedAnimation; // protect against cancel QWeakPointer m_fullScreenEffectLock; bool m_animated, m_damageDirty, m_needSceneRepaint, m_animationsTouched, m_isInitialized; }; } using namespace KWin; quint64 AnimationEffectPrivate::m_animCounter = 0; AnimationEffect::AnimationEffect() : d_ptr(new AnimationEffectPrivate()) { Q_D(AnimationEffect); d->m_animated = false; if (!s_clock.isValid()) s_clock.start(); /* this is the same as the QTimer::singleShot(0, SLOT(init())) kludge * defering the init and esp. the connection to the windowClosed slot */ QMetaObject::invokeMethod( this, "init", Qt::QueuedConnection ); } AnimationEffect::~AnimationEffect() { delete d_ptr; } void AnimationEffect::init() { Q_D(AnimationEffect); if (d->m_isInitialized) return; // not more than once, please d->m_isInitialized = true; /* by connecting the signal from a slot AFTER the inheriting class constructor had the chance to * connect it we can provide auto-referencing of animated and closed windows, since at the time * our slot will be called, the slot of the subclass has been (SIGNAL/SLOT connections are FIFO) * and has pot. started an animation so we have the window in our hash :) */ connect(effects, &EffectsHandler::windowClosed, this, &AnimationEffect::_windowClosed); connect(effects, &EffectsHandler::windowDeleted, this, &AnimationEffect::_windowDeleted); } bool AnimationEffect::isActive() const { Q_D(const AnimationEffect); return !d->m_animations.isEmpty(); } #define RELATIVE_XY(_FIELD_) const bool relative[2] = { static_cast(metaData(Relative##_FIELD_##X, meta)), \ static_cast(metaData(Relative##_FIELD_##Y, meta)) } void AnimationEffect::validate(Attribute a, uint &meta, FPx2 *from, FPx2 *to, const EffectWindow *w) const { if (a < NonFloatBase) { if (a == Scale) { QRect area = effects->clientArea(ScreenArea , w); if (from && from->isValid()) { RELATIVE_XY(Source); from->set(relative[0] ? (*from)[0] * area.width() / w->width() : (*from)[0], relative[1] ? (*from)[1] * area.height() / w->height() : (*from)[1]); } if (to && to->isValid()) { RELATIVE_XY(Target); to->set(relative[0] ? (*to)[0] * area.width() / w->width() : (*to)[0], relative[1] ? (*to)[1] * area.height() / w->height() : (*to)[1] ); } } else if (a == Rotation) { if (from && !from->isValid()) { setMetaData(SourceAnchor, metaData(TargetAnchor, meta), meta); from->set(0.0,0.0); } if (to && !to->isValid()) { setMetaData(TargetAnchor, metaData(SourceAnchor, meta), meta); to->set(0.0,0.0); } } if (from && !from->isValid()) from->set(1.0,1.0); if (to && !to->isValid()) to->set(1.0,1.0); } else if (a == Position) { QRect area = effects->clientArea(ScreenArea , w); QPoint pt = w->geometry().bottomRight(); // cannot be < 0 ;-) if (from) { if (from->isValid()) { RELATIVE_XY(Source); from->set(relative[0] ? area.x() + (*from)[0] * area.width() : (*from)[0], relative[1] ? area.y() + (*from)[1] * area.height() : (*from)[1]); } else { from->set(pt.x(), pt.y()); setMetaData(SourceAnchor, AnimationEffect::Bottom|AnimationEffect::Right, meta); } } if (to) { if (to->isValid()) { RELATIVE_XY(Target); to->set(relative[0] ? area.x() + (*to)[0] * area.width() : (*to)[0], relative[1] ? area.y() + (*to)[1] * area.height() : (*to)[1]); } else { to->set(pt.x(), pt.y()); setMetaData( TargetAnchor, AnimationEffect::Bottom|AnimationEffect::Right, meta ); } } } else if (a == Size) { QRect area = effects->clientArea(ScreenArea , w); if (from) { if (from->isValid()) { RELATIVE_XY(Source); from->set(relative[0] ? (*from)[0] * area.width() : (*from)[0], relative[1] ? (*from)[1] * area.height() : (*from)[1]); } else { from->set(w->width(), w->height()); } } if (to) { if (to->isValid()) { RELATIVE_XY(Target); to->set(relative[0] ? (*to)[0] * area.width() : (*to)[0], relative[1] ? (*to)[1] * area.height() : (*to)[1]); } else { to->set(w->width(), w->height()); } } } else if (a == Translation) { QRect area = w->rect(); if (from) { if (from->isValid()) { RELATIVE_XY(Source); from->set(relative[0] ? (*from)[0] * area.width() : (*from)[0], relative[1] ? (*from)[1] * area.height() : (*from)[1]); } else { from->set(0.0, 0.0); } } if (to) { if (to->isValid()) { RELATIVE_XY(Target); to->set(relative[0] ? (*to)[0] * area.width() : (*to)[0], relative[1] ? (*to)[1] * area.height() : (*to)[1]); } else { to->set(0.0, 0.0); } } } else if (a == Clip) { if (from && !from->isValid()) { from->set(1.0,1.0); setMetaData(SourceAnchor, metaData(TargetAnchor, meta), meta); } if (to && !to->isValid()) { to->set(1.0,1.0); setMetaData(TargetAnchor, metaData(SourceAnchor, meta), meta); } } else if (a == CrossFadePrevious) { if (from && !from->isValid()) { from->set(0.0); } if (to && !to->isValid()) { to->set(1.0); } } } quint64 AnimationEffect::p_animate( EffectWindow *w, Attribute a, uint meta, int ms, FPx2 to, const QEasingCurve &curve, int delay, FPx2 from, bool keepAtTarget, bool fullScreenEffect, bool keepAlive) { const bool waitAtSource = from.isValid(); validate(a, meta, &from, &to, w); Q_D(AnimationEffect); if (!d->m_isInitialized) init(); // needs to ensure the window gets removed if deleted in the same event cycle if (d->m_animations.isEmpty()) { connect(effects, &EffectsHandler::windowGeometryShapeChanged, this, &AnimationEffect::_expandedGeometryChanged); connect(effects, &EffectsHandler::windowStepUserMovedResized, this, &AnimationEffect::_expandedGeometryChanged); connect(effects, &EffectsHandler::windowPaddingChanged, this, &AnimationEffect::_expandedGeometryChanged); } AniMap::iterator it = d->m_animations.find(w); if (it == d->m_animations.end()) it = d->m_animations.insert(w, QPair, QRect>(QList(), QRect())); FullScreenEffectLockPtr fullscreen; if (fullScreenEffect) { if (d->m_fullScreenEffectLock.isNull()) { fullscreen = FullScreenEffectLockPtr::create(this); d->m_fullScreenEffectLock = fullscreen.toWeakRef(); } else { fullscreen = d->m_fullScreenEffectLock.toStrongRef(); } } PreviousWindowPixmapLockPtr previousPixmap; if (a == CrossFadePrevious) { previousPixmap = PreviousWindowPixmapLockPtr::create(w); } it->first.append(AniData( a, // Attribute meta, // Metadata to, // Target delay, // Delay from, // Source waitAtSource, // Whether the animation should be kept at source fullscreen, // Full screen effect lock keepAlive, // Keep alive flag previousPixmap // Previous window pixmap lock )); const quint64 ret_id = ++d->m_animCounter; AniData &animation = it->first.last(); animation.id = ret_id; animation.timeLine.setDirection(TimeLine::Forward); animation.timeLine.setDuration(std::chrono::milliseconds(ms)); animation.timeLine.setEasingCurve(curve); animation.timeLine.setSourceRedirectMode(TimeLine::RedirectMode::Strict); animation.timeLine.setTargetRedirectMode(TimeLine::RedirectMode::Relaxed); animation.terminationFlags = TerminateAtSource; if (!keepAtTarget) { animation.terminationFlags |= TerminateAtTarget; } it->second = QRect(); d->m_animationsTouched = true; if (delay > 0) { QTimer::singleShot(delay, this, &AnimationEffect::triggerRepaint); const QSize &s = effects->virtualScreenSize(); if (waitAtSource) w->addLayerRepaint(0, 0, s.width(), s.height()); } else { triggerRepaint(); } return ret_id; } bool AnimationEffect::retarget(quint64 animationId, FPx2 newTarget, int newRemainingTime) { Q_D(AnimationEffect); if (animationId == d->m_justEndedAnimation) return false; // this is just ending, do not try to retarget it for (AniMap::iterator entry = d->m_animations.begin(), mapEnd = d->m_animations.end(); entry != mapEnd; ++entry) { for (QList::iterator anim = entry->first.begin(), animEnd = entry->first.end(); anim != animEnd; ++anim) { if (anim->id == animationId) { anim->from.set(interpolated(*anim, 0), interpolated(*anim, 1)); validate(anim->attribute, anim->meta, nullptr, &newTarget, entry.key()); anim->to.set(newTarget[0], newTarget[1]); anim->timeLine.setDirection(TimeLine::Forward); anim->timeLine.setDuration(std::chrono::milliseconds(newRemainingTime)); anim->timeLine.reset(); return true; } } } return false; // no animation found } bool AnimationEffect::redirect(quint64 animationId, Direction direction, TerminationFlags terminationFlags) { Q_D(AnimationEffect); if (animationId == d->m_justEndedAnimation) { return false; } for (auto entryIt = d->m_animations.begin(); entryIt != d->m_animations.end(); ++entryIt) { auto animIt = std::find_if(entryIt->first.begin(), entryIt->first.end(), [animationId] (AniData &anim) { return anim.id == animationId; } ); if (animIt == entryIt->first.end()) { continue; } switch (direction) { case Backward: animIt->timeLine.setDirection(TimeLine::Backward); break; case Forward: animIt->timeLine.setDirection(TimeLine::Forward); break; } animIt->terminationFlags = terminationFlags & ~TerminateAtTarget; return true; } return false; } bool AnimationEffect::complete(quint64 animationId) { Q_D(AnimationEffect); if (animationId == d->m_justEndedAnimation) { return false; } for (auto entryIt = d->m_animations.begin(); entryIt != d->m_animations.end(); ++entryIt) { auto animIt = std::find_if(entryIt->first.begin(), entryIt->first.end(), [animationId] (AniData &anim) { return anim.id == animationId; } ); if (animIt == entryIt->first.end()) { continue; } animIt->timeLine.setElapsed(animIt->timeLine.duration()); return true; } return false; } bool AnimationEffect::cancel(quint64 animationId) { Q_D(AnimationEffect); if (animationId == d->m_justEndedAnimation) return true; // this is just ending, do not try to cancel it but fake success for (AniMap::iterator entry = d->m_animations.begin(), mapEnd = d->m_animations.end(); entry != mapEnd; ++entry) { for (QList::iterator anim = entry->first.begin(), animEnd = entry->first.end(); anim != animEnd; ++anim) { if (anim->id == animationId) { entry->first.erase(anim); // remove the animation if (entry->first.isEmpty()) { // no other animations on the window, release it. d->m_animations.erase(entry); } if (d->m_animations.isEmpty()) disconnectGeometryChanges(); d->m_animationsTouched = true; // could be called from animationEnded return true; } } } return false; } void AnimationEffect::prePaintScreen( ScreenPrePaintData& data, int time ) { Q_D(AnimationEffect); if (d->m_animations.isEmpty()) { effects->prePaintScreen(data, time); return; } d->m_animationsTouched = false; AniMap::iterator entry = d->m_animations.begin(), mapEnd = d->m_animations.end(); d->m_animated = false; // short int transformed = 0; while (entry != mapEnd) { bool invalidateLayerRect = false; QList::iterator anim = entry->first.begin(), animEnd = entry->first.end(); int animCounter = 0; while (anim != animEnd) { if (anim->startTime > clock()) { if (!anim->waitAtSource) { ++anim; ++animCounter; continue; } } else { anim->timeLine.update(std::chrono::milliseconds(time)); } if (anim->isActive()) { // if (anim->attribute != Brightness && anim->attribute != Saturation && anim->attribute != Opacity) // transformed = true; d->m_animated = true; ++anim; ++animCounter; } else { EffectWindow *oldW = entry.key(); d->m_justEndedAnimation = anim->id; animationEnded(oldW, anim->attribute, anim->meta); d->m_justEndedAnimation = 0; // NOTICE animationEnded is an external call and might have called "::animate" // as a result our iterators could now point random junk on the heap // so we've to restore the former states, ie. find our window list and animation if (d->m_animationsTouched) { d->m_animationsTouched = false; entry = d->m_animations.begin(), mapEnd = d->m_animations.end(); while (entry.key() != oldW && entry != mapEnd) ++entry; Q_ASSERT(entry != mapEnd); // usercode should not delete animations from animationEnded (not even possible atm.) anim = entry->first.begin(), animEnd = entry->first.end(); Q_ASSERT(animCounter < entry->first.count()); for (int i = 0; i < animCounter; ++i) ++anim; } anim = entry->first.erase(anim); invalidateLayerRect = d->m_damageDirty = true; animEnd = entry->first.end(); } } if (entry->first.isEmpty()) { data.paint |= entry->second; // d->m_damageDirty = true; // TODO likely no longer required entry = d->m_animations.erase(entry); mapEnd = d->m_animations.end(); } else { if (invalidateLayerRect) *const_cast(&(entry->second)) = QRect(); // invalidate ++entry; } } // janitorial... if (d->m_animations.isEmpty()) { disconnectGeometryChanges(); } effects->prePaintScreen(data, time); } static int xCoord(const QRect &r, int flag) { if (flag & AnimationEffect::Left) return r.x(); else if (flag & AnimationEffect::Right) return r.right(); else return r.x() + r.width()/2; } static int yCoord(const QRect &r, int flag) { if (flag & AnimationEffect::Top) return r.y(); else if (flag & AnimationEffect::Bottom) return r.bottom(); else return r.y() + r.height()/2; } QRect AnimationEffect::clipRect(const QRect &geo, const AniData &anim) const { QRect clip = geo; FPx2 ratio = anim.from + progress(anim) * (anim.to - anim.from); if (anim.from[0] < 1.0 || anim.to[0] < 1.0) { clip.setWidth(clip.width() * ratio[0]); } if (anim.from[1] < 1.0 || anim.to[1] < 1.0) { clip.setHeight(clip.height() * ratio[1]); } const QRect center = geo.adjusted(clip.width()/2, clip.height()/2, -(clip.width()+1)/2, -(clip.height()+1)/2 ); const int x[2] = { xCoord(center, metaData(SourceAnchor, anim.meta)), xCoord(center, metaData(TargetAnchor, anim.meta)) }; const int y[2] = { yCoord(center, metaData(SourceAnchor, anim.meta)), yCoord(center, metaData(TargetAnchor, anim.meta)) }; const QPoint d(x[0] + ratio[0]*(x[1]-x[0]), y[0] + ratio[1]*(y[1]-y[0])); clip.moveTopLeft(QPoint(d.x() - clip.width()/2, d.y() - clip.height()/2)); return clip; } void AnimationEffect::clipWindow(const EffectWindow *w, const AniData &anim, WindowQuadList &quads) const { return; const QRect geo = w->expandedGeometry(); QRect clip = AnimationEffect::clipRect(geo, anim); WindowQuadList filtered; if (clip.left() != geo.left()) { quads = quads.splitAtX(clip.left()); foreach (const WindowQuad &quad, quads) { if (quad.right() >= clip.left()) filtered << quad; } quads = filtered; filtered.clear(); } if (clip.right() != geo.right()) { quads = quads.splitAtX(clip.left()); foreach (const WindowQuad &quad, quads) { if (quad.right() <= clip.right()) filtered << quad; } quads = filtered; filtered.clear(); } if (clip.top() != geo.top()) { quads = quads.splitAtY(clip.top()); foreach (const WindowQuad &quad, quads) { if (quad.top() >= clip.top()) filtered << quad; } quads = filtered; filtered.clear(); } if (clip.bottom() != geo.bottom()) { quads = quads.splitAtY(clip.bottom()); foreach (const WindowQuad &quad, quads) { if (quad.bottom() <= clip.bottom()) filtered << quad; } quads = filtered; } } void AnimationEffect::disconnectGeometryChanges() { disconnect(effects, &EffectsHandler::windowGeometryShapeChanged, this, &AnimationEffect::_expandedGeometryChanged); disconnect(effects, &EffectsHandler::windowStepUserMovedResized, this, &AnimationEffect::_expandedGeometryChanged); disconnect(effects, &EffectsHandler::windowPaddingChanged, this, &AnimationEffect::_expandedGeometryChanged); } void AnimationEffect::prePaintWindow( EffectWindow* w, WindowPrePaintData& data, int time ) { Q_D(AnimationEffect); if ( d->m_animated ) { AniMap::const_iterator entry = d->m_animations.constFind( w ); if ( entry != d->m_animations.constEnd() ) { bool isUsed = false; bool paintDeleted = false; for (QList::const_iterator anim = entry->first.constBegin(); anim != entry->first.constEnd(); ++anim) { if (anim->startTime > clock() && !anim->waitAtSource) continue; isUsed = true; if (anim->attribute == Opacity || anim->attribute == CrossFadePrevious) data.setTranslucent(); else if (!(anim->attribute == Brightness || anim->attribute == Saturation)) { data.setTransformed(); if (anim->attribute == Clip) clipWindow(w, *anim, data.quads); } paintDeleted |= anim->keepAlive; } if ( isUsed ) { if ( w->isMinimized() ) w->enablePainting( EffectWindow::PAINT_DISABLED_BY_MINIMIZE ); else if ( w->isDeleted() && paintDeleted ) w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DELETE ); else if ( !w->isOnCurrentDesktop() ) w->enablePainting( EffectWindow::PAINT_DISABLED_BY_DESKTOP ); // if( !w->isPaintingEnabled() && !effects->activeFullScreenEffect() ) // effects->addLayerRepaint(w->expandedGeometry()); } } } effects->prePaintWindow( w, data, time ); } static inline float geometryCompensation(int flags, float v) { if (flags & (AnimationEffect::Left|AnimationEffect::Top)) return 0.0; // no compensation required if (flags & (AnimationEffect::Right|AnimationEffect::Bottom)) return 1.0 - v; // full compensation return 0.5 * (1.0 - v); // half compensation } void AnimationEffect::paintWindow( EffectWindow* w, int mask, QRegion region, WindowPaintData& data ) { Q_D(AnimationEffect); if ( d->m_animated ) { AniMap::const_iterator entry = d->m_animations.constFind( w ); if ( entry != d->m_animations.constEnd() ) { for ( QList::const_iterator anim = entry->first.constBegin(); anim != entry->first.constEnd(); ++anim ) { if (anim->startTime > clock() && !anim->waitAtSource) continue; switch (anim->attribute) { case Opacity: data.multiplyOpacity(interpolated(*anim)); break; case Brightness: data.multiplyBrightness(interpolated(*anim)); break; case Saturation: data.multiplySaturation(interpolated(*anim)); break; case Scale: { const QSize sz = w->geometry().size(); float f1(1.0), f2(0.0); if (anim->from[0] >= 0.0 && anim->to[0] >= 0.0) { // scale x f1 = interpolated(*anim, 0); f2 = geometryCompensation( anim->meta & AnimationEffect::Horizontal, f1 ); data.translate(f2 * sz.width()); data.setXScale(data.xScale() * f1); } if (anim->from[1] >= 0.0 && anim->to[1] >= 0.0) { // scale y if (!anim->isOneDimensional()) { f1 = interpolated(*anim, 1); f2 = geometryCompensation( anim->meta & AnimationEffect::Vertical, f1 ); } else if ( ((anim->meta & AnimationEffect::Vertical)>>1) != (anim->meta & AnimationEffect::Horizontal) ) f2 = geometryCompensation( anim->meta & AnimationEffect::Vertical, f1 ); data.translate(0.0, f2 * sz.height()); data.setYScale(data.yScale() * f1); } break; } case Clip: region = clipRect(w->expandedGeometry(), *anim); break; case Translation: data += QPointF(interpolated(*anim, 0), interpolated(*anim, 1)); break; case Size: { FPx2 dest = anim->from + progress(*anim) * (anim->to - anim->from); const QSize sz = w->geometry().size(); float f; if (anim->from[0] >= 0.0 && anim->to[0] >= 0.0) { // resize x f = dest[0]/sz.width(); data.translate(geometryCompensation( anim->meta & AnimationEffect::Horizontal, f ) * sz.width()); data.setXScale(data.xScale() * f); } if (anim->from[1] >= 0.0 && anim->to[1] >= 0.0) { // resize y f = dest[1]/sz.height(); data.translate(0.0, geometryCompensation( anim->meta & AnimationEffect::Vertical, f ) * sz.height()); data.setYScale(data.yScale() * f); } break; } case Position: { const QRect geo = w->geometry(); const float prgrs = progress(*anim); if ( anim->from[0] >= 0.0 && anim->to[0] >= 0.0 ) { float dest = interpolated(*anim, 0); const int x[2] = { xCoord(geo, metaData(SourceAnchor, anim->meta)), xCoord(geo, metaData(TargetAnchor, anim->meta)) }; data.translate(dest - (x[0] + prgrs*(x[1] - x[0]))); } if ( anim->from[1] >= 0.0 && anim->to[1] >= 0.0 ) { float dest = interpolated(*anim, 1); const int y[2] = { yCoord(geo, metaData(SourceAnchor, anim->meta)), yCoord(geo, metaData(TargetAnchor, anim->meta)) }; data.translate(0.0, dest - (y[0] + prgrs*(y[1] - y[0]))); } break; } case Rotation: { data.setRotationAxis((Qt::Axis)metaData(Axis, anim->meta)); const float prgrs = progress(*anim); data.setRotationAngle(anim->from[0] + prgrs*(anim->to[0] - anim->from[0])); const QRect geo = w->rect(); const uint sAnchor = metaData(SourceAnchor, anim->meta), tAnchor = metaData(TargetAnchor, anim->meta); QPointF pt(xCoord(geo, sAnchor), yCoord(geo, sAnchor)); if (tAnchor != sAnchor) { QPointF pt2(xCoord(geo, tAnchor), yCoord(geo, tAnchor)); pt += static_cast(prgrs)*(pt2 - pt); } data.setRotationOrigin(QVector3D(pt)); break; } case Generic: genericAnimation(w, data, progress(*anim), anim->meta); break; case CrossFadePrevious: data.setCrossFadeProgress(progress(*anim)); break; default: break; } } } } effects->paintWindow( w, mask, region, data ); } void AnimationEffect::postPaintScreen() { Q_D(AnimationEffect); if ( d->m_animated ) { if (d->m_damageDirty) updateLayerRepaints(); if (d->m_needSceneRepaint) { effects->addRepaintFull(); } else { AniMap::const_iterator it = d->m_animations.constBegin(), end = d->m_animations.constEnd(); for (; it != end; ++it) { bool addRepaint = false; QList::const_iterator anim = it->first.constBegin(); for (; anim != it->first.constEnd(); ++anim) { if (anim->startTime > clock()) continue; if (!anim->timeLine.done()) { addRepaint = true; break; } } if (addRepaint) { it.key()->addLayerRepaint(it->second); } } } } effects->postPaintScreen(); } float AnimationEffect::interpolated( const AniData &a, int i ) const { if (a.startTime > clock()) return a.from[i]; if (!a.timeLine.done()) return a.from[i] + a.timeLine.value() * (a.to[i] - a.from[i]); return a.to[i]; // we're done and "waiting" at the target value } float AnimationEffect::progress( const AniData &a ) const { return a.startTime < clock() ? a.timeLine.value() : 0.0; } // TODO - get this out of the header - the functionpointer usage of QEasingCurve somehow sucks ;-) // qreal AnimationEffect::qecGaussian(qreal progress) // exp(-5*(2*x-1)^2) // { // progress = 2*progress - 1; // progress *= -5*progress; // return qExp(progress); // } int AnimationEffect::metaData( MetaType type, uint meta ) { switch (type) { case SourceAnchor: return ((meta>>5) & 0x1f); case TargetAnchor: return (meta& 0x1f); case RelativeSourceX: case RelativeSourceY: case RelativeTargetX: case RelativeTargetY: { const int shift = 10 + type - RelativeSourceX; return ((meta>>shift) & 1); } case Axis: return ((meta>>10) & 3); default: return 0; } } void AnimationEffect::setMetaData( MetaType type, uint value, uint &meta ) { switch (type) { case SourceAnchor: meta &= ~(0x1f<<5); meta |= ((value & 0x1f)<<5); break; case TargetAnchor: meta &= ~(0x1f); meta |= (value & 0x1f); break; case RelativeSourceX: case RelativeSourceY: case RelativeTargetX: case RelativeTargetY: { const int shift = 10 + type - RelativeSourceX; if (value) meta |= (1<m_animations.constBegin(), mapEnd = d->m_animations.constEnd(); entry != mapEnd; ++entry) *const_cast(&(entry->second)) = QRect(); updateLayerRepaints(); if (d->m_needSceneRepaint) { effects->addRepaintFull(); } else { AniMap::const_iterator it = d->m_animations.constBegin(), end = d->m_animations.constEnd(); for (; it != end; ++it) { it.key()->addLayerRepaint(it->second); } } } static float fixOvershoot(float f, const AniData &d, short int dir, float s = 1.1) { switch(d.timeLine.easingCurve().type()) { case QEasingCurve::InOutElastic: case QEasingCurve::InOutBack: return f * s; case QEasingCurve::InElastic: case QEasingCurve::OutInElastic: case QEasingCurve::OutBack: return (dir&2) ? f * s : f; case QEasingCurve::OutElastic: case QEasingCurve::InBack: return (dir&1) ? f * s : f; default: return f; } } void AnimationEffect::updateLayerRepaints() { Q_D(AnimationEffect); d->m_needSceneRepaint = false; for (AniMap::const_iterator entry = d->m_animations.constBegin(), mapEnd = d->m_animations.constEnd(); entry != mapEnd; ++entry) { if (!entry->second.isNull()) continue; float f[2] = {1.0, 1.0}; float t[2] = {0.0, 0.0}; bool createRegion = false; QList rects; QRect *layerRect = const_cast(&(entry->second)); for (QList::const_iterator anim = entry->first.constBegin(), animEnd = entry->first.constEnd(); anim != animEnd; ++anim) { if (anim->startTime > clock()) continue; switch (anim->attribute) { case Opacity: case Brightness: case Saturation: case CrossFadePrevious: createRegion = true; break; case Rotation: createRegion = false; *layerRect = QRect(QPoint(0, 0), effects->virtualScreenSize()); goto region_creation; // sic! no need to do anything else case Generic: d->m_needSceneRepaint = true; // we don't know whether this will change visual stacking order return; // sic! no need to do anything else case Translation: case Position: { createRegion = true; QRect r(entry.key()->geometry()); int x[2] = {0,0}; int y[2] = {0,0}; if (anim->attribute == Translation) { x[0] = anim->from[0]; x[1] = anim->to[0]; y[0] = anim->from[1]; y[1] = anim->to[1]; } else { if ( anim->from[0] >= 0.0 && anim->to[0] >= 0.0 ) { x[0] = anim->from[0] - xCoord(r, metaData(SourceAnchor, anim->meta)); x[1] = anim->to[0] - xCoord(r, metaData(TargetAnchor, anim->meta)); } if ( anim->from[1] >= 0.0 && anim->to[1] >= 0.0 ) { y[0] = anim->from[1] - yCoord(r, metaData(SourceAnchor, anim->meta)); y[1] = anim->to[1] - yCoord(r, metaData(TargetAnchor, anim->meta)); } } r = entry.key()->expandedGeometry(); rects << r.translated(x[0], y[0]) << r.translated(x[1], y[1]); break; } case Clip: createRegion = true; break; case Size: case Scale: { createRegion = true; const QSize sz = entry.key()->geometry().size(); float fx = qMax(fixOvershoot(anim->from[0], *anim, 1), fixOvershoot(anim->to[0], *anim, 2)); // float fx = qMax(interpolated(*anim,0), anim->to[0]); if (fx >= 0.0) { if (anim->attribute == Size) fx /= sz.width(); f[0] *= fx; t[0] += geometryCompensation( anim->meta & AnimationEffect::Horizontal, fx ) * sz.width(); } // float fy = qMax(interpolated(*anim,1), anim->to[1]); float fy = qMax(fixOvershoot(anim->from[1], *anim, 1), fixOvershoot(anim->to[1], *anim, 2)); if (fy >= 0.0) { if (anim->attribute == Size) fy /= sz.height(); if (!anim->isOneDimensional()) { f[1] *= fy; t[1] += geometryCompensation( anim->meta & AnimationEffect::Vertical, fy ) * sz.height(); } else if ( ((anim->meta & AnimationEffect::Vertical)>>1) != (anim->meta & AnimationEffect::Horizontal) ) { f[1] *= fx; t[1] += geometryCompensation( anim->meta & AnimationEffect::Vertical, fx ) * sz.height(); } } break; } } } region_creation: if (createRegion) { const QRect geo = entry.key()->expandedGeometry(); if (rects.isEmpty()) rects << geo; QList::const_iterator r, rEnd = rects.constEnd(); for ( r = rects.constBegin(); r != rEnd; ++r) { // transform const_cast(&(*r))->setSize(QSize(qRound(r->width()*f[0]), qRound(r->height()*f[1]))); const_cast(&(*r))->translate(t[0], t[1]); // "const_cast" - don't do that at home, kids ;-) } QRect rect = rects.at(0); if (rects.count() > 1) { for ( r = rects.constBegin() + 1; r != rEnd; ++r) // unite rect |= *r; const int dx = 110*(rect.width() - geo.width())/100 + 1 - rect.width() + geo.width(); const int dy = 110*(rect.height() - geo.height())/100 + 1 - rect.height() + geo.height(); rect.adjust(-dx,-dy,dx,dy); // fix pot. overshoot } *layerRect = rect; } } d->m_damageDirty = false; } void AnimationEffect::_expandedGeometryChanged(KWin::EffectWindow *w, const QRect &old) { Q_UNUSED(old) Q_D(AnimationEffect); AniMap::const_iterator entry = d->m_animations.constFind(w); if (entry != d->m_animations.constEnd()) { *const_cast(&(entry->second)) = QRect(); updateLayerRepaints(); if (!entry->second.isNull()) // actually got updated, ie. is in use - ensure it get's a repaint w->addLayerRepaint(entry->second); } } void AnimationEffect::_windowClosed( EffectWindow* w ) { Q_D(AnimationEffect); auto it = d->m_animations.find(w); if (it == d->m_animations.end()) { return; } KeepAliveLockPtr keepAliveLock; QList &animations = (*it).first; for (auto animationIt = animations.begin(); animationIt != animations.end(); ++animationIt) { if (!(*animationIt).keepAlive) { continue; } if (keepAliveLock.isNull()) { keepAliveLock = KeepAliveLockPtr::create(w); } (*animationIt).keepAliveLock = keepAliveLock; } } void AnimationEffect::_windowDeleted( EffectWindow* w ) { Q_D(AnimationEffect); d->m_animations.remove( w ); } QString AnimationEffect::debug(const QString &/*parameter*/) const { Q_D(const AnimationEffect); QString dbg; if (d->m_animations.isEmpty()) dbg = QStringLiteral("No window is animated"); else { AniMap::const_iterator entry = d->m_animations.constBegin(), mapEnd = d->m_animations.constEnd(); for (; entry != mapEnd; ++entry) { QString caption = entry.key()->isDeleted() ? QStringLiteral("[Deleted]") : entry.key()->caption(); if (caption.isEmpty()) caption = QStringLiteral("[Untitled]"); dbg += QLatin1String("Animating window: ") + caption + QLatin1Char('\n'); QList::const_iterator anim = entry->first.constBegin(), animEnd = entry->first.constEnd(); for (; anim != animEnd; ++anim) dbg += anim->debugInfo(); } } return dbg; } AnimationEffect::AniMap AnimationEffect::state() const { Q_D(const AnimationEffect); return d->m_animations; } #include "moc_kwinanimationeffect.cpp" diff --git a/libkwineffects/kwinanimationeffect.h b/libkwineffects/kwinanimationeffect.h index 14471becc..debea6d0d 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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, const FPx2 &to, const QEasingCurve &curve = QEasingCurve(), int delay = 0, const 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, const FPx2 &to, const QEasingCurve &curve = QEasingCurve(), int delay = 0, const 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, const 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.cpp b/libkwineffects/kwineffects.cpp index 95e4b9ed8..7d398e52a 100644 --- a/libkwineffects/kwineffects.cpp +++ b/libkwineffects/kwineffects.cpp @@ -1,1944 +1,1944 @@ /******************************************************************** 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) 2018 Vlad Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 "kwineffects.h" #include "config-kwin.h" #ifdef KWIN_HAVE_XRENDER_COMPOSITING #include "kwinxrenderutils.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef KWIN_HAVE_XRENDER_COMPOSITING #include #endif #if defined(__SSE2__) # include #endif namespace KWin { void WindowPrePaintData::setTranslucent() { mask |= Effect::PAINT_WINDOW_TRANSLUCENT; mask &= ~Effect::PAINT_WINDOW_OPAQUE; clip = QRegion(); // cannot clip, will be transparent } void WindowPrePaintData::setTransformed() { mask |= Effect::PAINT_WINDOW_TRANSFORMED; } class PaintDataPrivate { public: QGraphicsScale scale; QVector3D translation; QGraphicsRotation rotation; }; PaintData::PaintData() : d(new PaintDataPrivate()) { } PaintData::~PaintData() { delete d; } qreal PaintData::xScale() const { return d->scale.xScale(); } qreal PaintData::yScale() const { return d->scale.yScale(); } qreal PaintData::zScale() const { return d->scale.zScale(); } void PaintData::setScale(const QVector2D &scale) { d->scale.setXScale(scale.x()); d->scale.setYScale(scale.y()); } void PaintData::setScale(const QVector3D &scale) { d->scale.setXScale(scale.x()); d->scale.setYScale(scale.y()); d->scale.setZScale(scale.z()); } void PaintData::setXScale(qreal scale) { d->scale.setXScale(scale); } void PaintData::setYScale(qreal scale) { d->scale.setYScale(scale); } void PaintData::setZScale(qreal scale) { d->scale.setZScale(scale); } const QGraphicsScale &PaintData::scale() const { return d->scale; } void PaintData::setXTranslation(qreal translate) { d->translation.setX(translate); } void PaintData::setYTranslation(qreal translate) { d->translation.setY(translate); } void PaintData::setZTranslation(qreal translate) { d->translation.setZ(translate); } void PaintData::translate(qreal x, qreal y, qreal z) { translate(QVector3D(x, y, z)); } void PaintData::translate(const QVector3D &t) { d->translation += t; } qreal PaintData::xTranslation() const { return d->translation.x(); } qreal PaintData::yTranslation() const { return d->translation.y(); } qreal PaintData::zTranslation() const { return d->translation.z(); } const QVector3D &PaintData::translation() const { return d->translation; } qreal PaintData::rotationAngle() const { return d->rotation.angle(); } QVector3D PaintData::rotationAxis() const { return d->rotation.axis(); } QVector3D PaintData::rotationOrigin() const { return d->rotation.origin(); } void PaintData::setRotationAngle(qreal angle) { d->rotation.setAngle(angle); } void PaintData::setRotationAxis(Qt::Axis axis) { d->rotation.setAxis(axis); } void PaintData::setRotationAxis(const QVector3D &axis) { d->rotation.setAxis(axis); } void PaintData::setRotationOrigin(const QVector3D &origin) { d->rotation.setOrigin(origin); } class WindowPaintDataPrivate { public: qreal opacity; qreal saturation; qreal brightness; int screen; qreal crossFadeProgress; QMatrix4x4 pMatrix; QMatrix4x4 mvMatrix; QMatrix4x4 screenProjectionMatrix; }; WindowPaintData::WindowPaintData(EffectWindow *w) : WindowPaintData(w, QMatrix4x4()) { } WindowPaintData::WindowPaintData(EffectWindow* w, const QMatrix4x4 &screenProjectionMatrix) : PaintData() , shader(nullptr) , d(new WindowPaintDataPrivate()) { d->screenProjectionMatrix = screenProjectionMatrix; quads = w->buildQuads(); setOpacity(w->opacity()); setSaturation(1.0); setBrightness(1.0); setScreen(0); setCrossFadeProgress(1.0); } WindowPaintData::WindowPaintData(const WindowPaintData &other) : PaintData() , quads(other.quads) , shader(other.shader) , d(new WindowPaintDataPrivate()) { setXScale(other.xScale()); setYScale(other.yScale()); setZScale(other.zScale()); translate(other.translation()); setRotationOrigin(other.rotationOrigin()); setRotationAxis(other.rotationAxis()); setRotationAngle(other.rotationAngle()); setOpacity(other.opacity()); setSaturation(other.saturation()); setBrightness(other.brightness()); setScreen(other.screen()); setCrossFadeProgress(other.crossFadeProgress()); setProjectionMatrix(other.projectionMatrix()); setModelViewMatrix(other.modelViewMatrix()); d->screenProjectionMatrix = other.d->screenProjectionMatrix; } WindowPaintData::~WindowPaintData() { delete d; } qreal WindowPaintData::opacity() const { return d->opacity; } qreal WindowPaintData::saturation() const { return d->saturation; } qreal WindowPaintData::brightness() const { return d->brightness; } int WindowPaintData::screen() const { return d->screen; } void WindowPaintData::setOpacity(qreal opacity) { d->opacity = opacity; } void WindowPaintData::setSaturation(qreal saturation) const { d->saturation = saturation; } void WindowPaintData::setBrightness(qreal brightness) { d->brightness = brightness; } void WindowPaintData::setScreen(int screen) const { d->screen = screen; } qreal WindowPaintData::crossFadeProgress() const { return d->crossFadeProgress; } void WindowPaintData::setCrossFadeProgress(qreal factor) { d->crossFadeProgress = qBound(qreal(0.0), factor, qreal(1.0)); } qreal WindowPaintData::multiplyOpacity(qreal factor) { d->opacity *= factor; return d->opacity; } qreal WindowPaintData::multiplySaturation(qreal factor) { d->saturation *= factor; return d->saturation; } qreal WindowPaintData::multiplyBrightness(qreal factor) { d->brightness *= factor; return d->brightness; } void WindowPaintData::setProjectionMatrix(const QMatrix4x4 &matrix) { d->pMatrix = matrix; } QMatrix4x4 WindowPaintData::projectionMatrix() const { return d->pMatrix; } QMatrix4x4 &WindowPaintData::rprojectionMatrix() { return d->pMatrix; } void WindowPaintData::setModelViewMatrix(const QMatrix4x4 &matrix) { d->mvMatrix = matrix; } QMatrix4x4 WindowPaintData::modelViewMatrix() const { return d->mvMatrix; } QMatrix4x4 &WindowPaintData::rmodelViewMatrix() { return d->mvMatrix; } WindowPaintData &WindowPaintData::operator*=(qreal scale) { this->setXScale(this->xScale() * scale); this->setYScale(this->yScale() * scale); this->setZScale(this->zScale() * scale); return *this; } WindowPaintData &WindowPaintData::operator*=(const QVector2D &scale) { this->setXScale(this->xScale() * scale.x()); this->setYScale(this->yScale() * scale.y()); return *this; } WindowPaintData &WindowPaintData::operator*=(const QVector3D &scale) { this->setXScale(this->xScale() * scale.x()); this->setYScale(this->yScale() * scale.y()); this->setZScale(this->zScale() * scale.z()); return *this; } WindowPaintData &WindowPaintData::operator+=(const QPointF &translation) { return this->operator+=(QVector3D(translation)); } WindowPaintData &WindowPaintData::operator+=(const QPoint &translation) { return this->operator+=(QVector3D(translation)); } WindowPaintData &WindowPaintData::operator+=(const QVector2D &translation) { return this->operator+=(QVector3D(translation)); } WindowPaintData &WindowPaintData::operator+=(const QVector3D &translation) { translate(translation); return *this; } QMatrix4x4 WindowPaintData::screenProjectionMatrix() const { return d->screenProjectionMatrix; } class ScreenPaintData::Private { public: QMatrix4x4 projectionMatrix; QRect outputGeometry; }; ScreenPaintData::ScreenPaintData() : PaintData() , d(new Private()) { } ScreenPaintData::ScreenPaintData(const QMatrix4x4 &projectionMatrix, const QRect &outputGeometry) : PaintData() , d(new Private()) { d->projectionMatrix = projectionMatrix; d->outputGeometry = outputGeometry; } ScreenPaintData::~ScreenPaintData() = default; ScreenPaintData::ScreenPaintData(const ScreenPaintData &other) : PaintData() , d(new Private()) { translate(other.translation()); setXScale(other.xScale()); setYScale(other.yScale()); setZScale(other.zScale()); setRotationOrigin(other.rotationOrigin()); setRotationAxis(other.rotationAxis()); setRotationAngle(other.rotationAngle()); d->projectionMatrix = other.d->projectionMatrix; d->outputGeometry = other.d->outputGeometry; } ScreenPaintData &ScreenPaintData::operator=(const ScreenPaintData &rhs) { setXScale(rhs.xScale()); setYScale(rhs.yScale()); setZScale(rhs.zScale()); setXTranslation(rhs.xTranslation()); setYTranslation(rhs.yTranslation()); setZTranslation(rhs.zTranslation()); setRotationOrigin(rhs.rotationOrigin()); setRotationAxis(rhs.rotationAxis()); setRotationAngle(rhs.rotationAngle()); d->projectionMatrix = rhs.d->projectionMatrix; d->outputGeometry = rhs.d->outputGeometry; return *this; } ScreenPaintData &ScreenPaintData::operator*=(qreal scale) { setXScale(this->xScale() * scale); setYScale(this->yScale() * scale); setZScale(this->zScale() * scale); return *this; } ScreenPaintData &ScreenPaintData::operator*=(const QVector2D &scale) { setXScale(this->xScale() * scale.x()); setYScale(this->yScale() * scale.y()); return *this; } ScreenPaintData &ScreenPaintData::operator*=(const QVector3D &scale) { setXScale(this->xScale() * scale.x()); setYScale(this->yScale() * scale.y()); setZScale(this->zScale() * scale.z()); return *this; } ScreenPaintData &ScreenPaintData::operator+=(const QPointF &translation) { return this->operator+=(QVector3D(translation)); } ScreenPaintData &ScreenPaintData::operator+=(const QPoint &translation) { return this->operator+=(QVector3D(translation)); } ScreenPaintData &ScreenPaintData::operator+=(const QVector2D &translation) { return this->operator+=(QVector3D(translation)); } ScreenPaintData &ScreenPaintData::operator+=(const QVector3D &translation) { translate(translation); return *this; } QMatrix4x4 ScreenPaintData::projectionMatrix() const { return d->projectionMatrix; } QRect ScreenPaintData::outputGeometry() const { return d->outputGeometry; } //**************************************** // Effect //**************************************** Effect::Effect() { } Effect::~Effect() { } void Effect::reconfigure(ReconfigureFlags) { } void* Effect::proxy() { return nullptr; } void Effect::windowInputMouseEvent(QEvent*) { } void Effect::grabbedKeyboardEvent(QKeyEvent*) { } bool Effect::borderActivated(ElectricBorder) { return false; } void Effect::prePaintScreen(ScreenPrePaintData& data, int time) { effects->prePaintScreen(data, time); } void Effect::paintScreen(int mask, const QRegion ®ion, ScreenPaintData& data) { effects->paintScreen(mask, region, data); } void Effect::postPaintScreen() { effects->postPaintScreen(); } void Effect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { effects->prePaintWindow(w, data, time); } void Effect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { effects->paintWindow(w, mask, region, data); } void Effect::postPaintWindow(EffectWindow* w) { effects->postPaintWindow(w); } void Effect::paintEffectFrame(KWin::EffectFrame* frame, const QRegion ®ion, double opacity, double frameOpacity) { effects->paintEffectFrame(frame, region, opacity, frameOpacity); } bool Effect::provides(Feature) { return false; } bool Effect::isActive() const { return true; } QString Effect::debug(const QString &) const { return QString(); } void Effect::drawWindow(EffectWindow* w, int mask, const QRegion ®ion, WindowPaintData& data) { effects->drawWindow(w, mask, region, data); } void Effect::buildQuads(EffectWindow* w, WindowQuadList& quadList) { effects->buildQuads(w, quadList); } void Effect::setPositionTransformations(WindowPaintData& data, QRect& region, EffectWindow* w, const QRect& r, Qt::AspectRatioMode aspect) { QSize size = w->size(); size.scale(r.size(), aspect); data.setXScale(size.width() / double(w->width())); data.setYScale(size.height() / double(w->height())); int width = int(w->width() * data.xScale()); int height = int(w->height() * data.yScale()); int x = r.x() + (r.width() - width) / 2; int y = r.y() + (r.height() - height) / 2; region = QRect(x, y, width, height); data.setXTranslation(x - w->x()); data.setYTranslation(y - w->y()); } QPoint Effect::cursorPos() { return effects->cursorPos(); } double Effect::animationTime(const KConfigGroup& cfg, const QString& key, int defaultTime) { int time = cfg.readEntry(key, 0); return time != 0 ? time : qMax(defaultTime * effects->animationTimeFactor(), 1.); } double Effect::animationTime(int defaultTime) { // at least 1ms, otherwise 0ms times can break some things return qMax(defaultTime * effects->animationTimeFactor(), 1.); } int Effect::requestedEffectChainPosition() const { return 0; } xcb_connection_t *Effect::xcbConnection() const { return effects->xcbConnection(); } xcb_window_t Effect::x11RootWindow() const { return effects->x11RootWindow(); } bool Effect::touchDown(qint32 id, const QPointF &pos, quint32 time) { Q_UNUSED(id) Q_UNUSED(pos) Q_UNUSED(time) return false; } bool Effect::touchMotion(qint32 id, const QPointF &pos, quint32 time) { Q_UNUSED(id) Q_UNUSED(pos) Q_UNUSED(time) return false; } bool Effect::touchUp(qint32 id, quint32 time) { Q_UNUSED(id) Q_UNUSED(time) return false; } bool Effect::perform(Feature feature, const QVariantList &arguments) { Q_UNUSED(feature) Q_UNUSED(arguments) return false; } //**************************************** // EffectFactory //**************************************** EffectPluginFactory::EffectPluginFactory() { } EffectPluginFactory::~EffectPluginFactory() { } bool EffectPluginFactory::enabledByDefault() const { return true; } bool EffectPluginFactory::isSupported() const { return true; } //**************************************** // EffectsHandler //**************************************** EffectsHandler::EffectsHandler(CompositingType type) : compositing_type(type) { if (compositing_type == NoCompositing) return; KWin::effects = this; } EffectsHandler::~EffectsHandler() { // All effects should already be unloaded by Impl dtor Q_ASSERT(loaded_effects.count() == 0); KWin::effects = nullptr; } CompositingType EffectsHandler::compositingType() const { return compositing_type; } bool EffectsHandler::isOpenGLCompositing() const { return compositing_type & OpenGLCompositing; } EffectsHandler* effects = nullptr; //**************************************** // EffectWindow //**************************************** class Q_DECL_HIDDEN EffectWindow::Private { public: Private(EffectWindow *q); EffectWindow *q; }; EffectWindow::Private::Private(EffectWindow *q) : q(q) { } EffectWindow::EffectWindow(QObject *parent) : QObject(parent) , d(new Private(this)) { } EffectWindow::~EffectWindow() { } bool EffectWindow::isOnActivity(const QString &activity) const { const QStringList _activities = activities(); return _activities.isEmpty() || _activities.contains(activity); } bool EffectWindow::isOnAllActivities() const { return activities().isEmpty(); } void EffectWindow::setMinimized(bool min) { if (min) { minimize(); } else { unminimize(); } } bool EffectWindow::isOnCurrentActivity() const { return isOnActivity(effects->currentActivity()); } bool EffectWindow::isOnCurrentDesktop() const { return isOnDesktop(effects->currentDesktop()); } bool EffectWindow::isOnDesktop(int d) const { const QVector ds = desktops(); return ds.isEmpty() || ds.contains(d); } bool EffectWindow::isOnAllDesktops() const { return desktops().isEmpty(); } bool EffectWindow::hasDecoration() const { return contentsRect() != QRect(0, 0, width(), height()); } bool EffectWindow::isVisible() const { return !isMinimized() && isOnCurrentDesktop() && isOnCurrentActivity(); } //**************************************** // EffectWindowGroup //**************************************** EffectWindowGroup::~EffectWindowGroup() { } /*************************************************************** WindowQuad ***************************************************************/ WindowQuad WindowQuad::makeSubQuad(double x1, double y1, double x2, double y2) const { Q_ASSERT(x1 < x2 && y1 < y2 && x1 >= left() && x2 <= right() && y1 >= top() && y2 <= bottom()); #if !defined(QT_NO_DEBUG) if (isTransformed()) qFatal("Splitting quads is allowed only in pre-paint calls!"); #endif WindowQuad ret(*this); // vertices are clockwise starting from topleft ret.verts[ 0 ].px = x1; ret.verts[ 3 ].px = x1; ret.verts[ 1 ].px = x2; ret.verts[ 2 ].px = x2; ret.verts[ 0 ].py = y1; ret.verts[ 1 ].py = y1; ret.verts[ 2 ].py = y2; ret.verts[ 3 ].py = y2; // original x/y are supposed to be the same, no transforming is done here ret.verts[ 0 ].ox = x1; ret.verts[ 3 ].ox = x1; ret.verts[ 1 ].ox = x2; ret.verts[ 2 ].ox = x2; ret.verts[ 0 ].oy = y1; ret.verts[ 1 ].oy = y1; ret.verts[ 2 ].oy = y2; ret.verts[ 3 ].oy = y2; const double my_u0 = verts[0].tx; const double my_u1 = verts[2].tx; const double my_v0 = verts[0].ty; const double my_v1 = verts[2].ty; const double width = right() - left(); const double height = bottom() - top(); const double texWidth = my_u1 - my_u0; const double texHeight = my_v1 - my_v0; if (!uvAxisSwapped()) { const double u0 = (x1 - left()) / width * texWidth + my_u0; const double u1 = (x2 - left()) / width * texWidth + my_u0; const double v0 = (y1 - top()) / height * texHeight + my_v0; const double v1 = (y2 - top()) / height * texHeight + my_v0; ret.verts[0].tx = u0; ret.verts[3].tx = u0; ret.verts[1].tx = u1; ret.verts[2].tx = u1; ret.verts[0].ty = v0; ret.verts[1].ty = v0; ret.verts[2].ty = v1; ret.verts[3].ty = v1; } else { const double u0 = (y1 - top()) / height * texWidth + my_u0; const double u1 = (y2 - top()) / height * texWidth + my_u0; const double v0 = (x1 - left()) / width * texHeight + my_v0; const double v1 = (x2 - left()) / width * texHeight + my_v0; ret.verts[0].tx = u0; ret.verts[1].tx = u0; ret.verts[2].tx = u1; ret.verts[3].tx = u1; ret.verts[0].ty = v0; ret.verts[3].ty = v0; ret.verts[1].ty = v1; ret.verts[2].ty = v1; } ret.setUVAxisSwapped(uvAxisSwapped()); return ret; } bool WindowQuad::smoothNeeded() const { // smoothing is needed if the width or height of the quad does not match the original size double width = verts[ 1 ].ox - verts[ 0 ].ox; double height = verts[ 2 ].oy - verts[ 1 ].oy; return(verts[ 1 ].px - verts[ 0 ].px != width || verts[ 2 ].px - verts[ 3 ].px != width || verts[ 2 ].py - verts[ 1 ].py != height || verts[ 3 ].py - verts[ 0 ].py != height); } /*************************************************************** WindowQuadList ***************************************************************/ WindowQuadList WindowQuadList::splitAtX(double x) const { WindowQuadList ret; foreach (const WindowQuad & quad, *this) { #if !defined(QT_NO_DEBUG) if (quad.isTransformed()) qFatal("Splitting quads is allowed only in pre-paint calls!"); #endif bool wholeleft = true; bool wholeright = true; for (int i = 0; i < 4; ++i) { if (quad[ i ].x() < x) wholeright = false; if (quad[ i ].x() > x) wholeleft = false; } if (wholeleft || wholeright) { // is whole in one split part ret.append(quad); continue; } if (quad.top() == quad.bottom() || quad.left() == quad.right()) { // quad has no size ret.append(quad); continue; } ret.append(quad.makeSubQuad(quad.left(), quad.top(), x, quad.bottom())); ret.append(quad.makeSubQuad(x, quad.top(), quad.right(), quad.bottom())); } return ret; } WindowQuadList WindowQuadList::splitAtY(double y) const { WindowQuadList ret; foreach (const WindowQuad & quad, *this) { #if !defined(QT_NO_DEBUG) if (quad.isTransformed()) qFatal("Splitting quads is allowed only in pre-paint calls!"); #endif bool wholetop = true; bool wholebottom = true; for (int i = 0; i < 4; ++i) { if (quad[ i ].y() < y) wholebottom = false; if (quad[ i ].y() > y) wholetop = false; } if (wholetop || wholebottom) { // is whole in one split part ret.append(quad); continue; } if (quad.top() == quad.bottom() || quad.left() == quad.right()) { // quad has no size ret.append(quad); continue; } ret.append(quad.makeSubQuad(quad.left(), quad.top(), quad.right(), y)); ret.append(quad.makeSubQuad(quad.left(), y, quad.right(), quad.bottom())); } return ret; } WindowQuadList WindowQuadList::makeGrid(int maxQuadSize) const { if (empty()) return *this; // Find the bounding rectangle double left = first().left(); double right = first().right(); double top = first().top(); double bottom = first().bottom(); foreach (const WindowQuad &quad, *this) { #if !defined(QT_NO_DEBUG) if (quad.isTransformed()) qFatal("Splitting quads is allowed only in pre-paint calls!"); #endif left = qMin(left, quad.left()); right = qMax(right, quad.right()); top = qMin(top, quad.top()); bottom = qMax(bottom, quad.bottom()); } WindowQuadList ret; foreach (const WindowQuad &quad, *this) { const double quadLeft = quad.left(); const double quadRight = quad.right(); const double quadTop = quad.top(); const double quadBottom = quad.bottom(); // sanity check, see BUG 390953 if (quadLeft == quadRight || quadTop == quadBottom) { ret.append(quad); continue; } // Compute the top-left corner of the first intersecting grid cell const double xBegin = left + qFloor((quadLeft - left) / maxQuadSize) * maxQuadSize; const double yBegin = top + qFloor((quadTop - top) / maxQuadSize) * maxQuadSize; // Loop over all intersecting cells and add sub-quads for (double y = yBegin; y < quadBottom; y += maxQuadSize) { const double y0 = qMax(y, quadTop); const double y1 = qMin(quadBottom, y + maxQuadSize); for (double x = xBegin; x < quadRight; x += maxQuadSize) { const double x0 = qMax(x, quadLeft); const double x1 = qMin(quadRight, x + maxQuadSize); ret.append(quad.makeSubQuad(x0, y0, x1, y1)); } } } return ret; } WindowQuadList WindowQuadList::makeRegularGrid(int xSubdivisions, int ySubdivisions) const { if (empty()) return *this; // Find the bounding rectangle double left = first().left(); double right = first().right(); double top = first().top(); double bottom = first().bottom(); foreach (const WindowQuad &quad, *this) { #if !defined(QT_NO_DEBUG) if (quad.isTransformed()) qFatal("Splitting quads is allowed only in pre-paint calls!"); #endif left = qMin(left, quad.left()); right = qMax(right, quad.right()); top = qMin(top, quad.top()); bottom = qMax(bottom, quad.bottom()); } double xIncrement = (right - left) / xSubdivisions; double yIncrement = (bottom - top) / ySubdivisions; WindowQuadList ret; foreach (const WindowQuad &quad, *this) { const double quadLeft = quad.left(); const double quadRight = quad.right(); const double quadTop = quad.top(); const double quadBottom = quad.bottom(); // sanity check, see BUG 390953 if (quadLeft == quadRight || quadTop == quadBottom) { ret.append(quad); continue; } // Compute the top-left corner of the first intersecting grid cell const double xBegin = left + qFloor((quadLeft - left) / xIncrement) * xIncrement; const double yBegin = top + qFloor((quadTop - top) / yIncrement) * yIncrement; // Loop over all intersecting cells and add sub-quads for (double y = yBegin; y < quadBottom; y += yIncrement) { const double y0 = qMax(y, quadTop); const double y1 = qMin(quadBottom, y + yIncrement); for (double x = xBegin; x < quadRight; x += xIncrement) { const double x0 = qMax(x, quadLeft); const double x1 = qMin(quadRight, x + xIncrement); ret.append(quad.makeSubQuad(x0, y0, x1, y1)); } } } return ret; } #ifndef GL_TRIANGLES # define GL_TRIANGLES 0x0004 #endif #ifndef GL_QUADS # define GL_QUADS 0x0007 #endif void WindowQuadList::makeInterleavedArrays(unsigned int type, GLVertex2D *vertices, const QMatrix4x4 &textureMatrix) const { // Since we know that the texture matrix just scales and translates // we can use this information to optimize the transformation const QVector2D coeff(textureMatrix(0, 0), textureMatrix(1, 1)); const QVector2D offset(textureMatrix(0, 3), textureMatrix(1, 3)); GLVertex2D *vertex = vertices; Q_ASSERT(type == GL_QUADS || type == GL_TRIANGLES); switch (type) { case GL_QUADS: #if defined(__SSE2__) if (!(intptr_t(vertex) & 0xf)) { for (int i = 0; i < count(); i++) { const WindowQuad &quad = at(i); alignas(16) GLVertex2D v[4]; for (int j = 0; j < 4; j++) { const WindowVertex &wv = quad[j]; v[j].position = QVector2D(wv.x(), wv.y()); v[j].texcoord = QVector2D(wv.u(), wv.v()) * coeff + offset; } const __m128i *srcP = reinterpret_cast(&v); __m128i *dstP = reinterpret_cast<__m128i *>(vertex); _mm_stream_si128(&dstP[0], _mm_load_si128(&srcP[0])); // Top-left _mm_stream_si128(&dstP[1], _mm_load_si128(&srcP[1])); // Top-right _mm_stream_si128(&dstP[2], _mm_load_si128(&srcP[2])); // Bottom-right _mm_stream_si128(&dstP[3], _mm_load_si128(&srcP[3])); // Bottom-left vertex += 4; } } else #endif // __SSE2__ { for (int i = 0; i < count(); i++) { const WindowQuad &quad = at(i); for (int j = 0; j < 4; j++) { const WindowVertex &wv = quad[j]; GLVertex2D v; v.position = QVector2D(wv.x(), wv.y()); v.texcoord = QVector2D(wv.u(), wv.v()) * coeff + offset; *(vertex++) = v; } } } break; case GL_TRIANGLES: #if defined(__SSE2__) if (!(intptr_t(vertex) & 0xf)) { for (int i = 0; i < count(); i++) { const WindowQuad &quad = at(i); alignas(16) GLVertex2D v[4]; for (int j = 0; j < 4; j++) { const WindowVertex &wv = quad[j]; v[j].position = QVector2D(wv.x(), wv.y()); v[j].texcoord = QVector2D(wv.u(), wv.v()) * coeff + offset; } const __m128i *srcP = reinterpret_cast(&v); __m128i *dstP = reinterpret_cast<__m128i *>(vertex); __m128i src[4]; src[0] = _mm_load_si128(&srcP[0]); // Top-left src[1] = _mm_load_si128(&srcP[1]); // Top-right src[2] = _mm_load_si128(&srcP[2]); // Bottom-right src[3] = _mm_load_si128(&srcP[3]); // Bottom-left // First triangle _mm_stream_si128(&dstP[0], src[1]); // Top-right _mm_stream_si128(&dstP[1], src[0]); // Top-left _mm_stream_si128(&dstP[2], src[3]); // Bottom-left // Second triangle _mm_stream_si128(&dstP[3], src[3]); // Bottom-left _mm_stream_si128(&dstP[4], src[2]); // Bottom-right _mm_stream_si128(&dstP[5], src[1]); // Top-right vertex += 6; } } else #endif // __SSE2__ { for (int i = 0; i < count(); i++) { const WindowQuad &quad = at(i); GLVertex2D v[4]; // Four unique vertices / quad for (int j = 0; j < 4; j++) { const WindowVertex &wv = quad[j]; v[j].position = QVector2D(wv.x(), wv.y()); v[j].texcoord = QVector2D(wv.u(), wv.v()) * coeff + offset; } // First triangle *(vertex++) = v[1]; // Top-right *(vertex++) = v[0]; // Top-left *(vertex++) = v[3]; // Bottom-left // Second triangle *(vertex++) = v[3]; // Bottom-left *(vertex++) = v[2]; // Bottom-right *(vertex++) = v[1]; // Top-right } } break; default: break; } } void WindowQuadList::makeArrays(float **vertices, float **texcoords, const QSizeF &size, bool yInverted) const { *vertices = new float[count() * 6 * 2]; *texcoords = new float[count() * 6 * 2]; float *vpos = *vertices; float *tpos = *texcoords; // Note: The positions in a WindowQuad are stored in clockwise order const int index[] = { 1, 0, 3, 3, 2, 1 }; for (int i = 0; i < count(); i++) { const WindowQuad &quad = at(i); for (int j = 0; j < 6; j++) { const WindowVertex &wv = quad[index[j]]; *vpos++ = wv.x(); *vpos++ = wv.y(); *tpos++ = wv.u() / size.width(); *tpos++ = yInverted ? (wv.v() / size.height()) : (1.0 - wv.v() / size.height()); } } } WindowQuadList WindowQuadList::select(WindowQuadType type) const { foreach (const WindowQuad & q, *this) { if (q.type() != type) { // something else than ones to select, make a copy and filter WindowQuadList ret; foreach (const WindowQuad & q, *this) { if (q.type() == type) ret.append(q); } return ret; } } return *this; // nothing to filter out } WindowQuadList WindowQuadList::filterOut(WindowQuadType type) const { foreach (const WindowQuad & q, *this) { if (q.type() == type) { // something to filter out, make a copy and filter WindowQuadList ret; foreach (const WindowQuad & q, *this) { if (q.type() != type) ret.append(q); } return ret; } } return *this; // nothing to filter out } bool WindowQuadList::smoothNeeded() const { foreach (const WindowQuad & q, *this) if (q.smoothNeeded()) return true; return false; } bool WindowQuadList::isTransformed() const { foreach (const WindowQuad & q, *this) if (q.isTransformed()) return true; return false; } /*************************************************************** PaintClipper ***************************************************************/ QStack< QRegion >* PaintClipper::areas = nullptr; PaintClipper::PaintClipper(const QRegion& allowed_area) : area(allowed_area) { push(area); } PaintClipper::~PaintClipper() { pop(area); } void PaintClipper::push(const QRegion& allowed_area) { if (allowed_area == infiniteRegion()) // don't push these return; if (areas == nullptr) areas = new QStack< QRegion >; areas->push(allowed_area); } void PaintClipper::pop(const QRegion& allowed_area) { if (allowed_area == infiniteRegion()) return; Q_ASSERT(areas != nullptr); Q_ASSERT(areas->top() == allowed_area); areas->pop(); if (areas->isEmpty()) { delete areas; areas = nullptr; } } bool PaintClipper::clip() { return areas != nullptr; } QRegion PaintClipper::paintArea() { Q_ASSERT(areas != nullptr); // can be called only with clip() == true const QSize &s = effects->virtualScreenSize(); QRegion ret = QRegion(0, 0, s.width(), s.height()); foreach (const QRegion & r, *areas) ret &= r; return ret; } struct PaintClipper::Iterator::Data { Data() : index(0) {} int index; QRegion region; }; PaintClipper::Iterator::Iterator() : data(new Data) { if (clip() && effects->isOpenGLCompositing()) { data->region = paintArea(); data->index = -1; next(); // move to the first one } #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (clip() && effects->compositingType() == XRenderCompositing) { XFixesRegion region(paintArea()); xcb_xfixes_set_picture_clip_region(connection(), effects->xrenderBufferPicture(), region, 0, 0); } #endif } PaintClipper::Iterator::~Iterator() { #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (clip() && effects->compositingType() == XRenderCompositing) xcb_xfixes_set_picture_clip_region(connection(), effects->xrenderBufferPicture(), XCB_XFIXES_REGION_NONE, 0, 0); #endif delete data; } bool PaintClipper::Iterator::isDone() { if (!clip()) return data->index == 1; // run once if (effects->isOpenGLCompositing()) return data->index >= data->region.rectCount(); // run once per each area #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (effects->compositingType() == XRenderCompositing) return data->index == 1; // run once #endif abort(); } void PaintClipper::Iterator::next() { data->index++; } QRect PaintClipper::Iterator::boundingRect() const { if (!clip()) return infiniteRegion(); if (effects->isOpenGLCompositing()) return *(data->region.begin() + data->index); #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (effects->compositingType() == XRenderCompositing) return data->region.boundingRect(); #endif abort(); return infiniteRegion(); } /*************************************************************** Motion1D ***************************************************************/ Motion1D::Motion1D(double initial, double strength, double smoothness) : Motion(initial, strength, smoothness) { } Motion1D::Motion1D(const Motion1D &other) : Motion(other) { } Motion1D::~Motion1D() { } /*************************************************************** Motion2D ***************************************************************/ Motion2D::Motion2D(QPointF initial, double strength, double smoothness) : Motion(initial, strength, smoothness) { } Motion2D::Motion2D(const Motion2D &other) : Motion(other) { } Motion2D::~Motion2D() { } /*************************************************************** WindowMotionManager ***************************************************************/ WindowMotionManager::WindowMotionManager(bool useGlobalAnimationModifier) : m_useGlobalAnimationModifier(useGlobalAnimationModifier) { // TODO: Allow developer to modify motion attributes } // TODO: What happens when the window moves by an external force? WindowMotionManager::~WindowMotionManager() { } void WindowMotionManager::manage(EffectWindow *w) { if (m_managedWindows.contains(w)) return; double strength = 0.08; double smoothness = 4.0; if (m_useGlobalAnimationModifier && effects->animationTimeFactor()) { // If the factor is == 0 then we just skip the calculation completely strength = 0.08 / effects->animationTimeFactor(); smoothness = effects->animationTimeFactor() * 4.0; } WindowMotion &motion = m_managedWindows[ w ]; motion.translation.setStrength(strength); motion.translation.setSmoothness(smoothness); motion.scale.setStrength(strength * 1.33); motion.scale.setSmoothness(smoothness / 2.0); motion.translation.setValue(w->pos()); motion.scale.setValue(QPointF(1.0, 1.0)); } void WindowMotionManager::unmanage(EffectWindow *w) { m_movingWindowsSet.remove(w); m_managedWindows.remove(w); } void WindowMotionManager::unmanageAll() { m_managedWindows.clear(); m_movingWindowsSet.clear(); } void WindowMotionManager::calculate(int time) { if (!effects->animationTimeFactor()) { // Just skip it completely if the user wants no animation m_movingWindowsSet.clear(); QHash::iterator it = m_managedWindows.begin(); for (; it != m_managedWindows.end(); ++it) { WindowMotion *motion = &it.value(); motion->translation.finish(); motion->scale.finish(); } } QHash::iterator it = m_managedWindows.begin(); for (; it != m_managedWindows.end(); ++it) { WindowMotion *motion = &it.value(); int stopped = 0; // TODO: What happens when distance() == 0 but we are still moving fast? // TODO: Motion needs to be calculated from the window's center Motion2D *trans = &motion->translation; if (trans->distance().isNull()) ++stopped; else { // Still moving trans->calculate(time); const short fx = trans->target().x() <= trans->startValue().x() ? -1 : 1; const short fy = trans->target().y() <= trans->startValue().y() ? -1 : 1; if (trans->distance().x()*fx/0.5 < 1.0 && trans->velocity().x()*fx/0.2 < 1.0 && trans->distance().y()*fy/0.5 < 1.0 && trans->velocity().y()*fy/0.2 < 1.0) { // Hide tiny oscillations motion->translation.finish(); ++stopped; } } Motion2D *scale = &motion->scale; if (scale->distance().isNull()) ++stopped; else { // Still scaling scale->calculate(time); const short fx = scale->target().x() < 1.0 ? -1 : 1; const short fy = scale->target().y() < 1.0 ? -1 : 1; if (scale->distance().x()*fx/0.001 < 1.0 && scale->velocity().x()*fx/0.05 < 1.0 && scale->distance().y()*fy/0.001 < 1.0 && scale->velocity().y()*fy/0.05 < 1.0) { // Hide tiny oscillations motion->scale.finish(); ++stopped; } } // We just finished this window's motion if (stopped == 2) m_movingWindowsSet.remove(it.key()); } } void WindowMotionManager::reset() { QHash::iterator it = m_managedWindows.begin(); for (; it != m_managedWindows.end(); ++it) { WindowMotion *motion = &it.value(); EffectWindow *window = it.key(); motion->translation.setTarget(window->pos()); motion->translation.finish(); motion->scale.setTarget(QPointF(1.0, 1.0)); motion->scale.finish(); } } void WindowMotionManager::reset(EffectWindow *w) { QHash::iterator it = m_managedWindows.find(w); if (it == m_managedWindows.end()) return; WindowMotion *motion = &it.value(); motion->translation.setTarget(w->pos()); motion->translation.finish(); motion->scale.setTarget(QPointF(1.0, 1.0)); motion->scale.finish(); } void WindowMotionManager::apply(EffectWindow *w, WindowPaintData &data) { QHash::iterator it = m_managedWindows.find(w); if (it == m_managedWindows.end()) return; // TODO: Take into account existing scale so that we can work with multiple managers (E.g. Present windows + grid) WindowMotion *motion = &it.value(); data += (motion->translation.value() - QPointF(w->x(), w->y())); data *= QVector2D(motion->scale.value()); } void WindowMotionManager::moveWindow(EffectWindow *w, QPoint target, double scale, double yScale) { QHash::iterator it = m_managedWindows.find(w); if (it == m_managedWindows.end()) abort(); // Notify the effect author that they did something wrong WindowMotion *motion = &it.value(); if (yScale == 0.0) yScale = scale; QPointF scalePoint(scale, yScale); if (motion->translation.value() == target && motion->scale.value() == scalePoint) return; // Window already at that position motion->translation.setTarget(target); motion->scale.setTarget(scalePoint); m_movingWindowsSet << w; } QRectF WindowMotionManager::transformedGeometry(EffectWindow *w) const { QHash::const_iterator it = m_managedWindows.constFind(w); if (it == m_managedWindows.end()) return w->geometry(); const WindowMotion *motion = &it.value(); QRectF geometry(w->geometry()); // TODO: Take into account existing scale so that we can work with multiple managers (E.g. Present windows + grid) geometry.moveTo(motion->translation.value()); geometry.setWidth(geometry.width() * motion->scale.value().x()); geometry.setHeight(geometry.height() * motion->scale.value().y()); return geometry; } void WindowMotionManager::setTransformedGeometry(EffectWindow *w, const QRectF &geometry) { QHash::iterator it = m_managedWindows.find(w); if (it == m_managedWindows.end()) return; WindowMotion *motion = &it.value(); motion->translation.setValue(geometry.topLeft()); motion->scale.setValue(QPointF(geometry.width() / qreal(w->width()), geometry.height() / qreal(w->height()))); } QRectF WindowMotionManager::targetGeometry(EffectWindow *w) const { QHash::const_iterator it = m_managedWindows.constFind(w); if (it == m_managedWindows.end()) return w->geometry(); const WindowMotion *motion = &it.value(); QRectF geometry(w->geometry()); // TODO: Take into account existing scale so that we can work with multiple managers (E.g. Present windows + grid) geometry.moveTo(motion->translation.target()); geometry.setWidth(geometry.width() * motion->scale.target().x()); geometry.setHeight(geometry.height() * motion->scale.target().y()); return geometry; } EffectWindow* WindowMotionManager::windowAtPoint(QPoint point, bool useStackingOrder) const { Q_UNUSED(useStackingOrder); // TODO: Stacking order uses EffectsHandler::stackingOrder() then filters by m_managedWindows QHash< EffectWindow*, WindowMotion >::ConstIterator it = m_managedWindows.constBegin(); while (it != m_managedWindows.constEnd()) { if (transformedGeometry(it.key()).contains(point)) return it.key(); ++it; } return nullptr; } /*************************************************************** EffectFramePrivate ***************************************************************/ class EffectFramePrivate { public: EffectFramePrivate(); ~EffectFramePrivate(); bool crossFading; qreal crossFadeProgress; QMatrix4x4 screenProjectionMatrix; }; EffectFramePrivate::EffectFramePrivate() : crossFading(false) , crossFadeProgress(1.0) { } EffectFramePrivate::~EffectFramePrivate() { } /*************************************************************** EffectFrame ***************************************************************/ EffectFrame::EffectFrame() : d(new EffectFramePrivate) { } EffectFrame::~EffectFrame() { delete d; } qreal EffectFrame::crossFadeProgress() const { return d->crossFadeProgress; } void EffectFrame::setCrossFadeProgress(qreal progress) { d->crossFadeProgress = progress; } bool EffectFrame::isCrossFade() const { return d->crossFading; } void EffectFrame::enableCrossFade(bool enable) { d->crossFading = enable; } QMatrix4x4 EffectFrame::screenProjectionMatrix() const { return d->screenProjectionMatrix; } void EffectFrame::setScreenProjectionMatrix(const QMatrix4x4 &spm) { d->screenProjectionMatrix = spm; } /*************************************************************** TimeLine ***************************************************************/ class Q_DECL_HIDDEN TimeLine::Data : public QSharedData { public: std::chrono::milliseconds duration; Direction direction; QEasingCurve easingCurve; std::chrono::milliseconds elapsed = std::chrono::milliseconds::zero(); bool done = false; RedirectMode sourceRedirectMode = RedirectMode::Relaxed; RedirectMode targetRedirectMode = RedirectMode::Strict; }; TimeLine::TimeLine(std::chrono::milliseconds duration, Direction direction) : d(new Data) { Q_ASSERT(duration > std::chrono::milliseconds::zero()); d->duration = duration; d->direction = direction; } TimeLine::TimeLine(const TimeLine &other) : d(other.d) { } TimeLine::~TimeLine() = default; qreal TimeLine::progress() const { return static_cast(d->elapsed.count()) / d->duration.count(); } qreal TimeLine::value() const { const qreal t = progress(); return d->easingCurve.valueForProgress( d->direction == Backward ? 1.0 - t : t); } void TimeLine::update(std::chrono::milliseconds delta) { Q_ASSERT(delta >= std::chrono::milliseconds::zero()); if (d->done) { return; } d->elapsed += delta; if (d->elapsed >= d->duration) { d->done = true; d->elapsed = d->duration; } } std::chrono::milliseconds TimeLine::elapsed() const { return d->elapsed; } void TimeLine::setElapsed(std::chrono::milliseconds elapsed) { Q_ASSERT(elapsed >= std::chrono::milliseconds::zero()); if (elapsed == d->elapsed) { return; } reset(); update(elapsed); } std::chrono::milliseconds TimeLine::duration() const { return d->duration; } void TimeLine::setDuration(std::chrono::milliseconds duration) { Q_ASSERT(duration > std::chrono::milliseconds::zero()); if (duration == d->duration) { return; } d->elapsed = std::chrono::milliseconds(qRound(progress() * duration.count())); d->duration = duration; if (d->elapsed == d->duration) { d->done = true; } } TimeLine::Direction TimeLine::direction() const { return d->direction; } void TimeLine::setDirection(TimeLine::Direction direction) { if (d->direction == direction) { return; } d->direction = direction; if (d->elapsed > std::chrono::milliseconds::zero() || d->sourceRedirectMode == RedirectMode::Strict) { d->elapsed = d->duration - d->elapsed; } if (d->done && d->targetRedirectMode == RedirectMode::Relaxed) { d->done = false; } if (d->elapsed >= d->duration) { d->done = true; } } void TimeLine::toggleDirection() { setDirection(d->direction == Forward ? Backward : Forward); } QEasingCurve TimeLine::easingCurve() const { return d->easingCurve; } void TimeLine::setEasingCurve(const QEasingCurve &easingCurve) { d->easingCurve = easingCurve; } void TimeLine::setEasingCurve(QEasingCurve::Type type) { d->easingCurve.setType(type); } bool TimeLine::running() const { return d->elapsed != std::chrono::milliseconds::zero() && d->elapsed != d->duration; } bool TimeLine::done() const { return d->done; } void TimeLine::reset() { d->elapsed = std::chrono::milliseconds::zero(); d->done = false; } TimeLine::RedirectMode TimeLine::sourceRedirectMode() const { return d->sourceRedirectMode; } void TimeLine::setSourceRedirectMode(RedirectMode mode) { d->sourceRedirectMode = mode; } TimeLine::RedirectMode TimeLine::targetRedirectMode() const { return d->targetRedirectMode; } void TimeLine::setTargetRedirectMode(RedirectMode mode) { d->targetRedirectMode = mode; } TimeLine &TimeLine::operator=(const TimeLine &other) { d = other.d; return *this; } } // namespace #include "moc_kwinglobals.cpp" diff --git a/libkwineffects/kwineffects.h b/libkwineffects/kwineffects.h index e3d25d633..7bac73f49 100644 --- a/libkwineffects/kwineffects.h +++ b/libkwineffects/kwineffects.h @@ -1,4012 +1,4012 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2018 Vlad Zahorodnii 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 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 EffectQuickView; 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 229 #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, const QRegion ®ion, 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, const QRegion ®ion, 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, const QRegion ®ion, 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(qint32 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(qint32 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(qint32 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) /** * The status of the session i.e if the user is logging out * @since 5.18 */ Q_PROPERTY(KWin::SessionState sessionState READ sessionState NOTIFY sessionStateChanged) 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, const QRegion ®ion, ScreenPaintData& data) = 0; virtual void postPaintScreen() = 0; virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) = 0; virtual void paintWindow(EffectWindow* w, int mask, const QRegion ®ion, WindowPaintData& data) = 0; virtual void postPaintWindow(EffectWindow* w) = 0; virtual void paintEffectFrame(EffectFrame* frame, const QRegion ®ion, double opacity, double frameOpacity) = 0; virtual void drawWindow(EffectWindow* w, int mask, const QRegion ®ion, 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; /** * Render the supplied EffectQuickView onto the scene * It can be called at any point during the scene rendering * @since 5.18 */ virtual void renderEffectQuickView(EffectQuickView *effectQuickView) const = 0; /** * The status of the session i.e if the user is logging out * @since 5.18 */ virtual SessionState sessionState() 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); /** * This signal is emitted when the session state was changed * @since 5.18 */ void sessionStateChanged(); 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) /** * The PID of the application this window belongs to. * * @since 5.18 */ 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, /** Deprecated, tab groups have been removed: 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(const 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 makes 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; /** * @deprecated Use frameGeometry() instead. */ virtual QRect geometry() const = 0; /** * Returns the geometry of the window excluding server-side and client-side * drop-shadows. * * @since 5.18 */ virtual QRect frameGeometry() const = 0; /** * Returns the geometry of the pixmap or buffer attached to this window. * * For X11 clients, this method returns server-side geometry of the Toplevel. * * For Wayland clients, this method returns rectangle that the main surface * occupies on the screen, in global screen coordinates. * * @since 5.18 */ virtual QRect bufferGeometry() 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; /// deprecated 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; /** * @since 5.18 */ virtual pid_t pid() 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(const 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(const QRegion ®ion = 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) { Q_ASSERT(index >= 0 && index < 4); return verts[ index ]; } inline const WindowVertex& WindowQuad::operator[](int index) const { Q_ASSERT(index >= 0 && index < 4); return verts[ index ]; } inline WindowQuadType WindowQuad::type() const { Q_ASSERT(quadType != WindowQuadError); return quadType; } inline int WindowQuad::id() const { return quadID; } inline bool WindowQuad::decoration() const { Q_ASSERT(quadType != WindowQuadError); return quadType == WindowQuadDecoration; } inline bool WindowQuad::effect() const { Q_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/main.cpp b/main.cpp index 0907eeee4..587b02e7e 100644 --- a/main.cpp +++ b/main.cpp @@ -1,462 +1,462 @@ /******************************************************************** 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 "main.h" #include // kwin #include "platform.h" #include "atoms.h" #include "composite.h" #include "cursor.h" #include "input.h" #include "logind.h" #include "options.h" #include "screens.h" #include "screenlockerwatcher.h" #include "sm.h" #include "workspace.h" #include "xcbutils.h" #include // KDE #include #include #include #include #include // Qt #include #include #include #include #include #include // system #ifdef HAVE_UNISTD_H #include #endif // HAVE_UNISTD_H #ifdef HAVE_MALLOC_H #include #endif // HAVE_MALLOC_H // xcb #include #ifndef XCB_GE_GENERIC #define XCB_GE_GENERIC 35 #endif Q_DECLARE_METATYPE(KSharedConfigPtr) namespace KWin { Options* options; Atoms* atoms; int screen_number = -1; bool is_multihead = false; int Application::crashes = 0; bool Application::isX11MultiHead() { return is_multihead; } void Application::setX11MultiHead(bool multiHead) { is_multihead = multiHead; } void Application::setX11ScreenNumber(int screenNumber) { screen_number = screenNumber; } int Application::x11ScreenNumber() { return screen_number; } Application::Application(Application::OperationMode mode, int &argc, char **argv) : QApplication(argc, argv) , m_eventFilter(new XcbEventFilter()) , m_configLock(false) , m_config() , m_kxkbConfig() , m_inputConfig() , m_operationMode(mode) { qRegisterMetaType("Options::WindowOperation"); qRegisterMetaType(); qRegisterMetaType("KWayland::Server::SurfaceInterface *"); qRegisterMetaType(); } void Application::setConfigLock(bool lock) { m_configLock = lock; } Application::OperationMode Application::operationMode() const { return m_operationMode; } void Application::setOperationMode(OperationMode mode) { m_operationMode = mode; } bool Application::shouldUseWaylandForCompositing() const { return m_operationMode == OperationModeWaylandOnly || m_operationMode == OperationModeXwayland; } void Application::start() { setQuitOnLastWindowClosed(false); if (!m_config) { m_config = KSharedConfig::openConfig(); } if (!m_config->isImmutable() && m_configLock) { // TODO: This shouldn't be necessary //config->setReadOnly( true ); m_config->reparseConfiguration(); } if (!m_kxkbConfig) { m_kxkbConfig = KSharedConfig::openConfig(QStringLiteral("kxkbrc"), KConfig::NoGlobals); } if (!m_inputConfig) { m_inputConfig = KSharedConfig::openConfig(QStringLiteral("kcminputrc"), KConfig::NoGlobals); } performStartup(); } Application::~Application() { delete options; destroyAtoms(); destroyPlatform(); } void Application::destroyAtoms() { delete atoms; atoms = nullptr; } void Application::destroyPlatform() { delete m_platform; m_platform = nullptr; } void Application::resetCrashesCount() { crashes = 0; } void Application::setCrashCount(int count) { crashes = count; } bool Application::wasCrash() { return crashes > 0; } static const char description[] = I18N_NOOP("KDE window manager"); void Application::createAboutData() { KAboutData aboutData(QStringLiteral(KWIN_NAME), // The program name used internally i18n("KWin"), // A displayable program name string QStringLiteral(KWIN_VERSION_STRING), // The program version string i18n(description), // Short description of what the app does KAboutLicense::GPL, // The license this code is released under i18n("(c) 1999-2019, The KDE Developers")); // Copyright Statement aboutData.addAuthor(i18n("Matthias Ettrich"), QString(), QStringLiteral("ettrich@kde.org")); aboutData.addAuthor(i18n("Cristian Tibirna"), QString(), QStringLiteral("tibirna@kde.org")); aboutData.addAuthor(i18n("Daniel M. Duley"), QString(), QStringLiteral("mosfet@kde.org")); aboutData.addAuthor(i18n("Luboš Luňák"), QString(), QStringLiteral("l.lunak@kde.org")); aboutData.addAuthor(i18n("Martin Flöser"), QString(), QStringLiteral("mgraesslin@kde.org")); aboutData.addAuthor(i18n("David Edmundson"), QStringLiteral("Maintainer"), QStringLiteral("davidedmundson@kde.org")); aboutData.addAuthor(i18n("Roman Gilg"), QStringLiteral("Maintainer"), QStringLiteral("subdiff@gmail.com")); - aboutData.addAuthor(i18n("Vlad Zahorodnii"), QStringLiteral("Maintainer"), QStringLiteral("vladzzag@gmail.com")); + aboutData.addAuthor(i18n("Vlad Zahorodnii"), QStringLiteral("Maintainer"), QStringLiteral("vlad.zahorodnii@kde.org")); KAboutData::setApplicationData(aboutData); } static const QString s_lockOption = QStringLiteral("lock"); static const QString s_crashesOption = QStringLiteral("crashes"); void Application::setupCommandLine(QCommandLineParser *parser) { QCommandLineOption lockOption(s_lockOption, i18n("Disable configuration options")); QCommandLineOption crashesOption(s_crashesOption, i18n("Indicate that KWin has recently crashed n times"), QStringLiteral("n")); parser->setApplicationDescription(i18n("KDE window manager")); parser->addOption(lockOption); parser->addOption(crashesOption); KAboutData::applicationData().setupCommandLine(parser); } void Application::processCommandLine(QCommandLineParser *parser) { KAboutData aboutData = KAboutData::applicationData(); aboutData.processCommandLine(parser); setConfigLock(parser->isSet(s_lockOption)); Application::setCrashCount(parser->value(s_crashesOption).toInt()); } void Application::setupTranslator() { QTranslator *qtTranslator = new QTranslator(qApp); qtTranslator->load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); installTranslator(qtTranslator); } void Application::setupMalloc() { #ifdef M_TRIM_THRESHOLD // Prevent fragmentation of the heap by malloc (glibc). // // The default threshold is 128*1024, which can result in a large memory usage // due to fragmentation especially if we use the raster graphicssystem. On the // otherside if the threshold is too low, free() starts to permanently ask the kernel // about shrinking the heap. #ifdef HAVE_UNISTD_H const int pagesize = sysconf(_SC_PAGESIZE); #else const int pagesize = 4*1024; #endif // HAVE_UNISTD_H mallopt(M_TRIM_THRESHOLD, 5*pagesize); #endif // M_TRIM_THRESHOLD } void Application::setupLocalizedString() { KLocalizedString::setApplicationDomain("kwin"); } void Application::createWorkspace() { // we want all QQuickWindows with an alpha buffer, do here as Workspace might create QQuickWindows QQuickWindow::setDefaultAlphaBuffer(true); // This tries to detect compositing options and can use GLX. GLX problems // (X errors) shouldn't cause kwin to abort, so this is out of the // critical startup section where x errors cause kwin to abort. // create workspace. (void) new Workspace(m_originalSessionKey); emit workspaceCreated(); } void Application::createInput() { ScreenLockerWatcher::create(this); LogindIntegration::create(this); auto input = InputRedirection::create(this); input->init(); m_platform->createPlatformCursor(this); } void Application::createScreens() { if (Screens::self()) { return; } Screens::create(this); emit screensCreated(); } void Application::createAtoms() { atoms = new Atoms; } void Application::createOptions() { options = new Options; } void Application::setupEventFilters() { installNativeEventFilter(m_eventFilter.data()); } void Application::destroyWorkspace() { delete Workspace::self(); } void Application::destroyCompositor() { delete Compositor::self(); } void Application::updateX11Time(xcb_generic_event_t *event) { xcb_timestamp_t time = XCB_TIME_CURRENT_TIME; const uint8_t eventType = event->response_type & ~0x80; switch(eventType) { case XCB_KEY_PRESS: case XCB_KEY_RELEASE: time = reinterpret_cast(event)->time; break; case XCB_BUTTON_PRESS: case XCB_BUTTON_RELEASE: time = reinterpret_cast(event)->time; break; case XCB_MOTION_NOTIFY: time = reinterpret_cast(event)->time; break; case XCB_ENTER_NOTIFY: case XCB_LEAVE_NOTIFY: time = reinterpret_cast(event)->time; break; case XCB_FOCUS_IN: case XCB_FOCUS_OUT: case XCB_KEYMAP_NOTIFY: case XCB_EXPOSE: case XCB_GRAPHICS_EXPOSURE: case XCB_NO_EXPOSURE: case XCB_VISIBILITY_NOTIFY: case XCB_CREATE_NOTIFY: case XCB_DESTROY_NOTIFY: case XCB_UNMAP_NOTIFY: case XCB_MAP_NOTIFY: case XCB_MAP_REQUEST: case XCB_REPARENT_NOTIFY: case XCB_CONFIGURE_NOTIFY: case XCB_CONFIGURE_REQUEST: case XCB_GRAVITY_NOTIFY: case XCB_RESIZE_REQUEST: case XCB_CIRCULATE_NOTIFY: case XCB_CIRCULATE_REQUEST: // no timestamp return; case XCB_PROPERTY_NOTIFY: time = reinterpret_cast(event)->time; break; case XCB_SELECTION_CLEAR: time = reinterpret_cast(event)->time; break; case XCB_SELECTION_REQUEST: time = reinterpret_cast(event)->time; break; case XCB_SELECTION_NOTIFY: time = reinterpret_cast(event)->time; break; case XCB_COLORMAP_NOTIFY: case XCB_CLIENT_MESSAGE: case XCB_MAPPING_NOTIFY: case XCB_GE_GENERIC: // no timestamp return; default: // extension handling if (Xcb::Extensions::self()) { if (eventType == Xcb::Extensions::self()->shapeNotifyEvent()) { time = reinterpret_cast(event)->server_time; } if (eventType == Xcb::Extensions::self()->damageNotifyEvent()) { time = reinterpret_cast(event)->timestamp; } } break; } setX11Time(time); } bool XcbEventFilter::nativeEventFilter(const QByteArray &eventType, void *message, long int *result) { Q_UNUSED(result) if (eventType != "xcb_generic_event_t") { return false; } auto event = static_cast(message); kwinApp()->updateX11Time(event); if (!Workspace::self()) { // Workspace not yet created return false; } return Workspace::self()->workspaceEvent(event); } static bool s_useLibinput = false; void Application::setUseLibinput(bool use) { s_useLibinput = use; } bool Application::usesLibinput() { return s_useLibinput; } QProcessEnvironment Application::processStartupEnvironment() const { return QProcessEnvironment::systemEnvironment(); } void Application::initPlatform(const KPluginMetaData &plugin) { Q_ASSERT(!m_platform); m_platform = qobject_cast(plugin.instantiate()); if (m_platform) { m_platform->setParent(this); // check whether it needs libinput const QJsonObject &metaData = plugin.rawData(); auto it = metaData.find(QStringLiteral("input")); if (it != metaData.end()) { if ((*it).isBool()) { if (!(*it).toBool()) { qCDebug(KWIN_CORE) << "Platform does not support input, enforcing libinput support"; setUseLibinput(true); } } } } } ApplicationWaylandAbstract::ApplicationWaylandAbstract(OperationMode mode, int &argc, char **argv) : Application(mode, argc, argv) { } ApplicationWaylandAbstract::~ApplicationWaylandAbstract() { } } // namespace diff --git a/plugins/kpackage/effect/effect.cpp b/plugins/kpackage/effect/effect.cpp index 1c66f0b36..35726d56d 100644 --- a/plugins/kpackage/effect/effect.cpp +++ b/plugins/kpackage/effect/effect.cpp @@ -1,63 +1,63 @@ /****************************************************************************** -* Copyright 2018 Vlad Zahorodnii * +* Copyright 2018 Vlad Zahorodnii * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public License * * along with this library; see the file COPYING.LIB. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * *******************************************************************************/ #include "effect.h" #include EffectPackageStructure::EffectPackageStructure(QObject *parent, const QVariantList &args) : KPackage::PackageStructure(parent, args) { } void EffectPackageStructure::initPackage(KPackage::Package *package) { package->setDefaultPackageRoot(QStringLiteral("kwin/effects/")); package->addDirectoryDefinition("code", QStringLiteral("code"), i18n("Executable Scripts")); package->setMimeTypes("code", {QStringLiteral("text/plain")}); package->addFileDefinition("mainscript", QStringLiteral("code/main.js"), i18n("Main Script File")); package->setRequired("mainscript", true); package->addFileDefinition("config", QStringLiteral("config/main.xml"), i18n("Configuration Definition File")); package->setMimeTypes("config", {QStringLiteral("text/xml")}); package->addFileDefinition("configui", QStringLiteral("ui/config.ui"), i18n("KCM User Interface File")); package->setMimeTypes("configui", {QStringLiteral("text/xml")}); } void EffectPackageStructure::pathChanged(KPackage::Package *package) { if (package->path().isEmpty()) { return; } const KPluginMetaData md(package->metadata().metaDataFileName()); const QString mainScript = md.value("X-Plasma-MainScript"); if (mainScript.isEmpty()) { return; } package->addFileDefinition("mainscript", mainScript, i18n("Main Script File")); } K_EXPORT_KPACKAGE_PACKAGE_WITH_JSON(EffectPackageStructure, "kwin-packagestructure-effect.json") #include "effect.moc" diff --git a/plugins/kpackage/effect/effect.h b/plugins/kpackage/effect/effect.h index 0692dacd2..e2b4b4663 100644 --- a/plugins/kpackage/effect/effect.h +++ b/plugins/kpackage/effect/effect.h @@ -1,33 +1,33 @@ /****************************************************************************** -* Copyright 2018 Vlad Zahorodnii * +* Copyright 2018 Vlad Zahorodnii * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public License * * along with this library; see the file COPYING.LIB. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * *******************************************************************************/ #pragma once #include class EffectPackageStructure : public KPackage::PackageStructure { Q_OBJECT public: EffectPackageStructure(QObject *parent = nullptr, const QVariantList &args = {}); void initPackage(KPackage::Package *package) override; void pathChanged(KPackage::Package *package) override; }; diff --git a/plugins/kpackage/effect/kwin-packagestructure-effect.desktop b/plugins/kpackage/effect/kwin-packagestructure-effect.desktop index 1be74c21f..439d4a9d9 100644 --- a/plugins/kpackage/effect/kwin-packagestructure-effect.desktop +++ b/plugins/kpackage/effect/kwin-packagestructure-effect.desktop @@ -1,41 +1,41 @@ [Desktop Entry] Name=KWin Effect Name[ca]=Efecte del KWin Name[ca@valencia]=Efecte de KWin Name[cs]=Efekt KWinu Name[da]=KWin-effekt Name[de]=KWin-Effekt Name[el]=Εφέ KWin Name[en_GB]=KWin Effect Name[es]=Efecto de KWin Name[et]=KWini efekt Name[eu]=KWin efektua Name[fi]=KWin-tehoste Name[fr]=Effet KWin Name[gl]=Efecto de KWin Name[hu]=KWin effektus Name[ia]=Effecto de KWin Name[id]=Efek KWin Name[it]=Effetto di KWin Name[ko]=KWin 효과 Name[lt]=KWin efektas Name[nl]=KWin-effect Name[nn]=KWin-effekt Name[pl]=Efekt KWin Name[pt]=Efeito do KWin Name[pt_BR]=Efeito do KWin Name[ru]=Эффект диспетчера окон Name[sk]=Efekty KWin Name[sv]=Kwin-effekt Name[uk]=Ефект KWin Name[x-test]=xxKWin Effectxx Name[zh_CN]=KWin 效果 Name[zh_TW]=KWin 效果 Type=Service X-KDE-ServiceTypes=KPackage/PackageStructure X-KDE-Library=kwin_packagestructure_effect X-KDE-PluginInfo-Author=Vlad Zahorodnii -X-KDE-PluginInfo-Email=vladzzag@gmail.com +X-KDE-PluginInfo-Email=vlad.zahorodnii@kde.org X-KDE-PluginInfo-Name=KWin/Effect X-KDE-PluginInfo-Version=1 diff --git a/plugins/platforms/drm/drm_pointer.h b/plugins/platforms/drm/drm_pointer.h index c4a71c473..149ee1ec8 100644 --- a/plugins/platforms/drm/drm_pointer.h +++ b/plugins/platforms/drm/drm_pointer.h @@ -1,148 +1,148 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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_POINTER_H #define KWIN_DRM_POINTER_H #include #include namespace KWin { template struct DrmDeleter; template <> struct DrmDeleter { static void cleanup(drmModeAtomicReq *req) { drmModeAtomicFree(req); } }; template <> struct DrmDeleter { static void cleanup(drmModeConnector *connector) { drmModeFreeConnector(connector); } }; template <> struct DrmDeleter { static void cleanup(drmModeCrtc *crtc) { drmModeFreeCrtc(crtc); } }; template <> struct DrmDeleter { static void cleanup(drmModeFB *fb) { drmModeFreeFB(fb); } }; template <> struct DrmDeleter { static void cleanup(drmModeEncoder *encoder) { drmModeFreeEncoder(encoder); } }; template <> struct DrmDeleter { static void cleanup(drmModeModeInfo *info) { drmModeFreeModeInfo(info); } }; template <> struct DrmDeleter { static void cleanup(drmModeObjectProperties *properties) { drmModeFreeObjectProperties(properties); } }; template <> struct DrmDeleter { static void cleanup(drmModePlane *plane) { drmModeFreePlane(plane); } }; template <> struct DrmDeleter { static void cleanup(drmModePlaneRes *resources) { drmModeFreePlaneResources(resources); } }; template <> struct DrmDeleter { static void cleanup(drmModePropertyRes *property) { drmModeFreeProperty(property); } }; template <> struct DrmDeleter { static void cleanup(drmModePropertyBlobRes *blob) { drmModeFreePropertyBlob(blob); } }; template <> struct DrmDeleter { static void cleanup(drmModeRes *resources) { drmModeFreeResources(resources); } }; template using DrmScopedPointer = QScopedPointer>; } #endif diff --git a/plugins/platforms/drm/edid.cpp b/plugins/platforms/drm/edid.cpp index 1a7725768..839b8363d 100644 --- a/plugins/platforms/drm/edid.cpp +++ b/plugins/platforms/drm/edid.cpp @@ -1,183 +1,183 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Flöser -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "edid.h" namespace KWin { static bool verifyHeader(const uint8_t *data) { if (data[0] != 0x0 || data[7] != 0x0) { return false; } return std::all_of(data + 1, data + 7, [](uint8_t byte) { return byte == 0xff; }); } static QSize parsePhysicalSize(const uint8_t *data) { // Convert physical size from centimeters to millimeters. return QSize(data[0x15], data[0x16]) * 10; } static QByteArray parseEisaId(const uint8_t *data) { for (int i = 72; i <= 108; i += 18) { // Skip the block if it isn't used as monitor descriptor. if (data[i]) { continue; } if (data[i + 1]) { continue; } // We have found the EISA ID, it's stored as ASCII. if (data[i + 3] == 0xfe) { return QByteArray(reinterpret_cast(&data[i + 5]), 12).trimmed(); } } // If there isn't an ASCII EISA ID descriptor, try to decode PNP ID from // three 5 bit words packed into 2 bytes: // // | Byte | Bit | // | | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // ---------------------------------------- // | 1 | 0)| (4| 3 | 2 | 1 | 0)| (4| 3 | // | | * | Character 1 | Char 2| // ---------------------------------------- // | 2 | 2 | 1 | 0)| (4| 3 | 2 | 1 | 0)| // | | Character2| Character 3 | // ---------------------------------------- const uint offset = 0x8; char pnpId[4]; pnpId[0] = 'A' + ((data[offset + 0] >> 2) & 0x1f) - 1; pnpId[1] = 'A' + (((data[offset + 0] & 0x3) << 3) | ((data[offset + 1] >> 5) & 0x7)) - 1; pnpId[2] = 'A' + (data[offset + 1] & 0x1f) - 1; pnpId[3] = '\0'; return QByteArray(pnpId); } static QByteArray parseMonitorName(const uint8_t *data) { for (int i = 72; i <= 108; i += 18) { // Skip the block if it isn't used as monitor descriptor. if (data[i]) { continue; } if (data[i + 1]) { continue; } // We have found the monitor name, it's stored as ASCII. if (data[i + 3] == 0xfc) { return QByteArray(reinterpret_cast(&data[i + 5]), 12).trimmed(); } } return QByteArray(); } static QByteArray parseSerialNumber(const uint8_t *data) { for (int i = 72; i <= 108; i += 18) { // Skip the block if it isn't used as monitor descriptor. if (data[i]) { continue; } if (data[i + 1]) { continue; } // We have found the serial number, it's stored as ASCII. if (data[i + 3] == 0xff) { return QByteArray(reinterpret_cast(&data[i + 5]), 12).trimmed(); } } // Maybe there isn't an ASCII serial number descriptor, so use this instead. const uint32_t offset = 0xc; uint32_t serialNumber = data[offset + 0]; serialNumber |= uint32_t(data[offset + 1]) << 8; serialNumber |= uint32_t(data[offset + 2]) << 16; serialNumber |= uint32_t(data[offset + 3]) << 24; if (serialNumber) { return QByteArray::number(serialNumber); } return QByteArray(); } Edid::Edid() { } Edid::Edid(const void *data, uint32_t size) { const uint8_t *bytes = static_cast(data); if (size < 128) { return; } if (!verifyHeader(bytes)) { return; } m_physicalSize = parsePhysicalSize(bytes); m_eisaId = parseEisaId(bytes); m_monitorName = parseMonitorName(bytes); m_serialNumber = parseSerialNumber(bytes); m_isValid = true; } bool Edid::isValid() const { return m_isValid; } QSize Edid::physicalSize() const { return m_physicalSize; } QByteArray Edid::eisaId() const { return m_eisaId; } QByteArray Edid::monitorName() const { return m_monitorName; } QByteArray Edid::serialNumber() const { return m_serialNumber; } } // namespace KWin diff --git a/plugins/platforms/drm/edid.h b/plugins/platforms/drm/edid.h index 469fe1248..15b06b4e1 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 Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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/qpa/backingstore.cpp b/plugins/qpa/backingstore.cpp index d509b4506..d2ec86ae5 100644 --- a/plugins/qpa/backingstore.cpp +++ b/plugins/qpa/backingstore.cpp @@ -1,103 +1,103 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "backingstore.h" #include "window.h" #include "internal_client.h" namespace KWin { namespace QPA { BackingStore::BackingStore(QWindow *window) : QPlatformBackingStore(window) { } BackingStore::~BackingStore() = default; QPaintDevice *BackingStore::paintDevice() { return &m_backBuffer; } void BackingStore::resize(const QSize &size, const QRegion &staticContents) { Q_UNUSED(staticContents) if (m_backBuffer.size() == size) { return; } const QPlatformWindow *platformWindow = static_cast(window()->handle()); const qreal devicePixelRatio = platformWindow->devicePixelRatio(); m_backBuffer = QImage(size * devicePixelRatio, QImage::Format_ARGB32_Premultiplied); m_backBuffer.setDevicePixelRatio(devicePixelRatio); m_frontBuffer = QImage(size * devicePixelRatio, QImage::Format_ARGB32_Premultiplied); m_frontBuffer.setDevicePixelRatio(devicePixelRatio); } static void blitImage(const QImage &source, QImage &target, const QRect &rect) { Q_ASSERT(source.format() == QImage::Format_ARGB32_Premultiplied); Q_ASSERT(target.format() == QImage::Format_ARGB32_Premultiplied); const int devicePixelRatio = target.devicePixelRatio(); const int x = rect.x() * devicePixelRatio; const int y = rect.y() * devicePixelRatio; const int width = rect.width() * devicePixelRatio; const int height = rect.height() * devicePixelRatio; for (int i = y; i < y + height; ++i) { const uint32_t *in = reinterpret_cast(source.scanLine(i)); uint32_t *out = reinterpret_cast(target.scanLine(i)); std::copy(in + x, in + x + width, out + x); } } static void blitImage(const QImage &source, QImage &target, const QRegion ®ion) { for (const QRect &rect : region) { blitImage(source, target, rect); } } void BackingStore::flush(QWindow *window, const QRegion ®ion, const QPoint &offset) { Q_UNUSED(offset) Window *platformWindow = static_cast(window->handle()); InternalClient *client = platformWindow->client(); if (!client) { return; } blitImage(m_backBuffer, m_frontBuffer, region); client->present(m_frontBuffer, region); } } } diff --git a/plugins/qpa/backingstore.h b/plugins/qpa/backingstore.h index b98174d58..796059b83 100644 --- a/plugins/qpa/backingstore.h +++ b/plugins/qpa/backingstore.h @@ -1,49 +1,49 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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_QPA_BACKINGSTORE_H #define KWIN_QPA_BACKINGSTORE_H #include namespace KWin { namespace QPA { class BackingStore : public QPlatformBackingStore { public: explicit BackingStore(QWindow *window); ~BackingStore() override; QPaintDevice *paintDevice() override; void flush(QWindow *window, const QRegion ®ion, const QPoint &offset) override; void resize(const QSize &size, const QRegion &staticContents) override; private: QImage m_backBuffer; QImage m_frontBuffer; }; } } #endif diff --git a/plugins/qpa/eglhelpers.cpp b/plugins/qpa/eglhelpers.cpp index 0a17ec7ee..321c15700 100644 --- a/plugins/qpa/eglhelpers.cpp +++ b/plugins/qpa/eglhelpers.cpp @@ -1,116 +1,116 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Flöser -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "eglhelpers.h" #include #include namespace KWin { namespace QPA { bool isOpenGLES() { if (qstrcmp(qgetenv("KWIN_COMPOSE"), "O2ES") == 0) { return true; } return QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES; } EGLConfig configFromFormat(EGLDisplay display, const QSurfaceFormat &surfaceFormat, EGLint surfaceType) { // qMax as these values are initialized to -1 by default. const EGLint redSize = qMax(surfaceFormat.redBufferSize(), 0); const EGLint greenSize = qMax(surfaceFormat.greenBufferSize(), 0); const EGLint blueSize = qMax(surfaceFormat.blueBufferSize(), 0); const EGLint alphaSize = qMax(surfaceFormat.alphaBufferSize(), 0); const EGLint depthSize = qMax(surfaceFormat.depthBufferSize(), 0); const EGLint stencilSize = qMax(surfaceFormat.stencilBufferSize(), 0); const EGLint renderableType = isOpenGLES() ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_BIT; // Not setting samples as QtQuick doesn't need it. const QVector attributes { EGL_SURFACE_TYPE, surfaceType, EGL_RED_SIZE, redSize, EGL_GREEN_SIZE, greenSize, EGL_BLUE_SIZE, blueSize, EGL_ALPHA_SIZE, alphaSize, EGL_DEPTH_SIZE, depthSize, EGL_STENCIL_SIZE, stencilSize, EGL_RENDERABLE_TYPE, renderableType, EGL_NONE }; EGLint configCount; EGLConfig configs[1024]; if (!eglChooseConfig(display, attributes.data(), configs, 1, &configCount)) { // FIXME: Don't bail out yet, we should try to find the most suitable config. qCWarning(KWIN_QPA, "eglChooseConfig failed: %x", eglGetError()); return EGL_NO_CONFIG_KHR; } if (configCount != 1) { qCWarning(KWIN_QPA) << "eglChooseConfig did not return any configs"; return EGL_NO_CONFIG_KHR; } return configs[0]; } QSurfaceFormat formatFromConfig(EGLDisplay display, EGLConfig config) { int redSize = 0; int blueSize = 0; int greenSize = 0; int alphaSize = 0; int stencilSize = 0; int depthSize = 0; int sampleCount = 0; eglGetConfigAttrib(display, config, EGL_RED_SIZE, &redSize); eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &greenSize); eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &blueSize); eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &alphaSize); eglGetConfigAttrib(display, config, EGL_STENCIL_SIZE, &stencilSize); eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE, &depthSize); eglGetConfigAttrib(display, config, EGL_SAMPLES, &sampleCount); QSurfaceFormat format; format.setRedBufferSize(redSize); format.setGreenBufferSize(greenSize); format.setBlueBufferSize(blueSize); format.setAlphaBufferSize(alphaSize); format.setStencilBufferSize(stencilSize); format.setDepthBufferSize(depthSize); format.setSamples(sampleCount); format.setRenderableType(isOpenGLES() ? QSurfaceFormat::OpenGLES : QSurfaceFormat::OpenGL); format.setStereo(false); return format; } } // namespace QPA } // namespace KWin diff --git a/plugins/qpa/eglhelpers.h b/plugins/qpa/eglhelpers.h index adf4711a5..1dccd059c 100644 --- a/plugins/qpa/eglhelpers.h +++ b/plugins/qpa/eglhelpers.h @@ -1,40 +1,40 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "fixqopengl.h" #include #include namespace KWin { namespace QPA { bool isOpenGLES(); EGLConfig configFromFormat(EGLDisplay display, const QSurfaceFormat &surfaceFormat, EGLint surfaceType = 0); QSurfaceFormat formatFromConfig(EGLDisplay display, EGLConfig config); } // namespace QPA } // namespace KWin diff --git a/plugins/qpa/integration.cpp b/plugins/qpa/integration.cpp index f26fc453a..3b9d11c92 100644 --- a/plugins/qpa/integration.cpp +++ b/plugins/qpa/integration.cpp @@ -1,217 +1,217 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "integration.h" #include "backingstore.h" #include "offscreensurface.h" #include "screen.h" #include "sharingplatformcontext.h" #include "window.h" #include "../../main.h" #include "../../platform.h" #include "../../screens.h" #include "../../virtualkeyboard.h" #include #include #include #include #include #include #include #include #include namespace KWin { namespace QPA { Integration::Integration() : QObject() , QPlatformIntegration() , m_fontDb(new QGenericUnixFontDatabase()) , m_inputContext() { } Integration::~Integration() = default; bool Integration::hasCapability(Capability cap) const { switch (cap) { case ThreadedPixmaps: return true; case OpenGL: return true; case ThreadedOpenGL: return false; case BufferQueueingOpenGL: return false; case MultipleWindows: case NonFullScreenWindows: return true; case RasterGLSurface: return false; default: return QPlatformIntegration::hasCapability(cap); } } void Integration::initialize() { connect(kwinApp(), &Application::screensCreated, this, [this] { connect(screens(), &Screens::changed, this, &Integration::initScreens); initScreens(); } ); QPlatformIntegration::initialize(); auto dummyScreen = new Screen(-1); #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) QWindowSystemInterface::handleScreenAdded(dummyScreen); #else screenAdded(dummyScreen); #endif m_screens << dummyScreen; m_inputContext.reset(QPlatformInputContextFactory::create(QStringLiteral("qtvirtualkeyboard"))); qunsetenv("QT_IM_MODULE"); if (!m_inputContext.isNull()) { connect(qApp, &QGuiApplication::focusObjectChanged, this, [this] { if (VirtualKeyboard::self() && qApp->focusObject() != VirtualKeyboard::self()) { m_inputContext->setFocusObject(VirtualKeyboard::self()); } } ); connect(kwinApp(), &Application::workspaceCreated, this, [this] { if (VirtualKeyboard::self()) { m_inputContext->setFocusObject(VirtualKeyboard::self()); } } ); connect(qApp->inputMethod(), &QInputMethod::visibleChanged, this, [] { if (qApp->inputMethod()->isVisible()) { if (QWindow *w = VirtualKeyboard::self()->inputPanel()) { QWindowSystemInterface::handleWindowActivated(w, Qt::ActiveWindowFocusReason); } } } ); } } QAbstractEventDispatcher *Integration::createEventDispatcher() const { return new QUnixEventDispatcherQPA; } QPlatformBackingStore *Integration::createPlatformBackingStore(QWindow *window) const { return new BackingStore(window); } QPlatformWindow *Integration::createPlatformWindow(QWindow *window) const { return new Window(window); } QPlatformOffscreenSurface *Integration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const { return new OffscreenSurface(surface); } QPlatformFontDatabase *Integration::fontDatabase() const { return m_fontDb; } QPlatformTheme *Integration::createPlatformTheme(const QString &name) const { return QGenericUnixTheme::createUnixTheme(name); } QStringList Integration::themeNames() const { if (qEnvironmentVariableIsSet("KDE_FULL_SESSION")) { return QStringList({QStringLiteral("kde")}); } return QStringList({QLatin1String(QGenericUnixTheme::name)}); } QPlatformOpenGLContext *Integration::createPlatformOpenGLContext(QOpenGLContext *context) const { if (kwinApp()->platform()->supportsQpaContext()) { return new SharingPlatformContext(context); } if (kwinApp()->platform()->sceneEglDisplay() != EGL_NO_DISPLAY) { auto s = kwinApp()->platform()->sceneEglSurface(); if (s != EGL_NO_SURFACE) { // try a SharingPlatformContext with a created surface return new SharingPlatformContext(context, s, kwinApp()->platform()->sceneEglConfig()); } } return nullptr; } void Integration::initScreens() { QVector newScreens; newScreens.reserve(qMax(screens()->count(), 1)); for (int i = 0; i < screens()->count(); i++) { auto screen = new Screen(i); #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) QWindowSystemInterface::handleScreenAdded(screen); #else screenAdded(screen); #endif newScreens << screen; } if (newScreens.isEmpty()) { auto dummyScreen = new Screen(-1); #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) QWindowSystemInterface::handleScreenAdded(dummyScreen); #else screenAdded(dummyScreen); #endif newScreens << dummyScreen; } while (!m_screens.isEmpty()) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) QWindowSystemInterface::handleScreenRemoved(m_screens.takeLast()); #else destroyScreen(m_screens.takeLast()); #endif } m_screens = newScreens; } QPlatformInputContext *Integration::inputContext() const { return m_inputContext.data(); } } } diff --git a/plugins/qpa/integration.h b/plugins/qpa/integration.h index 4a07109fc..4b63ffec5 100644 --- a/plugins/qpa/integration.h +++ b/plugins/qpa/integration.h @@ -1,71 +1,71 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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_QPA_INTEGRATION_H #define KWIN_QPA_INTEGRATION_H #include #include "fixqopengl.h" #include #include #include namespace KWin { namespace QPA { class Screen; class Integration : public QObject, public QPlatformIntegration { Q_OBJECT public: explicit Integration(); ~Integration() override; bool hasCapability(Capability cap) const override; QPlatformWindow *createPlatformWindow(QWindow *window) const override; QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const override; QPlatformBackingStore *createPlatformBackingStore(QWindow *window) const override; QAbstractEventDispatcher *createEventDispatcher() const override; QPlatformFontDatabase *fontDatabase() const override; QStringList themeNames() const override; QPlatformTheme *createPlatformTheme(const QString &name) const override; QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const override; QPlatformInputContext *inputContext() const override; void initialize() override; private: void initScreens(); QPlatformFontDatabase *m_fontDb; QPlatformNativeInterface *m_nativeInterface; Screen *m_dummyScreen = nullptr; QScopedPointer m_inputContext; QVector m_screens; }; } } #endif diff --git a/plugins/qpa/offscreensurface.cpp b/plugins/qpa/offscreensurface.cpp index 0fc74c8ca..da40eb1d8 100644 --- a/plugins/qpa/offscreensurface.cpp +++ b/plugins/qpa/offscreensurface.cpp @@ -1,82 +1,82 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "offscreensurface.h" #include "eglhelpers.h" #include "main.h" #include "platform.h" #include namespace KWin { namespace QPA { OffscreenSurface::OffscreenSurface(QOffscreenSurface *surface) : QPlatformOffscreenSurface(surface) , m_eglDisplay(kwinApp()->platform()->sceneEglDisplay()) { const QSize size = surface->size(); EGLConfig config = configFromFormat(m_eglDisplay, surface->requestedFormat(), EGL_PBUFFER_BIT); if (config == EGL_NO_CONFIG_KHR) { return; } const EGLint attributes[] = { EGL_WIDTH, size.width(), EGL_HEIGHT, size.height(), EGL_NONE }; m_surface = eglCreatePbufferSurface(m_eglDisplay, config, attributes); if (m_surface == EGL_NO_SURFACE) { return; } // Requested and actual surface format might be different. m_format = formatFromConfig(m_eglDisplay, config); } OffscreenSurface::~OffscreenSurface() { if (m_surface != EGL_NO_SURFACE) { eglDestroySurface(m_eglDisplay, m_surface); } } QSurfaceFormat OffscreenSurface::format() const { return m_format; } bool OffscreenSurface::isValid() const { return m_surface != EGL_NO_SURFACE; } EGLSurface OffscreenSurface::nativeHandle() const { return m_surface; } } // namespace QPA } // namespace KWin diff --git a/plugins/qpa/offscreensurface.h b/plugins/qpa/offscreensurface.h index a355fb4d5..959bbddf1 100644 --- a/plugins/qpa/offscreensurface.h +++ b/plugins/qpa/offscreensurface.h @@ -1,53 +1,53 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "fixqopengl.h" #include #include namespace KWin { namespace QPA { class OffscreenSurface : public QPlatformOffscreenSurface { public: explicit OffscreenSurface(QOffscreenSurface *surface); ~OffscreenSurface() override; QSurfaceFormat format() const override; bool isValid() const override; EGLSurface nativeHandle() const; private: QSurfaceFormat m_format; EGLDisplay m_eglDisplay = EGL_NO_DISPLAY; EGLSurface m_surface = EGL_NO_SURFACE; }; } // namespace QPA } // namespace KWin diff --git a/plugins/qpa/window.cpp b/plugins/qpa/window.cpp index 03649b39e..8c32be26d 100644 --- a/plugins/qpa/window.cpp +++ b/plugins/qpa/window.cpp @@ -1,158 +1,158 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "window.h" #include "screens.h" #include "internal_client.h" #include #include #include namespace KWin { namespace QPA { static quint32 s_windowId = 0; Window::Window(QWindow *window) : QPlatformWindow(window) , m_windowId(++s_windowId) , m_scale(screens()->maxScale()) { } Window::~Window() { unmap(); } void Window::setVisible(bool visible) { if (visible) { map(); } else { unmap(); } QPlatformWindow::setVisible(visible); } void Window::setGeometry(const QRect &rect) { const QRect &oldRect = geometry(); QPlatformWindow::setGeometry(rect); if (rect.x() != oldRect.x()) { emit window()->xChanged(rect.x()); } if (rect.y() != oldRect.y()) { emit window()->yChanged(rect.y()); } if (rect.width() != oldRect.width()) { emit window()->widthChanged(rect.width()); } if (rect.height() != oldRect.height()) { emit window()->heightChanged(rect.height()); } const QSize nativeSize = rect.size() * m_scale; if (m_contentFBO) { if (m_contentFBO->size() != nativeSize) { m_resized = true; } } QWindowSystemInterface::handleGeometryChange(window(), geometry()); } WId Window::winId() const { return m_windowId; } qreal Window::devicePixelRatio() const { return m_scale; } void Window::bindContentFBO() { if (m_resized || !m_contentFBO) { createFBO(); } m_contentFBO->bind(); } const QSharedPointer &Window::contentFBO() const { return m_contentFBO; } QSharedPointer Window::swapFBO() { QSharedPointer fbo = m_contentFBO; m_contentFBO.clear(); return fbo; } InternalClient *Window::client() const { return m_handle; } void Window::createFBO() { const QRect &r = geometry(); if (m_contentFBO && r.size().isEmpty()) { return; } const QSize nativeSize = r.size() * m_scale; m_contentFBO.reset(new QOpenGLFramebufferObject(nativeSize.width(), nativeSize.height(), QOpenGLFramebufferObject::CombinedDepthStencil)); if (!m_contentFBO->isValid()) { qCWarning(KWIN_QPA) << "Content FBO is not valid"; } m_resized = false; } void Window::map() { if (m_handle) { return; } m_handle = new InternalClient(window()); } void Window::unmap() { if (!m_handle) { return; } m_handle->destroyClient(); m_handle = nullptr; m_contentFBO = nullptr; } } } diff --git a/plugins/qpa/window.h b/plugins/qpa/window.h index c623547ad..ac092543d 100644 --- a/plugins/qpa/window.h +++ b/plugins/qpa/window.h @@ -1,68 +1,68 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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_QPA_WINDOW_H #define KWIN_QPA_WINDOW_H #include class QOpenGLFramebufferObject; namespace KWin { class InternalClient; namespace QPA { class Window : public QPlatformWindow { public: explicit Window(QWindow *window); ~Window() override; void setVisible(bool visible) override; void setGeometry(const QRect &rect) override; WId winId() const override; qreal devicePixelRatio() const override; void bindContentFBO(); const QSharedPointer &contentFBO() const; QSharedPointer swapFBO(); InternalClient *client() const; private: void createFBO(); void map(); void unmap(); InternalClient *m_handle = nullptr; QSharedPointer m_contentFBO; quint32 m_windowId; bool m_resized = false; int m_scale = 1; }; } } #endif diff --git a/plugins/scenes/opengl/scene_opengl.cpp b/plugins/scenes/opengl/scene_opengl.cpp index 13786a0d9..c5ea77eb4 100644 --- a/plugins/scenes/opengl/scene_opengl.cpp +++ b/plugins/scenes/opengl/scene_opengl.cpp @@ -1,2728 +1,2728 @@ /******************************************************************** 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 -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 #include "utils.h" #include "x11client.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() { Q_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. Q_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() { Q_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() { Q_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; } 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"; } } } SceneOpenGL::~SceneOpenGL() { if (init_ok) { makeOpenGLContextCurrent(); } SceneOpenGL::EffectFrame::cleanup(); delete m_syncManager; // backend might be still needed for a different scene delete m_backend; } 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; } } // 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: 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); #if !defined(QT_NO_DEBUG) // 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 nullptr; } SceneOpenGL *scene = nullptr; // first let's try an OpenGL 2 scene if (SceneOpenGL2::supported(backend)) { scene = new SceneOpenGL2(backend, parent); if (scene->initFailed()) { delete scene; scene = nullptr; } 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() const { return m_backend->overlayWindow(); } bool SceneOpenGL::hasSwapEvent() const { return m_backend->hasSwapEvent(); } 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, QList 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 { if (kwinApp()->operationMode() != Application::OperationModeX11) { // TODO: On Wayland we can't suspend. Find a solution that works here as well! return true; } GLint limit[2]; glGetIntegerv(GL_MAX_VIEWPORT_DIMS, limit); if (limit[0] < size.width() || limit[1] < size.height()) { auto compositor = static_cast(Compositor::self()); QMetaObject::invokeMethod(compositor, [compositor]() { compositor->suspend(X11Compositor::AllReasonSuspend); }, Qt::QueuedConnection); 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); } void SceneOpenGL::paintEffectQuickView(EffectQuickView *w) { GLShader *shader = ShaderManager::instance()->pushShader(ShaderTrait::MapTexture); const QRect rect = w->geometry(); GLTexture *t = w->bufferAsTexture(); if (!t) { return; } QMatrix4x4 mvp(projectionMatrix()); mvp.translate(rect.x(), rect.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); t->bind(); t->render(QRegion(infiniteRegion()), w->geometry()); t->unbind(); glDisable(GL_BLEND); ShaderManager::instance()->popShader(); } 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(nullptr) { 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(), nullptr); 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 = nullptr; }); } 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(nullptr) { } SceneOpenGL::Window::~Window() { } static SceneOpenGLTexture *s_frameTexture = nullptr; // Bind the window pixmap to an OpenGL texture. bool SceneOpenGL::Window::bindTexture() { s_frameTexture = nullptr; 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 (waylandServer()) { filter = ImageFilterGood; s_frameTexture->setFilter(GL_LINEAR); } else { 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() : nullptr; 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; bool useX11TextureClamp = false; GLShader *shader = data.shader; GLenum filter; if (waylandServer()) { filter = GL_LINEAR; } else { const bool isTransformed = mask & (Effect::PAINT_WINDOW_TRANSFORMED | Effect::PAINT_SCREEN_TRANSFORMED); useX11TextureClamp = isTransformed; if (isTransformed && options->glSmoothScale() != 0) { filter = GL_LINEAR; } else { filter = GL_NEAREST; } } if (!shader) { ShaderTraits traits = ShaderTrait::MapTexture; if (useX11TextureClamp) { traits |= ShaderTrait::ClampTexture; } 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()); 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(); if (i == ContentLeaf && useX11TextureClamp) { // X11 windows are reparented to have their buffer in the middle of a larger texture // holding the frame window. // This code passes the texture geometry to the fragment shader // any samples near the edge of the texture will be constrained to be // at least half a pixel in bounds, meaning we don't bleed the transparent border QRectF bufferContentRect = clientShape().boundingRect(); bufferContentRect.adjust(0.5, 0.5, -0.5, -0.5); const QRect bufferGeometry = toplevel->bufferGeometry(); float leftClamp = bufferContentRect.left() / bufferGeometry.width(); float topClamp = bufferContentRect.top() / bufferGeometry.height(); float rightClamp = bufferContentRect.right() / bufferGeometry.width(); float bottomClamp = bufferContentRect.bottom() / bufferGeometry.height(); shader->setUniform(GLShader::TextureClamp, QVector4D({leftClamp, topClamp, rightClamp, bottomClamp})); } else { shader->setUniform(GLShader::TextureClamp, QVector4D({0, 0, 1, 1})); } 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(); const QPoint mainSurfaceOffset = bufferOffset(); windowMatrix.translate(mainSurfaceOffset.x(), mainSurfaceOffset.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() { } static bool needsPixmapUpdate(const OpenGLWindowPixmap *pixmap) { // That's a regular Wayland client. if (pixmap->surface()) { return !pixmap->surface()->trackedDamage().isEmpty(); } // That's an internal client with a raster buffer attached. if (!pixmap->internalImage().isNull()) { return !pixmap->toplevel()->damage().isEmpty(); } // That's an internal client with an opengl framebuffer object attached. if (!pixmap->fbo().isNull()) { return !pixmap->toplevel()->damage().isEmpty(); } // That's an X11 client. return false; } bool OpenGLWindowPixmap::bind() { if (!m_texture->isNull()) { // always call updateBuffer to get the sub-surface tree updated if (subSurface().isNull() && !toplevel()->damage().isEmpty()) { updateBuffer(); } if (needsPixmapUpdate(this)) { 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 = nullptr; QPixmap* SceneOpenGL::EffectFrame::m_unstyledPixmap = nullptr; SceneOpenGL::EffectFrame::EffectFrame(EffectFrameImpl* frame, SceneOpenGL *scene) : Scene::EffectFrame(frame) , m_texture(nullptr) , m_textTexture(nullptr) , m_oldTextTexture(nullptr) , m_textPixmap(nullptr) , m_iconTexture(nullptr) , m_oldIconTexture(nullptr) , m_selectionTexture(nullptr) , m_unstyledVBO(nullptr) , 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 = nullptr; delete m_textTexture; m_textTexture = nullptr; delete m_textPixmap; m_textPixmap = nullptr; delete m_iconTexture; m_iconTexture = nullptr; delete m_selectionTexture; m_selectionTexture = nullptr; delete m_unstyledVBO; m_unstyledVBO = nullptr; delete m_oldIconTexture; m_oldIconTexture = nullptr; delete m_oldTextTexture; m_oldTextTexture = nullptr; } void SceneOpenGL::EffectFrame::freeIconFrame() { delete m_iconTexture; m_iconTexture = nullptr; } void SceneOpenGL::EffectFrame::freeTextFrame() { delete m_textTexture; m_textTexture = nullptr; delete m_textPixmap; m_textPixmap = nullptr; } void SceneOpenGL::EffectFrame::freeSelection() { delete m_selectionTexture; m_selectionTexture = nullptr; } void SceneOpenGL::EffectFrame::crossFadeIcon() { delete m_oldIconTexture; m_oldIconTexture = m_iconTexture; m_iconTexture = nullptr; } void SceneOpenGL::EffectFrame::crossFadeText() { delete m_oldTextTexture; m_oldTextTexture = m_textTexture; m_textTexture = nullptr; } 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 = nullptr; 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 = nullptr; delete m_textPixmap; m_textPixmap = nullptr; 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 = nullptr; delete m_unstyledPixmap; m_unstyledPixmap = nullptr; // 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 = nullptr; delete m_unstyledPixmap; m_unstyledPixmap = nullptr; } //**************************************** // 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; } static void clamp_row(int left, int width, int right, const uint32_t *src, uint32_t *dest) { std::fill_n(dest, left, *src); std::copy(src, src + width, dest + left); std::fill_n(dest + left + width, right, *(src + width - 1)); } static void clamp_sides(int left, int width, int right, const uint32_t *src, uint32_t *dest) { std::fill_n(dest, left, *src); std::fill_n(dest + left + width, right, *(src + width - 1)); } static void clamp(QImage &image, const QRect &viewport) { Q_ASSERT(image.depth() == 32); const QRect rect = image.rect(); const int left = viewport.left() - rect.left(); const int top = viewport.top() - rect.top(); const int right = rect.right() - viewport.right(); const int bottom = rect.bottom() - viewport.bottom(); const int width = rect.width() - left - right; const int height = rect.height() - top - bottom; const uint32_t *firstRow = reinterpret_cast(image.scanLine(top)); const uint32_t *lastRow = reinterpret_cast(image.scanLine(top + height - 1)); for (int i = 0; i < top; ++i) { uint32_t *dest = reinterpret_cast(image.scanLine(i)); clamp_row(left, width, right, firstRow + left, dest); } for (int i = 0; i < height; ++i) { uint32_t *dest = reinterpret_cast(image.scanLine(top + i)); clamp_sides(left, width, right, dest + left, dest); } for (int i = 0; i < bottom; ++i) { uint32_t *dest = reinterpret_cast(image.scanLine(top + height + i)); clamp_row(left, width, right, lastRow + left, dest); } } 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()->size()) : scheduled.boundingRect(); // We pad each part in the decoration atlas in order to avoid texture bleeding. const int padding = 1; auto renderPart = [=](const QRect &geo, const QRect &partRect, const QPoint &position, bool rotated = false) { if (!geo.isValid()) { return; } QRect rect = geo; // We allow partial decoration updates and it might just so happen that the dirty region // is completely contained inside the decoration part, i.e. the dirty region doesn't touch // any of the decoration's edges. In that case, we should **not** pad the dirty region. if (rect.left() == partRect.left()) { rect.setLeft(rect.left() - padding); } if (rect.top() == partRect.top()) { rect.setTop(rect.top() - padding); } if (rect.right() == partRect.right()) { rect.setRight(rect.right() + padding); } if (rect.bottom() == partRect.bottom()) { rect.setBottom(rect.bottom() + padding); } QRect viewport = geo.translated(-rect.x(), -rect.y()); const qreal devicePixelRatio = client()->client()->screenScale(); QImage image(rect.size() * devicePixelRatio, QImage::Format_ARGB32_Premultiplied); image.setDevicePixelRatio(devicePixelRatio); image.fill(Qt::transparent); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); painter.setViewport(QRect(viewport.topLeft(), viewport.size() * devicePixelRatio)); painter.setWindow(QRect(geo.topLeft(), geo.size() * devicePixelRatio)); painter.setClipRect(geo); renderToPainter(&painter, geo); painter.end(); clamp(image, QRect(viewport.topLeft(), viewport.size() * devicePixelRatio)); if (rotated) { // TODO: get this done directly when rendering to the image image = rotate(image, QRect(QPoint(), rect.size())); viewport = QRect(viewport.y(), viewport.x(), viewport.height(), viewport.width()); } const QPoint dirtyOffset = geo.topLeft() - partRect.topLeft(); m_texture->update(image, (position + dirtyOffset - viewport.topLeft()) * image.devicePixelRatio()); }; const QPoint topPosition(padding, padding); const QPoint bottomPosition(padding, topPosition.y() + top.height() + 2 * padding); const QPoint leftPosition(padding, bottomPosition.y() + bottom.height() + 2 * padding); const QPoint rightPosition(padding, leftPosition.y() + left.width() + 2 * padding); renderPart(left.intersected(geometry), left, leftPosition, true); renderPart(top.intersected(geometry), top, topPosition); renderPart(right.intersected(geometry), right, rightPosition, true); renderPart(bottom.intersected(geometry), bottom, bottomPosition); } 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(); // Reserve some space for padding. We pad decoration parts to avoid texture bleeding. const int padding = 1; size.rwidth() += 2 * padding; size.rheight() += 4 * 2 * padding; 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/pointer_input.cpp b/pointer_input.cpp index 74f7e9937..64d755831 100644 --- a/pointer_input.cpp +++ b/pointer_input.cpp @@ -1,1400 +1,1400 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "pointer_input.h" #include "platform.h" #include "x11client.h" #include "effects.h" #include "input_event.h" #include "input_event_spy.h" #include "osd.h" #include "screens.h" #include "xdgshellclient.h" #include "wayland_cursor_theme.h" #include "wayland_server.h" #include "workspace.h" #include "decorations/decoratedclient.h" #include "screens.h" // KDecoration #include // KWayland #include #include #include #include #include #include #include #include // screenlocker #include #include #include #include // Wayland #include #include namespace KWin { static const QHash s_buttonToQtMouseButton = { { BTN_LEFT , Qt::LeftButton }, { BTN_MIDDLE , Qt::MiddleButton }, { BTN_RIGHT , Qt::RightButton }, // in QtWayland mapped like that { BTN_SIDE , Qt::ExtraButton1 }, // in QtWayland mapped like that { BTN_EXTRA , Qt::ExtraButton2 }, { BTN_BACK , Qt::BackButton }, { BTN_FORWARD , Qt::ForwardButton }, { BTN_TASK , Qt::TaskButton }, // mapped like that in QtWayland { 0x118 , Qt::ExtraButton6 }, { 0x119 , Qt::ExtraButton7 }, { 0x11a , Qt::ExtraButton8 }, { 0x11b , Qt::ExtraButton9 }, { 0x11c , Qt::ExtraButton10 }, { 0x11d , Qt::ExtraButton11 }, { 0x11e , Qt::ExtraButton12 }, { 0x11f , Qt::ExtraButton13 }, }; uint32_t qtMouseButtonToButton(Qt::MouseButton button) { return s_buttonToQtMouseButton.key(button); } static Qt::MouseButton buttonToQtMouseButton(uint32_t button) { // all other values get mapped to ExtraButton24 // this is actually incorrect but doesn't matter in our usage // KWin internally doesn't use these high extra buttons anyway // it's only needed for recognizing whether buttons are pressed // if multiple buttons are mapped to the value the evaluation whether // buttons are pressed is correct and that's all we care about. return s_buttonToQtMouseButton.value(button, Qt::ExtraButton24); } static bool screenContainsPos(const QPointF &pos) { for (int i = 0; i < screens()->count(); ++i) { if (screens()->geometry(i).contains(pos.toPoint())) { return true; } } return false; } static QPointF confineToBoundingBox(const QPointF &pos, const QRectF &boundingBox) { return QPointF( qBound(boundingBox.left(), pos.x(), boundingBox.right() - 1.0), qBound(boundingBox.top(), pos.y(), boundingBox.bottom() - 1.0) ); } PointerInputRedirection::PointerInputRedirection(InputRedirection* parent) : InputDeviceHandler(parent) , m_cursor(nullptr) , m_supportsWarping(Application::usesLibinput()) { } PointerInputRedirection::~PointerInputRedirection() = default; void PointerInputRedirection::init() { Q_ASSERT(!inited()); m_cursor = new CursorImage(this); setInited(true); InputDeviceHandler::init(); connect(m_cursor, &CursorImage::changed, kwinApp()->platform(), &Platform::cursorChanged); emit m_cursor->changed(); connect(screens(), &Screens::changed, this, &PointerInputRedirection::updateAfterScreenChange); if (waylandServer()->hasScreenLockerIntegration()) { connect(ScreenLocker::KSldApp::self(), &ScreenLocker::KSldApp::lockStateChanged, this, [this] { waylandServer()->seat()->cancelPointerPinchGesture(); waylandServer()->seat()->cancelPointerSwipeGesture(); update(); } ); } connect(workspace(), &QObject::destroyed, this, [this] { setInited(false); }); connect(waylandServer(), &QObject::destroyed, this, [this] { setInited(false); }); connect(waylandServer()->seat(), &KWayland::Server::SeatInterface::dragEnded, this, [this] { // need to force a focused pointer change waylandServer()->seat()->setFocusedPointerSurface(nullptr); setFocus(nullptr); update(); } ); // connect the move resize of all window auto setupMoveResizeConnection = [this] (AbstractClient *c) { connect(c, &AbstractClient::clientStartUserMovedResized, this, &PointerInputRedirection::updateOnStartMoveResize); connect(c, &AbstractClient::clientFinishUserMovedResized, this, &PointerInputRedirection::update); }; const auto clients = workspace()->allClientList(); std::for_each(clients.begin(), clients.end(), setupMoveResizeConnection); connect(workspace(), &Workspace::clientAdded, this, setupMoveResizeConnection); connect(waylandServer(), &WaylandServer::shellClientAdded, this, setupMoveResizeConnection); // warp the cursor to center of screen warp(screens()->geometry().center()); updateAfterScreenChange(); } void PointerInputRedirection::updateOnStartMoveResize() { breakPointerConstraints(focus() ? focus()->surface() : nullptr); disconnectPointerConstraintsConnection(); setFocus(nullptr); waylandServer()->seat()->setFocusedPointerSurface(nullptr); } void PointerInputRedirection::updateToReset() { if (internalWindow()) { disconnect(m_internalWindowConnection); m_internalWindowConnection = QMetaObject::Connection(); QEvent event(QEvent::Leave); QCoreApplication::sendEvent(internalWindow().data(), &event); setInternalWindow(nullptr); } if (decoration()) { QHoverEvent event(QEvent::HoverLeave, QPointF(), QPointF()); QCoreApplication::instance()->sendEvent(decoration()->decoration(), &event); setDecoration(nullptr); } if (focus()) { if (AbstractClient *c = qobject_cast(focus().data())) { c->leaveEvent(); } disconnect(m_focusGeometryConnection); m_focusGeometryConnection = QMetaObject::Connection(); breakPointerConstraints(focus()->surface()); disconnectPointerConstraintsConnection(); setFocus(nullptr); } waylandServer()->seat()->setFocusedPointerSurface(nullptr); } void PointerInputRedirection::processMotion(const QPointF &pos, uint32_t time, LibInput::Device *device) { processMotion(pos, QSizeF(), QSizeF(), time, 0, device); } class PositionUpdateBlocker { public: PositionUpdateBlocker(PointerInputRedirection *pointer) : m_pointer(pointer) { s_counter++; } ~PositionUpdateBlocker() { s_counter--; if (s_counter == 0) { if (!s_scheduledPositions.isEmpty()) { const auto pos = s_scheduledPositions.takeFirst(); m_pointer->processMotion(pos.pos, pos.delta, pos.deltaNonAccelerated, pos.time, pos.timeUsec, nullptr); } } } static bool isPositionBlocked() { return s_counter > 0; } static void schedulePosition(const QPointF &pos, const QSizeF &delta, const QSizeF &deltaNonAccelerated, uint32_t time, quint64 timeUsec) { s_scheduledPositions.append({pos, delta, deltaNonAccelerated, time, timeUsec}); } private: static int s_counter; struct ScheduledPosition { QPointF pos; QSizeF delta; QSizeF deltaNonAccelerated; quint32 time; quint64 timeUsec; }; static QVector s_scheduledPositions; PointerInputRedirection *m_pointer; }; int PositionUpdateBlocker::s_counter = 0; QVector PositionUpdateBlocker::s_scheduledPositions; void PointerInputRedirection::processMotion(const QPointF &pos, const QSizeF &delta, const QSizeF &deltaNonAccelerated, uint32_t time, quint64 timeUsec, LibInput::Device *device) { if (!inited()) { return; } if (PositionUpdateBlocker::isPositionBlocked()) { PositionUpdateBlocker::schedulePosition(pos, delta, deltaNonAccelerated, time, timeUsec); return; } PositionUpdateBlocker blocker(this); updatePosition(pos); MouseEvent event(QEvent::MouseMove, m_pos, Qt::NoButton, m_qtButtons, input()->keyboardModifiers(), time, delta, deltaNonAccelerated, timeUsec, device); event.setModifiersRelevantForGlobalShortcuts(input()->modifiersRelevantForGlobalShortcuts()); update(); input()->processSpies(std::bind(&InputEventSpy::pointerEvent, std::placeholders::_1, &event)); input()->processFilters(std::bind(&InputEventFilter::pointerEvent, std::placeholders::_1, &event, 0)); } void PointerInputRedirection::processButton(uint32_t button, InputRedirection::PointerButtonState state, uint32_t time, LibInput::Device *device) { QEvent::Type type; switch (state) { case InputRedirection::PointerButtonReleased: type = QEvent::MouseButtonRelease; break; case InputRedirection::PointerButtonPressed: type = QEvent::MouseButtonPress; update(); break; default: Q_UNREACHABLE(); return; } updateButton(button, state); MouseEvent event(type, m_pos, buttonToQtMouseButton(button), m_qtButtons, input()->keyboardModifiers(), time, QSizeF(), QSizeF(), 0, device); event.setModifiersRelevantForGlobalShortcuts(input()->modifiersRelevantForGlobalShortcuts()); event.setNativeButton(button); input()->processSpies(std::bind(&InputEventSpy::pointerEvent, std::placeholders::_1, &event)); if (!inited()) { return; } input()->processFilters(std::bind(&InputEventFilter::pointerEvent, std::placeholders::_1, &event, button)); if (state == InputRedirection::PointerButtonReleased) { update(); } } void PointerInputRedirection::processAxis(InputRedirection::PointerAxis axis, qreal delta, qint32 discreteDelta, InputRedirection::PointerAxisSource source, uint32_t time, LibInput::Device *device) { update(); emit input()->pointerAxisChanged(axis, delta); WheelEvent wheelEvent(m_pos, delta, discreteDelta, (axis == InputRedirection::PointerAxisHorizontal) ? Qt::Horizontal : Qt::Vertical, m_qtButtons, input()->keyboardModifiers(), source, time, device); wheelEvent.setModifiersRelevantForGlobalShortcuts(input()->modifiersRelevantForGlobalShortcuts()); input()->processSpies(std::bind(&InputEventSpy::wheelEvent, std::placeholders::_1, &wheelEvent)); if (!inited()) { return; } input()->processFilters(std::bind(&InputEventFilter::wheelEvent, std::placeholders::_1, &wheelEvent)); } void PointerInputRedirection::processSwipeGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } input()->processSpies(std::bind(&InputEventSpy::swipeGestureBegin, std::placeholders::_1, fingerCount, time)); input()->processFilters(std::bind(&InputEventFilter::swipeGestureBegin, std::placeholders::_1, fingerCount, time)); } void PointerInputRedirection::processSwipeGestureUpdate(const QSizeF &delta, quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::swipeGestureUpdate, std::placeholders::_1, delta, time)); input()->processFilters(std::bind(&InputEventFilter::swipeGestureUpdate, std::placeholders::_1, delta, time)); } void PointerInputRedirection::processSwipeGestureEnd(quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::swipeGestureEnd, std::placeholders::_1, time)); input()->processFilters(std::bind(&InputEventFilter::swipeGestureEnd, std::placeholders::_1, time)); } void PointerInputRedirection::processSwipeGestureCancelled(quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::swipeGestureCancelled, std::placeholders::_1, time)); input()->processFilters(std::bind(&InputEventFilter::swipeGestureCancelled, std::placeholders::_1, time)); } void PointerInputRedirection::processPinchGestureBegin(int fingerCount, quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::pinchGestureBegin, std::placeholders::_1, fingerCount, time)); input()->processFilters(std::bind(&InputEventFilter::pinchGestureBegin, std::placeholders::_1, fingerCount, time)); } void PointerInputRedirection::processPinchGestureUpdate(qreal scale, qreal angleDelta, const QSizeF &delta, quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::pinchGestureUpdate, std::placeholders::_1, scale, angleDelta, delta, time)); input()->processFilters(std::bind(&InputEventFilter::pinchGestureUpdate, std::placeholders::_1, scale, angleDelta, delta, time)); } void PointerInputRedirection::processPinchGestureEnd(quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::pinchGestureEnd, std::placeholders::_1, time)); input()->processFilters(std::bind(&InputEventFilter::pinchGestureEnd, std::placeholders::_1, time)); } void PointerInputRedirection::processPinchGestureCancelled(quint32 time, KWin::LibInput::Device *device) { Q_UNUSED(device) if (!inited()) { return; } update(); input()->processSpies(std::bind(&InputEventSpy::pinchGestureCancelled, std::placeholders::_1, time)); input()->processFilters(std::bind(&InputEventFilter::pinchGestureCancelled, std::placeholders::_1, time)); } bool PointerInputRedirection::areButtonsPressed() const { for (auto state : m_buttons) { if (state == InputRedirection::PointerButtonPressed) { return true; } } return false; } bool PointerInputRedirection::focusUpdatesBlocked() { if (!inited()) { return true; } if (waylandServer()->seat()->isDragPointer()) { // ignore during drag and drop return true; } if (waylandServer()->seat()->isTouchSequence()) { // ignore during touch operations return true; } if (input()->isSelectingWindow()) { return true; } if (areButtonsPressed()) { return true; } return false; } void PointerInputRedirection::cleanupInternalWindow(QWindow *old, QWindow *now) { disconnect(m_internalWindowConnection); m_internalWindowConnection = QMetaObject::Connection(); if (old) { // leave internal window QEvent leaveEvent(QEvent::Leave); QCoreApplication::sendEvent(old, &leaveEvent); } if (now) { m_internalWindowConnection = connect(internalWindow().data(), &QWindow::visibleChanged, this, [this] (bool visible) { if (!visible) { update(); } } ); } } void PointerInputRedirection::cleanupDecoration(Decoration::DecoratedClientImpl *old, Decoration::DecoratedClientImpl *now) { disconnect(m_decorationGeometryConnection); m_decorationGeometryConnection = QMetaObject::Connection(); workspace()->updateFocusMousePosition(position().toPoint()); if (old) { // send leave event to old decoration QHoverEvent event(QEvent::HoverLeave, QPointF(), QPointF()); QCoreApplication::instance()->sendEvent(old->decoration(), &event); } if (!now) { // left decoration return; } waylandServer()->seat()->setFocusedPointerSurface(nullptr); auto pos = m_pos - now->client()->pos(); QHoverEvent event(QEvent::HoverEnter, pos, pos); QCoreApplication::instance()->sendEvent(now->decoration(), &event); now->client()->processDecorationMove(pos.toPoint(), m_pos.toPoint()); m_decorationGeometryConnection = connect(decoration()->client(), &AbstractClient::geometryChanged, this, [this] { // ensure maximize button gets the leave event when maximizing/restore a window, see BUG 385140 const auto oldDeco = decoration(); update(); if (oldDeco && oldDeco == decoration() && !decoration()->client()->isMove() && !decoration()->client()->isResize() && !areButtonsPressed()) { // position of window did not change, we need to send HoverMotion manually const QPointF p = m_pos - decoration()->client()->pos(); QHoverEvent event(QEvent::HoverMove, p, p); QCoreApplication::instance()->sendEvent(decoration()->decoration(), &event); } }, Qt::QueuedConnection); } static bool s_cursorUpdateBlocking = false; void PointerInputRedirection::focusUpdate(Toplevel *focusOld, Toplevel *focusNow) { if (AbstractClient *ac = qobject_cast(focusOld)) { ac->leaveEvent(); breakPointerConstraints(ac->surface()); disconnectPointerConstraintsConnection(); } disconnect(m_focusGeometryConnection); m_focusGeometryConnection = QMetaObject::Connection(); if (AbstractClient *ac = qobject_cast(focusNow)) { ac->enterEvent(m_pos.toPoint()); workspace()->updateFocusMousePosition(m_pos.toPoint()); } if (internalWindow()) { // enter internal window const auto pos = at()->pos(); QEnterEvent enterEvent(pos, pos, m_pos); QCoreApplication::sendEvent(internalWindow().data(), &enterEvent); } auto seat = waylandServer()->seat(); if (!focusNow || !focusNow->surface() || decoration()) { // Clean up focused pointer surface if there's no client to take focus, // or the pointer is on a client without surface or on a decoration. warpXcbOnSurfaceLeft(nullptr); seat->setFocusedPointerSurface(nullptr); return; } // TODO: add convenient API to update global pos together with updating focused surface warpXcbOnSurfaceLeft(focusNow->surface()); // TODO: why? in order to reset the cursor icon? s_cursorUpdateBlocking = true; seat->setFocusedPointerSurface(nullptr); s_cursorUpdateBlocking = false; seat->setPointerPos(m_pos.toPoint()); seat->setFocusedPointerSurface(focusNow->surface(), focusNow->inputTransformation()); m_focusGeometryConnection = connect(focusNow, &Toplevel::geometryChanged, this, [this] { // TODO: why no assert possible? if (!focus()) { return; } // TODO: can we check on the client instead? if (workspace()->moveResizeClient()) { // don't update while moving return; } auto seat = waylandServer()->seat(); if (focus()->surface() != seat->focusedPointerSurface()) { return; } seat->setFocusedPointerSurfaceTransformation(focus()->inputTransformation()); } ); m_constraintsConnection = connect(focusNow->surface(), &KWayland::Server::SurfaceInterface::pointerConstraintsChanged, this, &PointerInputRedirection::updatePointerConstraints); m_constraintsActivatedConnection = connect(workspace(), &Workspace::clientActivated, this, &PointerInputRedirection::updatePointerConstraints); updatePointerConstraints(); } void PointerInputRedirection::breakPointerConstraints(KWayland::Server::SurfaceInterface *surface) { // cancel pointer constraints if (surface) { auto c = surface->confinedPointer(); if (c && c->isConfined()) { c->setConfined(false); } auto l = surface->lockedPointer(); if (l && l->isLocked()) { l->setLocked(false); } } disconnectConfinedPointerRegionConnection(); m_confined = false; m_locked = false; } void PointerInputRedirection::disconnectConfinedPointerRegionConnection() { disconnect(m_confinedPointerRegionConnection); m_confinedPointerRegionConnection = QMetaObject::Connection(); } void PointerInputRedirection::disconnectLockedPointerAboutToBeUnboundConnection() { disconnect(m_lockedPointerAboutToBeUnboundConnection); m_lockedPointerAboutToBeUnboundConnection = QMetaObject::Connection(); } void PointerInputRedirection::disconnectPointerConstraintsConnection() { disconnect(m_constraintsConnection); m_constraintsConnection = QMetaObject::Connection(); disconnect(m_constraintsActivatedConnection); m_constraintsActivatedConnection = QMetaObject::Connection(); } template static QRegion getConstraintRegion(Toplevel *t, T *constraint) { const QRegion windowShape = t->inputShape(); const QRegion windowRegion = windowShape.isEmpty() ? QRegion(0, 0, t->clientSize().width(), t->clientSize().height()) : windowShape; const QRegion intersected = constraint->region().isEmpty() ? windowRegion : windowRegion.intersected(constraint->region()); return intersected.translated(t->pos() + t->clientPos()); } void PointerInputRedirection::setEnableConstraints(bool set) { if (m_enableConstraints == set) { return; } m_enableConstraints = set; updatePointerConstraints(); } void PointerInputRedirection::updatePointerConstraints() { if (focus().isNull()) { return; } const auto s = focus()->surface(); if (!s) { return; } if (s != waylandServer()->seat()->focusedPointerSurface()) { return; } if (!supportsWarping()) { return; } const bool canConstrain = m_enableConstraints && focus() == workspace()->activeClient(); const auto cf = s->confinedPointer(); if (cf) { if (cf->isConfined()) { if (!canConstrain) { cf->setConfined(false); m_confined = false; disconnectConfinedPointerRegionConnection(); } return; } const QRegion r = getConstraintRegion(focus().data(), cf.data()); if (canConstrain && r.contains(m_pos.toPoint())) { cf->setConfined(true); m_confined = true; m_confinedPointerRegionConnection = connect(cf.data(), &KWayland::Server::ConfinedPointerInterface::regionChanged, this, [this] { if (!focus()) { return; } const auto s = focus()->surface(); if (!s) { return; } const auto cf = s->confinedPointer(); if (!getConstraintRegion(focus().data(), cf.data()).contains(m_pos.toPoint())) { // pointer no longer in confined region, break the confinement cf->setConfined(false); m_confined = false; } else { if (!cf->isConfined()) { cf->setConfined(true); m_confined = true; } } } ); return; } } else { m_confined = false; disconnectConfinedPointerRegionConnection(); } const auto lock = s->lockedPointer(); if (lock) { if (lock->isLocked()) { if (!canConstrain) { const auto hint = lock->cursorPositionHint(); lock->setLocked(false); m_locked = false; disconnectLockedPointerAboutToBeUnboundConnection(); if (! (hint.x() < 0 || hint.y() < 0) && focus()) { processMotion(focus()->pos() - focus()->clientContentPos() + hint, waylandServer()->seat()->timestamp()); } } return; } const QRegion r = getConstraintRegion(focus().data(), lock.data()); if (canConstrain && r.contains(m_pos.toPoint())) { lock->setLocked(true); m_locked = true; // The client might cancel pointer locking from its side by unbinding the LockedPointerInterface. // In this case the cached cursor position hint must be fetched before the resource goes away m_lockedPointerAboutToBeUnboundConnection = connect(lock.data(), &KWayland::Server::LockedPointerInterface::aboutToBeUnbound, this, [this, lock]() { const auto hint = lock->cursorPositionHint(); if (hint.x() < 0 || hint.y() < 0 || !focus()) { return; } auto globalHint = focus()->pos() - focus()->clientContentPos() + hint; // When the resource finally goes away, reposition the cursor according to the hint connect(lock.data(), &KWayland::Server::LockedPointerInterface::unbound, this, [this, globalHint]() { processMotion(globalHint, waylandServer()->seat()->timestamp()); }); } ); // TODO: connect to region change - is it needed at all? If the pointer is locked it's always in the region } } else { m_locked = false; disconnectLockedPointerAboutToBeUnboundConnection(); } } void PointerInputRedirection::warpXcbOnSurfaceLeft(KWayland::Server::SurfaceInterface *newSurface) { auto xc = waylandServer()->xWaylandConnection(); if (!xc) { // No XWayland, no point in warping the x cursor return; } const auto c = kwinApp()->x11Connection(); if (!c) { return; } static bool s_hasXWayland119 = xcb_get_setup(c)->release_number >= 11900000; if (s_hasXWayland119) { return; } if (newSurface && newSurface->client() == xc) { // new window is an X window return; } auto s = waylandServer()->seat()->focusedPointerSurface(); if (!s || s->client() != xc) { // pointer was not on an X window return; } // warp pointer to 0/0 to trigger leave events on previously focused X window xcb_warp_pointer(c, XCB_WINDOW_NONE, kwinApp()->x11RootWindow(), 0, 0, 0, 0, 0, 0), xcb_flush(c); } QPointF PointerInputRedirection::applyPointerConfinement(const QPointF &pos) const { if (!focus()) { return pos; } auto s = focus()->surface(); if (!s) { return pos; } auto cf = s->confinedPointer(); if (!cf) { return pos; } if (!cf->isConfined()) { return pos; } const QRegion confinementRegion = getConstraintRegion(focus().data(), cf.data()); if (confinementRegion.contains(pos.toPoint())) { return pos; } QPointF p = pos; // allow either x or y to pass p = QPointF(m_pos.x(), pos.y()); if (confinementRegion.contains(p.toPoint())) { return p; } p = QPointF(pos.x(), m_pos.y()); if (confinementRegion.contains(p.toPoint())) { return p; } return m_pos; } void PointerInputRedirection::updatePosition(const QPointF &pos) { if (m_locked) { // locked pointer should not move return; } // verify that at least one screen contains the pointer position QPointF p = pos; if (!screenContainsPos(p)) { const QRectF unitedScreensGeometry = screens()->geometry(); p = confineToBoundingBox(p, unitedScreensGeometry); if (!screenContainsPos(p)) { const QRectF currentScreenGeometry = screens()->geometry(screens()->number(m_pos.toPoint())); p = confineToBoundingBox(p, currentScreenGeometry); } } p = applyPointerConfinement(p); if (p == m_pos) { // didn't change due to confinement return; } // verify screen confinement if (!screenContainsPos(p)) { return; } m_pos = p; emit input()->globalPointerChanged(m_pos); } void PointerInputRedirection::updateButton(uint32_t button, InputRedirection::PointerButtonState state) { m_buttons[button] = state; // update Qt buttons m_qtButtons = Qt::NoButton; for (auto it = m_buttons.constBegin(); it != m_buttons.constEnd(); ++it) { if (it.value() == InputRedirection::PointerButtonReleased) { continue; } m_qtButtons |= buttonToQtMouseButton(it.key()); } emit input()->pointerButtonStateChanged(button, state); } void PointerInputRedirection::warp(const QPointF &pos) { if (supportsWarping()) { kwinApp()->platform()->warpPointer(pos); processMotion(pos, waylandServer()->seat()->timestamp()); } } bool PointerInputRedirection::supportsWarping() const { if (!inited()) { return false; } if (m_supportsWarping) { return true; } if (kwinApp()->platform()->supportsPointerWarping()) { return true; } return false; } void PointerInputRedirection::updateAfterScreenChange() { if (!inited()) { return; } if (screenContainsPos(m_pos)) { // pointer still on a screen return; } // pointer no longer on a screen, reposition to closes screen const QPointF pos = screens()->geometry(screens()->number(m_pos.toPoint())).center(); // TODO: better way to get timestamps processMotion(pos, waylandServer()->seat()->timestamp()); } QImage PointerInputRedirection::cursorImage() const { if (!inited()) { return QImage(); } return m_cursor->image(); } QPoint PointerInputRedirection::cursorHotSpot() const { if (!inited()) { return QPoint(); } return m_cursor->hotSpot(); } void PointerInputRedirection::markCursorAsRendered() { if (!inited()) { return; } m_cursor->markAsRendered(); } QPointF PointerInputRedirection::position() const { return m_pos.toPoint(); } void PointerInputRedirection::setEffectsOverrideCursor(Qt::CursorShape shape) { if (!inited()) { return; } // current pointer focus window should get a leave event update(); m_cursor->setEffectsOverrideCursor(shape); } void PointerInputRedirection::removeEffectsOverrideCursor() { if (!inited()) { return; } // cursor position might have changed while there was an effect in place update(); m_cursor->removeEffectsOverrideCursor(); } void PointerInputRedirection::setWindowSelectionCursor(const QByteArray &shape) { if (!inited()) { return; } // send leave to current pointer focus window updateToReset(); m_cursor->setWindowSelectionCursor(shape); } void PointerInputRedirection::removeWindowSelectionCursor() { if (!inited()) { return; } update(); m_cursor->removeWindowSelectionCursor(); } CursorImage::CursorImage(PointerInputRedirection *parent) : QObject(parent) , m_pointer(parent) { connect(waylandServer()->seat(), &KWayland::Server::SeatInterface::focusedPointerChanged, this, &CursorImage::update); connect(waylandServer()->seat(), &KWayland::Server::SeatInterface::dragStarted, this, &CursorImage::updateDrag); connect(waylandServer()->seat(), &KWayland::Server::SeatInterface::dragEnded, this, [this] { disconnect(m_drag.connection); reevaluteSource(); } ); if (waylandServer()->hasScreenLockerIntegration()) { connect(ScreenLocker::KSldApp::self(), &ScreenLocker::KSldApp::lockStateChanged, this, &CursorImage::reevaluteSource); } connect(m_pointer, &PointerInputRedirection::decorationChanged, this, &CursorImage::updateDecoration); // connect the move resize of all window auto setupMoveResizeConnection = [this] (AbstractClient *c) { connect(c, &AbstractClient::moveResizedChanged, this, &CursorImage::updateMoveResize); connect(c, &AbstractClient::moveResizeCursorChanged, this, &CursorImage::updateMoveResize); }; const auto clients = workspace()->allClientList(); std::for_each(clients.begin(), clients.end(), setupMoveResizeConnection); connect(workspace(), &Workspace::clientAdded, this, setupMoveResizeConnection); connect(waylandServer(), &WaylandServer::shellClientAdded, this, setupMoveResizeConnection); loadThemeCursor(Qt::ArrowCursor, &m_fallbackCursor); if (m_cursorTheme) { connect(m_cursorTheme, &WaylandCursorTheme::themeChanged, this, [this] { m_cursors.clear(); m_cursorsByName.clear(); loadThemeCursor(Qt::ArrowCursor, &m_fallbackCursor); updateDecorationCursor(); updateMoveResize(); // TODO: update effects } ); } m_surfaceRenderedTimer.start(); } CursorImage::~CursorImage() = default; void CursorImage::markAsRendered() { if (m_currentSource == CursorSource::DragAndDrop) { // always sending a frame rendered to the drag icon surface to not freeze QtWayland (see https://bugreports.qt.io/browse/QTBUG-51599 ) if (auto ddi = waylandServer()->seat()->dragSource()) { if (auto s = ddi->icon()) { s->frameRendered(m_surfaceRenderedTimer.elapsed()); } } auto p = waylandServer()->seat()->dragPointer(); if (!p) { return; } auto c = p->cursor(); if (!c) { return; } auto cursorSurface = c->surface(); if (cursorSurface.isNull()) { return; } cursorSurface->frameRendered(m_surfaceRenderedTimer.elapsed()); return; } if (m_currentSource != CursorSource::LockScreen && m_currentSource != CursorSource::PointerSurface) { return; } auto p = waylandServer()->seat()->focusedPointer(); if (!p) { return; } auto c = p->cursor(); if (!c) { return; } auto cursorSurface = c->surface(); if (cursorSurface.isNull()) { return; } cursorSurface->frameRendered(m_surfaceRenderedTimer.elapsed()); } void CursorImage::update() { if (s_cursorUpdateBlocking) { return; } using namespace KWayland::Server; disconnect(m_serverCursor.connection); auto p = waylandServer()->seat()->focusedPointer(); if (p) { m_serverCursor.connection = connect(p, &PointerInterface::cursorChanged, this, &CursorImage::updateServerCursor); } else { m_serverCursor.connection = QMetaObject::Connection(); reevaluteSource(); } } void CursorImage::updateDecoration() { disconnect(m_decorationConnection); auto deco = m_pointer->decoration(); AbstractClient *c = deco.isNull() ? nullptr : deco->client(); if (c) { m_decorationConnection = connect(c, &AbstractClient::moveResizeCursorChanged, this, &CursorImage::updateDecorationCursor); } else { m_decorationConnection = QMetaObject::Connection(); } updateDecorationCursor(); } void CursorImage::updateDecorationCursor() { m_decorationCursor.image = QImage(); m_decorationCursor.hotSpot = QPoint(); auto deco = m_pointer->decoration(); if (AbstractClient *c = deco.isNull() ? nullptr : deco->client()) { loadThemeCursor(c->cursor(), &m_decorationCursor); if (m_currentSource == CursorSource::Decoration) { emit changed(); } } reevaluteSource(); } void CursorImage::updateMoveResize() { m_moveResizeCursor.image = QImage(); m_moveResizeCursor.hotSpot = QPoint(); if (AbstractClient *c = workspace()->moveResizeClient()) { loadThemeCursor(c->cursor(), &m_moveResizeCursor); if (m_currentSource == CursorSource::MoveResize) { emit changed(); } } reevaluteSource(); } void CursorImage::updateServerCursor() { m_serverCursor.image = QImage(); m_serverCursor.hotSpot = QPoint(); reevaluteSource(); const bool needsEmit = m_currentSource == CursorSource::LockScreen || m_currentSource == CursorSource::PointerSurface; auto p = waylandServer()->seat()->focusedPointer(); if (!p) { if (needsEmit) { emit changed(); } return; } auto c = p->cursor(); if (!c) { if (needsEmit) { emit changed(); } return; } auto cursorSurface = c->surface(); if (cursorSurface.isNull()) { if (needsEmit) { emit changed(); } return; } auto buffer = cursorSurface.data()->buffer(); if (!buffer) { if (needsEmit) { emit changed(); } return; } m_serverCursor.hotSpot = c->hotspot(); m_serverCursor.image = buffer->data().copy(); m_serverCursor.image.setDevicePixelRatio(cursorSurface->scale()); if (needsEmit) { emit changed(); } } void CursorImage::loadTheme() { if (m_cursorTheme) { return; } // check whether we can create it if (waylandServer()->internalShmPool()) { m_cursorTheme = new WaylandCursorTheme(waylandServer()->internalShmPool(), this); connect(waylandServer(), &WaylandServer::terminatingInternalClientConnection, this, [this] { delete m_cursorTheme; m_cursorTheme = nullptr; } ); } } void CursorImage::setEffectsOverrideCursor(Qt::CursorShape shape) { loadThemeCursor(shape, &m_effectsCursor); if (m_currentSource == CursorSource::EffectsOverride) { emit changed(); } reevaluteSource(); } void CursorImage::removeEffectsOverrideCursor() { reevaluteSource(); } void CursorImage::setWindowSelectionCursor(const QByteArray &shape) { if (shape.isEmpty()) { loadThemeCursor(Qt::CrossCursor, &m_windowSelectionCursor); } else { loadThemeCursor(shape, &m_windowSelectionCursor); } if (m_currentSource == CursorSource::WindowSelector) { emit changed(); } reevaluteSource(); } void CursorImage::removeWindowSelectionCursor() { reevaluteSource(); } void CursorImage::updateDrag() { using namespace KWayland::Server; disconnect(m_drag.connection); m_drag.cursor.image = QImage(); m_drag.cursor.hotSpot = QPoint(); reevaluteSource(); if (auto p = waylandServer()->seat()->dragPointer()) { m_drag.connection = connect(p, &PointerInterface::cursorChanged, this, &CursorImage::updateDragCursor); } else { m_drag.connection = QMetaObject::Connection(); } updateDragCursor(); } void CursorImage::updateDragCursor() { m_drag.cursor.image = QImage(); m_drag.cursor.hotSpot = QPoint(); const bool needsEmit = m_currentSource == CursorSource::DragAndDrop; QImage additionalIcon; if (auto ddi = waylandServer()->seat()->dragSource()) { if (auto dragIcon = ddi->icon()) { if (auto buffer = dragIcon->buffer()) { additionalIcon = buffer->data().copy(); } } } auto p = waylandServer()->seat()->dragPointer(); if (!p) { if (needsEmit) { emit changed(); } return; } auto c = p->cursor(); if (!c) { if (needsEmit) { emit changed(); } return; } auto cursorSurface = c->surface(); if (cursorSurface.isNull()) { if (needsEmit) { emit changed(); } return; } auto buffer = cursorSurface.data()->buffer(); if (!buffer) { if (needsEmit) { emit changed(); } return; } m_drag.cursor.hotSpot = c->hotspot(); m_drag.cursor.image = buffer->data().copy(); if (needsEmit) { emit changed(); } // TODO: add the cursor image } void CursorImage::loadThemeCursor(CursorShape shape, Image *image) { loadThemeCursor(shape, m_cursors, image); } void CursorImage::loadThemeCursor(const QByteArray &shape, Image *image) { loadThemeCursor(shape, m_cursorsByName, image); } template void CursorImage::loadThemeCursor(const T &shape, QHash &cursors, Image *image) { loadTheme(); if (!m_cursorTheme) { return; } auto it = cursors.constFind(shape); if (it == cursors.constEnd()) { image->image = QImage(); image->hotSpot = QPoint(); wl_cursor_image *cursor = m_cursorTheme->get(shape); if (!cursor) { return; } wl_buffer *b = wl_cursor_image_get_buffer(cursor); if (!b) { return; } waylandServer()->internalClientConection()->flush(); waylandServer()->dispatch(); auto buffer = KWayland::Server::BufferInterface::get(waylandServer()->internalConnection()->getResource(KWayland::Client::Buffer::getId(b))); if (!buffer) { return; } auto scale = screens()->maxScale(); int hotSpotX = qRound(cursor->hotspot_x / scale); int hotSpotY = qRound(cursor->hotspot_y / scale); QImage img = buffer->data().copy(); img.setDevicePixelRatio(scale); it = decltype(it)(cursors.insert(shape, {img, QPoint(hotSpotX, hotSpotY)})); } image->hotSpot = it.value().hotSpot; image->image = it.value().image; } void CursorImage::reevaluteSource() { if (waylandServer()->seat()->isDragPointer()) { // TODO: touch drag? setSource(CursorSource::DragAndDrop); return; } if (waylandServer()->isScreenLocked()) { setSource(CursorSource::LockScreen); return; } if (input()->isSelectingWindow()) { setSource(CursorSource::WindowSelector); return; } if (effects && static_cast(effects)->isMouseInterception()) { setSource(CursorSource::EffectsOverride); return; } if (workspace() && workspace()->moveResizeClient()) { setSource(CursorSource::MoveResize); return; } if (!m_pointer->decoration().isNull()) { setSource(CursorSource::Decoration); return; } if (!m_pointer->focus().isNull() && waylandServer()->seat()->focusedPointer()) { setSource(CursorSource::PointerSurface); return; } setSource(CursorSource::Fallback); } void CursorImage::setSource(CursorSource source) { if (m_currentSource == source) { return; } m_currentSource = source; emit changed(); } QImage CursorImage::image() const { switch (m_currentSource) { case CursorSource::EffectsOverride: return m_effectsCursor.image; case CursorSource::MoveResize: return m_moveResizeCursor.image; case CursorSource::LockScreen: case CursorSource::PointerSurface: // lockscreen also uses server cursor image return m_serverCursor.image; case CursorSource::Decoration: return m_decorationCursor.image; case CursorSource::DragAndDrop: return m_drag.cursor.image; case CursorSource::Fallback: return m_fallbackCursor.image; case CursorSource::WindowSelector: return m_windowSelectionCursor.image; default: Q_UNREACHABLE(); } } QPoint CursorImage::hotSpot() const { switch (m_currentSource) { case CursorSource::EffectsOverride: return m_effectsCursor.hotSpot; case CursorSource::MoveResize: return m_moveResizeCursor.hotSpot; case CursorSource::LockScreen: case CursorSource::PointerSurface: // lockscreen also uses server cursor image return m_serverCursor.hotSpot; case CursorSource::Decoration: return m_decorationCursor.hotSpot; case CursorSource::DragAndDrop: return m_drag.cursor.hotSpot; case CursorSource::Fallback: return m_fallbackCursor.hotSpot; case CursorSource::WindowSelector: return m_windowSelectionCursor.hotSpot; default: Q_UNREACHABLE(); } } } diff --git a/pointer_input.h b/pointer_input.h index 0d85e72d1..b2ae58ca6 100644 --- a/pointer_input.h +++ b/pointer_input.h @@ -1,261 +1,261 @@ /******************************************************************** 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 Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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; } uint32_t qtMouseButtonToButton(Qt::MouseButton button); 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/workspace.cpp b/workspace.cpp index 05b44797e..eec37dcaa 100644 --- a/workspace.cpp +++ b/workspace.cpp @@ -1,1936 +1,1936 @@ /******************************************************************** 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) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "x11client.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 "internal_client.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 "xdgshellclient.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 (X11Client *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 = nullptr; Workspace::Workspace(const QString &sessionKey) : QObject(nullptr) , m_compositor(nullptr) // Unsorted , active_popup(nullptr) , active_popup_client(nullptr) , m_initialDesktop(1) , active_client(nullptr) , last_active_client(nullptr) , most_recently_raised(nullptr) , movingClient(nullptr) , delayfocus_client(nullptr) , force_restacking(false) , showing_desktop(false) , was_user_interaction(false) , block_focus(0) , m_userActionsMenu(new UserActionsMenu(this)) , client_keys_dialog(nullptr) , client_keys_client(nullptr) , global_shortcuts_disabled_for_client(false) , workspaceInit(true) , startup(nullptr) , set_active_client_recursion(0) , block_stacking_updates(0) , m_sessionManager(new SessionManager(this)) { // 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 = nullptr; if (!sessionKey.isEmpty()) loadSessionInfo(sessionKey); 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 { Q_ASSERT(kwinApp()->operationMode() == Application::OperationMode::OperationModeX11); m_compositor = X11Compositor::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 = nullptr; initWithX11(); Scripting::create(this); if (auto w = waylandServer()) { connect(w, &WaylandServer::shellClientAdded, this, [this] (XdgShellClient *c) { setupClientConnections(c); c->updateDecoration(false); updateClientLayer(c); if (!c->isInternal()) { const 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, &XdgShellClient::windowShown, this, [this, c] { updateClientLayer(c); // TODO: when else should we send the client through placement? if (c->hasTransientPlacementHint()) { const QRect area = clientArea(PlacementArea, Screens::self()->current(), c->desktop()); c->placeIn(area); } markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); if (c->wantsInput()) { activateClient(c); } } ); connect(c, &XdgShellClient::windowHidden, this, [this] { // TODO: update tabbox if it's displayed markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); } ); } ); connect(w, &WaylandServer::shellClientRemoved, this, [this] (XdgShellClient *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 == nullptr && activeClient() == nullptr && should_get_focus.count() == 0) { // No client activated in manage() if (new_active_client == nullptr) new_active_client = topClientOnDesktop(VirtualDesktopManager::self()->current(), -1); if (new_active_client == nullptr && !desktops.isEmpty()) new_active_client = findDesktop(true, VirtualDesktopManager::self()->current()); } if (new_active_client != nullptr) activateClient(new_active_client); } Workspace::~Workspace() { blockStackingUpdates(true); // TODO: grabXServer(); // Use stacking_order, so that kwin --replace keeps stacking order const QList 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 (auto it = stack.constBegin(), end = stack.constEnd(); it != end; ++it) { X11Client *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); } X11Client::cleanupX11(); if (waylandServer()) { const QList shellClients = waylandServer()->clients(); for (XdgShellClient *shellClient : shellClients) { shellClient->destroyClient(); } } for (auto it = unmanaged.begin(), end = unmanaged.end(); it != end; ++it) (*it)->release(ReleaseReason::KWinShutsDown); for (InternalClient *client : m_internalClients) { client->destroyClient(); } 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 = nullptr; } 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)); } X11Client *Workspace::createClient(xcb_window_t w, bool is_mapped) { StackingUpdatesBlocker blocker(this); X11Client *c = new X11Client(); setupClientConnections(c); if (X11Compositor *compositor = X11Compositor::self()) { connect(c, &X11Client::blockingCompositingChanged, compositor, &X11Compositor::updateClientCompositeBlocking); } connect(c, SIGNAL(clientFullScreenSet(KWin::X11Client *,bool,bool)), ScreenEdges::self(), SIGNAL(checkBlocking())); if (!c->manage(w, is_mapped)) { X11Client::deleteClient(c); return nullptr; } addClient(c); return c; } Unmanaged* Workspace::createUnmanaged(xcb_window_t w) { if (X11Compositor *compositor = X11Compositor::self()) { if (compositor->checkForOverlayWindow(w)) { return nullptr; } } Unmanaged* c = new Unmanaged(); if (!c->track(w)) { Unmanaged::deleteUnmanaged(c); return nullptr; } connect(c, &Unmanaged::needsRepaint, m_compositor, &Compositor::scheduleRepaint); addUnmanaged(c); emit unmanagedAdded(c); return c; } void Workspace::addClient(X11Client *c) { Group* grp = findGroup(c->window()); emit clientAdded(c); if (grp != nullptr) grp->gotLeader(c); if (c->isDesktop()) { desktops.append(c); if (active_client == nullptr && 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() == nullptr && 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(X11Client *c) { if (c == active_popup_client) closeActivePopup(); if (m_userActionsMenu->isMenuClient(c)) { m_userActionsMenu->close(); } 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 != nullptr) group->lostLeader(); if (c == most_recently_raised) most_recently_raised = nullptr; should_get_focus.removeAll(c); Q_ASSERT(c != active_client); if (c == last_active_client) last_active_client = nullptr; if (c == delayfocus_client) cancelDelayFocus(); emit clientRemoved(c); updateStackingOrder(true); updateClientArea(); updateTabbox(); } void Workspace::removeUnmanaged(Unmanaged* c) { Q_ASSERT(unmanaged.contains(c)); unmanaged.removeAll(c); emit unmanagedRemoved(c); markXStackingOrderAsDirty(); } void Workspace::addDeleted(Deleted* c, Toplevel *orig) { Q_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) { Q_ASSERT(deleted.contains(c)); emit deletedRemoved(c); deleted.removeAll(c); unconstrained_stacking_order.removeAll(c); stacking_order.removeAll(c); markXStackingOrderAsDirty(); if (!c->wasClient()) { return; } if (X11Compositor *compositor = X11Compositor::self()) { compositor->updateClientCompositeBlocking(); } } 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 (auto it = clients.constBegin(); it != clients.constEnd(); ++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 (auto 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 != nullptr && c->group() == client->group()) show = true; else show = false; } else { if (group != nullptr && c->group() == group) show = true; else if (client != nullptr && 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 (auto it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { X11Client *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) { X11Client *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 = nullptr; 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 == nullptr && !desktops.isEmpty()) c = findDesktop(true, desktop); if (c != active_client) setActiveClient(nullptr); if (c) requestFocus(c); else if (!desktops.isEmpty()) requestFocus(findDesktop(true, desktop)); else focusToNull(); } AbstractClient *Workspace::findClientToActivateOnDesktop(uint desktop) { if (movingClient != nullptr && 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()) { auto it = stackingOrder().constEnd(); while (it != stackingOrder().constBegin()) { X11Client *client = qobject_cast(*(--it)); if (!client) { continue; } if (!(client->isShown(false) && client->isOnDesktop(desktop) && client->isOnCurrentActivity() && client->isOnActiveScreen())) continue; if (client->frameGeometry().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 (auto it = stacking_order.constBegin(); it != stacking_order.constEnd(); ++it) { X11Client *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) { X11Client *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 = nullptr; //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 == nullptr && !desktops.isEmpty()) c = findDesktop(true, VirtualDesktopManager::self()->current()); if (c != active_client) setActiveClient(nullptr); 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 = nullptr; } 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 (X11Client *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 (auto 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")); 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; } X11Client *Workspace::findClient(std::function func) const { if (X11Client *ret = Toplevel::findInList(clients, func)) { return ret; } if (X11Client *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 (X11Client *ret = Toplevel::findInList(desktops, func)) { return ret; } if (InternalClient *ret = Toplevel::findInList(m_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; }); } X11Client *Workspace::findClient(Predicate predicate, xcb_window_t w) const { switch (predicate) { case Predicate::WindowMatch: return findClient([w](const X11Client *c) { return c->window() == w; }); case Predicate::WrapperIdMatch: return findClient([w](const X11Client *c) { return c->wrapperId() == w; }); case Predicate::FrameIdMatch: return findClient([w](const X11Client *c) { return c->frameId() == w; }); case Predicate::InputIdMatch: return findClient([w](const X11Client *c) { return c->inputId() == w; }); } return nullptr; } Toplevel *Workspace::findToplevel(std::function func) const { if (X11Client *ret = Toplevel::findInList(clients, func)) { return ret; } if (X11Client *ret = Toplevel::findInList(desktops, func)) { return ret; } if (Unmanaged *ret = Toplevel::findInList(unmanaged, func)) { return ret; } if (InternalClient *ret = Toplevel::findInList(m_internalClients, func)) { return ret; } return nullptr; } void Workspace::forEachToplevel(std::function func) { std::for_each(m_allClients.constBegin(), m_allClients.constEnd(), func); std::for_each(desktops.constBegin(), desktops.constEnd(), func); std::for_each(deleted.constBegin(), deleted.constEnd(), func); std::for_each(unmanaged.constBegin(), unmanaged.constEnd(), func); std::for_each(m_internalClients.constBegin(), m_internalClients.constEnd(), func); } 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); std::for_each(m_internalClients.constBegin(), m_internalClients.constEnd(), func); } Toplevel *Workspace::findInternal(QWindow *w) const { if (!w) { return nullptr; } if (kwinApp()->operationMode() == Application::OperationModeX11) { return findUnmanaged(w->winId()); } for (InternalClient *client : m_internalClients) { if (client->internalWindow() == w) { return client; } } return nullptr; } bool Workspace::compositing() const { return m_compositor && m_compositor->scene(); } 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 TabBox::TabBox *tabBox = TabBox::TabBox::self(); if (tabBox->isDisplayed()) { tabBox->reset(true); } #endif } void Workspace::addInternalClient(InternalClient *client) { m_internalClients.append(client); setupClientConnections(client); client->updateLayer(); if (client->isDecorated()) { client->keepInArea(clientArea(FullScreenArea, client)); } markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); emit internalClientAdded(client); } void Workspace::removeInternalClient(InternalClient *client) { m_internalClients.removeOne(client); markXStackingOrderAsDirty(); updateStackingOrder(true); updateClientArea(); emit internalClientRemoved(client); } Group* Workspace::findGroup(xcb_window_t leader) const { Q_ASSERT(leader != XCB_WINDOW_NONE); for (auto it = groups.constBegin(); it != groups.constEnd(); ++it) if ((*it)->leader() == leader) return *it; return nullptr; } // Client is group transient, but has no group set. Try to find // group with windows with the same client leader. Group* Workspace::findClientLeaderGroup(const X11Client *c) const { Group* ret = nullptr; for (auto it = clients.constBegin(); it != clients.constEnd(); ++it) { if (*it == c) continue; if ((*it)->wmClientLeader() == c->wmClientLeader()) { if (ret == nullptr || 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. QList old_group = (*it)->group()->members(); // old_group autodeletes when being empty for (int pos = 0; pos < old_group.count(); ++pos) { X11Client *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 (auto it = clients.constBegin(); it != clients.constEnd(); ++it) (*it)->checkTransient(w); } } // namespace diff --git a/workspace.h b/workspace.h index 27d33a4ae..547750c5c 100644 --- a/workspace.h +++ b/workspace.h @@ -1,808 +1,808 @@ /******************************************************************** 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) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "options.h" #include "sm.h" #include "utils.h" // Qt #include #include // std #include #include class KConfig; class KConfigGroup; class KStartupInfo; class KStartupInfoData; class KStartupInfoId; class QStringList; namespace KWin { namespace Xcb { class Tree; class Window; } class AbstractClient; class Compositor; class Deleted; class Group; class InternalClient; class KillWindow; class ShortcutDialog; class Toplevel; class Unmanaged; class UserActionsMenu; class X11Client; 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 X11Client *); 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 * X11Client *client = findClient([w](const X11Client *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 * X11Client *client = findClient(Predicate::WindowMatch, w); * @endcode * * @param func Unary function that accepts a X11Client *as argument and * returns a value convertible to bool. The value returned indicates whether the * X11Client *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::X11Client *The found Client or @c null * @see findClient(Predicate, xcb_window_t) */ X11Client *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::X11Client *The found Client or @c null * @see findClient(std::function) */ X11Client *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; void forEachToplevel(std::function func); /** * @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 XdgShellClient 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(X11Client *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(X11Client *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 QList &clientList() const { return clients; } /** * @return List of unmanaged "clients" currently registered in Workspace */ const QList &unmanagedList() const { return unmanaged; } /** * @return List of desktop "clients" currently managed by Workspace */ const QList &desktopList() const { return desktops; } /** * @return List of deleted "clients" currently managed by Workspace */ const QList &deletedList() const { return deleted; } /** * @returns List of all clients (either X11 or Wayland) currently managed by Workspace */ const QList allClientList() const { return m_allClients; } /** * @returns List of all internal clients currently managed by Workspace */ const QList &internalClients() const { return m_internalClients; } void stackScreenEdgesUnderOverrideRedirect(); SessionManager *sessionManager() const; 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 QList &stackingOrder() const; QList xStackingOrder() const; QList ensureStackingOrder(const QList &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, X11Client *c); void storeSubSession(const QString &name, QSet sessionIds); void loadSubSessionInfo(const QString &name); SessionInfo* takeSessionInfo(X11Client *); // 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 X11Client::pingWindow() void removeClient(X11Client *); // Only called from X11Client::destroyClient() or X11Client::releaseWindow() void setActiveClient(AbstractClient*); Group* findGroup(xcb_window_t leader) const; void addGroup(Group* group); void removeGroup(Group* group); Group* findClientLeaderGroup(const X11Client *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 = nullptr) const; bool globalShortcutsDisabled() const; void disableGlobalShortcutsForClient(bool disable); void setWasUserInteraction(); bool wasUserInteraction() const; int packPositionLeft(const AbstractClient *client, int oldX, bool leftEdge) const; int packPositionRight(const AbstractClient *client, int oldX, bool rightEdge) const; int packPositionUp(const AbstractClient *client, int oldY, bool topEdge) const; int packPositionDown(const AbstractClient *client, int oldY, bool bottomEdge) 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; } /** * Adds the internal client to Workspace. * * This method will be called by InternalClient when it's mapped. * * @see internalClientAdded * @internal */ void addInternalClient(InternalClient *client); /** * Removes the internal client from Workspace. * * This method is meant to be called only by InternalClient. * * @see internalClientRemoved * @internal */ void removeInternalClient(InternalClient *client); 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(); 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); 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::X11Client *); 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(); /** * This signal is emitted whenever an internal client is created. */ void internalClientAdded(KWin::InternalClient *client); /** * This signal is emitted whenever an internal client gets removed. */ void internalClientRemoved(KWin::InternalClient *client); 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 QList 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 X11Client *createClient(xcb_window_t w, bool is_mapped); void setupClientConnections(AbstractClient *client); void addClient(X11Client *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; QList clients; QList m_allClients; QList desktops; QList unmanaged; QList deleted; QList m_internalClients; QList unconstrained_stacking_order; // Topmost last QList stacking_order; // Topmost last QVector manual_overlays; //Topmost last bool force_restacking; QList 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; QList groups; bool was_user_interaction; QScopedPointer m_wasUserInteractionFilter; 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; SessionManager *m_sessionManager; 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 QList &Workspace::stackingOrder() const { // TODO: Q_ASSERT( block_stacking_updates == 0 ); return stacking_order; } inline bool Workspace::wasUserInteraction() const { return was_user_interaction; } inline SessionManager *Workspace::sessionManager() const { return m_sessionManager; } 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 (X11Client *) > 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 X11Client *c) { return findClient([c](const X11Client *test) { return test == c; }); } inline Workspace *workspace() { return Workspace::_self; } } // namespace Q_DECLARE_OPERATORS_FOR_FLAGS(KWin::Workspace::ActivityFlags) #endif diff --git a/xdgshellclient.cpp b/xdgshellclient.cpp index 65b50c4cb..58bb1ee05 100644 --- a/xdgshellclient.cpp +++ b/xdgshellclient.cpp @@ -1,1988 +1,1988 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin Copyright (C) 2018 David Edmundson -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "xdgshellclient.h" #include "cursor.h" #include "decorations/decoratedclient.h" #include "decorations/decorationbridge.h" #include "deleted.h" #include "placement.h" #include "screenedge.h" #include "screens.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "virtualdesktops.h" #include "wayland_server.h" #include "workspace.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(NET::WindowType) using namespace KWayland::Server; namespace KWin { XdgShellClient::XdgShellClient(XdgShellSurfaceInterface *surface) : AbstractClient() , m_xdgShellSurface(surface) , m_xdgShellPopup(nullptr) { setSurface(surface->surface()); init(); } XdgShellClient::XdgShellClient(XdgShellPopupInterface *surface) : AbstractClient() , m_xdgShellSurface(nullptr) , m_xdgShellPopup(surface) { setSurface(surface->surface()); init(); } XdgShellClient::~XdgShellClient() = default; void XdgShellClient::init() { m_requestGeometryBlockCounter++; connect(this, &XdgShellClient::desktopFileNameChanged, this, &XdgShellClient::updateIcon); createWindowId(); setupCompositing(); updateIcon(); // TODO: Initialize with null rect. m_frameGeometry = QRect(0, 0, -1, -1); m_windowGeometry = QRect(0, 0, -1, -1); if (waylandServer()->inputMethodConnection() == surface()->client()) { m_windowType = NET::OnScreenDisplay; } connect(surface(), &SurfaceInterface::unmapped, this, &XdgShellClient::unmap); connect(surface(), &SurfaceInterface::unbound, this, &XdgShellClient::destroyClient); connect(surface(), &SurfaceInterface::destroyed, this, &XdgShellClient::destroyClient); if (m_xdgShellSurface) { connect(m_xdgShellSurface, &XdgShellSurfaceInterface::destroyed, this, &XdgShellClient::destroyClient); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::configureAcknowledged, this, &XdgShellClient::handleConfigureAcknowledged); m_caption = m_xdgShellSurface->title().simplified(); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::titleChanged, this, &XdgShellClient::handleWindowTitleChanged); QTimer::singleShot(0, this, &XdgShellClient::updateCaption); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::moveRequested, this, &XdgShellClient::handleMoveRequested); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::resizeRequested, this, &XdgShellClient::handleResizeRequested); // Determine the resource name, this is inspired from ICCCM 4.1.2.5 // the binary name of the invoked client. QFileInfo info{m_xdgShellSurface->client()->executablePath()}; QByteArray resourceName; if (info.exists()) { resourceName = info.fileName().toUtf8(); } setResourceClass(resourceName, m_xdgShellSurface->windowClass()); setDesktopFileName(m_xdgShellSurface->windowClass()); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::windowClassChanged, this, &XdgShellClient::handleWindowClassChanged); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::minimizeRequested, this, &XdgShellClient::handleMinimizeRequested); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::maximizedChanged, this, &XdgShellClient::handleMaximizeRequested); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::fullscreenChanged, this, &XdgShellClient::handleFullScreenRequested); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::windowMenuRequested, this, &XdgShellClient::handleWindowMenuRequested); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::transientForChanged, this, &XdgShellClient::handleTransientForChanged); connect(m_xdgShellSurface, &XdgShellSurfaceInterface::windowGeometryChanged, this, &XdgShellClient::handleWindowGeometryChanged); auto global = static_cast(m_xdgShellSurface->global()); connect(global, &XdgShellInterface::pingDelayed, this, &XdgShellClient::handlePingDelayed); connect(global, &XdgShellInterface::pingTimeout, this, &XdgShellClient::handlePingTimeout); connect(global, &XdgShellInterface::pongReceived, this, &XdgShellClient::handlePongReceived); auto configure = [this] { if (m_closing) { return; } if (m_requestGeometryBlockCounter != 0 || areGeometryUpdatesBlocked()) { return; } m_xdgShellSurface->configure(xdgSurfaceStates(), m_requestedClientSize); }; connect(this, &AbstractClient::activeChanged, this, configure); connect(this, &AbstractClient::clientStartUserMovedResized, this, configure); connect(this, &AbstractClient::clientFinishUserMovedResized, this, configure); connect(this, &XdgShellClient::geometryChanged, this, &XdgShellClient::updateClientOutputs); connect(screens(), &Screens::changed, this, &XdgShellClient::updateClientOutputs); } else if (m_xdgShellPopup) { connect(m_xdgShellPopup, &XdgShellPopupInterface::configureAcknowledged, this, &XdgShellClient::handleConfigureAcknowledged); connect(m_xdgShellPopup, &XdgShellPopupInterface::grabRequested, this, &XdgShellClient::handleGrabRequested); connect(m_xdgShellPopup, &XdgShellPopupInterface::destroyed, this, &XdgShellClient::destroyClient); connect(m_xdgShellPopup, &XdgShellPopupInterface::windowGeometryChanged, this, &XdgShellClient::handleWindowGeometryChanged); } // set initial desktop setDesktop(VirtualDesktopManager::self()->current()); // setup shadow integration updateShadow(); connect(surface(), &SurfaceInterface::shadowChanged, this, &Toplevel::updateShadow); connect(waylandServer(), &WaylandServer::foreignTransientChanged, this, [this](KWayland::Server::SurfaceInterface *child) { if (child == surface()) { handleTransientForChanged(); } }); handleTransientForChanged(); AbstractClient::updateColorScheme(QString()); connect(surface(), &SurfaceInterface::committed, this, &XdgShellClient::finishInit); } void XdgShellClient::finishInit() { disconnect(surface(), &SurfaceInterface::committed, this, &XdgShellClient::finishInit); connect(surface(), &SurfaceInterface::committed, this, &XdgShellClient::handleCommitted); bool needsPlacement = !isInitialPositionSet(); if (supportsWindowRules()) { setupWindowRules(false); const QRect originalGeometry = QRect(pos(), sizeForClientSize(clientSize())); const QRect ruledGeometry = rules()->checkGeometry(originalGeometry, true); if (originalGeometry != ruledGeometry) { setFrameGeometry(ruledGeometry); } maximize(rules()->checkMaximize(maximizeMode(), true)); setDesktop(rules()->checkDesktop(desktop(), true)); setDesktopFileName(rules()->checkDesktopFile(desktopFileName(), true).toUtf8()); if (rules()->checkMinimize(isMinimized(), true)) { minimize(true); // No animation. } setSkipTaskbar(rules()->checkSkipTaskbar(skipTaskbar(), true)); setSkipPager(rules()->checkSkipPager(skipPager(), true)); setSkipSwitcher(rules()->checkSkipSwitcher(skipSwitcher(), true)); setKeepAbove(rules()->checkKeepAbove(keepAbove(), true)); setKeepBelow(rules()->checkKeepBelow(keepBelow(), true)); setShortcut(rules()->checkShortcut(shortcut().toString(), true)); updateColorScheme(); // Don't place the client if its position is set by a rule. if (rules()->checkPosition(invalidPoint, true) != invalidPoint) { needsPlacement = false; } // Don't place the client if the maximize state is set by a rule. if (requestedMaximizeMode() != MaximizeRestore) { needsPlacement = false; } discardTemporaryRules(); RuleBook::self()->discardUsed(this, false); // Remove Apply Now rules. updateWindowRules(Rules::All); } if (isFullScreen()) { needsPlacement = false; } if (needsPlacement) { const QRect area = workspace()->clientArea(PlacementArea, Screens::self()->current(), desktop()); placeIn(area); } m_requestGeometryBlockCounter--; if (m_requestGeometryBlockCounter == 0) { requestGeometry(m_blockedRequestGeometry); } m_isInitialized = true; } void XdgShellClient::destroyClient() { m_closing = true; #ifdef KWIN_BUILD_TABBOX TabBox::TabBox *tabBox = TabBox::TabBox::self(); if (tabBox->isDisplayed() && tabBox->currentClient() == this) { tabBox->nextPrev(true); } #endif if (isMoveResize()) { leaveMoveResize(); } // Replace ShellClient with an instance of Deleted in the stacking order. Deleted *deleted = Deleted::create(this); emit windowClosed(this, deleted); // Remove Force Temporarily rules. RuleBook::self()->discardUsed(this, true); destroyWindowManagementInterface(); destroyDecoration(); StackingUpdatesBlocker blocker(workspace()); if (transientFor()) { transientFor()->removeTransient(this); } 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; } } waylandServer()->removeClient(this); deleted->unrefWindow(); m_xdgShellSurface = nullptr; m_xdgShellPopup = nullptr; deleteClient(this); } void XdgShellClient::deleteClient(XdgShellClient *c) { delete c; } QRect XdgShellClient::bufferGeometry() const { return m_bufferGeometry; } QStringList XdgShellClient::activities() const { // TODO: implement return QStringList(); } QPoint XdgShellClient::clientContentPos() const { return -1 * clientPos(); } static QRect subSurfaceTreeRect(const SurfaceInterface *surface, const QPoint &position = QPoint()) { QRect rect(position, surface->size()); const QList> subSurfaces = surface->childSubSurfaces(); for (const QPointer &subSurface : subSurfaces) { if (Q_UNLIKELY(!subSurface)) { continue; } const SurfaceInterface *child = subSurface->surface(); if (Q_UNLIKELY(!child)) { continue; } rect |= subSurfaceTreeRect(child, position + subSurface->position()); } return rect; } QSize XdgShellClient::clientSize() const { const QRect boundingRect = subSurfaceTreeRect(surface()); return m_windowGeometry.size().boundedTo(boundingRect.size()); } void XdgShellClient::debug(QDebug &stream) const { stream.nospace(); stream << "\'XdgShellClient:" << surface() << ";WMCLASS:" << resourceClass() << ":" << resourceName() << ";Caption:" << caption() << "\'"; } bool XdgShellClient::belongsToDesktop() const { const auto clients = waylandServer()->clients(); return std::any_of(clients.constBegin(), clients.constEnd(), [this](const XdgShellClient *client) { if (belongsToSameApplication(client, SameApplicationChecks())) { return client->isDesktop(); } return false; } ); } Layer XdgShellClient::layerForDock() const { if (m_plasmaShellSurface) { switch (m_plasmaShellSurface->panelBehavior()) { case PlasmaShellSurfaceInterface::PanelBehavior::WindowsCanCover: return NormalLayer; case PlasmaShellSurfaceInterface::PanelBehavior::AutoHide: return AboveLayer; case PlasmaShellSurfaceInterface::PanelBehavior::WindowsGoBelow: case PlasmaShellSurfaceInterface::PanelBehavior::AlwaysVisible: return DockLayer; default: Q_UNREACHABLE(); break; } } return AbstractClient::layerForDock(); } QRect XdgShellClient::transparentRect() const { // TODO: implement return QRect(); } NET::WindowType XdgShellClient::windowType(bool direct, int supported_types) const { // TODO: implement Q_UNUSED(direct) Q_UNUSED(supported_types) return m_windowType; } double XdgShellClient::opacity() const { return m_opacity; } void XdgShellClient::setOpacity(double opacity) { const qreal newOpacity = qBound(0.0, opacity, 1.0); if (newOpacity == m_opacity) { return; } const qreal oldOpacity = m_opacity; m_opacity = newOpacity; addRepaintFull(); emit opacityChanged(this, oldOpacity); } void XdgShellClient::addDamage(const QRegion &damage) { const int offsetX = m_bufferGeometry.x() - frameGeometry().x(); const int offsetY = m_bufferGeometry.y() - frameGeometry().y(); repaints_region += damage.translated(offsetX, offsetY); Toplevel::addDamage(damage); } void XdgShellClient::markAsMapped() { if (!m_unmapped) { return; } m_unmapped = false; if (!ready_for_painting) { setReadyForPainting(); } else { addRepaintFull(); emit windowShown(this); } if (shouldExposeToWindowManagement()) { setupWindowManagementInterface(); } updateShowOnScreenEdge(); } void XdgShellClient::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::updateShadow); connect(decoration, &KDecoration2::Decoration::bordersChanged, this, [this]() { GeometryUpdatesBlocker blocker(this); RequestGeometryBlocker requestBlocker(this); const QRect oldGeometry = frameGeometry(); if (!isShade()) { checkWorkspacePosition(oldGeometry); } emit geometryShapeChanged(this, oldGeometry); } ); } setDecoration(decoration); // TODO: ensure the new geometry still fits into the client area (e.g. maximized windows) doSetGeometry(QRect(oldGeom.topLeft(), m_windowGeometry.size() + QSize(borderLeft() + borderRight(), borderBottom() + borderTop()))); emit geometryShapeChanged(this, oldGeom); } void XdgShellClient::updateDecoration(bool check_workspace_pos, bool force) { if (!force && ((!isDecorated() && noBorder()) || (isDecorated() && !noBorder()))) return; QRect oldgeom = frameGeometry(); QRect oldClientGeom = oldgeom.adjusted(borderLeft(), borderTop(), -borderRight(), -borderBottom()); blockGeometryUpdates(true); if (force) destroyDecoration(); if (!noBorder()) { createDecoration(oldgeom); } else destroyDecoration(); if (m_serverDecoration && isDecorated()) { m_serverDecoration->setMode(KWayland::Server::ServerSideDecorationManagerInterface::Mode::Server); } if (m_xdgDecoration) { auto mode = isDecorated() || m_userNoBorder ? XdgDecorationInterface::Mode::ServerSide: XdgDecorationInterface::Mode::ClientSide; m_xdgDecoration->configure(mode); if (m_requestGeometryBlockCounter == 0) { m_xdgShellSurface->configure(xdgSurfaceStates(), m_requestedClientSize); } } updateShadow(); if (check_workspace_pos) checkWorkspacePosition(oldgeom, -2, oldClientGeom); blockGeometryUpdates(false); } void XdgShellClient::setFrameGeometry(int x, int y, int w, int h, ForceGeometry_t force) { const QRect newGeometry = rules()->checkGeometry(QRect(x, y, w, h)); if (areGeometryUpdatesBlocked()) { // when the GeometryUpdateBlocker exits the current geom is passed to setGeometry // thus we need to set it here. m_frameGeometry = newGeometry; if (pendingGeometryUpdate() == PendingGeometryForced) { // maximum, nothing needed } else if (force == ForceGeometrySet) { setPendingGeometryUpdate(PendingGeometryForced); } else { setPendingGeometryUpdate(PendingGeometryNormal); } return; } if (pendingGeometryUpdate() != PendingGeometryNone) { // reset geometry to the one before blocking, so that we can compare properly m_frameGeometry = frameGeometryBeforeUpdateBlocking(); } const QSize requestedClientSize = newGeometry.size() - QSize(borderLeft() + borderRight(), borderTop() + borderBottom()); if (requestedClientSize == m_windowGeometry.size() && (m_requestedClientSize.isEmpty() || requestedClientSize == m_requestedClientSize)) { // size didn't change, and we don't need to explicitly request a new size doSetGeometry(newGeometry); updateMaximizeMode(m_requestedMaximizeMode); } else { // size did change, Client needs to provide a new buffer requestGeometry(newGeometry); } } QRect XdgShellClient::determineBufferGeometry() const { // Offset of the main surface relative to the frame rect. const int offsetX = borderLeft() - m_windowGeometry.left(); const int offsetY = borderTop() - m_windowGeometry.top(); QRect bufferGeometry; bufferGeometry.setX(x() + offsetX); bufferGeometry.setY(y() + offsetY); bufferGeometry.setSize(surface()->size()); return bufferGeometry; } void XdgShellClient::doSetGeometry(const QRect &rect) { bool frameGeometryIsChanged = false; bool bufferGeometryIsChanged = false; if (m_frameGeometry != rect) { m_frameGeometry = rect; frameGeometryIsChanged = true; } const QRect bufferGeometry = determineBufferGeometry(); if (m_bufferGeometry != bufferGeometry) { m_bufferGeometry = bufferGeometry; bufferGeometryIsChanged = true; } if (!frameGeometryIsChanged && !bufferGeometryIsChanged) { return; } if (m_unmapped && m_geomMaximizeRestore.isEmpty() && !m_frameGeometry.isEmpty()) { // use first valid geometry as restore geometry m_geomMaximizeRestore = m_frameGeometry; } if (frameGeometryIsChanged) { if (hasStrut()) { workspace()->updateClientArea(); } updateWindowRules(Rules::Position | Rules::Size); } const auto old = frameGeometryBeforeUpdateBlocking(); addRepaintDuringGeometryUpdates(); updateGeometryBeforeUpdateBlocking(); emit geometryShapeChanged(this, old); if (isResize()) { performMoveResize(); } } void XdgShellClient::doMove(int x, int y) { Q_UNUSED(x) Q_UNUSED(y) m_bufferGeometry = determineBufferGeometry(); } QByteArray XdgShellClient::windowRole() const { return QByteArray(); } bool XdgShellClient::belongsToSameApplication(const AbstractClient *other, SameApplicationChecks checks) const { if (checks.testFlag(SameApplicationCheck::AllowCrossProcesses)) { if (other->desktopFileName() == desktopFileName()) { return true; } } if (auto s = other->surface()) { return s->client() == surface()->client(); } return false; } void XdgShellClient::blockActivityUpdates(bool b) { Q_UNUSED(b) } QString XdgShellClient::captionNormal() const { return m_caption; } QString XdgShellClient::captionSuffix() const { return m_captionSuffix; } void XdgShellClient::updateCaption() { const QString oldSuffix = m_captionSuffix; const auto shortcut = shortcutCaptionSuffix(); m_captionSuffix = shortcut; if ((!isSpecialWindow() || isToolbar()) && findClientWithSameCaption()) { int i = 2; do { m_captionSuffix = shortcut + QLatin1String(" <") + QString::number(i) + QLatin1Char('>'); i++; } while (findClientWithSameCaption()); } if (m_captionSuffix != oldSuffix) { emit captionChanged(); } } void XdgShellClient::closeWindow() { if (m_xdgShellSurface && isCloseable()) { m_xdgShellSurface->close(); const qint32 pingSerial = static_cast(m_xdgShellSurface->global())->ping(m_xdgShellSurface); m_pingSerials.insert(pingSerial, PingReason::CloseWindow); } } AbstractClient *XdgShellClient::findModal(bool allow_itself) { Q_UNUSED(allow_itself) return nullptr; } bool XdgShellClient::isCloseable() const { if (m_windowType == NET::Desktop || m_windowType == NET::Dock) { return false; } if (m_xdgShellSurface) { return true; } return false; } bool XdgShellClient::isFullScreen() const { return m_fullScreen; } bool XdgShellClient::isMaximizable() const { if (!isResizable()) { return false; } if (rules()->checkMaximize(MaximizeRestore) != MaximizeRestore || rules()->checkMaximize(MaximizeFull) != MaximizeFull) { return false; } return true; } bool XdgShellClient::isMinimizable() const { if (!rules()->checkMinimize(true)) { return false; } return (!m_plasmaShellSurface || m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Normal); } bool XdgShellClient::isMovable() const { if (isFullScreen()) { return false; } if (rules()->checkPosition(invalidPoint) != invalidPoint) { return false; } if (m_plasmaShellSurface) { return m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Normal; } if (m_xdgShellPopup) { return false; } return true; } bool XdgShellClient::isMovableAcrossScreens() const { if (rules()->checkPosition(invalidPoint) != invalidPoint) { return false; } if (m_plasmaShellSurface) { return m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Normal; } if (m_xdgShellPopup) { return false; } return true; } bool XdgShellClient::isResizable() const { if (isFullScreen()) { return false; } if (rules()->checkSize(QSize()).isValid()) { return false; } if (m_plasmaShellSurface) { return m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Normal; } if (m_xdgShellPopup) { return false; } return true; } bool XdgShellClient::isShown(bool shaded_is_shown) const { Q_UNUSED(shaded_is_shown) return !m_closing && !m_unmapped && !isMinimized() && !m_hidden; } bool XdgShellClient::isHiddenInternal() const { return m_unmapped || m_hidden; } void XdgShellClient::hideClient(bool hide) { if (m_hidden == hide) { return; } m_hidden = hide; if (hide) { addWorkspaceRepaint(visibleRect()); workspace()->clientHidden(this); emit windowHidden(this); } else { emit windowShown(this); } } static bool changeMaximizeRecursion = false; void XdgShellClient::changeMaximize(bool horizontal, bool vertical, bool adjust) { if (changeMaximizeRecursion) { return; } if (!isResizable()) { return; } const QRect clientArea = isElectricBorderMaximizing() ? workspace()->clientArea(MaximizeArea, Cursor::pos(), desktop()) : workspace()->clientArea(MaximizeArea, this); const MaximizeMode oldMode = m_requestedMaximizeMode; const QRect oldGeometry = frameGeometry(); // 'adjust == true' means to update the size only, e.g. after changing workspace size if (!adjust) { if (vertical) m_requestedMaximizeMode = MaximizeMode(m_requestedMaximizeMode ^ MaximizeVertical); if (horizontal) m_requestedMaximizeMode = MaximizeMode(m_requestedMaximizeMode ^ MaximizeHorizontal); } m_requestedMaximizeMode = rules()->checkMaximize(m_requestedMaximizeMode); if (!adjust && m_requestedMaximizeMode == oldMode) { return; } StackingUpdatesBlocker blocker(workspace()); RequestGeometryBlocker geometryBlocker(this); // call into decoration update borders if (isDecorated() && decoration()->client() && !(options->borderlessMaximizedWindows() && m_requestedMaximizeMode == KWin::MaximizeFull)) { changeMaximizeRecursion = true; const auto c = decoration()->client().data(); if ((m_requestedMaximizeMode & MaximizeVertical) != (oldMode & MaximizeVertical)) { emit c->maximizedVerticallyChanged(m_requestedMaximizeMode & MaximizeVertical); } if ((m_requestedMaximizeMode & MaximizeHorizontal) != (oldMode & MaximizeHorizontal)) { emit c->maximizedHorizontallyChanged(m_requestedMaximizeMode & MaximizeHorizontal); } if ((m_requestedMaximizeMode == MaximizeFull) != (oldMode == MaximizeFull)) { emit c->maximizedChanged(m_requestedMaximizeMode & 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(m_requestedMaximizeMode == MaximizeFull)); changeMaximizeRecursion = false; } // Conditional quick tiling exit points const auto oldQuickTileMode = quickTileMode(); if (quickTileMode() != QuickTileMode(QuickTileFlag::None)) { if (oldMode == MaximizeFull && !clientArea.contains(m_geomMaximizeRestore.center())) { // Not restoring on the same screen // TODO: The following doesn't work for some reason //quick_tile_mode = QuickTileNone; // And exit quick tile mode manually } else if ((oldMode == MaximizeVertical && m_requestedMaximizeMode == MaximizeRestore) || (oldMode == MaximizeFull && m_requestedMaximizeMode == MaximizeHorizontal)) { // Modifying geometry of a tiled window updateQuickTileMode(QuickTileFlag::None); // Exit quick tile mode without restoring geometry } } if (m_requestedMaximizeMode == MaximizeFull) { m_geomMaximizeRestore = oldGeometry; // TODO: Client has more checks if (options->electricBorderMaximize()) { updateQuickTileMode(QuickTileFlag::Maximize); } else { updateQuickTileMode(QuickTileFlag::None); } if (quickTileMode() != oldQuickTileMode) { emit quickTileModeChanged(); } setFrameGeometry(workspace()->clientArea(MaximizeArea, this)); workspace()->raiseClient(this); } else { if (m_requestedMaximizeMode == MaximizeRestore) { updateQuickTileMode(QuickTileFlag::None); } if (quickTileMode() != oldQuickTileMode) { emit quickTileModeChanged(); } if (m_geomMaximizeRestore.isValid()) { setFrameGeometry(m_geomMaximizeRestore); } else { setFrameGeometry(workspace()->clientArea(PlacementArea, this)); } } } void XdgShellClient::setGeometryRestore(const QRect &geo) { m_geomMaximizeRestore = geo; } MaximizeMode XdgShellClient::maximizeMode() const { return m_maximizeMode; } MaximizeMode XdgShellClient::requestedMaximizeMode() const { return m_requestedMaximizeMode; } QRect XdgShellClient::geometryRestore() const { return m_geomMaximizeRestore; } bool XdgShellClient::noBorder() const { if (m_serverDecoration) { if (m_serverDecoration->mode() == ServerSideDecorationManagerInterface::Mode::Server) { return m_userNoBorder || isFullScreen(); } } if (m_xdgDecoration && m_xdgDecoration->requestedMode() != XdgDecorationInterface::Mode::ClientSide) { return m_userNoBorder || isFullScreen(); } return true; } bool XdgShellClient::isFullScreenable() const { if (!rules()->checkFullScreen(true)) { return false; } return !isSpecialWindow(); } void XdgShellClient::setFullScreen(bool set, bool user) { set = rules()->checkFullScreen(set); const bool wasFullscreen = isFullScreen(); if (wasFullscreen == set) { return; } if (isSpecialWindow()) { return; } if (user && !userCanSetFullScreen()) { return; } if (wasFullscreen) { workspace()->updateFocusMousePosition(Cursor::pos()); // may cause leave event } else { m_geomFsRestore = frameGeometry(); } m_fullScreen = set; if (set) { workspace()->raiseClient(this); } RequestGeometryBlocker requestBlocker(this); StackingUpdatesBlocker blocker1(workspace()); GeometryUpdatesBlocker blocker2(this); workspace()->updateClientLayer(this); // active fullscreens get different layer updateDecoration(false, false); if (set) { setFrameGeometry(workspace()->clientArea(FullScreenArea, this)); } else { if (m_geomFsRestore.isValid()) { int currentScreen = screen(); setFrameGeometry(QRect(m_geomFsRestore.topLeft(), adjustedSize(m_geomFsRestore.size()))); if( currentScreen != screen()) workspace()->sendClientToScreen( this, currentScreen ); } else { // this can happen when the window was first shown already fullscreen, // so let the client set the size by itself setFrameGeometry(QRect(workspace()->clientArea(PlacementArea, this).topLeft(), QSize(0, 0))); } } updateWindowRules(Rules::Fullscreen|Rules::Position|Rules::Size); emit fullScreenChanged(); } void XdgShellClient::setNoBorder(bool set) { if (!userCanSetNoBorder()) { return; } set = rules()->checkNoBorder(set); if (m_userNoBorder == set) { return; } m_userNoBorder = set; updateDecoration(true, false); updateWindowRules(Rules::NoBorder); } void XdgShellClient::setOnAllActivities(bool set) { Q_UNUSED(set) } void XdgShellClient::takeFocus() { if (rules()->checkAcceptFocus(wantsInput())) { if (m_xdgShellSurface) { const qint32 pingSerial = static_cast(m_xdgShellSurface->global())->ping(m_xdgShellSurface); m_pingSerials.insert(pingSerial, PingReason::FocusWindow); } setActive(true); } if (!keepAbove() && !isOnScreenDisplay() && !belongsToDesktop()) { workspace()->setShowingDesktop(false); } } void XdgShellClient::doSetActive() { if (!isActive()) { return; } StackingUpdatesBlocker blocker(workspace()); workspace()->focusToNull(); } bool XdgShellClient::userCanSetFullScreen() const { if (m_xdgShellSurface) { return true; } return false; } bool XdgShellClient::userCanSetNoBorder() const { if (m_serverDecoration && m_serverDecoration->mode() == ServerSideDecorationManagerInterface::Mode::Server) { return !isFullScreen() && !isShade(); } if (m_xdgDecoration && m_xdgDecoration->requestedMode() != XdgDecorationInterface::Mode::ClientSide) { return !isFullScreen() && !isShade(); } return false; } bool XdgShellClient::wantsInput() const { return rules()->checkAcceptFocus(acceptsFocus()); } bool XdgShellClient::acceptsFocus() const { if (waylandServer()->inputMethodConnection() == surface()->client()) { return false; } if (m_plasmaShellSurface) { if (m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::OnScreenDisplay || m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::ToolTip) { return false; } if (m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Notification || m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::CriticalNotification) { return m_plasmaShellSurface->panelTakesFocus(); } } if (m_closing) { // a closing window does not accept focus return false; } if (m_unmapped) { // an unmapped window does not accept focus return false; } if (m_xdgShellSurface) { // TODO: proper return true; } return false; } void XdgShellClient::createWindowId() { m_windowId = waylandServer()->createWindowId(surface()); } pid_t XdgShellClient::pid() const { return surface()->client()->processId(); } bool XdgShellClient::isLockScreen() const { return surface()->client() == waylandServer()->screenLockerClientConnection(); } bool XdgShellClient::isInputMethod() const { return surface()->client() == waylandServer()->inputMethodConnection(); } void XdgShellClient::requestGeometry(const QRect &rect) { if (m_requestGeometryBlockCounter != 0) { m_blockedRequestGeometry = rect; return; } QSize size; if (rect.isValid()) { size = rect.size() - QSize(borderLeft() + borderRight(), borderTop() + borderBottom()); } else { size = QSize(0, 0); } m_requestedClientSize = size; quint64 serialId = 0; if (m_xdgShellSurface) { serialId = m_xdgShellSurface->configure(xdgSurfaceStates(), size); } if (m_xdgShellPopup) { auto parent = transientFor(); if (parent) { const QPoint globalClientContentPos = parent->frameGeometry().topLeft() + parent->clientPos(); const QPoint relativeOffset = rect.topLeft() - globalClientContentPos; serialId = m_xdgShellPopup->configure(QRect(relativeOffset, size)); } } if (rect.isValid()) { //if there's no requested size, then there's implicity no positional information worth using PendingConfigureRequest configureRequest; configureRequest.serialId = serialId; configureRequest.positionAfterResize = rect.topLeft(); configureRequest.maximizeMode = m_requestedMaximizeMode; m_pendingConfigureRequests.append(configureRequest); } m_blockedRequestGeometry = QRect(); } void XdgShellClient::updatePendingGeometry() { QPoint position = pos(); MaximizeMode maximizeMode = m_maximizeMode; for (auto it = m_pendingConfigureRequests.begin(); it != m_pendingConfigureRequests.end(); it++) { if (it->serialId > m_lastAckedConfigureRequest) { //this serial is not acked yet, therefore we know all future serials are not break; } if (it->serialId == m_lastAckedConfigureRequest) { if (position != it->positionAfterResize) { addLayerRepaint(frameGeometry()); } position = it->positionAfterResize; maximizeMode = it->maximizeMode; m_pendingConfigureRequests.erase(m_pendingConfigureRequests.begin(), ++it); break; } //else serialId < m_lastAckedConfigureRequest and the state is now irrelevant and can be ignored } doSetGeometry(QRect(position, m_windowGeometry.size() + QSize(borderLeft() + borderRight(), borderTop() + borderBottom()))); updateMaximizeMode(maximizeMode); } void XdgShellClient::handleConfigureAcknowledged(quint32 serial) { m_lastAckedConfigureRequest = serial; } void XdgShellClient::handleTransientForChanged() { SurfaceInterface *transientSurface = nullptr; if (m_xdgShellSurface) { if (auto transient = m_xdgShellSurface->transientFor().data()) { transientSurface = transient->surface(); } } if (m_xdgShellPopup) { transientSurface = m_xdgShellPopup->transientFor().data(); } if (!transientSurface) { transientSurface = waylandServer()->findForeignTransientForSurface(surface()); } XdgShellClient *transientClient = waylandServer()->findClient(transientSurface); if (transientClient != transientFor()) { // Remove from main client. if (transientFor()) { transientFor()->removeTransient(this); } setTransientFor(transientClient); if (transientClient) { transientClient->addTransient(this); } } m_transient = (transientSurface != nullptr); } void XdgShellClient::handleWindowClassChanged(const QByteArray &windowClass) { setResourceClass(resourceName(), windowClass); if (m_isInitialized && supportsWindowRules()) { setupWindowRules(true); applyWindowRules(); } setDesktopFileName(windowClass); } void XdgShellClient::handleWindowGeometryChanged(const QRect &windowGeometry) { m_windowGeometry = windowGeometry; m_hasWindowGeometry = true; } void XdgShellClient::handleWindowTitleChanged(const QString &title) { const QString oldSuffix = m_captionSuffix; m_caption = title.simplified(); updateCaption(); if (m_captionSuffix == oldSuffix) { // Don't emit caption change twice it already got emitted by the changing suffix. emit captionChanged(); } } void XdgShellClient::handleMoveRequested(SeatInterface *seat, quint32 serial) { // FIXME: Check the seat and serial. Q_UNUSED(seat) Q_UNUSED(serial) performMouseCommand(Options::MouseMove, Cursor::pos()); } void XdgShellClient::handleResizeRequested(SeatInterface *seat, quint32 serial, Qt::Edges edges) { // FIXME: Check the seat and serial. Q_UNUSED(seat) Q_UNUSED(serial) if (!isResizable() || isShade()) { return; } if (isMoveResize()) { finishMoveResize(false); } setMoveResizePointerButtonDown(true); setMoveOffset(Cursor::pos() - pos()); // map from global setInvertedMoveOffset(rect().bottomRight() - moveOffset()); setUnrestrictedMoveResize(false); auto toPosition = [edges] { Position position = PositionCenter; if (edges.testFlag(Qt::TopEdge)) { position = PositionTop; } else if (edges.testFlag(Qt::BottomEdge)) { position = PositionBottom; } if (edges.testFlag(Qt::LeftEdge)) { position = Position(position | PositionLeft); } else if (edges.testFlag(Qt::RightEdge)) { position = Position(position | PositionRight); } return position; }; setMoveResizePointerMode(toPosition()); if (!startMoveResize()) { setMoveResizePointerButtonDown(false); } updateCursor(); } void XdgShellClient::handleMinimizeRequested() { performMouseCommand(Options::MouseMinimize, Cursor::pos()); } void XdgShellClient::handleMaximizeRequested(bool maximized) { // If the maximized state of the client hasn't been changed due to a window // rule or because the requested state is the same as the current, then the // compositor still has to send a configure event. RequestGeometryBlocker blocker(this); maximize(maximized ? MaximizeFull : MaximizeRestore); } void XdgShellClient::handleFullScreenRequested(bool fullScreen, OutputInterface *output) { // FIXME: Consider output as well. Q_UNUSED(output); setFullScreen(fullScreen, false); } void XdgShellClient::handleWindowMenuRequested(SeatInterface *seat, quint32 serial, const QPoint &surfacePos) { // FIXME: Check the seat and serial. Q_UNUSED(seat) Q_UNUSED(serial) performMouseCommand(Options::MouseOperationsMenu, pos() + surfacePos); } void XdgShellClient::handleGrabRequested(SeatInterface *seat, quint32 serial) { // FIXME: Check the seat and serial as well whether the parent had focus. Q_UNUSED(seat) Q_UNUSED(serial) m_hasPopupGrab = true; } void XdgShellClient::handlePingDelayed(quint32 serial) { auto it = m_pingSerials.find(serial); if (it != m_pingSerials.end()) { qCDebug(KWIN_CORE) << "First ping timeout:" << caption(); setUnresponsive(true); } } void XdgShellClient::handlePingTimeout(quint32 serial) { auto it = m_pingSerials.find(serial); if (it != m_pingSerials.end()) { if (it.value() == PingReason::CloseWindow) { qCDebug(KWIN_CORE) << "Final ping timeout on a close attempt, asking to kill:" << caption(); //for internal windows, killing the window will delete this QPointer guard(this); killWindow(); if (!guard) { return; } } m_pingSerials.erase(it); } } void XdgShellClient::handlePongReceived(quint32 serial) { auto it = m_pingSerials.find(serial); if (it != m_pingSerials.end()) { setUnresponsive(false); m_pingSerials.erase(it); } } void XdgShellClient::handleCommitted() { if (!surface()->buffer()) { return; } if (!m_hasWindowGeometry) { m_windowGeometry = subSurfaceTreeRect(surface()); } updatePendingGeometry(); setDepth((surface()->buffer()->hasAlphaChannel() && !isDesktop()) ? 32 : 24); markAsMapped(); } void XdgShellClient::resizeWithChecks(int w, int h, ForceGeometry_t force) { const 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(); } setFrameGeometry(x(), y(), w, h, force); } void XdgShellClient::unmap() { m_unmapped = true; if (isMoveResize()) { leaveMoveResize(); } m_requestedClientSize = QSize(0, 0); destroyWindowManagementInterface(); if (Workspace::self()) { addWorkspaceRepaint(visibleRect()); workspace()->clientHidden(this); } emit windowHidden(this); } void XdgShellClient::installPlasmaShellSurface(PlasmaShellSurfaceInterface *surface) { m_plasmaShellSurface = surface; auto updatePosition = [this, surface] { // That's a mis-use of doSetGeometry method. One should instead use move method. QRect rect = QRect(surface->position(), size()); doSetGeometry(rect); }; auto updateRole = [this, surface] { NET::WindowType type = NET::Unknown; switch (surface->role()) { case PlasmaShellSurfaceInterface::Role::Desktop: type = NET::Desktop; break; case PlasmaShellSurfaceInterface::Role::Panel: type = NET::Dock; break; case PlasmaShellSurfaceInterface::Role::OnScreenDisplay: type = NET::OnScreenDisplay; break; case PlasmaShellSurfaceInterface::Role::Notification: type = NET::Notification; break; case PlasmaShellSurfaceInterface::Role::ToolTip: type = NET::Tooltip; break; case PlasmaShellSurfaceInterface::Role::CriticalNotification: type = NET::CriticalNotification; break; case PlasmaShellSurfaceInterface::Role::Normal: default: type = NET::Normal; break; } if (type != m_windowType) { m_windowType = type; if (m_windowType == NET::Desktop || type == NET::Dock || type == NET::OnScreenDisplay || type == NET::Notification || type == NET::Tooltip || type == NET::CriticalNotification) { setOnAllDesktops(true); } workspace()->updateClientArea(); } }; connect(surface, &PlasmaShellSurfaceInterface::positionChanged, this, updatePosition); connect(surface, &PlasmaShellSurfaceInterface::roleChanged, this, updateRole); connect(surface, &PlasmaShellSurfaceInterface::panelBehaviorChanged, this, [this] { updateShowOnScreenEdge(); workspace()->updateClientArea(); } ); connect(surface, &PlasmaShellSurfaceInterface::panelAutoHideHideRequested, this, [this] { hideClient(true); m_plasmaShellSurface->hideAutoHidingPanel(); updateShowOnScreenEdge(); } ); connect(surface, &PlasmaShellSurfaceInterface::panelAutoHideShowRequested, this, [this] { hideClient(false); ScreenEdges::self()->reserve(this, ElectricNone); m_plasmaShellSurface->showAutoHidingPanel(); } ); updatePosition(); updateRole(); updateShowOnScreenEdge(); connect(this, &XdgShellClient::geometryChanged, this, &XdgShellClient::updateShowOnScreenEdge); setSkipTaskbar(surface->skipTaskbar()); connect(surface, &PlasmaShellSurfaceInterface::skipTaskbarChanged, this, [this] { setSkipTaskbar(m_plasmaShellSurface->skipTaskbar()); }); setSkipSwitcher(surface->skipSwitcher()); connect(surface, &PlasmaShellSurfaceInterface::skipSwitcherChanged, this, [this] { setSkipSwitcher(m_plasmaShellSurface->skipSwitcher()); }); } void XdgShellClient::updateShowOnScreenEdge() { if (!ScreenEdges::self()) { return; } if (m_unmapped || !m_plasmaShellSurface || m_plasmaShellSurface->role() != PlasmaShellSurfaceInterface::Role::Panel) { ScreenEdges::self()->reserve(this, ElectricNone); return; } if ((m_plasmaShellSurface->panelBehavior() == PlasmaShellSurfaceInterface::PanelBehavior::AutoHide && m_hidden) || m_plasmaShellSurface->panelBehavior() == PlasmaShellSurfaceInterface::PanelBehavior::WindowsCanCover) { // screen edge API requires an edge, thus we need to figure out which edge the window borders const QRect clientGeometry = frameGeometry(); Qt::Edges edges; for (int i = 0; i < screens()->count(); i++) { const QRect screenGeometry = screens()->geometry(i); if (screenGeometry.left() == clientGeometry.left()) { edges |= Qt::LeftEdge; } if (screenGeometry.right() == clientGeometry.right()) { edges |= Qt::RightEdge; } if (screenGeometry.top() == clientGeometry.top()) { edges |= Qt::TopEdge; } if (screenGeometry.bottom() == clientGeometry.bottom()) { edges |= Qt::BottomEdge; } } // a panel might border multiple screen edges. E.g. a horizontal panel at the bottom will // also border the left and right edge // let's remove such cases if (edges.testFlag(Qt::LeftEdge) && edges.testFlag(Qt::RightEdge)) { edges = edges & (~(Qt::LeftEdge | Qt::RightEdge)); } if (edges.testFlag(Qt::TopEdge) && edges.testFlag(Qt::BottomEdge)) { edges = edges & (~(Qt::TopEdge | Qt::BottomEdge)); } // it's still possible that a panel borders two edges, e.g. bottom and left // in that case the one which is sharing more with the edge wins auto check = [clientGeometry](Qt::Edges edges, Qt::Edge horiz, Qt::Edge vert) { if (edges.testFlag(horiz) && edges.testFlag(vert)) { if (clientGeometry.width() >= clientGeometry.height()) { return edges & ~horiz; } else { return edges & ~vert; } } return edges; }; edges = check(edges, Qt::LeftEdge, Qt::TopEdge); edges = check(edges, Qt::LeftEdge, Qt::BottomEdge); edges = check(edges, Qt::RightEdge, Qt::TopEdge); edges = check(edges, Qt::RightEdge, Qt::BottomEdge); ElectricBorder border = ElectricNone; if (edges.testFlag(Qt::LeftEdge)) { border = ElectricLeft; } if (edges.testFlag(Qt::RightEdge)) { border = ElectricRight; } if (edges.testFlag(Qt::TopEdge)) { border = ElectricTop; } if (edges.testFlag(Qt::BottomEdge)) { border = ElectricBottom; } ScreenEdges::self()->reserve(this, border); } else { ScreenEdges::self()->reserve(this, ElectricNone); } } bool XdgShellClient::isInitialPositionSet() const { if (m_plasmaShellSurface) { return m_plasmaShellSurface->isPositionSet(); } return false; } void XdgShellClient::installAppMenu(AppMenuInterface *menu) { m_appMenuInterface = menu; auto updateMenu = [this](AppMenuInterface::InterfaceAddress address) { updateApplicationMenuServiceName(address.serviceName); updateApplicationMenuObjectPath(address.objectPath); }; connect(m_appMenuInterface, &AppMenuInterface::addressChanged, this, [=](AppMenuInterface::InterfaceAddress address) { updateMenu(address); }); updateMenu(menu->address()); } void XdgShellClient::installPalette(ServerSideDecorationPaletteInterface *palette) { m_paletteInterface = palette; auto updatePalette = [this](const QString &palette) { AbstractClient::updateColorScheme(rules()->checkDecoColor(palette)); }; connect(m_paletteInterface, &ServerSideDecorationPaletteInterface::paletteChanged, this, [=](const QString &palette) { updatePalette(palette); }); connect(m_paletteInterface, &QObject::destroyed, this, [=]() { updatePalette(QString()); }); updatePalette(palette->palette()); } void XdgShellClient::updateColorScheme() { if (m_paletteInterface) { AbstractClient::updateColorScheme(rules()->checkDecoColor(m_paletteInterface->palette())); } else { AbstractClient::updateColorScheme(rules()->checkDecoColor(QString())); } } void XdgShellClient::updateMaximizeMode(MaximizeMode maximizeMode) { if (maximizeMode == m_maximizeMode) { return; } m_maximizeMode = maximizeMode; updateWindowRules(Rules::MaximizeHoriz | Rules::MaximizeVert | Rules::Position | Rules::Size); emit clientMaximizedStateChanged(this, m_maximizeMode); emit clientMaximizedStateChanged(this, m_maximizeMode & MaximizeHorizontal, m_maximizeMode & MaximizeVertical); } bool XdgShellClient::hasStrut() const { if (!isShown(true)) { return false; } if (!m_plasmaShellSurface) { return false; } if (m_plasmaShellSurface->role() != PlasmaShellSurfaceInterface::Role::Panel) { return false; } return m_plasmaShellSurface->panelBehavior() == PlasmaShellSurfaceInterface::PanelBehavior::AlwaysVisible; } quint32 XdgShellClient::windowId() const { return m_windowId; } void XdgShellClient::updateIcon() { const QString waylandIconName = QStringLiteral("wayland"); const QString dfIconName = iconFromDesktopFile(); const QString iconName = dfIconName.isEmpty() ? waylandIconName : dfIconName; if (iconName == icon().name()) { return; } setIcon(QIcon::fromTheme(iconName)); } bool XdgShellClient::isTransient() const { return m_transient; } bool XdgShellClient::hasTransientPlacementHint() const { return isTransient() && transientFor() && m_xdgShellPopup; } QRect XdgShellClient::transientPlacement(const QRect &bounds) const { QRect anchorRect; Qt::Edges anchorEdge; Qt::Edges gravity; QPoint offset; PositionerConstraints constraintAdjustments; QSize size = frameGeometry().size(); const QPoint parentClientPos = transientFor()->pos() + transientFor()->clientPos(); QRect popupPosition; // returns if a target is within the supplied bounds, optional edges argument states which side to check auto inBounds = [bounds](const QRect &target, Qt::Edges edges = Qt::LeftEdge | Qt::RightEdge | Qt::TopEdge | Qt::BottomEdge) -> bool { if (edges & Qt::LeftEdge && target.left() < bounds.left()) { return false; } if (edges & Qt::TopEdge && target.top() < bounds.top()) { return false; } if (edges & Qt::RightEdge && target.right() > bounds.right()) { //normal QRect::right issue cancels out return false; } if (edges & Qt::BottomEdge && target.bottom() > bounds.bottom()) { return false; } return true; }; if (m_xdgShellPopup) { anchorRect = m_xdgShellPopup->anchorRect(); anchorEdge = m_xdgShellPopup->anchorEdge(); gravity = m_xdgShellPopup->gravity(); offset = m_xdgShellPopup->anchorOffset(); constraintAdjustments = m_xdgShellPopup->constraintAdjustments(); if (!size.isValid()) { size = m_xdgShellPopup->initialSize(); } } else { Q_UNREACHABLE(); } //initial position popupPosition = QRect(popupOffset(anchorRect, anchorEdge, gravity, size) + offset + parentClientPos, size); //if that fits, we don't need to do anything if (inBounds(popupPosition)) { return popupPosition; } //otherwise apply constraint adjustment per axis in order XDG Shell Popup states if (constraintAdjustments & PositionerConstraint::FlipX) { if (!inBounds(popupPosition, Qt::LeftEdge | Qt::RightEdge)) { //flip both edges (if either bit is set, XOR both) auto flippedAnchorEdge = anchorEdge; if (flippedAnchorEdge & (Qt::LeftEdge | Qt::RightEdge)) { flippedAnchorEdge ^= (Qt::LeftEdge | Qt::RightEdge); } auto flippedGravity = gravity; if (flippedGravity & (Qt::LeftEdge | Qt::RightEdge)) { flippedGravity ^= (Qt::LeftEdge | Qt::RightEdge); } auto flippedPopupPosition = QRect(popupOffset(anchorRect, flippedAnchorEdge, flippedGravity, size) + offset + parentClientPos, size); //if it still doesn't fit we should continue with the unflipped version if (inBounds(flippedPopupPosition, Qt::LeftEdge | Qt::RightEdge)) { popupPosition.moveLeft(flippedPopupPosition.x()); } } } if (constraintAdjustments & PositionerConstraint::SlideX) { if (!inBounds(popupPosition, Qt::LeftEdge)) { popupPosition.moveLeft(bounds.x()); } if (!inBounds(popupPosition, Qt::RightEdge)) { // moveRight suffers from the classic QRect off by one issue popupPosition.moveLeft(bounds.x() + bounds.width() - size.width()); } } if (constraintAdjustments & PositionerConstraint::ResizeX) { //TODO //but we need to sort out when this is run as resize should only happen before first configure } if (constraintAdjustments & PositionerConstraint::FlipY) { if (!inBounds(popupPosition, Qt::TopEdge | Qt::BottomEdge)) { //flip both edges (if either bit is set, XOR both) auto flippedAnchorEdge = anchorEdge; if (flippedAnchorEdge & (Qt::TopEdge | Qt::BottomEdge)) { flippedAnchorEdge ^= (Qt::TopEdge | Qt::BottomEdge); } auto flippedGravity = gravity; if (flippedGravity & (Qt::TopEdge | Qt::BottomEdge)) { flippedGravity ^= (Qt::TopEdge | Qt::BottomEdge); } auto flippedPopupPosition = QRect(popupOffset(anchorRect, flippedAnchorEdge, flippedGravity, size) + offset + parentClientPos, size); //if it still doesn't fit we should continue with the unflipped version if (inBounds(flippedPopupPosition, Qt::TopEdge | Qt::BottomEdge)) { popupPosition.moveTop(flippedPopupPosition.y()); } } } if (constraintAdjustments & PositionerConstraint::SlideY) { if (!inBounds(popupPosition, Qt::TopEdge)) { popupPosition.moveTop(bounds.y()); } if (!inBounds(popupPosition, Qt::BottomEdge)) { popupPosition.moveTop(bounds.y() + bounds.height() - size.height()); } } if (constraintAdjustments & PositionerConstraint::ResizeY) { //TODO } return popupPosition; } QPoint XdgShellClient::popupOffset(const QRect &anchorRect, const Qt::Edges anchorEdge, const Qt::Edges gravity, const QSize popupSize) const { QPoint anchorPoint; switch (anchorEdge & (Qt::LeftEdge | Qt::RightEdge)) { case Qt::LeftEdge: anchorPoint.setX(anchorRect.x()); break; case Qt::RightEdge: anchorPoint.setX(anchorRect.x() + anchorRect.width()); break; default: anchorPoint.setX(qRound(anchorRect.x() + anchorRect.width() / 2.0)); } switch (anchorEdge & (Qt::TopEdge | Qt::BottomEdge)) { case Qt::TopEdge: anchorPoint.setY(anchorRect.y()); break; case Qt::BottomEdge: anchorPoint.setY(anchorRect.y() + anchorRect.height()); break; default: anchorPoint.setY(qRound(anchorRect.y() + anchorRect.height() / 2.0)); } // calculate where the top left point of the popup will end up with the applied gravity // gravity indicates direction. i.e if gravitating towards the top the popup's bottom edge // will next to the anchor point QPoint popupPosAdjust; switch (gravity & (Qt::LeftEdge | Qt::RightEdge)) { case Qt::LeftEdge: popupPosAdjust.setX(-popupSize.width()); break; case Qt::RightEdge: popupPosAdjust.setX(0); break; default: popupPosAdjust.setX(qRound(-popupSize.width() / 2.0)); } switch (gravity & (Qt::TopEdge | Qt::BottomEdge)) { case Qt::TopEdge: popupPosAdjust.setY(-popupSize.height()); break; case Qt::BottomEdge: popupPosAdjust.setY(0); break; default: popupPosAdjust.setY(qRound(-popupSize.height() / 2.0)); } return anchorPoint + popupPosAdjust; } void XdgShellClient::doResizeSync() { requestGeometry(moveResizeGeometry()); } QMatrix4x4 XdgShellClient::inputTransformation() const { QMatrix4x4 matrix; matrix.translate(-m_bufferGeometry.x(), -m_bufferGeometry.y()); return matrix; } void XdgShellClient::installServerSideDecoration(KWayland::Server::ServerSideDecorationInterface *deco) { if (m_serverDecoration == deco) { return; } m_serverDecoration = deco; connect(m_serverDecoration, &ServerSideDecorationInterface::destroyed, this, [this] { m_serverDecoration = nullptr; if (m_closing || !Workspace::self()) { return; } if (!m_unmapped) { // maybe delay to next event cycle in case the XdgShellClient is getting destroyed, too updateDecoration(true); } } ); if (!m_unmapped) { updateDecoration(true); } connect(m_serverDecoration, &ServerSideDecorationInterface::modeRequested, this, [this] (ServerSideDecorationManagerInterface::Mode mode) { const bool changed = mode != m_serverDecoration->mode(); if (changed && !m_unmapped) { updateDecoration(false); } } ); } void XdgShellClient::installXdgDecoration(XdgDecorationInterface *deco) { Q_ASSERT(m_xdgShellSurface); m_xdgDecoration = deco; connect(m_xdgDecoration, &QObject::destroyed, this, [this] { m_xdgDecoration = nullptr; if (m_closing || !Workspace::self()) { return; } updateDecoration(true); } ); connect(m_xdgDecoration, &XdgDecorationInterface::modeRequested, this, [this] () { //force is true as we must send a new configure response updateDecoration(false, true); }); } bool XdgShellClient::shouldExposeToWindowManagement() { if (isLockScreen()) { return false; } if (m_xdgShellPopup) { return false; } return true; } KWayland::Server::XdgShellSurfaceInterface::States XdgShellClient::xdgSurfaceStates() const { XdgShellSurfaceInterface::States states; if (isActive()) { states |= XdgShellSurfaceInterface::State::Activated; } if (isFullScreen()) { states |= XdgShellSurfaceInterface::State::Fullscreen; } if (m_requestedMaximizeMode == MaximizeMode::MaximizeFull) { states |= XdgShellSurfaceInterface::State::Maximized; } if (isResize()) { states |= XdgShellSurfaceInterface::State::Resizing; } return states; } void XdgShellClient::doMinimize() { if (isMinimized()) { workspace()->clientHidden(this); } else { emit windowShown(this); } workspace()->updateMinimizedOfTransients(this); } void XdgShellClient::placeIn(const QRect &area) { Placement::self()->place(this, area); setGeometryRestore(frameGeometry()); } void XdgShellClient::showOnScreenEdge() { if (!m_plasmaShellSurface || m_unmapped) { return; } hideClient(false); workspace()->raiseClient(this); if (m_plasmaShellSurface->panelBehavior() == PlasmaShellSurfaceInterface::PanelBehavior::AutoHide) { m_plasmaShellSurface->showAutoHidingPanel(); } } bool XdgShellClient::dockWantsInput() const { if (m_plasmaShellSurface) { if (m_plasmaShellSurface->role() == PlasmaShellSurfaceInterface::Role::Panel) { return m_plasmaShellSurface->panelTakesFocus(); } } return false; } void XdgShellClient::killWindow() { if (!surface()) { return; } auto c = surface()->client(); if (c->processId() == getpid() || c->processId() == 0) { c->destroy(); return; } ::kill(c->processId(), SIGTERM); // give it time to terminate and only if terminate fails, try destroy Wayland connection QTimer::singleShot(5000, c, &ClientConnection::destroy); } bool XdgShellClient::isLocalhost() const { return true; } bool XdgShellClient::hasPopupGrab() const { return m_hasPopupGrab; } void XdgShellClient::popupDone() { if (m_xdgShellPopup) { m_xdgShellPopup->popupDone(); } } void XdgShellClient::updateClientOutputs() { QVector clientOutputs; const auto outputs = waylandServer()->display()->outputs(); for (OutputInterface* output: qAsConst(outputs)) { const QRect outputGeom(output->globalPosition(), output->pixelSize() / output->scale()); if (frameGeometry().intersects(outputGeom)) { clientOutputs << output; } } surface()->setOutputs(clientOutputs); } bool XdgShellClient::isPopupWindow() const { if (Toplevel::isPopupWindow()) { return true; } if (m_xdgShellPopup != nullptr) { return true; } return false; } bool XdgShellClient::supportsWindowRules() const { if (m_plasmaShellSurface) { return false; } return m_xdgShellSurface; } } diff --git a/xdgshellclient.h b/xdgshellclient.h index 3b6a39f9b..9c23aacd4 100644 --- a/xdgshellclient.h +++ b/xdgshellclient.h @@ -1,268 +1,268 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2015 Martin Gräßlin Copyright (C) 2018 David Edmundson -Copyright (C) 2019 Vlad Zahorodnii +Copyright (C) 2019 Vlad Zahorodnii 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 "abstract_client.h" #include namespace KWayland { namespace Server { 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 XdgShellClient : public AbstractClient { Q_OBJECT public: XdgShellClient(KWayland::Server::XdgShellSurfaceInterface *surface); XdgShellClient(KWayland::Server::XdgShellPopupInterface *surface); ~XdgShellClient() override; QRect bufferGeometry() const 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; QString captionSuffix() const override; 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; void hideClient(bool hide) override; MaximizeMode maximizeMode() const override; MaximizeMode requestedMaximizeMode() const override; QRect geometryRestore() const override; 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::setFrameGeometry; void setFrameGeometry(int x, int y, int w, int h, ForceGeometry_t force = NormalGeometrySet) override; bool hasStrut() const override; quint32 windowId() const override; pid_t pid() const override; bool isLockScreen() const override; bool isInputMethod() const override; bool isInitialPositionSet() const override; bool isTransient() const override; bool hasTransientPlacementHint() const override; QRect transientPlacement(const QRect &bounds) const override; QMatrix4x4 inputTransformation() const override; void showOnScreenEdge() override; bool hasPopupGrab() const override; void popupDone() override; void updateColorScheme() override; bool isPopupWindow() const override; void killWindow() override; bool isLocalhost() const override; bool supportsWindowRules() const override; 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); void placeIn(const QRect &area); 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; void doResizeSync() override; bool acceptsFocus() const override; void doMinimize() override; void updateCaption() override; void doMove(int x, int y) override; private Q_SLOTS: void handleConfigureAcknowledged(quint32 serial); void handleTransientForChanged(); void handleWindowClassChanged(const QByteArray &windowClass); void handleWindowGeometryChanged(const QRect &windowGeometry); void handleWindowTitleChanged(const QString &title); void handleMoveRequested(KWayland::Server::SeatInterface *seat, quint32 serial); void handleResizeRequested(KWayland::Server::SeatInterface *seat, quint32 serial, Qt::Edges edges); void handleMinimizeRequested(); void handleMaximizeRequested(bool maximized); void handleFullScreenRequested(bool fullScreen, KWayland::Server::OutputInterface *output); void handleWindowMenuRequested(KWayland::Server::SeatInterface *seat, quint32 serial, const QPoint &surfacePos); void handleGrabRequested(KWayland::Server::SeatInterface *seat, quint32 serial); void handlePingDelayed(quint32 serial); void handlePingTimeout(quint32 serial); void handlePongReceived(quint32 serial); void handleCommitted(); 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(); void createDecoration(const QRect &oldgeom); void destroyClient(); void createWindowId(); void updateIcon(); bool shouldExposeToWindowManagement(); void updateClientOutputs(); 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; void requestGeometry(const QRect &rect); void doSetGeometry(const QRect &rect); void unmap(); void markAsMapped(); QRect determineBufferGeometry() const; static void deleteClient(XdgShellClient *c); KWayland::Server::XdgShellSurfaceInterface *m_xdgShellSurface; KWayland::Server::XdgShellPopupInterface *m_xdgShellPopup; QRect m_bufferGeometry; QRect m_windowGeometry; bool m_hasWindowGeometry = false; // 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_hasPopupGrab = false; qreal m_opacity = 1.0; class RequestGeometryBlocker { //TODO rename ConfigureBlocker when this class is Xdg only public: RequestGeometryBlocker(XdgShellClient *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: XdgShellClient *m_client; }; friend class RequestGeometryBlocker; int m_requestGeometryBlockCounter = 0; QRect m_blockedRequestGeometry; QString m_caption; QString m_captionSuffix; QHash m_pingSerials; bool m_isInitialized = false; friend class Workspace; }; } Q_DECLARE_METATYPE(KWin::XdgShellClient *)