diff --git a/autotests/integration/effects/translucency_test.cpp b/autotests/integration/effects/translucency_test.cpp index 0a8b7f2a1..507e87361 100644 --- a/autotests/integration/effects/translucency_test.cpp +++ b/autotests/integration/effects/translucency_test.cpp @@ -1,185 +1,186 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2016 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "kwin_wayland_test.h" #include "composite.h" #include "effects.h" #include "effectloader.h" #include "cursor.h" #include "platform.h" #include "scene_qpainter.h" #include "shell_client.h" #include "wayland_server.h" #include "workspace.h" #include "effect_builtins.h" #include #include #include using namespace KWin; static const QString s_socketName = QStringLiteral("wayland_test_effects_translucency-0"); class TranslucencyTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testMoveAfterDesktopChange(); private: Effect *m_translucencyEffect = nullptr; }; void TranslucencyTest::initTestCase() { qRegisterMetaType(); 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->group("Outline").writeEntry(QStringLiteral("QmlPath"), QString("/does/not/exist.qml")); config->sync(); kwinApp()->setConfig(config); + qputenv("KWIN_EFFECTS_FORCE_ANIMATIONS", "1"); kwinApp()->start(); QVERIFY(workspaceCreatedSpy.wait()); QVERIFY(Compositor::self()); } void TranslucencyTest::init() { // load the translucency effect EffectsHandlerImpl *e = static_cast(effects); // find the effectsloader auto effectloader = e->findChild(); QVERIFY(effectloader); QSignalSpy effectLoadedSpy(effectloader, &AbstractEffectLoader::effectLoaded); QVERIFY(effectLoadedSpy.isValid()); QVERIFY(!e->isEffectLoaded(QStringLiteral("kwin4_effect_translucency"))); QVERIFY(e->loadEffect(QStringLiteral("kwin4_effect_translucency"))); QVERIFY(e->isEffectLoaded(QStringLiteral("kwin4_effect_translucency"))); QCOMPARE(effectLoadedSpy.count(), 1); m_translucencyEffect = effectLoadedSpy.first().first().value(); QVERIFY(m_translucencyEffect); } void TranslucencyTest::cleanup() { EffectsHandlerImpl *e = static_cast(effects); if (e->isEffectLoaded(QStringLiteral("kwin4_effect_translucency"))) { e->unloadEffect(QStringLiteral("kwin4_effect_translucency")); } QVERIFY(!e->isEffectLoaded(QStringLiteral("kwin4_effect_translucency"))); m_translucencyEffect = nullptr; } void TranslucencyTest::testMoveAfterDesktopChange() { // test tries to simulate the condition of bug 366081 QVERIFY(!m_translucencyEffect->isActive()); QSignalSpy windowAddedSpy(effects, &EffectsHandler::windowAdded); QVERIFY(windowAddedSpy.isValid()); // create an xcb window struct XcbConnectionDeleter { static inline void cleanup(xcb_connection_t *pointer) { xcb_disconnect(pointer); } }; QScopedPointer c(xcb_connect(nullptr, nullptr)); QVERIFY(!xcb_connection_has_error(c.data())); const QRect windowGeometry(0, 0, 100, 200); xcb_window_t w = xcb_generate_id(c.data()); xcb_create_window(c.data(), XCB_COPY_FROM_PARENT, w, rootWindow(), windowGeometry.x(), windowGeometry.y(), windowGeometry.width(), windowGeometry.height(), 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_COPY_FROM_PARENT, 0, nullptr); xcb_size_hints_t hints; memset(&hints, 0, sizeof(hints)); xcb_icccm_size_hints_set_position(&hints, 1, windowGeometry.x(), windowGeometry.y()); xcb_icccm_size_hints_set_size(&hints, 1, windowGeometry.width(), windowGeometry.height()); xcb_icccm_set_wm_normal_hints(c.data(), w, &hints); xcb_map_window(c.data(), w); xcb_flush(c.data()); // we should get a client for it QSignalSpy windowCreatedSpy(workspace(), &Workspace::clientAdded); QVERIFY(windowCreatedSpy.isValid()); QVERIFY(windowCreatedSpy.wait()); Client *client = windowCreatedSpy.first().first().value(); QVERIFY(client); QCOMPARE(client->window(), w); QVERIFY(client->isDecorated()); QVERIFY(windowAddedSpy.wait()); QVERIFY(!m_translucencyEffect->isActive()); // let's send the window to desktop 2 effects->setNumberOfDesktops(2); QCOMPARE(effects->numberOfDesktops(), 2); workspace()->sendClientToDesktop(client, 2, false); effects->setCurrentDesktop(2); QVERIFY(!m_translucencyEffect->isActive()); KWin::Cursor::setPos(client->geometry().center()); workspace()->performWindowOperation(client, Options::MoveOp); QVERIFY(m_translucencyEffect->isActive()); QTest::qWait(200); QVERIFY(m_translucencyEffect->isActive()); // now end move resize client->endMoveResize(); QVERIFY(m_translucencyEffect->isActive()); QTest::qWait(500); QVERIFY(!m_translucencyEffect->isActive()); // and destroy the window again xcb_unmap_window(c.data(), w); xcb_flush(c.data()); QSignalSpy windowClosedSpy(client, &Client::windowClosed); QVERIFY(windowClosedSpy.isValid()); QVERIFY(windowClosedSpy.wait()); xcb_destroy_window(c.data(), w); c.reset(); } WAYLANDTEST_MAIN(TranslucencyTest) #include "translucency_test.moc" diff --git a/autotests/mock_effectshandler.h b/autotests/mock_effectshandler.h index 276780b56..ef1320acc 100644 --- a/autotests/mock_effectshandler.h +++ b/autotests/mock_effectshandler.h @@ -1,233 +1,243 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef MOCK_EFFECTS_HANDLER_H #define MOCK_EFFECTS_HANDLER_H #include class MockEffectsHandler : public KWin::EffectsHandler { Q_OBJECT public: explicit MockEffectsHandler(KWin::CompositingType type); void activateWindow(KWin::EffectWindow *) override {} KWin::Effect *activeFullScreenEffect() const { return nullptr; } int activeScreen() const override { return 0; } KWin::EffectWindow *activeWindow() const override { return nullptr; } void addRepaint(const QRect &) override {} void addRepaint(const QRegion &) override {} void addRepaint(int, int, int, int) override {} void addRepaintFull() override {} double animationTimeFactor() const override { return 0; } xcb_atom_t announceSupportProperty(const QByteArray &, KWin::Effect *) override { return XCB_ATOM_NONE; } void buildQuads(KWin::EffectWindow *, KWin::WindowQuadList &) override {} QRect clientArea(KWin::clientAreaOption, const QPoint &, int) const override { return QRect(); } QRect clientArea(KWin::clientAreaOption, const KWin::EffectWindow *) const override { return QRect(); } QRect clientArea(KWin::clientAreaOption, int, int) const override { return QRect(); } void closeTabBox() override {} QString currentActivity() const override { return QString(); } int currentDesktop() const override { return 0; } int currentTabBoxDesktop() const override { return 0; } QList< int > currentTabBoxDesktopList() const override { return QList(); } KWin::EffectWindow *currentTabBoxWindow() const override { return nullptr; } KWin::EffectWindowList currentTabBoxWindowList() const override { return KWin::EffectWindowList(); } QPoint cursorPos() const override { return QPoint(); } bool decorationsHaveAlpha() const override { return false; } bool decorationSupportsBlurBehind() const override { return false; } void defineCursor(Qt::CursorShape) override {} void deleteRootProperty(long int) const override {} int desktopAbove(int, bool) const override { return 0; } int desktopAtCoords(QPoint) const override { return 0; } int desktopBelow(int, bool) const override { return 0; } QPoint desktopCoords(int) const override { return QPoint(); } QPoint desktopGridCoords(int) const override { return QPoint(); } int desktopGridHeight() const override { return 0; } QSize desktopGridSize() const override { return QSize(); } int desktopGridWidth() const override { return 0; } QString desktopName(int) const override { return QString(); } int desktopToLeft(int, bool) const override { return 0; } int desktopToRight(int, bool) const override { return 0; } void doneOpenGLContextCurrent() override {} void drawWindow(KWin::EffectWindow *, int, QRegion, KWin::WindowPaintData &) override {} KWin::EffectFrame *effectFrame(KWin::EffectFrameStyle, bool, const QPoint &, Qt::Alignment) const override { return nullptr; } KWin::EffectWindow *findWindow(WId) const override { return nullptr; } KWin::EffectWindow *findWindow(KWayland::Server::SurfaceInterface *) const override { return nullptr; } void *getProxy(QString) override { return nullptr; } bool grabKeyboard(KWin::Effect *) override { return false; } bool hasDecorationShadows() const override { return false; } bool isScreenLocked() const override { return false; } QVariant kwinOption(KWin::KWinOption) override { return QVariant(); } bool makeOpenGLContextCurrent() override { return false; } void moveWindow(KWin::EffectWindow *, const QPoint &, bool, double) override {} KWin::WindowQuadType newWindowQuadType() override { return KWin::WindowQuadError; } int numberOfDesktops() const override { return 0; } int numScreens() const override { return 0; } bool optionRollOverDesktops() const override { return false; } void paintEffectFrame(KWin::EffectFrame *, QRegion, double, double) override {} void paintScreen(int, QRegion, KWin::ScreenPaintData &) override {} void paintWindow(KWin::EffectWindow *, int, QRegion, KWin::WindowPaintData &) override {} void postPaintScreen() override {} void postPaintWindow(KWin::EffectWindow *) override {} void prePaintScreen(KWin::ScreenPrePaintData &, int) override {} void prePaintWindow(KWin::EffectWindow *, KWin::WindowPrePaintData &, int) override {} QByteArray readRootProperty(long int, long int, int) const override { return QByteArray(); } void reconfigure() override {} void refTabBox() override {} void registerAxisShortcut(Qt::KeyboardModifiers, KWin::PointerAxisDirection, QAction *) override {} void registerGlobalShortcut(const QKeySequence &, QAction *) override {} void registerPointerShortcut(Qt::KeyboardModifiers, Qt::MouseButton, QAction *) override {} void registerPropertyType(long int, bool) override {} void reloadEffect(KWin::Effect *) override {} void removeSupportProperty(const QByteArray &, KWin::Effect *) override {} void reserveElectricBorder(KWin::ElectricBorder, KWin::Effect *) override {} QPainter *scenePainter() override { return nullptr; } int screenNumber(const QPoint &) const override { return 0; } void setActiveFullScreenEffect(KWin::Effect *) override {} void setCurrentDesktop(int) override {} void setElevatedWindow(KWin::EffectWindow *, bool) override {} void setNumberOfDesktops(int) override {} void setShowingDesktop(bool) override {} void setTabBoxDesktop(int) override {} void setTabBoxWindow(KWin::EffectWindow*) override {} KWin::EffectWindowList stackingOrder() const override { return KWin::EffectWindowList(); } void startMouseInterception(KWin::Effect *, Qt::CursorShape) override {} void startMousePolling() override {} void stopMouseInterception(KWin::Effect *) override {} void stopMousePolling() override {} void ungrabKeyboard() override {} void unrefTabBox() override {} void unreserveElectricBorder(KWin::ElectricBorder, KWin::Effect *) override {} QRect virtualScreenGeometry() const override { return QRect(); } QSize virtualScreenSize() const override { return QSize(); } void windowToDesktop(KWin::EffectWindow *, int) override {} void windowToScreen(KWin::EffectWindow *, int) override {} int workspaceHeight() const override { return 0; } int workspaceWidth() const override { return 0; } long unsigned int xrenderBufferPicture() override { return 0; } xcb_connection_t *xcbConnection() const override { return QX11Info::connection(); } xcb_window_t x11RootWindow() const override { return QX11Info::appRootWindow(); } KWayland::Server::Display *waylandDisplay() const override { return nullptr; } + + bool animationsSupported() const override { + return m_animationsSuported; + } + void setAnimationsSupported(bool set) { + m_animationsSuported = set; + } + +private: + bool m_animationsSuported = true; }; #endif diff --git a/autotests/test_builtin_effectloader.cpp b/autotests/test_builtin_effectloader.cpp index e480e260a..de7896577 100644 --- a/autotests/test_builtin_effectloader.cpp +++ b/autotests/test_builtin_effectloader.cpp @@ -1,552 +1,568 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "../effectloader.h" #include "../effects/effect_builtins.h" #include "mock_effectshandler.h" #include "../scripting/scriptedeffect.h" // for mocking ScriptedEffect::create // KDE #include #include // Qt #include #include Q_DECLARE_METATYPE(KWin::CompositingType) Q_DECLARE_METATYPE(KWin::LoadEffectFlag) Q_DECLARE_METATYPE(KWin::LoadEffectFlags) Q_DECLARE_METATYPE(KWin::BuiltInEffect) Q_DECLARE_METATYPE(KWin::Effect*) Q_LOGGING_CATEGORY(KWIN_CORE, "kwin_core") namespace KWin { ScriptedEffect *ScriptedEffect::create(const KPluginMetaData&) { return nullptr; } +bool ScriptedEffect::supported() +{ + return true; +} + } class TestBuiltInEffectLoader : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void testHasEffect_data(); void testHasEffect(); void testKnownEffects(); void testSupported_data(); void testSupported(); void testLoadEffect_data(); void testLoadEffect(); void testLoadBuiltInEffect_data(); void testLoadBuiltInEffect(); void testLoadAllEffects(); }; void TestBuiltInEffectLoader::initTestCase() { qApp->setProperty("x11Connection", QVariant::fromValue(QX11Info::connection())); } void TestBuiltInEffectLoader::testHasEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::newRow("blur") << QStringLiteral("blur") << true; QTest::newRow("with kwin4_effect_ prefix") << QStringLiteral("kwin4_effect_blur") << false; QTest::newRow("case sensitive") << QStringLiteral("BlUR") << true; QTest::newRow("Contrast") << QStringLiteral("contrast") << true; QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << true; QTest::newRow("Cube") << QStringLiteral("cube") << true; QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << true; QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << true; QTest::newRow("DimInactive") << QStringLiteral("diminactive") << true; QTest::newRow("DimScreen") << QStringLiteral("dimscreen") << true; QTest::newRow("FallApart") << QStringLiteral("fallapart") << true; QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << true; QTest::newRow("Glide") << QStringLiteral("glide") << true; QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << true; QTest::newRow("Invert") << QStringLiteral("invert") << true; QTest::newRow("Kscreen") << QStringLiteral("kscreen") << true; QTest::newRow("Logout") << QStringLiteral("logout") << true; QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << true; QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << true; QTest::newRow("Magnifier") << QStringLiteral("magnifier") << true; QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << true; QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << true; QTest::newRow("MouseMark") << QStringLiteral("mousemark") << true; QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << true; QTest::newRow("Resize") << QStringLiteral("resize") << true; QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << true; QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << true; QTest::newRow("Sheet") << QStringLiteral("sheet") << true; QTest::newRow("ShowFps") << QStringLiteral("showfps") << true; QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << true; QTest::newRow("Slide") << QStringLiteral("slide") << true; QTest::newRow("SlideBack") << QStringLiteral("slideback") << true; QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << true; QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << true; QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << true; QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << true; QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << true; QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << true; QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << true; QTest::newRow("Zoom") << QStringLiteral("zoom") << true; QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false; QTest::newRow("Fade - Scripted") << QStringLiteral("fade") << false; QTest::newRow("Fade - Scripted + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << false; } void TestBuiltInEffectLoader::testHasEffect() { QFETCH(QString, name); QFETCH(bool, expected); KWin::BuiltInEffectLoader loader; QCOMPARE(loader.hasEffect(name), expected); } void TestBuiltInEffectLoader::testKnownEffects() { QStringList expectedEffects; expectedEffects << QStringLiteral("blur") << QStringLiteral("contrast") << QStringLiteral("coverswitch") << QStringLiteral("cube") << QStringLiteral("cubeslide") << QStringLiteral("desktopgrid") << QStringLiteral("diminactive") << QStringLiteral("dimscreen") << QStringLiteral("fallapart") << QStringLiteral("flipswitch") << QStringLiteral("glide") << QStringLiteral("highlightwindow") << QStringLiteral("invert") << QStringLiteral("kscreen") << QStringLiteral("logout") << QStringLiteral("lookingglass") << QStringLiteral("magiclamp") << QStringLiteral("magnifier") << QStringLiteral("minimizeanimation") << QStringLiteral("mouseclick") << QStringLiteral("mousemark") << QStringLiteral("presentwindows") << QStringLiteral("resize") << QStringLiteral("screenedge") << QStringLiteral("screenshot") << QStringLiteral("sheet") << QStringLiteral("showfps") << QStringLiteral("showpaint") << QStringLiteral("slide") << QStringLiteral("slideback") << QStringLiteral("slidingpopups") << QStringLiteral("snaphelper") << QStringLiteral("startupfeedback") << QStringLiteral("thumbnailaside") << QStringLiteral("trackmouse") << QStringLiteral("windowgeometry") << QStringLiteral("wobblywindows") << QStringLiteral("zoom"); KWin::BuiltInEffectLoader loader; QStringList result = loader.listOfKnownEffects(); QCOMPARE(result.size(), expectedEffects.size()); qSort(result); for (int i = 0; i < expectedEffects.size(); ++i) { QCOMPARE(result.at(i), expectedEffects.at(i)); } } void TestBuiltInEffectLoader::testSupported_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); + QTest::addColumn("animationsSupported"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; - QTest::newRow("blur") << QStringLiteral("blur") << false << xc; + QTest::newRow("blur") << QStringLiteral("blur") << false << xc << true; // fails for GL as it does proper tests on what's supported and doesn't just check whether it's GL - QTest::newRow("blur-GL") << QStringLiteral("blur") << false << oc; - QTest::newRow("Contrast") << QStringLiteral("contrast") << false << xc; + QTest::newRow("blur-GL") << QStringLiteral("blur") << false << oc << true; + QTest::newRow("Contrast") << QStringLiteral("contrast") << false << xc << true; // fails for GL as it does proper tests on what's supported and doesn't just check whether it's GL - QTest::newRow("Contrast-GL") << QStringLiteral("contrast") << false << oc; - QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << false << xc; - QTest::newRow("CoverSwitch-GL") << QStringLiteral("coverswitch") << true << oc; - QTest::newRow("Cube") << QStringLiteral("cube") << false << xc; - QTest::newRow("Cube-GL") << QStringLiteral("cube") << true << oc; - QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << false << xc; - QTest::newRow("CubeSlide-GL") << QStringLiteral("cubeslide") << true << oc; - QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << true << xc; - QTest::newRow("DimInactive") << QStringLiteral("diminactive") << true << xc; - QTest::newRow("DimScreen") << QStringLiteral("dimscreen") << true << xc; - QTest::newRow("FallApart") << QStringLiteral("fallapart") << false << xc; - QTest::newRow("FallApart-GL") << QStringLiteral("fallapart") << true << oc; - QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << false << xc; - QTest::newRow("FlipSwitch-GL") << QStringLiteral("flipswitch") << true << oc; - QTest::newRow("Glide") << QStringLiteral("glide") << false << xc; - QTest::newRow("Glide-GL") << QStringLiteral("glide") << true << oc; - QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << true << xc; - QTest::newRow("Invert") << QStringLiteral("invert") << false << xc; - QTest::newRow("Invert-GL") << QStringLiteral("invert") << true << oc; - QTest::newRow("Kscreen") << QStringLiteral("kscreen") << true << xc; - QTest::newRow("Logout") << QStringLiteral("logout") << true << xc; - QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << false << xc; - QTest::newRow("LookingGlass-GL") << QStringLiteral("lookingglass") << true << oc; - QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << false << xc; - QTest::newRow("MagicLamp-GL") << QStringLiteral("magiclamp") << true << oc; - QTest::newRow("Magnifier") << QStringLiteral("magnifier") << true << xc; - QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << true << xc; - QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << true << xc; - QTest::newRow("MouseMark") << QStringLiteral("mousemark") << true << xc; - QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << true << xc; - QTest::newRow("Resize") << QStringLiteral("resize") << true << xc; - QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << true << xc; - QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << true << xc; - QTest::newRow("Sheet") << QStringLiteral("sheet") << false << xc; - QTest::newRow("Sheet-GL") << QStringLiteral("sheet") << true << oc; - QTest::newRow("ShowFps") << QStringLiteral("showfps") << true << xc; - QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << true << xc; - QTest::newRow("Slide") << QStringLiteral("slide") << true << xc; - QTest::newRow("SlideBack") << QStringLiteral("slideback") << true << xc; - QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << true << xc; - QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << true << xc; - QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << false << xc; - QTest::newRow("StartupFeedback-GL") << QStringLiteral("startupfeedback") << true << oc; - QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << true << xc; - QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << true << xc; - QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << true << xc; - QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << false << xc; - QTest::newRow("WobblyWindows-GL") << QStringLiteral("wobblywindows") << true << oc; - QTest::newRow("Zoom") << QStringLiteral("zoom") << true << xc; - QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false << xc; - QTest::newRow("Fade - Scripted") << QStringLiteral("fade") << false << xc; - QTest::newRow("Fade - Scripted + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << false << xc; + QTest::newRow("Contrast-GL") << QStringLiteral("contrast") << false << oc << true; + QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << false << xc << true; + QTest::newRow("CoverSwitch-GL") << QStringLiteral("coverswitch") << true << oc << true; + QTest::newRow("CoverSwitch-GL-no-anim") << QStringLiteral("coverswitch") << false << oc << false; + QTest::newRow("Cube") << QStringLiteral("cube") << false << xc << true; + QTest::newRow("Cube-GL") << QStringLiteral("cube") << true << oc << true; + QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << false << xc << true; + QTest::newRow("CubeSlide-GL") << QStringLiteral("cubeslide") << true << oc << true; + QTest::newRow("CubeSlide-GL-no-anim") << QStringLiteral("cubeslide") << false << oc << false; + QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << true << xc << true; + QTest::newRow("DimInactive") << QStringLiteral("diminactive") << true << xc << true; + QTest::newRow("DimScreen") << QStringLiteral("dimscreen") << true << xc << true; + QTest::newRow("FallApart") << QStringLiteral("fallapart") << false << xc << true; + QTest::newRow("FallApart-GL") << QStringLiteral("fallapart") << true << oc << true; + QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << false << xc << true; + QTest::newRow("FlipSwitch-GL") << QStringLiteral("flipswitch") << true << oc << true; + QTest::newRow("FlipSwitch-GL-no-anim") << QStringLiteral("flipswitch") << false << oc << false; + QTest::newRow("Glide") << QStringLiteral("glide") << false << xc << true; + QTest::newRow("Glide-GL") << QStringLiteral("glide") << true << oc << true; + QTest::newRow("Glide-GL-no-anim") << QStringLiteral("glide") << false << oc << false; + QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << true << xc << true; + QTest::newRow("Invert") << QStringLiteral("invert") << false << xc << true; + QTest::newRow("Invert-GL") << QStringLiteral("invert") << true << oc << true; + QTest::newRow("Kscreen") << QStringLiteral("kscreen") << true << xc << true; + QTest::newRow("Logout") << QStringLiteral("logout") << true << xc << true; + QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << false << xc << true; + QTest::newRow("LookingGlass-GL") << QStringLiteral("lookingglass") << true << oc << true; + QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << false << xc << true; + QTest::newRow("MagicLamp-GL") << QStringLiteral("magiclamp") << true << oc << true; + QTest::newRow("MagicLamp-GL-no-anim") << QStringLiteral("magiclamp") << false << oc << false; + QTest::newRow("Magnifier") << QStringLiteral("magnifier") << true << xc << true; + QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << true << xc << true; + QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << true << xc << true; + QTest::newRow("MouseMark") << QStringLiteral("mousemark") << true << xc << true; + QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << true << xc << true; + QTest::newRow("Resize") << QStringLiteral("resize") << true << xc << true; + QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << true << xc << true; + QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << true << xc << true; + QTest::newRow("Sheet") << QStringLiteral("sheet") << false << xc << true; + QTest::newRow("Sheet-GL") << QStringLiteral("sheet") << true << oc << true; + QTest::newRow("Sheet-GL-no-anim") << QStringLiteral("sheet") << false << oc << false; + QTest::newRow("ShowFps") << QStringLiteral("showfps") << true << xc << true; + QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << true << xc << true; + QTest::newRow("Slide") << QStringLiteral("slide") << true << xc << true; + QTest::newRow("SlideBack") << QStringLiteral("slideback") << true << xc << true; + QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << true << xc << true; + QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << true << xc << true; + QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << false << xc << true; + QTest::newRow("StartupFeedback-GL") << QStringLiteral("startupfeedback") << true << oc << true; + QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << true << xc << true; + QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << true << xc << true; + QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << true << xc << true; + QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << false << xc << true; + QTest::newRow("WobblyWindows-GL") << QStringLiteral("wobblywindows") << true << oc << true; + QTest::newRow("WobblyWindows-GL-no-anim") << QStringLiteral("wobblywindows") << false << oc << false; + QTest::newRow("Zoom") << QStringLiteral("zoom") << true << xc << true; + QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false << xc << true; + QTest::newRow("Fade - Scripted") << QStringLiteral("fade") << false << xc << true; + QTest::newRow("Fade - Scripted + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << false << xc << true; } void TestBuiltInEffectLoader::testSupported() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); + QFETCH(bool, animationsSupported); MockEffectsHandler mockHandler(type); + mockHandler.setAnimationsSupported(animationsSupported); + QCOMPARE(mockHandler.animationsSupported(), animationsSupported); KWin::BuiltInEffectLoader loader; QCOMPARE(loader.isEffectSupported(name), expected); } void TestBuiltInEffectLoader::testLoadEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; QTest::newRow("blur") << QStringLiteral("blur") << false << xc; // fails for GL as it does proper tests on what's supported and doesn't just check whether it's GL QTest::newRow("blur-GL") << QStringLiteral("blur") << false << oc; QTest::newRow("Contrast") << QStringLiteral("contrast") << false << xc; // fails for GL as it does proper tests on what's supported and doesn't just check whether it's GL QTest::newRow("Contrast-GL") << QStringLiteral("contrast") << false << oc; QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << false << xc; // TODO: needs GL mocking // QTest::newRow("CoverSwitch-GL") << QStringLiteral("coverswitch") << true << oc; QTest::newRow("Cube") << QStringLiteral("cube") << false << xc; // TODO: needs GL mocking // QTest::newRow("Cube-GL") << QStringLiteral("cube") << true << oc; QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << false << xc; QTest::newRow("CubeSlide-GL") << QStringLiteral("cubeslide") << true << oc; QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << true << xc; QTest::newRow("DimInactive") << QStringLiteral("diminactive") << true << xc; QTest::newRow("DimScreen") << QStringLiteral("dimScreen") << true << xc; QTest::newRow("FallApart") << QStringLiteral("fallapart") << false << xc; QTest::newRow("FallApart-GL") << QStringLiteral("fallapart") << true << oc; QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << false << xc; QTest::newRow("FlipSwitch-GL") << QStringLiteral("flipswitch") << true << oc; QTest::newRow("Glide") << QStringLiteral("glide") << false << xc; QTest::newRow("Glide-GL") << QStringLiteral("glide") << true << oc; QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << true << xc; QTest::newRow("Invert") << QStringLiteral("invert") << false << xc; QTest::newRow("Invert-GL") << QStringLiteral("invert") << true << oc; QTest::newRow("Kscreen") << QStringLiteral("kscreen") << true << xc; QTest::newRow("Logout") << QStringLiteral("logout") << true << xc; QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << false << xc; QTest::newRow("LookingGlass-GL") << QStringLiteral("lookingglass") << true << oc; QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << false << xc; QTest::newRow("MagicLamp-GL") << QStringLiteral("magiclamp") << true << oc; QTest::newRow("Magnifier") << QStringLiteral("magnifier") << true << xc; QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << true << xc; QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << true << xc; QTest::newRow("MouseMark") << QStringLiteral("mousemark") << true << xc; QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << true << xc; QTest::newRow("Resize") << QStringLiteral("resize") << true << xc; QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << true << xc; QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << true << xc; QTest::newRow("Sheet") << QStringLiteral("sheet") << false << xc; QTest::newRow("Sheet-GL") << QStringLiteral("sheet") << true << oc; // TODO: Accesses EffectFrame and crashes // QTest::newRow("ShowFps") << QStringLiteral("showfps") << true << xc; QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << true << xc; QTest::newRow("Slide") << QStringLiteral("slide") << true << xc; QTest::newRow("SlideBack") << QStringLiteral("slideback") << true << xc; QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << true << xc; QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << true << xc; QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << false << xc; // Tries to load shader and makes our test abort // QTest::newRow("StartupFeedback-GL") << QStringLiteral("startupfeedback") << true << oc; QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << true << xc; QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << true << xc; // TODO: Accesses EffectFrame and crashes // QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << true << xc; QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << false << xc; QTest::newRow("WobblyWindows-GL") << QStringLiteral("wobblywindows") << true << oc; QTest::newRow("Zoom") << QStringLiteral("zoom") << true << xc; QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false << xc; QTest::newRow("Fade - Scripted") << QStringLiteral("fade") << false << xc; QTest::newRow("Fade - Scripted + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << false << xc; } void TestBuiltInEffectLoader::testLoadEffect() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); MockEffectsHandler mockHandler(type); KWin::BuiltInEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::BuiltInEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(name), expected); // loading again should fail QVERIFY(!loader.loadEffect(name)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(name), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } } void TestBuiltInEffectLoader::testLoadBuiltInEffect_data() { // TODO: this test cannot yet test the checkEnabledByDefault functionality as that requires // mocking enough of GL to get the blur effect to think it's supported and enabled by default QTest::addColumn("effect"); QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); QTest::addColumn("loadFlags"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; const KWin::LoadEffectFlags checkDefault = KWin::LoadEffectFlag::Load | KWin::LoadEffectFlag::CheckDefaultFunction; const KWin::LoadEffectFlags forceFlags = KWin::LoadEffectFlag::Load; const KWin::LoadEffectFlags dontLoadFlags = KWin::LoadEffectFlags(); // enabled by default, but not supported QTest::newRow("blur") << KWin::BuiltInEffect::Blur << QStringLiteral("blur") << false << oc << checkDefault; // enabled by default QTest::newRow("HighlightWindow") << KWin::BuiltInEffect::HighlightWindow << QStringLiteral("highlightwindow") << true << xc << checkDefault; // supported but not enabled by default QTest::newRow("LookingGlass-GL") << KWin::BuiltInEffect::LookingGlass << QStringLiteral("lookingglass") << true << oc << checkDefault; // not enabled by default QTest::newRow("MouseClick") << KWin::BuiltInEffect::MouseClick << QStringLiteral("mouseclick") << true << xc << checkDefault; // Force an Effect which will load QTest::newRow("MouseClick-Force") << KWin::BuiltInEffect::MouseClick << QStringLiteral("mouseclick") << true << xc << forceFlags; // Force an Effect which is not supported QTest::newRow("LookingGlass-Force") << KWin::BuiltInEffect::LookingGlass << QStringLiteral("lookingglass") << false << xc << forceFlags; // Force the Effect as supported QTest::newRow("LookingGlass-Force-GL") << KWin::BuiltInEffect::LookingGlass << QStringLiteral("lookingglass") << true << oc << forceFlags; // Enforce no load of effect which is enabled by default QTest::newRow("HighlightWindow-DontLoad") << KWin::BuiltInEffect::HighlightWindow << QStringLiteral("highlightwindow") << false << xc << dontLoadFlags; // Enforce no load of effect which is not enabled by default, but enforced QTest::newRow("MouseClick-DontLoad") << KWin::BuiltInEffect::MouseClick << QStringLiteral("mouseclick") << false << xc << dontLoadFlags; } void TestBuiltInEffectLoader::testLoadBuiltInEffect() { QFETCH(KWin::BuiltInEffect, effect); QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); QFETCH(KWin::LoadEffectFlags, loadFlags); MockEffectsHandler mockHandler(type); KWin::BuiltInEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::BuiltInEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(effect, loadFlags), expected); // loading again should fail QVERIFY(!loader.loadEffect(effect, loadFlags)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(effect, loadFlags), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } } void TestBuiltInEffectLoader::testLoadAllEffects() { MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::BuiltInEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); // prepare the configuration to hard enable/disable the effects we want to load KConfigGroup plugins = config->group("Plugins"); plugins.writeEntry(QStringLiteral("desktopgridEnabled"), false); plugins.writeEntry(QStringLiteral("highlightwindowEnabled"), false); plugins.writeEntry(QStringLiteral("kscreenEnabled"), false); plugins.writeEntry(QStringLiteral("logoutEnabled"), false); plugins.writeEntry(QStringLiteral("minimizeanimationEnabled"), false); plugins.writeEntry(QStringLiteral("presentwindowsEnabled"), false); plugins.writeEntry(QStringLiteral("screenedgeEnabled"), false); plugins.writeEntry(QStringLiteral("screenshotEnabled"), false); plugins.writeEntry(QStringLiteral("slideEnabled"), false); plugins.writeEntry(QStringLiteral("slidingpopupsEnabled"), false); plugins.writeEntry(QStringLiteral("startupfeedbackEnabled"), false); plugins.writeEntry(QStringLiteral("zoomEnabled"), false); // enable lookingglass as it's not supported plugins.writeEntry(QStringLiteral("lookingglassEnabled"), true); plugins.sync(); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::BuiltInEffectLoader::effectLoaded, [](KWin::Effect *effect) { effect->deleteLater(); } ); // the config is prepared so that no Effect gets loaded! loader.queryAndLoadAll(); // we need to wait some time because it's queued QVERIFY(!spy.wait(10)); // now let's prepare a config which has one effect explicitly enabled plugins.writeEntry(QStringLiteral("mouseclickEnabled"), true); plugins.sync(); loader.queryAndLoadAll(); // should load one effect in first go QVERIFY(spy.wait(10)); // and afterwards it should not load another one QVERIFY(!spy.wait(10)); QCOMPARE(spy.size(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), QStringLiteral("mouseclick")); spy.clear(); // let's delete one of the default entries plugins.deleteEntry(QStringLiteral("kscreenEnabled")); plugins.sync(); QVERIFY(spy.isEmpty()); loader.queryAndLoadAll(); // let's use qWait as we need to wait for two signals to be emitted QTest::qWait(100); QCOMPARE(spy.size(), 2); QStringList loadedEffects; for (auto &list : spy) { QCOMPARE(list.size(), 2); loadedEffects << list.at(1).toString(); } qSort(loadedEffects); QCOMPARE(loadedEffects.at(0), QStringLiteral("kscreen")); QCOMPARE(loadedEffects.at(1), QStringLiteral("mouseclick")); } QTEST_MAIN(TestBuiltInEffectLoader) #include "test_builtin_effectloader.moc" diff --git a/autotests/test_plugin_effectloader.cpp b/autotests/test_plugin_effectloader.cpp index df6e5f4eb..208471d92 100644 --- a/autotests/test_plugin_effectloader.cpp +++ b/autotests/test_plugin_effectloader.cpp @@ -1,413 +1,418 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "../effectloader.h" #include "mock_effectshandler.h" #include "../scripting/scriptedeffect.h" // for mocking ScriptedEffect::create // KDE #include #include #include // Qt #include #include Q_DECLARE_METATYPE(KWin::CompositingType) Q_DECLARE_METATYPE(KWin::LoadEffectFlag) Q_DECLARE_METATYPE(KWin::LoadEffectFlags) Q_DECLARE_METATYPE(KWin::Effect*) Q_LOGGING_CATEGORY(KWIN_CORE, "kwin_core") namespace KWin { ScriptedEffect *ScriptedEffect::create(const KPluginMetaData&) { return nullptr; } +bool ScriptedEffect::supported() +{ + return true; +} + } class TestPluginEffectLoader : public QObject { Q_OBJECT private Q_SLOTS: void testHasEffect_data(); void testHasEffect(); void testKnownEffects(); void testSupported_data(); void testSupported(); void testLoadEffect_data(); void testLoadEffect(); void testLoadPluginEffect_data(); void testLoadPluginEffect(); void testLoadAllEffects(); void testCancelLoadAllEffects(); }; void TestPluginEffectLoader::testHasEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); // all the built-in effects should fail QTest::newRow("blur") << QStringLiteral("blur") << false; QTest::newRow("Contrast") << QStringLiteral("contrast") << false; QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << false; QTest::newRow("Cube") << QStringLiteral("cube") << false; QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << false; QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << false; QTest::newRow("DimInactive") << QStringLiteral("diminactive") << false; QTest::newRow("DimScreen") << QStringLiteral("dimscreen") << false; QTest::newRow("FallApart") << QStringLiteral("fallapart") << false; QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << false; QTest::newRow("Glide") << QStringLiteral("glide") << false; QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << false; QTest::newRow("Invert") << QStringLiteral("invert") << false; QTest::newRow("Kscreen") << QStringLiteral("kscreen") << false; QTest::newRow("Logout") << QStringLiteral("logout") << false; QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << false; QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << false; QTest::newRow("Magnifier") << QStringLiteral("magnifier") << false; QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << false; QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << false; QTest::newRow("MouseMark") << QStringLiteral("mousemark") << false; QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << false; QTest::newRow("Resize") << QStringLiteral("resize") << false; QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << false; QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << false; QTest::newRow("Sheet") << QStringLiteral("sheet") << false; QTest::newRow("ShowFps") << QStringLiteral("showfps") << false; QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << false; QTest::newRow("Slide") << QStringLiteral("slide") << false; QTest::newRow("SlideBack") << QStringLiteral("slideback") << false; QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << false; QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << false; QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << false; QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << false; QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << false; QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << false; QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << false; QTest::newRow("Zoom") << QStringLiteral("zoom") << false; QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false; // all the scripted effects should fail QTest::newRow("Fade") << QStringLiteral("kwin4_effect_fade") << false; QTest::newRow("FadeDesktop") << QStringLiteral("kwin4_effect_fadedesktop") << false; QTest::newRow("DialogParent") << QStringLiteral("kwin4_effect_dialogparent") << false; QTest::newRow("Login") << QStringLiteral("kwin4_effect_login") << false; QTest::newRow("Maximize") << QStringLiteral("kwin4_effect_maximize") << false; QTest::newRow("ScaleIn") << QStringLiteral("kwin4_effect_scalein") << false; QTest::newRow("Translucency") << QStringLiteral("kwin4_effect_translucency") << false; // and the fake effects we use here QTest::newRow("fakeeffectplugin") << QStringLiteral("fakeeffectplugin") << true; QTest::newRow("fakeeffectplugin CS") << QStringLiteral("fakeEffectPlugin") << true; QTest::newRow("effectversion") << QStringLiteral("effectversion") << true; } void TestPluginEffectLoader::testHasEffect() { QFETCH(QString, name); QFETCH(bool, expected); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); QCOMPARE(loader.hasEffect(name), expected); } void TestPluginEffectLoader::testKnownEffects() { QStringList expectedEffects; expectedEffects << QStringLiteral("fakeeffectplugin") << QStringLiteral("effectversion"); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); QStringList result = loader.listOfKnownEffects(); // at least as many effects as we expect - system running the test could have more effects QVERIFY(result.size() >= expectedEffects.size()); for (const QString &effect : expectedEffects) { QVERIFY(result.contains(effect)); } } void TestPluginEffectLoader::testSupported_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; QTest::newRow("invalid") << QStringLiteral("blur") << false << xc; QTest::newRow("fake - xrender") << QStringLiteral("fakeeffectplugin") << false << xc; QTest::newRow("fake - opengl") << QStringLiteral("fakeeffectplugin") << true << oc; QTest::newRow("fake - CS") << QStringLiteral("fakeEffectPlugin") << true << oc; QTest::newRow("version") << QStringLiteral("effectversion") << false << xc; } void TestPluginEffectLoader::testSupported() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); MockEffectsHandler mockHandler(type); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); QCOMPARE(loader.isEffectSupported(name), expected); } void TestPluginEffectLoader::testLoadEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; QTest::newRow("invalid") << QStringLiteral("slide") << false << xc; QTest::newRow("fake - xrender") << QStringLiteral("fakeeffectplugin") << false << xc; QTest::newRow("fake - opengl") << QStringLiteral("fakeeffectplugin") << true << oc; QTest::newRow("fake - CS") << QStringLiteral("fakeEffectPlugin") << true << oc; QTest::newRow("version") << QStringLiteral("effectversion") << false << xc; } void TestPluginEffectLoader::testLoadEffect() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); MockEffectsHandler mockHandler(type); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::PluginEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name.toLower()); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(name), expected); // loading again should fail QVERIFY(!loader.loadEffect(name)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(name), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } } void TestPluginEffectLoader::testLoadPluginEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("type"); QTest::addColumn("loadFlags"); QTest::addColumn("enabledByDefault"); const KWin::CompositingType xc = KWin::XRenderCompositing; const KWin::CompositingType oc = KWin::OpenGL2Compositing; const KWin::LoadEffectFlags checkDefault = KWin::LoadEffectFlag::Load | KWin::LoadEffectFlag::CheckDefaultFunction; const KWin::LoadEffectFlags forceFlags = KWin::LoadEffectFlag::Load; const KWin::LoadEffectFlags dontLoadFlags = KWin::LoadEffectFlags(); // enabled by default, but not supported QTest::newRow("fakeeffectplugin") << QStringLiteral("fakeeffectplugin") << false << xc << checkDefault << false; // enabled by default, check default false QTest::newRow("supported, check default error") << QStringLiteral("fakeeffectplugin") << false << oc << checkDefault << false; // enabled by default, check default true QTest::newRow("supported, check default") << QStringLiteral("fakeeffectplugin") << true << oc << checkDefault << true; // enabled by default, check default false QTest::newRow("supported, check default error, forced") << QStringLiteral("fakeeffectplugin") << true << oc << forceFlags << false; // enabled by default, check default true QTest::newRow("supported, check default, don't load") << QStringLiteral("fakeeffectplugin") << false << oc << dontLoadFlags << true; // incorrect version QTest::newRow("Version") << QStringLiteral("effectversion") << false << xc << forceFlags << true; } void TestPluginEffectLoader::testLoadPluginEffect() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::CompositingType, type); QFETCH(KWin::LoadEffectFlags, loadFlags); QFETCH(bool, enabledByDefault); MockEffectsHandler mockHandler(type); mockHandler.setProperty("testEnabledByDefault", enabledByDefault); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); const auto plugins = KPluginLoader::findPlugins(QString(), [name] (const KPluginMetaData &data) { return data.pluginId().compare(name, Qt::CaseInsensitive) == 0 && data.serviceTypes().contains(QStringLiteral("KWin/Effect")); } ); QCOMPARE(plugins.size(), 1); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::PluginEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(plugins.first(), loadFlags), expected); // loading again should fail QVERIFY(!loader.loadEffect(plugins.first(), loadFlags)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(plugins.first(), loadFlags), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name); } } void TestPluginEffectLoader::testLoadAllEffects() { MockEffectsHandler mockHandler(KWin::OpenGL2Compositing); mockHandler.setProperty("testEnabledByDefault", true); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); // prepare the configuration to hard enable/disable the effects we want to load KConfigGroup plugins = config->group("Plugins"); plugins.writeEntry(QStringLiteral("fakeeffectpluginEnabled"), false); plugins.sync(); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::PluginEffectLoader::effectLoaded, [](KWin::Effect *effect) { effect->deleteLater(); } ); // the config is prepared so that no Effect gets loaded! loader.queryAndLoadAll(); // we need to wait some time because it's queued and in a thread QVERIFY(!spy.wait(100)); // now let's prepare a config which has one effect explicitly enabled plugins.writeEntry(QStringLiteral("fakeeffectpluginEnabled"), true); plugins.sync(); loader.queryAndLoadAll(); // should load one effect in first go QVERIFY(spy.wait(100)); // and afterwards it should not load another one QVERIFY(!spy.wait(10)); QCOMPARE(spy.size(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), QStringLiteral("fakeeffectplugin")); spy.clear(); } void TestPluginEffectLoader::testCancelLoadAllEffects() { // this test verifies that no test gets loaded when the loader gets cleared MockEffectsHandler mockHandler(KWin::OpenGL2Compositing); KWin::PluginEffectLoader loader; loader.setPluginSubDirectory(QString()); // prepare the configuration to hard enable/disable the effects we want to load KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); KConfigGroup plugins = config->group("Plugins"); plugins.writeEntry(QStringLiteral("fakeeffectpluginEnabled"), true); plugins.sync(); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, &KWin::PluginEffectLoader::effectLoaded); QVERIFY(spy.isValid()); loader.queryAndLoadAll(); loader.clear(); // Should not load any effect QVERIFY(!spy.wait(100)); QVERIFY(spy.isEmpty()); } QTEST_MAIN(TestPluginEffectLoader) #include "test_plugin_effectloader.moc" diff --git a/autotests/test_scripted_effectloader.cpp b/autotests/test_scripted_effectloader.cpp index fee8e014c..5c0743de1 100644 --- a/autotests/test_scripted_effectloader.cpp +++ b/autotests/test_scripted_effectloader.cpp @@ -1,419 +1,425 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "../effectloader.h" #include "mock_effectshandler.h" #include "../scripting/scriptedeffect.h" // for mocking #include "../input.h" #include "../screenedge.h" // KDE #include #include #include // Qt #include #include Q_DECLARE_METATYPE(KWin::LoadEffectFlag) Q_DECLARE_METATYPE(KWin::LoadEffectFlags) Q_DECLARE_METATYPE(KWin::Effect*) Q_LOGGING_CATEGORY(KWIN_CORE, "kwin_core") namespace KWin { ScreenEdges *ScreenEdges::s_self = nullptr; void ScreenEdges::reserve(ElectricBorder, QObject *, const char *) { } InputRedirection *InputRedirection::s_self = nullptr; void InputRedirection::registerShortcut(const QKeySequence &, QAction *) { } namespace MetaScripting { void registration(QScriptEngine *) { } } } class TestScriptedEffectLoader : public QObject { Q_OBJECT private Q_SLOTS: void testHasEffect_data(); void testHasEffect(); void testKnownEffects(); void testLoadEffect_data(); void testLoadEffect(); void testLoadScriptedEffect_data(); void testLoadScriptedEffect(); void testLoadAllEffects(); void testCancelLoadAllEffects(); }; void TestScriptedEffectLoader::testHasEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); // all the built-in effects should fail QTest::newRow("blur") << QStringLiteral("blur") << false; QTest::newRow("Contrast") << QStringLiteral("contrast") << false; QTest::newRow("CoverSwitch") << QStringLiteral("coverswitch") << false; QTest::newRow("Cube") << QStringLiteral("cube") << false; QTest::newRow("CubeSlide") << QStringLiteral("cubeslide") << false; QTest::newRow("DesktopGrid") << QStringLiteral("desktopgrid") << false; QTest::newRow("DimInactive") << QStringLiteral("diminactive") << false; QTest::newRow("DimScreen") << QStringLiteral("dimscreen") << false; QTest::newRow("FallApart") << QStringLiteral("fallapart") << false; QTest::newRow("FlipSwitch") << QStringLiteral("flipswitch") << false; QTest::newRow("Glide") << QStringLiteral("glide") << false; QTest::newRow("HighlightWindow") << QStringLiteral("highlightwindow") << false; QTest::newRow("Invert") << QStringLiteral("invert") << false; QTest::newRow("Kscreen") << QStringLiteral("kscreen") << false; QTest::newRow("Logout") << QStringLiteral("logout") << false; QTest::newRow("LookingGlass") << QStringLiteral("lookingglass") << false; QTest::newRow("MagicLamp") << QStringLiteral("magiclamp") << false; QTest::newRow("Magnifier") << QStringLiteral("magnifier") << false; QTest::newRow("MinimizeAnimation") << QStringLiteral("minimizeanimation") << false; QTest::newRow("MouseClick") << QStringLiteral("mouseclick") << false; QTest::newRow("MouseMark") << QStringLiteral("mousemark") << false; QTest::newRow("PresentWindows") << QStringLiteral("presentwindows") << false; QTest::newRow("Resize") << QStringLiteral("resize") << false; QTest::newRow("ScreenEdge") << QStringLiteral("screenedge") << false; QTest::newRow("ScreenShot") << QStringLiteral("screenshot") << false; QTest::newRow("Sheet") << QStringLiteral("sheet") << false; QTest::newRow("ShowFps") << QStringLiteral("showfps") << false; QTest::newRow("ShowPaint") << QStringLiteral("showpaint") << false; QTest::newRow("Slide") << QStringLiteral("slide") << false; QTest::newRow("SlideBack") << QStringLiteral("slideback") << false; QTest::newRow("SlidingPopups") << QStringLiteral("slidingpopups") << false; QTest::newRow("SnapHelper") << QStringLiteral("snaphelper") << false; QTest::newRow("StartupFeedback") << QStringLiteral("startupfeedback") << false; QTest::newRow("ThumbnailAside") << QStringLiteral("thumbnailaside") << false; QTest::newRow("TrackMouse") << QStringLiteral("trackmouse") << false; QTest::newRow("WindowGeometry") << QStringLiteral("windowgeometry") << false; QTest::newRow("WobblyWindows") << QStringLiteral("wobblywindows") << false; QTest::newRow("Zoom") << QStringLiteral("zoom") << false; QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false; QTest::newRow("Fade - without kwin4_effect") << QStringLiteral("fade") << false; QTest::newRow("Fade + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << true; QTest::newRow("Fade + kwin4_effect + CS") << QStringLiteral("kwin4_eFfect_fAde") << true; QTest::newRow("FadeDesktop") << QStringLiteral("kwin4_effect_fadedesktop") << true; QTest::newRow("DialogParent") << QStringLiteral("kwin4_effect_dialogparent") << true; QTest::newRow("Login") << QStringLiteral("kwin4_effect_login") << true; QTest::newRow("Maximize") << QStringLiteral("kwin4_effect_maximize") << true; QTest::newRow("ScaleIn") << QStringLiteral("kwin4_effect_scalein") << true; QTest::newRow("Translucency") << QStringLiteral("kwin4_effect_translucency") << true; } void TestScriptedEffectLoader::testHasEffect() { QFETCH(QString, name); QFETCH(bool, expected); + MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::ScriptedEffectLoader loader; QCOMPARE(loader.hasEffect(name), expected); // each available effect should also be supported QCOMPARE(loader.isEffectSupported(name), expected); + + if (expected) { + mockHandler.setAnimationsSupported(false); + QVERIFY(!loader.isEffectSupported(name)); + } } void TestScriptedEffectLoader::testKnownEffects() { QStringList expectedEffects; expectedEffects << QStringLiteral("kwin4_effect_dialogparent") << QStringLiteral("kwin4_effect_fade") << QStringLiteral("kwin4_effect_fadedesktop") << QStringLiteral("kwin4_effect_login") << QStringLiteral("kwin4_effect_maximize") << QStringLiteral("kwin4_effect_scalein") << QStringLiteral("kwin4_effect_translucency"); KWin::ScriptedEffectLoader loader; QStringList result = loader.listOfKnownEffects(); // at least as many effects as we expect - system running the test could have more effects QVERIFY(result.size() >= expectedEffects.size()); for (const QString &effect : expectedEffects) { QVERIFY(result.contains(effect)); } } void TestScriptedEffectLoader::testLoadEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::newRow("Non Existing") << QStringLiteral("InvalidName") << false; QTest::newRow("Fade - without kwin4_effect") << QStringLiteral("fade") << false; QTest::newRow("Fade + kwin4_effect") << QStringLiteral("kwin4_effect_fade") << true; QTest::newRow("Fade + kwin4_effect + CS") << QStringLiteral("kwin4_eFfect_fAde") << true; QTest::newRow("FadeDesktop") << QStringLiteral("kwin4_effect_fadedesktop") << true; QTest::newRow("DialogParent") << QStringLiteral("kwin4_effect_dialogparent") << true; QTest::newRow("Login") << QStringLiteral("kwin4_effect_login") << true; QTest::newRow("Maximize") << QStringLiteral("kwin4_effect_maximize") << true; QTest::newRow("ScaleIn") << QStringLiteral("kwin4_effect_scalein") << true; QTest::newRow("Translucency") << QStringLiteral("kwin4_effect_translucency") << true; } void TestScriptedEffectLoader::testLoadEffect() { QFETCH(QString, name); QFETCH(bool, expected); MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::ScriptedEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::ScriptedEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name.toLower()); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(name), expected); // loading again should fail QVERIFY(!loader.loadEffect(name)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(name), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } } void TestScriptedEffectLoader::testLoadScriptedEffect_data() { QTest::addColumn("name"); QTest::addColumn("expected"); QTest::addColumn("loadFlags"); const KWin::LoadEffectFlags checkDefault = KWin::LoadEffectFlag::Load | KWin::LoadEffectFlag::CheckDefaultFunction; const KWin::LoadEffectFlags forceFlags = KWin::LoadEffectFlag::Load; const KWin::LoadEffectFlags dontLoadFlags = KWin::LoadEffectFlags(); // enabled by default QTest::newRow("Fade") << QStringLiteral("kwin4_effect_fade") << true << checkDefault; // not enabled by default QTest::newRow("Scalein") << QStringLiteral("kwin4_effect_scalein") << true << checkDefault; // Force an Effect which will load QTest::newRow("Scalein-Force") << QStringLiteral("kwin4_effect_scalein") << true << forceFlags; // Enforce no load of effect which is enabled by default QTest::newRow("Fade-DontLoad") << QStringLiteral("kwin4_effect_fade") << false << dontLoadFlags; // Enforce no load of effect which is not enabled by default, but enforced QTest::newRow("Scalein-DontLoad") << QStringLiteral("kwin4_effect_scalein") << false << dontLoadFlags; } void TestScriptedEffectLoader::testLoadScriptedEffect() { QFETCH(QString, name); QFETCH(bool, expected); QFETCH(KWin::LoadEffectFlags, loadFlags); MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::ScriptedEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); loader.setConfig(config); const auto services = KPackage::PackageLoader::self()->findPackages(QStringLiteral("KWin/Effect"), QStringLiteral("kwin/effects"), [name] (const KPluginMetaData &metadata) { return metadata.pluginId().compare(name, Qt::CaseInsensitive) == 0; } ); QCOMPARE(services.count(), 1); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::ScriptedEffectLoader::effectLoaded, [&name](KWin::Effect *effect, const QString &effectName) { QCOMPARE(effectName, name.toLower()); effect->deleteLater(); } ); // try to load the Effect QCOMPARE(loader.loadEffect(services.first(), loadFlags), expected); // loading again should fail QVERIFY(!loader.loadEffect(services.first(), loadFlags)); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } spy.clear(); QVERIFY(spy.isEmpty()); // now if we wait for the events being processed, the effect will get deleted and it should load again QTest::qWait(1); QCOMPARE(loader.loadEffect(services.first(), loadFlags), expected); // signal spy should have got the signal if it was expected QCOMPARE(spy.isEmpty(), !expected); if (!spy.isEmpty()) { QCOMPARE(spy.count(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), name.toLower()); } } void TestScriptedEffectLoader::testLoadAllEffects() { MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::ScriptedEffectLoader loader; KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); const QString kwin4 = QStringLiteral("kwin4_effect_"); // prepare the configuration to hard enable/disable the effects we want to load KConfigGroup plugins = config->group("Plugins"); plugins.writeEntry(kwin4 + QStringLiteral("dialogparentEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("fadeEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("fadedesktopEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("loginEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("maximizeEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("minimizeanimationEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("scaleinEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("translucencyEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("eyeonscreenEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("windowapertureEnabled"), false); plugins.writeEntry(kwin4 + QStringLiteral("morphingpopupsEnabled"), false); plugins.sync(); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, SIGNAL(effectLoaded(KWin::Effect*,QString))); // connect to signal to ensure that we delete the Effect again as the Effect doesn't have a parent connect(&loader, &KWin::ScriptedEffectLoader::effectLoaded, [](KWin::Effect *effect) { effect->deleteLater(); } ); // the config is prepared so that no Effect gets loaded! loader.queryAndLoadAll(); // we need to wait some time because it's queued and in a thread QVERIFY(!spy.wait(100)); // now let's prepare a config which has one effect explicitly enabled plugins.writeEntry(kwin4 + QStringLiteral("scaleinEnabled"), true); plugins.sync(); loader.queryAndLoadAll(); // should load one effect in first go QVERIFY(spy.wait(100)); // and afterwards it should not load another one QVERIFY(!spy.wait(10)); QCOMPARE(spy.size(), 1); // if we caught a signal it should have the effect name we passed in QList arguments = spy.takeFirst(); QCOMPARE(arguments.count(), 2); QCOMPARE(arguments.at(1).toString(), kwin4 + QStringLiteral("scalein")); spy.clear(); // let's delete one of the default entries plugins.deleteEntry(kwin4 + QStringLiteral("fadeEnabled")); plugins.sync(); QVERIFY(spy.isEmpty()); loader.queryAndLoadAll(); // let's use qWait as we need to wait for two signals to be emitted QTest::qWait(100); QCOMPARE(spy.size(), 2); QStringList loadedEffects; for (auto &list : spy) { QCOMPARE(list.size(), 2); loadedEffects << list.at(1).toString(); } qSort(loadedEffects); QCOMPARE(loadedEffects.at(0), kwin4 + QStringLiteral("fade")); QCOMPARE(loadedEffects.at(1), kwin4 + QStringLiteral("scalein")); } void TestScriptedEffectLoader::testCancelLoadAllEffects() { // this test verifies that no test gets loaded when the loader gets cleared MockEffectsHandler mockHandler(KWin::XRenderCompositing); KWin::ScriptedEffectLoader loader; // prepare the configuration to hard enable/disable the effects we want to load KSharedConfig::Ptr config = KSharedConfig::openConfig(QString(), KConfig::SimpleConfig); const QString kwin4 = QStringLiteral("kwin4_effect_"); KConfigGroup plugins = config->group("Plugins"); plugins.writeEntry(kwin4 + QStringLiteral("scaleinEnabled"), true); plugins.sync(); loader.setConfig(config); qRegisterMetaType(); QSignalSpy spy(&loader, &KWin::ScriptedEffectLoader::effectLoaded); QVERIFY(spy.isValid()); loader.queryAndLoadAll(); loader.clear(); // Should not load any effect QVERIFY(!spy.wait(100)); QVERIFY(spy.isEmpty()); } QTEST_MAIN(TestScriptedEffectLoader) #include "test_scripted_effectloader.moc" diff --git a/effectloader.cpp b/effectloader.cpp index 030aa2134..7ed120d0c 100644 --- a/effectloader.cpp +++ b/effectloader.cpp @@ -1,550 +1,558 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2014 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ // own #include "effectloader.h" // KWin #include #include #include "effects/effect_builtins.h" #include "scripting/scriptedeffect.h" #include "utils.h" // KDE #include #include #include #include // Qt #include #include #include #include #include namespace KWin { AbstractEffectLoader::AbstractEffectLoader(QObject *parent) : QObject(parent) { } AbstractEffectLoader::~AbstractEffectLoader() { } void AbstractEffectLoader::setConfig(KSharedConfig::Ptr config) { m_config = config; } LoadEffectFlags AbstractEffectLoader::readConfig(const QString &effectName, bool defaultValue) const { Q_ASSERT(m_config); KConfigGroup plugins(m_config, QStringLiteral("Plugins")); const QString key = effectName + QStringLiteral("Enabled"); // do we have a key for the effect? if (plugins.hasKey(key)) { // we have a key in the config, so read the enabled state const bool load = plugins.readEntry(key, defaultValue); return load ? LoadEffectFlags(LoadEffectFlag::Load) : LoadEffectFlags(); } // we don't have a key, so we just use the enabled by default value if (defaultValue) { return LoadEffectFlag::Load | LoadEffectFlag::CheckDefaultFunction; } return LoadEffectFlags(); } BuiltInEffectLoader::BuiltInEffectLoader(QObject *parent) : AbstractEffectLoader(parent) , m_queue(new EffectLoadQueue(this)) { } BuiltInEffectLoader::~BuiltInEffectLoader() { } bool BuiltInEffectLoader::hasEffect(const QString &name) const { return BuiltInEffects::available(internalName(name)); } bool BuiltInEffectLoader::isEffectSupported(const QString &name) const { return BuiltInEffects::supported(BuiltInEffects::builtInForName(internalName(name))); } QStringList BuiltInEffectLoader::listOfKnownEffects() const { return BuiltInEffects::availableEffectNames(); } bool BuiltInEffectLoader::loadEffect(const QString &name) { return loadEffect(name, BuiltInEffects::builtInForName(internalName(name)), LoadEffectFlag::Load); } void BuiltInEffectLoader::queryAndLoadAll() { const QList effects = BuiltInEffects::availableEffects(); for (BuiltInEffect effect : effects) { // check whether it is already loaded if (m_loadedEffects.contains(effect)) { continue; } const QString key = BuiltInEffects::nameForEffect(effect); const LoadEffectFlags flags = readConfig(key, BuiltInEffects::enabledByDefault(effect)); if (flags.testFlag(LoadEffectFlag::Load)) { m_queue->enqueue(qMakePair(effect, flags)); } } } bool BuiltInEffectLoader::loadEffect(BuiltInEffect effect, LoadEffectFlags flags) { return loadEffect(BuiltInEffects::nameForEffect(effect), effect, flags); } bool BuiltInEffectLoader::loadEffect(const QString &name, BuiltInEffect effect, LoadEffectFlags flags) { if (effect == BuiltInEffect::Invalid) { return false; } if (!flags.testFlag(LoadEffectFlag::Load)) { qCDebug(KWIN_CORE) << "Loading flags disable effect: " << name; return false; } // check that it is not already loaded if (m_loadedEffects.contains(effect)) { return false; } // supported might need a context #ifndef KWIN_UNIT_TEST effects->makeOpenGLContextCurrent(); #endif if (!BuiltInEffects::supported(effect)) { qCDebug(KWIN_CORE) << "Effect is not supported: " << name; return false; } if (flags.testFlag(LoadEffectFlag::CheckDefaultFunction)) { if (!BuiltInEffects::checkEnabledByDefault(effect)) { qCDebug(KWIN_CORE) << "Enabled by default function disables effect: " << name; return false; } } // ok, now we can try to create the Effect Effect *e = BuiltInEffects::create(effect); if (!e) { qCDebug(KWIN_CORE) << "Failed to create effect: " << name; return false; } // insert in our loaded effects m_loadedEffects.insert(effect, e); connect(e, &Effect::destroyed, this, [this, effect]() { m_loadedEffects.remove(effect); } ); qCDebug(KWIN_CORE) << "Successfully loaded built-in effect: " << name; emit effectLoaded(e, name); return true; } QString BuiltInEffectLoader::internalName(const QString& name) const { return name.toLower(); } void BuiltInEffectLoader::clear() { m_queue->clear(); } static const QString s_nameProperty = QStringLiteral("X-KDE-PluginInfo-Name"); static const QString s_jsConstraint = QStringLiteral("[X-Plasma-API] == 'javascript'"); static const QString s_serviceType = QStringLiteral("KWin/Effect"); ScriptedEffectLoader::ScriptedEffectLoader(QObject *parent) : AbstractEffectLoader(parent) , m_queue(new EffectLoadQueue(this)) { } ScriptedEffectLoader::~ScriptedEffectLoader() { } bool ScriptedEffectLoader::hasEffect(const QString &name) const { return findEffect(name).isValid(); } bool ScriptedEffectLoader::isEffectSupported(const QString &name) const { // scripted effects are in general supported + if (!ScriptedEffect::supported()) { + return false; + } return hasEffect(name); } QStringList ScriptedEffectLoader::listOfKnownEffects() const { const auto effects = findAllEffects(); QStringList result; for (const auto &service : effects) { result << service.pluginId(); } return result; } bool ScriptedEffectLoader::loadEffect(const QString &name) { auto effect = findEffect(name); if (!effect.isValid()) { return false; } return loadEffect(effect, LoadEffectFlag::Load); } bool ScriptedEffectLoader::loadEffect(const KPluginMetaData &effect, LoadEffectFlags flags) { const QString name = effect.pluginId(); if (!flags.testFlag(LoadEffectFlag::Load)) { qCDebug(KWIN_CORE) << "Loading flags disable effect: " << name; return false; } if (m_loadedEffects.contains(name)) { qCDebug(KWIN_CORE) << name << "already loaded"; return false; } + if (!ScriptedEffect::supported()) { + qCDebug(KWIN_CORE) << "Effect is not supported: " << name; + return false; + } + ScriptedEffect *e = ScriptedEffect::create(effect); if (!e) { qCDebug(KWIN_CORE) << "Could not initialize scripted effect: " << name; return false; } connect(e, &ScriptedEffect::destroyed, this, [this, name]() { m_loadedEffects.removeAll(name); } ); qCDebug(KWIN_CORE) << "Successfully loaded scripted effect: " << name; emit effectLoaded(e, name); m_loadedEffects << name; return true; } void ScriptedEffectLoader::queryAndLoadAll() { if (m_queryConnection) { return; } // perform querying for the services in a thread QFutureWatcher> *watcher = new QFutureWatcher>(this); m_queryConnection = connect(watcher, &QFutureWatcher>::finished, this, [this, watcher]() { const auto effects = watcher->result(); for (auto effect : effects) { const LoadEffectFlags flags = readConfig(effect.pluginId(), effect.isEnabledByDefault()); if (flags.testFlag(LoadEffectFlag::Load)) { m_queue->enqueue(qMakePair(effect, flags)); } } watcher->deleteLater(); m_queryConnection = QMetaObject::Connection(); }, Qt::QueuedConnection); watcher->setFuture(QtConcurrent::run(this, &ScriptedEffectLoader::findAllEffects)); } QList ScriptedEffectLoader::findAllEffects() const { return KPackage::PackageLoader::self()->listPackages(s_serviceType, QStringLiteral("kwin/effects")); } KPluginMetaData ScriptedEffectLoader::findEffect(const QString &name) const { const auto plugins = KPackage::PackageLoader::self()->findPackages(s_serviceType, QStringLiteral("kwin/effects"), [name] (const KPluginMetaData &metadata) { return metadata.pluginId().compare(name, Qt::CaseInsensitive) == 0; } ); if (!plugins.isEmpty()) { return plugins.first(); } return KPluginMetaData(); } void ScriptedEffectLoader::clear() { disconnect(m_queryConnection); m_queryConnection = QMetaObject::Connection(); m_queue->clear(); } PluginEffectLoader::PluginEffectLoader(QObject *parent) : AbstractEffectLoader(parent) , m_queue(new EffectLoadQueue< PluginEffectLoader, KPluginMetaData>(this)) , m_pluginSubDirectory(QStringLiteral("kwin/effects/plugins/")) { } PluginEffectLoader::~PluginEffectLoader() { } bool PluginEffectLoader::hasEffect(const QString &name) const { const auto info = findEffect(name); return info.isValid(); } KPluginMetaData PluginEffectLoader::findEffect(const QString &name) const { const auto plugins = KPluginLoader::findPlugins(m_pluginSubDirectory, [name] (const KPluginMetaData &data) { return data.pluginId().compare(name, Qt::CaseInsensitive) == 0 && data.serviceTypes().contains(s_serviceType); } ); if (plugins.isEmpty()) { return KPluginMetaData(); } return plugins.first(); } bool PluginEffectLoader::isEffectSupported(const QString &name) const { if (EffectPluginFactory *effectFactory = factory(findEffect(name))) { return effectFactory->isSupported(); } return false; } EffectPluginFactory *PluginEffectLoader::factory(const KPluginMetaData &info) const { if (!info.isValid()) { return nullptr; } KPluginLoader loader(info.fileName()); if (loader.pluginVersion() != KWIN_EFFECT_API_VERSION) { qCDebug(KWIN_CORE) << info.pluginId() << " has not matching plugin version, expected " << KWIN_EFFECT_API_VERSION << "got " << loader.pluginVersion(); return nullptr; } KPluginFactory *factory = loader.factory(); if (!factory) { qCDebug(KWIN_CORE) << "Did not get KPluginFactory for " << info.pluginId(); return nullptr; } return dynamic_cast< EffectPluginFactory* >(factory); } QStringList PluginEffectLoader::listOfKnownEffects() const { const auto plugins = findAllEffects(); QStringList result; for (const auto &plugin : plugins) { result << plugin.pluginId(); } qCDebug(KWIN_CORE) << result; return result; } bool PluginEffectLoader::loadEffect(const QString &name) { const auto info = findEffect(name); if (!info.isValid()) { return false; } return loadEffect(info, LoadEffectFlag::Load); } bool PluginEffectLoader::loadEffect(const KPluginMetaData &info, LoadEffectFlags flags) { if (!info.isValid()) { qCDebug(KWIN_CORE) << "Plugin info is not valid"; return false; } const QString name = info.pluginId(); if (!flags.testFlag(LoadEffectFlag::Load)) { qCDebug(KWIN_CORE) << "Loading flags disable effect: " << name; return false; } if (m_loadedEffects.contains(name)) { qCDebug(KWIN_CORE) << name << " already loaded"; return false; } EffectPluginFactory *effectFactory = factory(info); if (!effectFactory) { qCDebug(KWIN_CORE) << "Couldn't get an EffectPluginFactory for: " << name; return false; } #ifndef KWIN_UNIT_TEST effects->makeOpenGLContextCurrent(); #endif if (!effectFactory->isSupported()) { qCDebug(KWIN_CORE) << "Effect is not supported: " << name; return false; } if (flags.testFlag(LoadEffectFlag::CheckDefaultFunction)) { if (!effectFactory->enabledByDefault()) { qCDebug(KWIN_CORE) << "Enabled by default function disables effect: " << name; return false; } } // ok, now we can try to create the Effect Effect *e = effectFactory->createEffect(); if (!e) { qCDebug(KWIN_CORE) << "Failed to create effect: " << name; return false; } // insert in our loaded effects m_loadedEffects << name; connect(e, &Effect::destroyed, this, [this, name]() { m_loadedEffects.removeAll(name); } ); qCDebug(KWIN_CORE) << "Successfully loaded plugin effect: " << name; emit effectLoaded(e, name); return true; } void PluginEffectLoader::queryAndLoadAll() { if (m_queryConnection) { return; } // perform querying for the services in a thread QFutureWatcher> *watcher = new QFutureWatcher>(this); m_queryConnection = connect(watcher, &QFutureWatcher>::finished, this, [this, watcher]() { const auto effects = watcher->result(); for (const auto &effect : effects) { const LoadEffectFlags flags = readConfig(effect.pluginId(), effect.isEnabledByDefault()); if (flags.testFlag(LoadEffectFlag::Load)) { m_queue->enqueue(qMakePair(effect, flags)); } } watcher->deleteLater(); m_queryConnection = QMetaObject::Connection(); }, Qt::QueuedConnection); watcher->setFuture(QtConcurrent::run(this, &PluginEffectLoader::findAllEffects)); } QVector PluginEffectLoader::findAllEffects() const { return KPluginLoader::findPlugins(m_pluginSubDirectory, [] (const KPluginMetaData &data) { return data.serviceTypes().contains(s_serviceType); }); } void PluginEffectLoader::setPluginSubDirectory(const QString &directory) { m_pluginSubDirectory = directory; } void PluginEffectLoader::clear() { disconnect(m_queryConnection); m_queryConnection = QMetaObject::Connection(); m_queue->clear(); } EffectLoader::EffectLoader(QObject *parent) : AbstractEffectLoader(parent) { m_loaders << new BuiltInEffectLoader(this) << new ScriptedEffectLoader(this) << new PluginEffectLoader(this); for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { connect(*it, &AbstractEffectLoader::effectLoaded, this, &AbstractEffectLoader::effectLoaded); } } EffectLoader::~EffectLoader() { } #define BOOL_MERGE( method ) \ bool EffectLoader::method(const QString &name) const \ { \ for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { \ if ((*it)->method(name)) { \ return true; \ } \ } \ return false; \ } BOOL_MERGE(hasEffect) BOOL_MERGE(isEffectSupported) #undef BOOL_MERGE QStringList EffectLoader::listOfKnownEffects() const { QStringList result; for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { result << (*it)->listOfKnownEffects(); } return result; } bool EffectLoader::loadEffect(const QString &name) { for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { if ((*it)->loadEffect(name)) { return true; } } return false; } void EffectLoader::queryAndLoadAll() { for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { (*it)->queryAndLoadAll(); } } void EffectLoader::setConfig(KSharedConfig::Ptr config) { AbstractEffectLoader::setConfig(config); for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { (*it)->setConfig(config); } } void EffectLoader::clear() { for (auto it = m_loaders.constBegin(); it != m_loaders.constEnd(); ++it) { (*it)->clear(); } } } // namespace KWin diff --git a/effects.cpp b/effects.cpp index c76f0a3fa..77d52da58 100644 --- a/effects.cpp +++ b/effects.cpp @@ -1,1971 +1,1981 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2010, 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "effects.h" #include "effectsadaptor.h" #include "effectloader.h" #ifdef KWIN_BUILD_ACTIVITIES #include "activities.h" #endif #include "deleted.h" #include "client.h" #include "cursor.h" #include "group.h" #include "pointer_input.h" #include "scene_xrender.h" #include "scene_qpainter.h" #include "unmanaged.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "screenedge.h" #include "scripting/scriptedeffect.h" #include "screens.h" #include "screenlockerwatcher.h" #include "thumbnailitem.h" #include "virtualdesktops.h" #include "workspace.h" #include "kwinglutils.h" #include #include #include #include "composite.h" #include "xcbutils.h" #include "platform.h" #include "shell_client.h" #include "wayland_server.h" #include "decorations/decorationbridge.h" #include namespace KWin { //--------------------- // Static static QByteArray readWindowProperty(xcb_window_t win, xcb_atom_t atom, xcb_atom_t type, int format) { if (win == XCB_WINDOW_NONE) { return QByteArray(); } uint32_t len = 32768; for (;;) { Xcb::Property prop(false, win, atom, XCB_ATOM_ANY, 0, len); if (prop.isNull()) { // get property failed return QByteArray(); } if (prop->bytes_after > 0) { len *= 2; continue; } return prop.toByteArray(format, type); } } static void deleteWindowProperty(Window win, long int atom) { if (win == XCB_WINDOW_NONE) { return; } xcb_delete_property(connection(), win, atom); } //--------------------- EffectsHandlerImpl::EffectsHandlerImpl(Compositor *compositor, Scene *scene) : EffectsHandler(scene->compositingType()) , keyboard_grab_effect(NULL) , fullscreen_effect(0) , next_window_quad_type(EFFECT_QUAD_TYPE_START) , m_compositor(compositor) , m_scene(scene) , m_desktopRendering(false) , m_currentRenderedDesktop(0) , m_effectLoader(new EffectLoader(this)) , m_trackingCursorChanges(0) { connect(m_effectLoader, &AbstractEffectLoader::effectLoaded, this, [this](Effect *effect, const QString &name) { effect_order.insert(effect->requestedEffectChainPosition(), EffectPair(name, effect)); loaded_effects << EffectPair(name, effect); effectsChanged(); } ); m_effectLoader->setConfig(kwinApp()->config()); new EffectsAdaptor(this); QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.registerObject(QStringLiteral("/Effects"), this); // init is important, otherwise causes crashes when quads are build before the first painting pass start m_currentBuildQuadsIterator = m_activeEffects.constEnd(); Workspace *ws = Workspace::self(); VirtualDesktopManager *vds = VirtualDesktopManager::self(); connect(ws, &Workspace::showingDesktopChanged, this, &EffectsHandlerImpl::showingDesktopChanged); connect(ws, &Workspace::currentDesktopChanged, this, [this](int old, AbstractClient *c) { const int newDesktop = VirtualDesktopManager::self()->current(); if (old != 0 && newDesktop != old) { emit desktopChanged(old, newDesktop, c ? c->effectWindow() : 0); // TODO: remove in 4.10 emit desktopChanged(old, newDesktop); } } ); connect(ws, &Workspace::desktopPresenceChanged, this, [this](AbstractClient *c, int old) { if (!c->effectWindow()) { return; } // the visibility update hasn't happed yet, thus the signal is delayed to prevent glitches, see also BUG 347490 QMetaObject::invokeMethod(this, "desktopPresenceChanged", Qt::QueuedConnection, Q_ARG(KWin::EffectWindow*, c->effectWindow()), Q_ARG(int, old), Q_ARG(int, c->desktop())); } ); connect(ws, &Workspace::clientAdded, this, [this](Client *c) { if (c->readyForPainting()) slotClientShown(c); else connect(c, &Toplevel::windowShown, this, &EffectsHandlerImpl::slotClientShown); } ); connect(ws, &Workspace::unmanagedAdded, this, [this](Unmanaged *u) { // it's never initially ready but has synthetic 50ms delay connect(u, &Toplevel::windowShown, this, &EffectsHandlerImpl::slotUnmanagedShown); } ); connect(ws, &Workspace::clientActivated, this, [this](KWin::AbstractClient *c) { emit windowActivated(c ? c->effectWindow() : nullptr); } ); connect(ws, &Workspace::deletedRemoved, this, [this](KWin::Deleted *d) { emit windowDeleted(d->effectWindow()); elevated_windows.removeAll(d->effectWindow()); } ); connect(vds, &VirtualDesktopManager::countChanged, this, &EffectsHandler::numberDesktopsChanged); connect(Cursor::self(), &Cursor::mouseChanged, this, &EffectsHandler::mouseChanged); connect(ws, &Workspace::propertyNotify, this, [this](long int atom) { if (!registered_atoms.contains(atom)) return; emit propertyNotify(nullptr, atom); } ); connect(screens(), &Screens::countChanged, this, &EffectsHandler::numberScreensChanged); connect(screens(), &Screens::sizeChanged, this, &EffectsHandler::virtualScreenSizeChanged); connect(screens(), &Screens::geometryChanged, this, &EffectsHandler::virtualScreenGeometryChanged); #ifdef KWIN_BUILD_ACTIVITIES if (Activities *activities = Activities::self()) { connect(activities, &Activities::added, this, &EffectsHandler::activityAdded); connect(activities, &Activities::removed, this, &EffectsHandler::activityRemoved); connect(activities, &Activities::currentChanged, this, &EffectsHandler::currentActivityChanged); } #endif connect(ws, &Workspace::stackingOrderChanged, this, &EffectsHandler::stackingOrderChanged); #ifdef KWIN_BUILD_TABBOX TabBox::TabBox *tabBox = TabBox::TabBox::self(); connect(tabBox, &TabBox::TabBox::tabBoxAdded, this, &EffectsHandler::tabBoxAdded); connect(tabBox, &TabBox::TabBox::tabBoxUpdated, this, &EffectsHandler::tabBoxUpdated); connect(tabBox, &TabBox::TabBox::tabBoxClosed, this, &EffectsHandler::tabBoxClosed); connect(tabBox, &TabBox::TabBox::tabBoxKeyEvent, this, &EffectsHandler::tabBoxKeyEvent); #endif connect(ScreenEdges::self(), &ScreenEdges::approaching, this, &EffectsHandler::screenEdgeApproaching); connect(ScreenLockerWatcher::self(), &ScreenLockerWatcher::locked, this, &EffectsHandler::screenLockingChanged); // connect all clients for (Client *c : ws->clientList()) { setupClientConnections(c); } for (Unmanaged *u : ws->unmanagedList()) { setupUnmanagedConnections(u); } if (auto w = waylandServer()) { connect(w, &WaylandServer::shellClientAdded, this, [this](ShellClient *c) { if (c->readyForPainting()) slotShellClientShown(c); else connect(c, &Toplevel::windowShown, this, &EffectsHandlerImpl::slotShellClientShown); } ); } reconfigure(); } EffectsHandlerImpl::~EffectsHandlerImpl() { unloadAllEffects(); } void EffectsHandlerImpl::unloadAllEffects() { makeOpenGLContextCurrent(); if (keyboard_grab_effect != NULL) ungrabKeyboard(); setActiveFullScreenEffect(nullptr); for (auto it = loaded_effects.begin(); it != loaded_effects.end(); ++it) { Effect *effect = (*it).second; stopMouseInterception(effect); // remove support properties for the effect const QList properties = m_propertiesForEffects.keys(); for (const QByteArray &property : properties) { removeSupportProperty(property, effect); } delete effect; } loaded_effects.clear(); m_effectLoader->clear(); } void EffectsHandlerImpl::setupAbstractClientConnections(AbstractClient* c) { connect(c, &AbstractClient::windowClosed, this, &EffectsHandlerImpl::slotWindowClosed); connect(c, static_cast(&AbstractClient::clientMaximizedStateChanged), this, &EffectsHandlerImpl::slotClientMaximized); connect(c, &AbstractClient::clientStartUserMovedResized, this, [this](AbstractClient *c) { emit windowStartUserMovedResized(c->effectWindow()); } ); connect(c, &AbstractClient::clientStepUserMovedResized, this, [this](AbstractClient *c, const QRect &geometry) { emit windowStepUserMovedResized(c->effectWindow(), geometry); } ); connect(c, &AbstractClient::clientFinishUserMovedResized, this, [this](AbstractClient *c) { emit windowFinishUserMovedResized(c->effectWindow()); } ); connect(c, &AbstractClient::opacityChanged, this, &EffectsHandlerImpl::slotOpacityChanged); connect(c, &AbstractClient::clientMinimized, this, [this](AbstractClient *c, bool animate) { // TODO: notify effects even if it should not animate? if (animate) { emit windowMinimized(c->effectWindow()); } } ); connect(c, &AbstractClient::clientUnminimized, this, [this](AbstractClient* c, bool animate) { // TODO: notify effects even if it should not animate? if (animate) { emit windowUnminimized(c->effectWindow()); } } ); connect(c, &AbstractClient::modalChanged, this, &EffectsHandlerImpl::slotClientModalityChanged); connect(c, &AbstractClient::geometryShapeChanged, this, &EffectsHandlerImpl::slotGeometryShapeChanged); connect(c, &AbstractClient::damaged, this, &EffectsHandlerImpl::slotWindowDamaged); connect(c, &AbstractClient::windowShown, this, [this](Toplevel *c) { emit windowShown(c->effectWindow()); } ); connect(c, &AbstractClient::windowHidden, this, [this](Toplevel *c) { emit windowHidden(c->effectWindow()); } ); } void EffectsHandlerImpl::setupClientConnections(Client* c) { setupAbstractClientConnections(c); connect(c, &Client::paddingChanged, this, &EffectsHandlerImpl::slotPaddingChanged); connect(c, &Client::propertyNotify, this, &EffectsHandlerImpl::slotPropertyNotify); } void EffectsHandlerImpl::setupUnmanagedConnections(Unmanaged* u) { connect(u, &Unmanaged::windowClosed, this, &EffectsHandlerImpl::slotWindowClosed); connect(u, &Unmanaged::opacityChanged, this, &EffectsHandlerImpl::slotOpacityChanged); connect(u, &Unmanaged::geometryShapeChanged, this, &EffectsHandlerImpl::slotGeometryShapeChanged); connect(u, &Unmanaged::paddingChanged, this, &EffectsHandlerImpl::slotPaddingChanged); connect(u, &Unmanaged::damaged, this, &EffectsHandlerImpl::slotWindowDamaged); connect(u, &Unmanaged::propertyNotify, this, &EffectsHandlerImpl::slotPropertyNotify); } void EffectsHandlerImpl::reconfigure() { m_effectLoader->queryAndLoadAll(); } // the idea is that effects call this function again which calls the next one void EffectsHandlerImpl::prePaintScreen(ScreenPrePaintData& data, int time) { if (m_currentPaintScreenIterator != m_activeEffects.constEnd()) { (*m_currentPaintScreenIterator++)->prePaintScreen(data, time); --m_currentPaintScreenIterator; } // no special final code } void EffectsHandlerImpl::paintScreen(int mask, QRegion region, ScreenPaintData& data) { if (m_currentPaintScreenIterator != m_activeEffects.constEnd()) { (*m_currentPaintScreenIterator++)->paintScreen(mask, region, data); --m_currentPaintScreenIterator; } else m_scene->finalPaintScreen(mask, region, data); } void EffectsHandlerImpl::paintDesktop(int desktop, int mask, QRegion region, ScreenPaintData &data) { if (desktop < 1 || desktop > numberOfDesktops()) { return; } m_currentRenderedDesktop = desktop; m_desktopRendering = true; // save the paint screen iterator EffectsIterator savedIterator = m_currentPaintScreenIterator; m_currentPaintScreenIterator = m_activeEffects.constBegin(); effects->paintScreen(mask, region, data); // restore the saved iterator m_currentPaintScreenIterator = savedIterator; m_desktopRendering = false; } void EffectsHandlerImpl::postPaintScreen() { if (m_currentPaintScreenIterator != m_activeEffects.constEnd()) { (*m_currentPaintScreenIterator++)->postPaintScreen(); --m_currentPaintScreenIterator; } // no special final code } void EffectsHandlerImpl::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (m_currentPaintWindowIterator != m_activeEffects.constEnd()) { (*m_currentPaintWindowIterator++)->prePaintWindow(w, data, time); --m_currentPaintWindowIterator; } // no special final code } void EffectsHandlerImpl::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (m_currentPaintWindowIterator != m_activeEffects.constEnd()) { (*m_currentPaintWindowIterator++)->paintWindow(w, mask, region, data); --m_currentPaintWindowIterator; } else m_scene->finalPaintWindow(static_cast(w), mask, region, data); } void EffectsHandlerImpl::paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) { if (m_currentPaintEffectFrameIterator != m_activeEffects.constEnd()) { (*m_currentPaintEffectFrameIterator++)->paintEffectFrame(frame, region, opacity, frameOpacity); --m_currentPaintEffectFrameIterator; } else { const EffectFrameImpl* frameImpl = static_cast(frame); frameImpl->finalRender(region, opacity, frameOpacity); } } void EffectsHandlerImpl::postPaintWindow(EffectWindow* w) { if (m_currentPaintWindowIterator != m_activeEffects.constEnd()) { (*m_currentPaintWindowIterator++)->postPaintWindow(w); --m_currentPaintWindowIterator; } // no special final code } Effect *EffectsHandlerImpl::provides(Effect::Feature ef) { for (int i = 0; i < loaded_effects.size(); ++i) if (loaded_effects.at(i).second->provides(ef)) return loaded_effects.at(i).second; return NULL; } void EffectsHandlerImpl::drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (m_currentDrawWindowIterator != m_activeEffects.constEnd()) { (*m_currentDrawWindowIterator++)->drawWindow(w, mask, region, data); --m_currentDrawWindowIterator; } else m_scene->finalDrawWindow(static_cast(w), mask, region, data); } void EffectsHandlerImpl::buildQuads(EffectWindow* w, WindowQuadList& quadList) { static bool initIterator = true; if (initIterator) { m_currentBuildQuadsIterator = m_activeEffects.constBegin(); initIterator = false; } if (m_currentBuildQuadsIterator != m_activeEffects.constEnd()) { (*m_currentBuildQuadsIterator++)->buildQuads(w, quadList); --m_currentBuildQuadsIterator; } if (m_currentBuildQuadsIterator == m_activeEffects.constBegin()) initIterator = true; } bool EffectsHandlerImpl::hasDecorationShadows() const { return false; } bool EffectsHandlerImpl::decorationsHaveAlpha() const { return true; } bool EffectsHandlerImpl::decorationSupportsBlurBehind() const { return Decoration::DecorationBridge::self()->needsBlur(); } // start another painting pass void EffectsHandlerImpl::startPaint() { m_activeEffects.clear(); m_activeEffects.reserve(loaded_effects.count()); for(QVector< KWin::EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { if (it->second->isActive()) { m_activeEffects << it->second; } } m_currentDrawWindowIterator = m_activeEffects.constBegin(); m_currentPaintWindowIterator = m_activeEffects.constBegin(); m_currentPaintScreenIterator = m_activeEffects.constBegin(); m_currentPaintEffectFrameIterator = m_activeEffects.constBegin(); } void EffectsHandlerImpl::slotClientMaximized(KWin::AbstractClient *c, MaximizeMode maxMode) { bool horizontal = false; bool vertical = false; switch (maxMode) { case MaximizeHorizontal: horizontal = true; break; case MaximizeVertical: vertical = true; break; case MaximizeFull: horizontal = true; vertical = true; break; case MaximizeRestore: // fall through default: // default - nothing to do break; } if (EffectWindowImpl *w = c->effectWindow()) { emit windowMaximizedStateChanged(w, horizontal, vertical); } } void EffectsHandlerImpl::slotOpacityChanged(Toplevel *t, qreal oldOpacity) { if (t->opacity() == oldOpacity || !t->effectWindow()) { return; } emit windowOpacityChanged(t->effectWindow(), oldOpacity, (qreal)t->opacity()); } void EffectsHandlerImpl::slotClientShown(KWin::Toplevel *t) { Q_ASSERT(dynamic_cast(t)); Client *c = static_cast(t); disconnect(c, &Toplevel::windowShown, this, &EffectsHandlerImpl::slotClientShown); setupClientConnections(c); if (!c->tabGroup()) // the "window" has already been there emit windowAdded(c->effectWindow()); } void EffectsHandlerImpl::slotShellClientShown(Toplevel *t) { ShellClient *c = static_cast(t); setupAbstractClientConnections(c); emit windowAdded(t->effectWindow()); } void EffectsHandlerImpl::slotUnmanagedShown(KWin::Toplevel *t) { // regardless, unmanaged windows are -yet?- not synced anyway Q_ASSERT(dynamic_cast(t)); Unmanaged *u = static_cast(t); setupUnmanagedConnections(u); emit windowAdded(u->effectWindow()); } void EffectsHandlerImpl::slotWindowClosed(KWin::Toplevel *c, KWin::Deleted *d) { c->disconnect(this); if (d) { emit windowClosed(c->effectWindow()); } } void EffectsHandlerImpl::slotClientModalityChanged() { emit windowModalityChanged(static_cast(sender())->effectWindow()); } void EffectsHandlerImpl::slotCurrentTabAboutToChange(EffectWindow *from, EffectWindow *to) { emit currentTabAboutToChange(from, to); } void EffectsHandlerImpl::slotTabAdded(EffectWindow* w, EffectWindow* to) { emit tabAdded(w, to); } void EffectsHandlerImpl::slotTabRemoved(EffectWindow *w, EffectWindow* leaderOfFormerGroup) { emit tabRemoved(w, leaderOfFormerGroup); } void EffectsHandlerImpl::slotWindowDamaged(Toplevel* t, const QRect& r) { if (!t->effectWindow()) { // can happen during tear down of window return; } emit windowDamaged(t->effectWindow(), r); } void EffectsHandlerImpl::slotGeometryShapeChanged(Toplevel* t, const QRect& old) { // during late cleanup effectWindow() may be already NULL // in some functions that may still call this if (t == NULL || t->effectWindow() == NULL) return; emit windowGeometryShapeChanged(t->effectWindow(), old); } void EffectsHandlerImpl::slotPaddingChanged(Toplevel* t, const QRect& old) { // during late cleanup effectWindow() may be already NULL // in some functions that may still call this if (t == NULL || t->effectWindow() == NULL) return; emit windowPaddingChanged(t->effectWindow(), old); } void EffectsHandlerImpl::setActiveFullScreenEffect(Effect* e) { fullscreen_effect = e; } Effect* EffectsHandlerImpl::activeFullScreenEffect() const { return fullscreen_effect; } bool EffectsHandlerImpl::grabKeyboard(Effect* effect) { if (keyboard_grab_effect != NULL) return false; if (kwinApp()->operationMode() == Application::OperationModeX11) { bool ret = grabXKeyboard(); if (!ret) return false; } keyboard_grab_effect = effect; return true; } void EffectsHandlerImpl::ungrabKeyboard() { assert(keyboard_grab_effect != NULL); if (kwinApp()->operationMode() == Application::OperationModeX11) { ungrabXKeyboard(); } keyboard_grab_effect = NULL; } void EffectsHandlerImpl::grabbedKeyboardEvent(QKeyEvent* e) { if (keyboard_grab_effect != NULL) keyboard_grab_effect->grabbedKeyboardEvent(e); } void EffectsHandlerImpl::startMouseInterception(Effect *effect, Qt::CursorShape shape) { if (m_grabbedMouseEffects.contains(effect)) { return; } m_grabbedMouseEffects.append(effect); if (m_grabbedMouseEffects.size() != 1) { return; } if (kwinApp()->operationMode() != Application::OperationModeX11) { input()->pointer()->setEffectsOverrideCursor(shape); return; } // NOTE: it is intended to not perform an XPointerGrab on X11. See documentation in kwineffects.h // The mouse grab is implemented by using a full screen input only window if (!m_mouseInterceptionWindow.isValid()) { const QSize &s = screens()->size(); const QRect geo(0, 0, s.width(), s.height()); const uint32_t mask = XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK; const uint32_t values[] = { true, XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_POINTER_MOTION }; m_mouseInterceptionWindow.reset(Xcb::createInputWindow(geo, mask, values)); defineCursor(shape); } else { defineCursor(shape); } m_mouseInterceptionWindow.map(); m_mouseInterceptionWindow.raise(); // Raise electric border windows above the input windows // so they can still be triggered. ScreenEdges::self()->ensureOnTop(); } void EffectsHandlerImpl::stopMouseInterception(Effect *effect) { if (!m_grabbedMouseEffects.contains(effect)) { return; } m_grabbedMouseEffects.removeAll(effect); if (kwinApp()->operationMode() != Application::OperationModeX11) { input()->pointer()->removeEffectsOverrideCursor(); return; } if (m_grabbedMouseEffects.isEmpty()) { m_mouseInterceptionWindow.unmap(); Workspace::self()->stackScreenEdgesUnderOverrideRedirect(); } } bool EffectsHandlerImpl::isMouseInterception() const { return m_grabbedMouseEffects.count() > 0; } void EffectsHandlerImpl::registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) { input()->registerShortcut(shortcut, action); } void EffectsHandlerImpl::registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) { input()->registerPointerShortcut(modifiers, pointerButtons, action); } void EffectsHandlerImpl::registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) { input()->registerAxisShortcut(modifiers, axis, action); } void* EffectsHandlerImpl::getProxy(QString name) { for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) if ((*it).first == name) return (*it).second->proxy(); return NULL; } void EffectsHandlerImpl::startMousePolling() { if (Cursor::self()) Cursor::self()->startMousePolling(); } void EffectsHandlerImpl::stopMousePolling() { if (Cursor::self()) Cursor::self()->stopMousePolling(); } bool EffectsHandlerImpl::hasKeyboardGrab() const { return keyboard_grab_effect != NULL; } void EffectsHandlerImpl::desktopResized(const QSize &size) { m_scene->screenGeometryChanged(size); if (m_mouseInterceptionWindow.isValid()) { m_mouseInterceptionWindow.setGeometry(QRect(0, 0, size.width(), size.height())); } emit screenGeometryChanged(size); } void EffectsHandlerImpl::slotPropertyNotify(Toplevel* t, long int atom) { if (!registered_atoms.contains(atom)) return; emit propertyNotify(t->effectWindow(), atom); } void EffectsHandlerImpl::registerPropertyType(long atom, bool reg) { if (reg) ++registered_atoms[ atom ]; // initialized to 0 if not present yet else { if (--registered_atoms[ atom ] == 0) registered_atoms.remove(atom); } } xcb_atom_t EffectsHandlerImpl::announceSupportProperty(const QByteArray &propertyName, Effect *effect) { PropertyEffectMap::iterator it = m_propertiesForEffects.find(propertyName); if (it != m_propertiesForEffects.end()) { // property has already been registered for an effect // just append Effect and return the atom stored in m_managedProperties if (!it.value().contains(effect)) { it.value().append(effect); } return m_managedProperties.value(propertyName); } // get the atom for the propertyName ScopedCPointer atomReply(xcb_intern_atom_reply(connection(), xcb_intern_atom_unchecked(connection(), false, propertyName.size(), propertyName.constData()), NULL)); if (atomReply.isNull()) { return XCB_ATOM_NONE; } m_compositor->keepSupportProperty(atomReply->atom); // announce property on root window unsigned char dummy = 0; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, rootWindow(), atomReply->atom, atomReply->atom, 8, 1, &dummy); // TODO: add to _NET_SUPPORTED m_managedProperties.insert(propertyName, atomReply->atom); m_propertiesForEffects.insert(propertyName, QList() << effect); registerPropertyType(atomReply->atom, true); return atomReply->atom; } void EffectsHandlerImpl::removeSupportProperty(const QByteArray &propertyName, Effect *effect) { PropertyEffectMap::iterator it = m_propertiesForEffects.find(propertyName); if (it == m_propertiesForEffects.end()) { // property is not registered - nothing to do return; } if (!it.value().contains(effect)) { // property is not registered for given effect - nothing to do return; } it.value().removeAll(effect); if (!it.value().isEmpty()) { // property still registered for another effect - nothing further to do return; } const xcb_atom_t atom = m_managedProperties.take(propertyName); registerPropertyType(atom, false); m_propertiesForEffects.remove(propertyName); m_compositor->removeSupportProperty(atom); // delayed removal } QByteArray EffectsHandlerImpl::readRootProperty(long atom, long type, int format) const { return readWindowProperty(rootWindow(), atom, type, format); } void EffectsHandlerImpl::deleteRootProperty(long atom) const { deleteWindowProperty(rootWindow(), atom); } void EffectsHandlerImpl::activateWindow(EffectWindow* c) { if (AbstractClient* cl = dynamic_cast< AbstractClient* >(static_cast(c)->window())) Workspace::self()->activateClient(cl, true); } EffectWindow* EffectsHandlerImpl::activeWindow() const { return Workspace::self()->activeClient() ? Workspace::self()->activeClient()->effectWindow() : NULL; } void EffectsHandlerImpl::moveWindow(EffectWindow* w, const QPoint& pos, bool snap, double snapAdjust) { AbstractClient* cl = dynamic_cast< AbstractClient* >(static_cast(w)->window()); if (!cl || !cl->isMovable()) return; if (snap) cl->move(Workspace::self()->adjustClientPosition(cl, pos, true, snapAdjust)); else cl->move(pos); } void EffectsHandlerImpl::windowToDesktop(EffectWindow* w, int desktop) { AbstractClient* cl = dynamic_cast< AbstractClient* >(static_cast(w)->window()); if (cl && !cl->isDesktop() && !cl->isDock()) Workspace::self()->sendClientToDesktop(cl, desktop, true); } void EffectsHandlerImpl::windowToScreen(EffectWindow* w, int screen) { AbstractClient* cl = dynamic_cast< AbstractClient* >(static_cast(w)->window()); if (cl && !cl->isDesktop() && !cl->isDock()) Workspace::self()->sendClientToScreen(cl, screen); } void EffectsHandlerImpl::setShowingDesktop(bool showing) { Workspace::self()->setShowingDesktop(showing); } QString EffectsHandlerImpl::currentActivity() const { #ifdef KWIN_BUILD_ACTIVITIES if (!Activities::self()) { return QString(); } return Activities::self()->current(); #else return QString(); #endif } int EffectsHandlerImpl::currentDesktop() const { return VirtualDesktopManager::self()->current(); } int EffectsHandlerImpl::numberOfDesktops() const { return VirtualDesktopManager::self()->count(); } void EffectsHandlerImpl::setCurrentDesktop(int desktop) { VirtualDesktopManager::self()->setCurrent(desktop); } void EffectsHandlerImpl::setNumberOfDesktops(int desktops) { VirtualDesktopManager::self()->setCount(desktops); } QSize EffectsHandlerImpl::desktopGridSize() const { return VirtualDesktopManager::self()->grid().size(); } int EffectsHandlerImpl::desktopGridWidth() const { return desktopGridSize().width(); } int EffectsHandlerImpl::desktopGridHeight() const { return desktopGridSize().height(); } int EffectsHandlerImpl::workspaceWidth() const { return desktopGridWidth() * displayWidth(); } int EffectsHandlerImpl::workspaceHeight() const { return desktopGridHeight() * displayHeight(); } int EffectsHandlerImpl::desktopAtCoords(QPoint coords) const { return VirtualDesktopManager::self()->grid().at(coords); } QPoint EffectsHandlerImpl::desktopGridCoords(int id) const { return VirtualDesktopManager::self()->grid().gridCoords(id); } QPoint EffectsHandlerImpl::desktopCoords(int id) const { QPoint coords = VirtualDesktopManager::self()->grid().gridCoords(id); if (coords.x() == -1) return QPoint(-1, -1); return QPoint(coords.x() * displayWidth(), coords.y() * displayHeight()); } int EffectsHandlerImpl::desktopAbove(int desktop, bool wrap) const { return getDesktop(desktop, wrap); } int EffectsHandlerImpl::desktopToRight(int desktop, bool wrap) const { return getDesktop(desktop, wrap); } int EffectsHandlerImpl::desktopBelow(int desktop, bool wrap) const { return getDesktop(desktop, wrap); } int EffectsHandlerImpl::desktopToLeft(int desktop, bool wrap) const { return getDesktop(desktop, wrap); } QString EffectsHandlerImpl::desktopName(int desktop) const { return VirtualDesktopManager::self()->name(desktop); } bool EffectsHandlerImpl::optionRollOverDesktops() const { return options->isRollOverDesktops(); } double EffectsHandlerImpl::animationTimeFactor() const { return options->animationTimeFactor(); } WindowQuadType EffectsHandlerImpl::newWindowQuadType() { return WindowQuadType(next_window_quad_type++); } EffectWindow* EffectsHandlerImpl::findWindow(WId id) const { if (Client* w = Workspace::self()->findClient(Predicate::WindowMatch, id)) return w->effectWindow(); if (Unmanaged* w = Workspace::self()->findUnmanaged(id)) return w->effectWindow(); if (waylandServer()) { if (ShellClient *w = waylandServer()->findClient(id)) { return w->effectWindow(); } } return NULL; } EffectWindow* EffectsHandlerImpl::findWindow(KWayland::Server::SurfaceInterface *surf) const { if (waylandServer()) { if (ShellClient *w = waylandServer()->findClient(surf)) { return w->effectWindow(); } } return nullptr; } EffectWindowList EffectsHandlerImpl::stackingOrder() const { ToplevelList list = Workspace::self()->xStackingOrder(); EffectWindowList ret; for (Toplevel *t : list) { if (EffectWindow *w = effectWindow(t)) ret.append(w); } return ret; } void EffectsHandlerImpl::setElevatedWindow(KWin::EffectWindow* w, bool set) { elevated_windows.removeAll(w); if (set) elevated_windows.append(w); } void EffectsHandlerImpl::setTabBoxWindow(EffectWindow* w) { #ifdef KWIN_BUILD_TABBOX if (AbstractClient* c = dynamic_cast< AbstractClient* >(static_cast< EffectWindowImpl* >(w)->window())) { TabBox::TabBox::self()->setCurrentClient(c); } #else Q_UNUSED(w) #endif } void EffectsHandlerImpl::setTabBoxDesktop(int desktop) { #ifdef KWIN_BUILD_TABBOX TabBox::TabBox::self()->setCurrentDesktop(desktop); #else Q_UNUSED(desktop) #endif } EffectWindowList EffectsHandlerImpl::currentTabBoxWindowList() const { #ifdef KWIN_BUILD_TABBOX EffectWindowList ret; const auto clients = TabBox::TabBox::self()->currentClientList(); for (auto c : clients) ret.append(c->effectWindow()); return ret; #else return EffectWindowList(); #endif } void EffectsHandlerImpl::refTabBox() { #ifdef KWIN_BUILD_TABBOX TabBox::TabBox::self()->reference(); #endif } void EffectsHandlerImpl::unrefTabBox() { #ifdef KWIN_BUILD_TABBOX TabBox::TabBox::self()->unreference(); #endif } void EffectsHandlerImpl::closeTabBox() { #ifdef KWIN_BUILD_TABBOX TabBox::TabBox::self()->close(); #endif } QList< int > EffectsHandlerImpl::currentTabBoxDesktopList() const { #ifdef KWIN_BUILD_TABBOX return TabBox::TabBox::self()->currentDesktopList(); #endif return QList< int >(); } int EffectsHandlerImpl::currentTabBoxDesktop() const { #ifdef KWIN_BUILD_TABBOX return TabBox::TabBox::self()->currentDesktop(); #endif return -1; } EffectWindow* EffectsHandlerImpl::currentTabBoxWindow() const { #ifdef KWIN_BUILD_TABBOX if (auto c = TabBox::TabBox::self()->currentClient()) return c->effectWindow(); #endif return NULL; } void EffectsHandlerImpl::addRepaintFull() { m_compositor->addRepaintFull(); } void EffectsHandlerImpl::addRepaint(const QRect& r) { m_compositor->addRepaint(r); } void EffectsHandlerImpl::addRepaint(const QRegion& r) { m_compositor->addRepaint(r); } void EffectsHandlerImpl::addRepaint(int x, int y, int w, int h) { m_compositor->addRepaint(x, y, w, h); } int EffectsHandlerImpl::activeScreen() const { return screens()->current(); } int EffectsHandlerImpl::numScreens() const { return screens()->count(); } int EffectsHandlerImpl::screenNumber(const QPoint& pos) const { return screens()->number(pos); } QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, int screen, int desktop) const { return Workspace::self()->clientArea(opt, screen, desktop); } QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, const EffectWindow* c) const { const Toplevel* t = static_cast< const EffectWindowImpl* >(c)->window(); if (const AbstractClient* cl = dynamic_cast< const AbstractClient* >(t)) return Workspace::self()->clientArea(opt, cl); else return Workspace::self()->clientArea(opt, t->geometry().center(), VirtualDesktopManager::self()->current()); } QRect EffectsHandlerImpl::clientArea(clientAreaOption opt, const QPoint& p, int desktop) const { return Workspace::self()->clientArea(opt, p, desktop); } QRect EffectsHandlerImpl::virtualScreenGeometry() const { return screens()->geometry(); } QSize EffectsHandlerImpl::virtualScreenSize() const { return screens()->size(); } void EffectsHandlerImpl::defineCursor(Qt::CursorShape shape) { if (!m_mouseInterceptionWindow.isValid()) { input()->pointer()->setEffectsOverrideCursor(shape); return; } const xcb_cursor_t c = Cursor::x11Cursor(shape); if (c != XCB_CURSOR_NONE) { m_mouseInterceptionWindow.defineCursor(c); } } bool EffectsHandlerImpl::checkInputWindowEvent(xcb_button_press_event_t *e) { if (m_grabbedMouseEffects.isEmpty() || m_mouseInterceptionWindow != e->event) { return false; } for (Effect *effect : m_grabbedMouseEffects) { Qt::MouseButton button = x11ToQtMouseButton(e->detail); Qt::MouseButtons buttons = x11ToQtMouseButtons(e->state); const QEvent::Type type = ((e->response_type & ~0x80) == XCB_BUTTON_PRESS) ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease; if (type == QEvent::MouseButtonPress) { buttons |= button; } else { buttons &= ~button; } QMouseEvent ev(type, QPoint(e->event_x, e->event_y), QPoint(e->root_x, e->root_y), button, buttons, x11ToQtKeyboardModifiers(e->state)); effect->windowInputMouseEvent(&ev); } return true; // eat event } bool EffectsHandlerImpl::checkInputWindowEvent(xcb_motion_notify_event_t *e) { if (m_grabbedMouseEffects.isEmpty() || m_mouseInterceptionWindow != e->event) { return false; } for (Effect *effect : m_grabbedMouseEffects) { QMouseEvent ev(QEvent::MouseMove, QPoint(e->event_x, e->event_y), QPoint(e->root_x, e->root_y), Qt::NoButton, x11ToQtMouseButtons(e->state), x11ToQtKeyboardModifiers(e->state)); effect->windowInputMouseEvent(&ev); } return true; // eat event } bool EffectsHandlerImpl::checkInputWindowEvent(QMouseEvent *e) { if (m_grabbedMouseEffects.isEmpty()) { return false; } foreach (Effect *effect, m_grabbedMouseEffects) { effect->windowInputMouseEvent(e); } return true; } bool EffectsHandlerImpl::checkInputWindowEvent(QWheelEvent *e) { if (m_grabbedMouseEffects.isEmpty()) { return false; } foreach (Effect *effect, m_grabbedMouseEffects) { effect->windowInputMouseEvent(e); } return true; } void EffectsHandlerImpl::connectNotify(const QMetaMethod &signal) { if (signal == QMetaMethod::fromSignal(&EffectsHandler::cursorShapeChanged)) { if (!m_trackingCursorChanges) { connect(Cursor::self(), &Cursor::cursorChanged, this, &EffectsHandler::cursorShapeChanged); Cursor::self()->startCursorTracking(); } ++m_trackingCursorChanges; } EffectsHandler::connectNotify(signal); } void EffectsHandlerImpl::disconnectNotify(const QMetaMethod &signal) { if (signal == QMetaMethod::fromSignal(&EffectsHandler::cursorShapeChanged)) { Q_ASSERT(m_trackingCursorChanges > 0); if (!--m_trackingCursorChanges) { Cursor::self()->stopCursorTracking(); disconnect(Cursor::self(), &Cursor::cursorChanged, this, &EffectsHandler::cursorShapeChanged); } } EffectsHandler::disconnectNotify(signal); } void EffectsHandlerImpl::checkInputWindowStacking() { if (m_grabbedMouseEffects.isEmpty()) { return; } if (kwinApp()->operationMode() != Application::OperationModeX11) { return; } m_mouseInterceptionWindow.raise(); // Raise electric border windows above the input windows // so they can still be triggered. TODO: Do both at once. ScreenEdges::self()->ensureOnTop(); } QPoint EffectsHandlerImpl::cursorPos() const { return Cursor::pos(); } void EffectsHandlerImpl::reserveElectricBorder(ElectricBorder border, Effect *effect) { ScreenEdges::self()->reserve(border, effect, "borderActivated"); } void EffectsHandlerImpl::unreserveElectricBorder(ElectricBorder border, Effect *effect) { ScreenEdges::self()->unreserve(border, effect); } unsigned long EffectsHandlerImpl::xrenderBufferPicture() { #ifdef KWIN_HAVE_XRENDER_COMPOSITING if (SceneXrender* s = dynamic_cast< SceneXrender* >(m_scene)) return s->bufferPicture(); #endif return None; } QPainter *EffectsHandlerImpl::scenePainter() { if (SceneQPainter *s = dynamic_cast(m_scene)) { return s->painter(); } else { return NULL; } } void EffectsHandlerImpl::toggleEffect(const QString& name) { if (isEffectLoaded(name)) unloadEffect(name); else loadEffect(name); } QStringList EffectsHandlerImpl::loadedEffects() const { QStringList listModules; for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { listModules << (*it).first; } return listModules; } QStringList EffectsHandlerImpl::listOfEffects() const { return m_effectLoader->listOfKnownEffects(); } bool EffectsHandlerImpl::loadEffect(const QString& name) { makeOpenGLContextCurrent(); m_compositor->addRepaintFull(); return m_effectLoader->loadEffect(name); } void EffectsHandlerImpl::unloadEffect(const QString& name) { makeOpenGLContextCurrent(); m_compositor->addRepaintFull(); for (QMap< int, EffectPair >::iterator it = effect_order.begin(); it != effect_order.end(); ++it) { if (it.value().first == name) { qCDebug(KWIN_CORE) << "EffectsHandler::unloadEffect : Unloading Effect : " << name; if (activeFullScreenEffect() == it.value().second) { setActiveFullScreenEffect(0); } stopMouseInterception(it.value().second); // remove support properties for the effect const QList properties = m_propertiesForEffects.keys(); for (const QByteArray &property : properties) { removeSupportProperty(property, it.value().second); } delete it.value().second; effect_order.erase(it); effectsChanged(); return; } } qCDebug(KWIN_CORE) << "EffectsHandler::unloadEffect : Effect not loaded : " << name; } void EffectsHandlerImpl::reconfigureEffect(const QString& name) { for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) if ((*it).first == name) { kwinApp()->config()->reparseConfiguration(); makeOpenGLContextCurrent(); (*it).second->reconfigure(Effect::ReconfigureAll); return; } } bool EffectsHandlerImpl::isEffectLoaded(const QString& name) const { for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) if ((*it).first == name) return true; return false; } bool EffectsHandlerImpl::isEffectSupported(const QString &name) { // if the effect is loaded, it is obviously supported auto it = std::find_if(loaded_effects.constBegin(), loaded_effects.constEnd(), [name](const EffectPair &pair) { return pair.first == name; }); if (it != loaded_effects.constEnd()) { return true; } // next checks might require a context makeOpenGLContextCurrent(); m_compositor->addRepaintFull(); return m_effectLoader->isEffectSupported(name); } QList< bool > EffectsHandlerImpl::areEffectsSupported(const QStringList &names) { QList< bool > retList; for (const QString &name : names) { retList << isEffectSupported(name); } return retList; } void EffectsHandlerImpl::reloadEffect(Effect *effect) { QString effectName; for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { if ((*it).second == effect) { effectName = (*it).first; break; } } if (!effectName.isNull()) { unloadEffect(effectName); m_effectLoader->loadEffect(effectName); } } void EffectsHandlerImpl::effectsChanged() { loaded_effects.clear(); m_activeEffects.clear(); // it's possible to have a reconfigure and a quad rebuild between two paint cycles - bug #308201 // qDebug() << "Recreating effects' list:"; for (const EffectPair & effect : effect_order) { // qDebug() << effect.first; loaded_effects.append(effect); } m_activeEffects.reserve(loaded_effects.count()); } QStringList EffectsHandlerImpl::activeEffects() const { QStringList ret; for(QVector< KWin::EffectPair >::const_iterator it = loaded_effects.constBegin(), end = loaded_effects.constEnd(); it != end; ++it) { if (it->second->isActive()) { ret << it->first; } } return ret; } KWayland::Server::Display *EffectsHandlerImpl::waylandDisplay() const { if (waylandServer()) { return waylandServer()->display(); } return nullptr; } EffectFrame* EffectsHandlerImpl::effectFrame(EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment) const { return new EffectFrameImpl(style, staticSize, position, alignment); } QVariant EffectsHandlerImpl::kwinOption(KWinOption kwopt) { switch (kwopt) { case CloseButtonCorner: // TODO: this could become per window and be derived from the actual position in the deco return Decoration::DecorationBridge::self()->settings()->decorationButtonsLeft().contains(KDecoration2::DecorationButtonType::Close) ? Qt::TopLeftCorner : Qt::TopRightCorner; case SwitchDesktopOnScreenEdge: return ScreenEdges::self()->isDesktopSwitching(); case SwitchDesktopOnScreenEdgeMovingWindows: return ScreenEdges::self()->isDesktopSwitchingMovingClients(); default: return QVariant(); // an invalid one } } QString EffectsHandlerImpl::supportInformation(const QString &name) const { if (!isEffectLoaded(name)) { return QString(); } for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { if ((*it).first == name) { QString support((*it).first + QLatin1String(":\n")); const QMetaObject *metaOptions = (*it).second->metaObject(); for (int i=0; ipropertyCount(); ++i) { const QMetaProperty property = metaOptions->property(i); if (qstrcmp(property.name(), "objectName") == 0) { continue; } support += QString::fromUtf8(property.name()) + QLatin1String(": ") + (*it).second->property(property.name()).toString() + QLatin1Char('\n'); } return support; } } return QString(); } bool EffectsHandlerImpl::isScreenLocked() const { return ScreenLockerWatcher::self()->isLocked(); } QString EffectsHandlerImpl::debug(const QString& name, const QString& parameter) const { QString internalName = name.toLower();; for (QVector< EffectPair >::const_iterator it = loaded_effects.constBegin(); it != loaded_effects.constEnd(); ++it) { if ((*it).first == internalName) { return it->second->debug(parameter); } } return QString(); } bool EffectsHandlerImpl::makeOpenGLContextCurrent() { return m_scene->makeOpenGLContextCurrent(); } void EffectsHandlerImpl::doneOpenGLContextCurrent() { m_scene->doneOpenGLContextCurrent(); } +bool EffectsHandlerImpl::animationsSupported() const +{ + static const QByteArray forceEnvVar = qgetenv("KWIN_EFFECTS_FORCE_ANIMATIONS"); + if (!forceEnvVar.isEmpty()) { + static const int forceValue = forceEnvVar.toInt(); + return forceValue == 1; + } + return m_scene->animationsSupported(); +} + //**************************************** // EffectWindowImpl //**************************************** EffectWindowImpl::EffectWindowImpl(Toplevel *toplevel) : EffectWindow(toplevel) , toplevel(toplevel) , sw(NULL) { } EffectWindowImpl::~EffectWindowImpl() { QVariant cachedTextureVariant = data(LanczosCacheRole); if (cachedTextureVariant.isValid()) { GLTexture *cachedTexture = static_cast< GLTexture*>(cachedTextureVariant.value()); delete cachedTexture; } } bool EffectWindowImpl::isPaintingEnabled() { return sceneWindow()->isPaintingEnabled(); } void EffectWindowImpl::enablePainting(int reason) { sceneWindow()->enablePainting(reason); } void EffectWindowImpl::disablePainting(int reason) { sceneWindow()->disablePainting(reason); } const EffectWindowGroup* EffectWindowImpl::group() const { if (Client* c = dynamic_cast< Client* >(toplevel)) return c->group()->effectGroup(); return NULL; // TODO } void EffectWindowImpl::refWindow() { if (Deleted* d = dynamic_cast< Deleted* >(toplevel)) return d->refWindow(); abort(); // TODO } void EffectWindowImpl::unrefWindow() { if (Deleted* d = dynamic_cast< Deleted* >(toplevel)) return d->unrefWindow(); // delays deletion in case abort(); // TODO } void EffectWindowImpl::setWindow(Toplevel* w) { toplevel = w; setParent(w); } void EffectWindowImpl::setSceneWindow(Scene::Window* w) { sw = w; } QRegion EffectWindowImpl::shape() const { return sw ? sw->shape() : geometry(); } QRect EffectWindowImpl::decorationInnerRect() const { Client *client = dynamic_cast(toplevel); return client ? client->transparentRect() : contentsRect(); } QByteArray EffectWindowImpl::readProperty(long atom, long type, int format) const { return readWindowProperty(window()->window(), atom, type, format); } void EffectWindowImpl::deleteProperty(long int atom) const { deleteWindowProperty(window()->window(), atom); } EffectWindow* EffectWindowImpl::findModal() { if (AbstractClient* c = dynamic_cast< AbstractClient* >(toplevel)) { if (AbstractClient* c2 = c->findModal()) return c2->effectWindow(); } return NULL; } template EffectWindowList getMainWindows(Toplevel *toplevel) { T *c = static_cast(toplevel); EffectWindowList ret; const auto mainclients = c->mainClients(); for (auto tmp : mainclients) ret.append(tmp->effectWindow()); return ret; } EffectWindowList EffectWindowImpl::mainWindows() const { if (dynamic_cast(toplevel)) { return getMainWindows(toplevel); } else if (toplevel->isDeleted()) { return getMainWindows(toplevel); } return EffectWindowList(); } WindowQuadList EffectWindowImpl::buildQuads(bool force) const { return sceneWindow()->buildQuads(force); } void EffectWindowImpl::setData(int role, const QVariant &data) { if (!data.isNull()) dataMap[ role ] = data; else dataMap.remove(role); } QVariant EffectWindowImpl::data(int role) const { if (!dataMap.contains(role)) return QVariant(); return dataMap[ role ]; } EffectWindow* effectWindow(Toplevel* w) { EffectWindowImpl* ret = w->effectWindow(); return ret; } EffectWindow* effectWindow(Scene::Window* w) { EffectWindowImpl* ret = w->window()->effectWindow(); ret->setSceneWindow(w); return ret; } void EffectWindowImpl::elevate(bool elevate) { effects->setElevatedWindow(this, elevate); } void EffectWindowImpl::registerThumbnail(AbstractThumbnailItem *item) { if (WindowThumbnailItem *thumb = qobject_cast(item)) { insertThumbnail(thumb); connect(thumb, SIGNAL(destroyed(QObject*)), SLOT(thumbnailDestroyed(QObject*))); connect(thumb, SIGNAL(wIdChanged(qulonglong)), SLOT(thumbnailTargetChanged())); } else if (DesktopThumbnailItem *desktopThumb = qobject_cast(item)) { m_desktopThumbnails.append(desktopThumb); connect(desktopThumb, SIGNAL(destroyed(QObject*)), SLOT(desktopThumbnailDestroyed(QObject*))); } } void EffectWindowImpl::thumbnailDestroyed(QObject *object) { // we know it is a ThumbnailItem m_thumbnails.remove(static_cast(object)); } void EffectWindowImpl::thumbnailTargetChanged() { if (WindowThumbnailItem *item = qobject_cast(sender())) { insertThumbnail(item); } } void EffectWindowImpl::insertThumbnail(WindowThumbnailItem *item) { EffectWindow *w = effects->findWindow(item->wId()); if (w) { m_thumbnails.insert(item, QWeakPointer(static_cast(w))); } else { m_thumbnails.insert(item, QWeakPointer()); } } void EffectWindowImpl::desktopThumbnailDestroyed(QObject *object) { // we know it is a DesktopThumbnailItem m_desktopThumbnails.removeAll(static_cast(object)); } void EffectWindowImpl::referencePreviousWindowPixmap() { if (sw) { sw->referencePreviousPixmap(); } } void EffectWindowImpl::unreferencePreviousWindowPixmap() { if (sw) { sw->unreferencePreviousPixmap(); } } //**************************************** // EffectWindowGroupImpl //**************************************** EffectWindowList EffectWindowGroupImpl::members() const { EffectWindowList ret; for (Toplevel * c : group->members()) ret.append(c->effectWindow()); return ret; } //**************************************** // EffectFrameImpl //**************************************** EffectFrameImpl::EffectFrameImpl(EffectFrameStyle style, bool staticSize, QPoint position, Qt::Alignment alignment) : QObject(0) , EffectFrame() , m_style(style) , m_static(staticSize) , m_point(position) , m_alignment(alignment) , m_shader(NULL) , m_theme(new Plasma::Theme(this)) { if (m_style == EffectFrameStyled) { m_frame.setImagePath(QStringLiteral("widgets/background")); m_frame.setCacheAllRenderedFrames(true); connect(m_theme, SIGNAL(themeChanged()), this, SLOT(plasmaThemeChanged())); } m_selection.setImagePath(QStringLiteral("widgets/viewitem")); m_selection.setElementPrefix(QStringLiteral("hover")); m_selection.setCacheAllRenderedFrames(true); m_selection.setEnabledBorders(Plasma::FrameSvg::AllBorders); m_sceneFrame = Compositor::self()->scene()->createEffectFrame(this); } EffectFrameImpl::~EffectFrameImpl() { delete m_sceneFrame; } const QFont& EffectFrameImpl::font() const { return m_font; } void EffectFrameImpl::setFont(const QFont& font) { if (m_font == font) { return; } m_font = font; QRect oldGeom = m_geometry; if (!m_text.isEmpty()) { autoResize(); } if (oldGeom == m_geometry) { // Wasn't updated in autoResize() m_sceneFrame->freeTextFrame(); } } void EffectFrameImpl::free() { m_sceneFrame->free(); } const QRect& EffectFrameImpl::geometry() const { return m_geometry; } void EffectFrameImpl::setGeometry(const QRect& geometry, bool force) { QRect oldGeom = m_geometry; m_geometry = geometry; if (m_geometry == oldGeom && !force) { return; } effects->addRepaint(oldGeom); effects->addRepaint(m_geometry); if (m_geometry.size() == oldGeom.size() && !force) { return; } if (m_style == EffectFrameStyled) { qreal left, top, right, bottom; m_frame.getMargins(left, top, right, bottom); // m_geometry is the inner geometry m_frame.resizeFrame(m_geometry.adjusted(-left, -top, right, bottom).size()); } free(); } const QIcon& EffectFrameImpl::icon() const { return m_icon; } void EffectFrameImpl::setIcon(const QIcon& icon) { m_icon = icon; if (isCrossFade()) { m_sceneFrame->crossFadeIcon(); } if (m_iconSize.isEmpty() && !m_icon.availableSizes().isEmpty()) { // Set a size if we don't already have one setIconSize(m_icon.availableSizes().first()); } m_sceneFrame->freeIconFrame(); } const QSize& EffectFrameImpl::iconSize() const { return m_iconSize; } void EffectFrameImpl::setIconSize(const QSize& size) { if (m_iconSize == size) { return; } m_iconSize = size; autoResize(); m_sceneFrame->freeIconFrame(); } void EffectFrameImpl::plasmaThemeChanged() { free(); } void EffectFrameImpl::render(QRegion region, double opacity, double frameOpacity) { if (m_geometry.isEmpty()) { return; // Nothing to display } m_shader = NULL; setScreenProjectionMatrix(static_cast(effects)->scene()->screenProjectionMatrix()); effects->paintEffectFrame(this, region, opacity, frameOpacity); } void EffectFrameImpl::finalRender(QRegion region, double opacity, double frameOpacity) const { region = infiniteRegion(); // TODO: Old region doesn't seem to work with OpenGL m_sceneFrame->render(region, opacity, frameOpacity); } Qt::Alignment EffectFrameImpl::alignment() const { return m_alignment; } void EffectFrameImpl::align(QRect &geometry) { if (m_alignment & Qt::AlignLeft) geometry.moveLeft(m_point.x()); else if (m_alignment & Qt::AlignRight) geometry.moveLeft(m_point.x() - geometry.width()); else geometry.moveLeft(m_point.x() - geometry.width() / 2); if (m_alignment & Qt::AlignTop) geometry.moveTop(m_point.y()); else if (m_alignment & Qt::AlignBottom) geometry.moveTop(m_point.y() - geometry.height()); else geometry.moveTop(m_point.y() - geometry.height() / 2); } void EffectFrameImpl::setAlignment(Qt::Alignment alignment) { m_alignment = alignment; align(m_geometry); setGeometry(m_geometry); } void EffectFrameImpl::setPosition(const QPoint& point) { m_point = point; QRect geometry = m_geometry; // this is important, setGeometry need call repaint for old & new geometry align(geometry); setGeometry(geometry); } const QString& EffectFrameImpl::text() const { return m_text; } void EffectFrameImpl::setText(const QString& text) { if (m_text == text) { return; } if (isCrossFade()) { m_sceneFrame->crossFadeText(); } m_text = text; QRect oldGeom = m_geometry; autoResize(); if (oldGeom == m_geometry) { // Wasn't updated in autoResize() m_sceneFrame->freeTextFrame(); } } void EffectFrameImpl::setSelection(const QRect& selection) { if (selection == m_selectionGeometry) { return; } m_selectionGeometry = selection; if (m_selectionGeometry.size() != m_selection.frameSize().toSize()) { m_selection.resizeFrame(m_selectionGeometry.size()); } // TODO; optimize to only recreate when resizing m_sceneFrame->freeSelection(); } void EffectFrameImpl::autoResize() { if (m_static) return; // Not automatically resizing QRect geometry; // Set size if (!m_text.isEmpty()) { QFontMetrics metrics(m_font); geometry.setSize(metrics.size(0, m_text)); } if (!m_icon.isNull() && !m_iconSize.isEmpty()) { geometry.setLeft(-m_iconSize.width()); if (m_iconSize.height() > geometry.height()) geometry.setHeight(m_iconSize.height()); } align(geometry); setGeometry(geometry); } QColor EffectFrameImpl::styledTextColor() { return m_theme->color(Plasma::Theme::TextColor); } } // namespace diff --git a/effects.h b/effects.h index 2551e00f3..e6f26621a 100644 --- a/effects.h +++ b/effects.h @@ -1,510 +1,512 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2010, 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_EFFECTSIMPL_H #define KWIN_EFFECTSIMPL_H #include "kwineffects.h" #include "client.h" #include "scene.h" #include "xcbutils.h" #include #include namespace Plasma { class Theme; } namespace KWayland { namespace Server { class Display; } } class QDBusPendingCallWatcher; class QDBusServiceWatcher; namespace KWin { class AbstractThumbnailItem; class DesktopThumbnailItem; class WindowThumbnailItem; class Client; class Compositor; class Deleted; class EffectLoader; class Unmanaged; class KWIN_EXPORT EffectsHandlerImpl : public EffectsHandler { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kwin.Effects") Q_PROPERTY(QStringList activeEffects READ activeEffects) Q_PROPERTY(QStringList loadedEffects READ loadedEffects) Q_PROPERTY(QStringList listOfEffects READ listOfEffects) public: EffectsHandlerImpl(Compositor *compositor, Scene *scene); virtual ~EffectsHandlerImpl(); void prePaintScreen(ScreenPrePaintData& data, int time) override; void paintScreen(int mask, QRegion region, ScreenPaintData& data) override; /** * Special hook to perform a paintScreen but just with the windows on @p desktop. **/ void paintDesktop(int desktop, int mask, QRegion region, ScreenPaintData& data); void postPaintScreen() override; void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) override; void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void postPaintWindow(EffectWindow* w) override; void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) override; Effect *provides(Effect::Feature ef); void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) override; void buildQuads(EffectWindow* w, WindowQuadList& quadList) override; void activateWindow(EffectWindow* c) override; EffectWindow* activeWindow() const override; void moveWindow(EffectWindow* w, const QPoint& pos, bool snap = false, double snapAdjust = 1.0) override; void windowToDesktop(EffectWindow* w, int desktop) override; void windowToScreen(EffectWindow* w, int screen) override; void setShowingDesktop(bool showing) override; QString currentActivity() const override; int currentDesktop() const override; int numberOfDesktops() const override; void setCurrentDesktop(int desktop) override; void setNumberOfDesktops(int desktops) override; QSize desktopGridSize() const override; int desktopGridWidth() const override; int desktopGridHeight() const override; int workspaceWidth() const override; int workspaceHeight() const override; int desktopAtCoords(QPoint coords) const override; QPoint desktopGridCoords(int id) const override; QPoint desktopCoords(int id) const override; int desktopAbove(int desktop = 0, bool wrap = true) const override; int desktopToRight(int desktop = 0, bool wrap = true) const override; int desktopBelow(int desktop = 0, bool wrap = true) const override; int desktopToLeft(int desktop = 0, bool wrap = true) const override; QString desktopName(int desktop) const override; bool optionRollOverDesktops() const override; QPoint cursorPos() const override; bool grabKeyboard(Effect* effect) override; void ungrabKeyboard() override; // not performing XGrabPointer void startMouseInterception(Effect *effect, Qt::CursorShape shape) override; void stopMouseInterception(Effect *effect) override; bool isMouseInterception() const; void registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) override; void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) override; void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) override; void* getProxy(QString name) override; void startMousePolling() override; void stopMousePolling() override; EffectWindow* findWindow(WId id) const override; EffectWindow* findWindow(KWayland::Server::SurfaceInterface *surf) const override; EffectWindowList stackingOrder() const override; void setElevatedWindow(KWin::EffectWindow* w, bool set) override; void setTabBoxWindow(EffectWindow*) override; void setTabBoxDesktop(int) override; EffectWindowList currentTabBoxWindowList() const override; void refTabBox() override; void unrefTabBox() override; void closeTabBox() override; QList< int > currentTabBoxDesktopList() const override; int currentTabBoxDesktop() const override; EffectWindow* currentTabBoxWindow() const override; void setActiveFullScreenEffect(Effect* e) override; Effect* activeFullScreenEffect() const override; void addRepaintFull() override; void addRepaint(const QRect& r) override; void addRepaint(const QRegion& r) override; void addRepaint(int x, int y, int w, int h) override; int activeScreen() const override; int numScreens() const override; int screenNumber(const QPoint& pos) const override; QRect clientArea(clientAreaOption, int screen, int desktop) const override; QRect clientArea(clientAreaOption, const EffectWindow* c) const override; QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const override; QSize virtualScreenSize() const override; QRect virtualScreenGeometry() const override; double animationTimeFactor() const override; WindowQuadType newWindowQuadType() override; void defineCursor(Qt::CursorShape shape) override; bool checkInputWindowEvent(xcb_button_press_event_t *e); bool checkInputWindowEvent(xcb_motion_notify_event_t *e); bool checkInputWindowEvent(QMouseEvent *e); bool checkInputWindowEvent(QWheelEvent *e); void checkInputWindowStacking(); void reserveElectricBorder(ElectricBorder border, Effect *effect) override; void unreserveElectricBorder(ElectricBorder border, Effect *effect) override; unsigned long xrenderBufferPicture() override; QPainter* scenePainter() override; void reconfigure() override; void registerPropertyType(long atom, bool reg) override; QByteArray readRootProperty(long atom, long type, int format) const override; void deleteRootProperty(long atom) const override; xcb_atom_t announceSupportProperty(const QByteArray& propertyName, Effect* effect) override; void removeSupportProperty(const QByteArray& propertyName, Effect* effect) override; bool hasDecorationShadows() const override; bool decorationsHaveAlpha() const override; bool decorationSupportsBlurBehind() const override; EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize, const QPoint& position, Qt::Alignment alignment) const override; QVariant kwinOption(KWinOption kwopt) override; bool isScreenLocked() const override; bool makeOpenGLContextCurrent() override; void doneOpenGLContextCurrent() override; xcb_connection_t *xcbConnection() const override; xcb_window_t x11RootWindow() const override; // internal (used by kwin core or compositing code) void startPaint(); void grabbedKeyboardEvent(QKeyEvent* e); bool hasKeyboardGrab() const; void desktopResized(const QSize &size); void reloadEffect(Effect *effect) override; QStringList loadedEffects() const; QStringList listOfEffects() const; void unloadAllEffects(); QList elevatedWindows() const; QStringList activeEffects() const; /** * @returns Whether we are currently in a desktop rendering process triggered by paintDesktop hook **/ bool isDesktopRendering() const { return m_desktopRendering; } /** * @returns the desktop currently being rendered in the paintDesktop hook. **/ int currentRenderedDesktop() const { return m_currentRenderedDesktop; } KWayland::Server::Display *waylandDisplay() const override; + bool animationsSupported() const override; + Scene *scene() const { return m_scene; } public Q_SLOTS: void slotCurrentTabAboutToChange(EffectWindow* from, EffectWindow* to); void slotTabAdded(EffectWindow* from, EffectWindow* to); void slotTabRemoved(EffectWindow* c, EffectWindow* newActiveWindow); // slots for D-Bus interface Q_SCRIPTABLE void reconfigureEffect(const QString& name); Q_SCRIPTABLE bool loadEffect(const QString& name); Q_SCRIPTABLE void toggleEffect(const QString& name); Q_SCRIPTABLE void unloadEffect(const QString& name); Q_SCRIPTABLE bool isEffectLoaded(const QString& name) const; Q_SCRIPTABLE bool isEffectSupported(const QString& name); Q_SCRIPTABLE QList areEffectsSupported(const QStringList &names); Q_SCRIPTABLE QString supportInformation(const QString& name) const; Q_SCRIPTABLE QString debug(const QString& name, const QString& parameter = QString()) const; protected Q_SLOTS: void slotClientShown(KWin::Toplevel*); void slotShellClientShown(KWin::Toplevel*); void slotUnmanagedShown(KWin::Toplevel*); void slotWindowClosed(KWin::Toplevel *c, KWin::Deleted *d); void slotClientMaximized(KWin::AbstractClient *c, MaximizeMode maxMode); void slotOpacityChanged(KWin::Toplevel *t, qreal oldOpacity); void slotClientModalityChanged(); void slotGeometryShapeChanged(KWin::Toplevel *t, const QRect &old); void slotPaddingChanged(KWin::Toplevel *t, const QRect &old); void slotWindowDamaged(KWin::Toplevel *t, const QRect& r); void slotPropertyNotify(KWin::Toplevel *t, long atom); protected: void connectNotify(const QMetaMethod &signal) override; void disconnectNotify(const QMetaMethod &signal) override; void effectsChanged(); void setupAbstractClientConnections(KWin::AbstractClient *c); void setupClientConnections(KWin::Client *c); void setupUnmanagedConnections(KWin::Unmanaged *u); Effect* keyboard_grab_effect; Effect* fullscreen_effect; QList elevated_windows; QMultiMap< int, EffectPair > effect_order; QHash< long, int > registered_atoms; int next_window_quad_type; private: typedef QVector< Effect*> EffectsList; typedef EffectsList::const_iterator EffectsIterator; EffectsList m_activeEffects; EffectsIterator m_currentDrawWindowIterator; EffectsIterator m_currentPaintWindowIterator; EffectsIterator m_currentPaintEffectFrameIterator; EffectsIterator m_currentPaintScreenIterator; EffectsIterator m_currentBuildQuadsIterator; typedef QHash< QByteArray, QList< Effect*> > PropertyEffectMap; PropertyEffectMap m_propertiesForEffects; QHash m_managedProperties; Compositor *m_compositor; Scene *m_scene; bool m_desktopRendering; int m_currentRenderedDesktop; Xcb::Window m_mouseInterceptionWindow; QList m_grabbedMouseEffects; EffectLoader *m_effectLoader; int m_trackingCursorChanges; }; class EffectWindowImpl : public EffectWindow { Q_OBJECT public: explicit EffectWindowImpl(Toplevel *toplevel); virtual ~EffectWindowImpl(); void enablePainting(int reason) override; void disablePainting(int reason) override; bool isPaintingEnabled() override; void refWindow() override; void unrefWindow() override; const EffectWindowGroup* group() const override; QRegion shape() const override; QRect decorationInnerRect() const override; QByteArray readProperty(long atom, long type, int format) const override; void deleteProperty(long atom) const override; EffectWindow* findModal() override; EffectWindowList mainWindows() const override; WindowQuadList buildQuads(bool force = false) const override; void referencePreviousWindowPixmap() override; void unreferencePreviousWindowPixmap() override; const Toplevel* window() const; Toplevel* window(); void setWindow(Toplevel* w); // internal void setSceneWindow(Scene::Window* w); // internal const Scene::Window* sceneWindow() const; // internal Scene::Window* sceneWindow(); // internal void elevate(bool elevate); void setData(int role, const QVariant &data); QVariant data(int role) const; void registerThumbnail(AbstractThumbnailItem *item); QHash > const &thumbnails() const { return m_thumbnails; } QList const &desktopThumbnails() const { return m_desktopThumbnails; } private Q_SLOTS: void thumbnailDestroyed(QObject *object); void thumbnailTargetChanged(); void desktopThumbnailDestroyed(QObject *object); private: void insertThumbnail(WindowThumbnailItem *item); Toplevel* toplevel; Scene::Window* sw; // This one is used only during paint pass. QHash dataMap; QHash > m_thumbnails; QList m_desktopThumbnails; }; class EffectWindowGroupImpl : public EffectWindowGroup { public: explicit EffectWindowGroupImpl(Group* g); EffectWindowList members() const override; private: Group* group; }; class EffectFrameImpl : public QObject, public EffectFrame { Q_OBJECT public: explicit EffectFrameImpl(EffectFrameStyle style, bool staticSize = true, QPoint position = QPoint(-1, -1), Qt::Alignment alignment = Qt::AlignCenter); virtual ~EffectFrameImpl(); void free() override; void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0) override; Qt::Alignment alignment() const override; void setAlignment(Qt::Alignment alignment) override; const QFont& font() const override; void setFont(const QFont& font) override; const QRect& geometry() const override; void setGeometry(const QRect& geometry, bool force = false) override; const QIcon& icon() const override; void setIcon(const QIcon& icon) override; const QSize& iconSize() const override; void setIconSize(const QSize& size) override; void setPosition(const QPoint& point) override; const QString& text() const override; void setText(const QString& text) override; EffectFrameStyle style() const override { return m_style; }; Plasma::FrameSvg& frame() { return m_frame; } bool isStatic() const { return m_static; }; void finalRender(QRegion region, double opacity, double frameOpacity) const; void setShader(GLShader* shader) override { m_shader = shader; } GLShader* shader() const override { return m_shader; } void setSelection(const QRect& selection) override; const QRect& selection() const { return m_selectionGeometry; } Plasma::FrameSvg& selectionFrame() { return m_selection; } /** * The foreground text color as specified by the default Plasma theme. */ QColor styledTextColor(); private Q_SLOTS: void plasmaThemeChanged(); private: Q_DISABLE_COPY(EffectFrameImpl) // As we need to use Qt slots we cannot copy this class void align(QRect &geometry); // positions geometry around m_point respecting m_alignment void autoResize(); // Auto-resize if not a static size EffectFrameStyle m_style; Plasma::FrameSvg m_frame; // TODO: share between all EffectFrames Plasma::FrameSvg m_selection; // Position bool m_static; QPoint m_point; Qt::Alignment m_alignment; QRect m_geometry; // Contents QString m_text; QFont m_font; QIcon m_icon; QSize m_iconSize; QRect m_selectionGeometry; Scene::EffectFrame* m_sceneFrame; GLShader* m_shader; Plasma::Theme *m_theme; }; inline QList EffectsHandlerImpl::elevatedWindows() const { if (isScreenLocked()) return QList(); return elevated_windows; } inline xcb_window_t EffectsHandlerImpl::x11RootWindow() const { return rootWindow(); } inline xcb_connection_t *EffectsHandlerImpl::xcbConnection() const { return connection(); } inline EffectWindowGroupImpl::EffectWindowGroupImpl(Group* g) : group(g) { } EffectWindow* effectWindow(Toplevel* w); EffectWindow* effectWindow(Scene::Window* w); inline const Scene::Window* EffectWindowImpl::sceneWindow() const { return sw; } inline Scene::Window* EffectWindowImpl::sceneWindow() { return sw; } inline const Toplevel* EffectWindowImpl::window() const { return toplevel; } inline Toplevel* EffectWindowImpl::window() { return toplevel; } } // namespace #endif diff --git a/effects/coverswitch/coverswitch.cpp b/effects/coverswitch/coverswitch.cpp index 8b9167664..b6bf9eebb 100644 --- a/effects/coverswitch/coverswitch.cpp +++ b/effects/coverswitch/coverswitch.cpp @@ -1,999 +1,999 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "coverswitch.h" // KConfigSkeleton #include "coverswitchconfig.h" #include #include #include #include #include #include #include #include #include #include #include namespace KWin { CoverSwitchEffect::CoverSwitchEffect() : mActivated(0) , angle(60.0) , animation(false) , start(false) , stop(false) , stopRequested(false) , startRequested(false) , zPosition(900.0) , scaleFactor(0.0) , direction(Left) , selected_window(0) , captionFrame(NULL) , primaryTabBox(false) , secondaryTabBox(false) { reconfigure(ReconfigureAll); // Caption frame captionFont.setBold(true); captionFont.setPointSize(captionFont.pointSize() * 2); if (effects->compositingType() == OpenGL2Compositing) { m_reflectionShader = ShaderManager::instance()->generateShaderFromResources(ShaderTrait::MapTexture, QString(), QStringLiteral("coverswitch-reflection.glsl")); } else { m_reflectionShader = NULL; } connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(tabBoxAdded(int)), this, SLOT(slotTabBoxAdded(int))); connect(effects, SIGNAL(tabBoxClosed()), this, SLOT(slotTabBoxClosed())); connect(effects, SIGNAL(tabBoxUpdated()), this, SLOT(slotTabBoxUpdated())); connect(effects, SIGNAL(tabBoxKeyEvent(QKeyEvent*)), this, SLOT(slotTabBoxKeyEvent(QKeyEvent*))); } CoverSwitchEffect::~CoverSwitchEffect() { delete captionFrame; delete m_reflectionShader; } bool CoverSwitchEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void CoverSwitchEffect::reconfigure(ReconfigureFlags) { CoverSwitchConfig::self()->read(); animationDuration = animationTime(200); animateSwitch = CoverSwitchConfig::animateSwitch(); animateStart = CoverSwitchConfig::animateStart(); animateStop = CoverSwitchConfig::animateStop(); reflection = CoverSwitchConfig::reflection(); windowTitle = CoverSwitchConfig::windowTitle(); zPosition = CoverSwitchConfig::zPosition(); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); timeLine.setDuration(animationDuration); // Defined outside the ui primaryTabBox = CoverSwitchConfig::tabBox(); secondaryTabBox = CoverSwitchConfig::tabBoxAlternative(); QColor tmp = CoverSwitchConfig::mirrorFrontColor(); mirrorColor[0][0] = tmp.redF(); mirrorColor[0][1] = tmp.greenF(); mirrorColor[0][2] = tmp.blueF(); mirrorColor[0][3] = 1.0; tmp = CoverSwitchConfig::mirrorRearColor(); mirrorColor[1][0] = tmp.redF(); mirrorColor[1][1] = tmp.greenF(); mirrorColor[1][2] = tmp.blueF(); mirrorColor[1][3] = -1.0; } void CoverSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (mActivated || stop || stopRequested) { data.mask |= Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; if (animation || start || stop) { timeLine.setCurrentTime(timeLine.currentTime() + time); } if (selected_window == NULL) abort(); } effects->prePaintScreen(data, time); } void CoverSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); if (mActivated || stop || stopRequested) { QList< EffectWindow* > tempList = currentWindowList; int index = tempList.indexOf(selected_window); if (animation || start || stop) { if (!start && !stop) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } foreach (Direction direction, scheduled_directions) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } } int leftIndex = index - 1; if (leftIndex < 0) leftIndex = tempList.count() - 1; int rightIndex = index + 1; if (rightIndex == tempList.count()) rightIndex = 0; EffectWindow* frontWindow = tempList[ index ]; leftWindows.clear(); rightWindows.clear(); bool evenWindows = (tempList.count() % 2 == 0) ? true : false; int leftWindowCount = 0; if (evenWindows) leftWindowCount = tempList.count() / 2 - 1; else leftWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < leftWindowCount; i++) { int tempIndex = (leftIndex - i); if (tempIndex < 0) tempIndex = tempList.count() + tempIndex; leftWindows.prepend(tempList[ tempIndex ]); } int rightWindowCount = 0; if (evenWindows) rightWindowCount = tempList.count() / 2; else rightWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < rightWindowCount; i++) { int tempIndex = (rightIndex + i) % tempList.count(); rightWindows.prepend(tempList[ tempIndex ]); } if (reflection) { // no reflections during start and stop animation // except when using a shader if ((!start && !stop) || effects->compositingType() == OpenGL2Compositing) paintScene(frontWindow, leftWindows, rightWindows, true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // we can use a huge scale factor (needed to calculate the rearground vertices) // as we restrict with a PaintClipper painting on the current screen float reflectionScaleFactor = 100000 * tan(60.0 * M_PI / 360.0f) / area.width(); const float width = area.width(); const float height = area.height(); float vertices[] = { -width * 0.5f, height, 0.0, width * 0.5f, height, 0.0, width*reflectionScaleFactor, height, -5000, -width*reflectionScaleFactor, height, -5000 }; // foreground if (start) { mirrorColor[0][3] = timeLine.currentValue(); } else if (stop) { mirrorColor[0][3] = 1.0 - timeLine.currentValue(); } else { mirrorColor[0][3] = 1.0; } int y = 0; // have to adjust the y values to fit OpenGL // in OpenGL y==0 is at bottom, in Qt at top if (effects->numScreens() > 1) { QRect fullArea = effects->clientArea(FullArea, 0, 1); if (fullArea.height() != area.height()) { if (area.y() == 0) y = fullArea.height() - area.height(); else y = fullArea.height() - area.y() - area.height(); } } // use scissor to restrict painting of the reflection plane to current screen glScissor(area.x(), y, area.width(), area.height()); glEnable(GL_SCISSOR_TEST); if (m_reflectionShader && m_reflectionShader->isValid()) { ShaderManager::instance()->pushShader(m_reflectionShader); QMatrix4x4 windowTransformation = data.projectionMatrix(); windowTransformation.translate(area.x() + area.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform(GLShader::ModelViewProjectionMatrix, windowTransformation); m_reflectionShader->setUniform("u_frontColor", QVector4D(mirrorColor[0][0], mirrorColor[0][1], mirrorColor[0][2], mirrorColor[0][3])); m_reflectionShader->setUniform("u_backColor", QVector4D(mirrorColor[1][0], mirrorColor[1][1], mirrorColor[1][2], mirrorColor[1][3])); // TODO: make this one properly QVector verts; QVector texcoords; verts.reserve(18); texcoords.reserve(12); texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; texcoords << 1.0 << 0.0; verts << vertices[9] << vertices[10] << vertices[11]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[3] << vertices[4] << vertices[5]; texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setData(6, 3, verts.data(), texcoords.data()); vbo->render(GL_TRIANGLES); ShaderManager::instance()->popShader(); } glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); } paintScene(frontWindow, leftWindows, rightWindows); // Render the caption frame if (windowTitle) { double opacity = 1.0; if (start) opacity = timeLine.currentValue(); else if (stop) opacity = 1.0 - timeLine.currentValue(); if (animation) captionFrame->setCrossFadeProgress(timeLine.currentValue()); captionFrame->render(region, opacity); } } } void CoverSwitchEffect::postPaintScreen() { if ((mActivated && (animation || start)) || stop || stopRequested) { if (timeLine.currentValue() == 1.0) { timeLine.setCurrentTime(0); if (stop) { stop = false; effects->setActiveFullScreenEffect(0); foreach (EffectWindow * window, referrencedWindows) { window->unrefWindow(); } referrencedWindows.clear(); currentWindowList.clear(); if (startRequested) { startRequested = false; mActivated = true; effects->refTabBox(); currentWindowList = effects->currentTabBoxWindowList(); if (animateStart) { start = true; } } } else if (!scheduled_directions.isEmpty()) { direction = scheduled_directions.dequeue(); if (start) { animation = true; start = false; } } else { animation = false; start = false; if (stopRequested) { stopRequested = false; stop = true; } } } effects->addRepaintFull(); } effects->postPaintScreen(); } void CoverSwitchEffect::paintScene(EffectWindow* frontWindow, const EffectWindowList& leftWindows, const EffectWindowList& rightWindows, bool reflectedWindows) { // LAYOUT // one window in the front. Other windows left and right rotated // for odd number of windows: left: (n-1)/2; front: 1; right: (n-1)/2 // for even number of windows: left: n/2; front: 1; right: n/2 -1 // // ANIMATION // forward (alt+tab) // all left windows are moved to next position // top most left window is rotated and moved to front window position // front window is rotated and moved to next right window position // right windows are moved to next position // last right window becomes totally transparent in half the time // appears transparent on left side and becomes totally opaque again // backward (alt+shift+tab) same as forward but opposite direction int width = area.width(); int leftWindowCount = leftWindows.count(); int rightWindowCount = rightWindows.count(); // Problem during animation: a window which is painted after another window // appears in front of the other // so during animation the painting order has to be rearreanged // paint sequence no animation: left, right, front // paint sequence forward animation: right, front, left if (!animation) { paintWindows(leftWindows, true, reflectedWindows); paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { if (direction == Right) { if (timeLine.currentValue() < 0.5) { // paint in normal way paintWindows(leftWindows, true, reflectedWindows); paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); paintWindows(leftWindows, true, reflectedWindows, rightWindows.at(0)); } } else { paintWindows(leftWindows, true, reflectedWindows); if (timeLine.currentValue() < 0.5) { paintWindows(rightWindows, false, reflectedWindows); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else { EffectWindow* leftWindow; if (leftWindowCount > 0) { leftWindow = leftWindows.at(0); paintFrontWindow(frontWindow, width, leftWindowCount, rightWindowCount, reflectedWindows); } else leftWindow = frontWindow; paintWindows(rightWindows, false, reflectedWindows, leftWindow); } } } } void CoverSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (mActivated || stop || stopRequested) { if (!(mask & PAINT_WINDOW_TRANSFORMED) && !w->isDesktop()) { if ((start || stop) && w->isDock()) { data.setOpacity(1.0 - timeLine.currentValue()); if (stop) data.setOpacity(timeLine.currentValue()); } else return; } } if ((start || stop) && (!w->isOnCurrentDesktop() || w->isMinimized())) { if (stop) // Fade out windows not on the current desktop data.setOpacity((1.0 - timeLine.currentValue())); else // Fade in Windows from other desktops when animation is started data.setOpacity(timeLine.currentValue()); } effects->paintWindow(w, mask, region, data); } void CoverSwitchEffect::slotTabBoxAdded(int mode) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; if (!mActivated) { effects->setShowingDesktop(false); // only for windows mode if (((mode == TabBoxWindowsMode && primaryTabBox) || (mode == TabBoxWindowsAlternativeMode && secondaryTabBox) || (mode == TabBoxCurrentAppWindowsMode && primaryTabBox) || (mode == TabBoxCurrentAppWindowsAlternativeMode && secondaryTabBox)) && effects->currentTabBoxWindowList().count() > 0) { effects->startMouseInterception(this, Qt::ArrowCursor); activeScreen = effects->activeScreen(); if (!stop && !stopRequested) { effects->refTabBox(); effects->setActiveFullScreenEffect(this); scheduled_directions.clear(); selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); direction = Left; mActivated = true; if (animateStart) { start = true; } // Calculation of correct area area = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); const QSize screenSize = effects->virtualScreenSize(); scaleFactor = (zPosition + 1100) * 2.0 * tan(60.0 * M_PI / 360.0f) / screenSize.width(); if (screenSize.width() - area.width() != 0) { // one of the screens is smaller than the other (horizontal) if (area.width() < screenSize.width() - area.width()) scaleFactor *= (float)area.width() / (float)(screenSize.width() - area.width()); else if (area.width() != screenSize.width() - area.width()) { // vertical layout with different width // but we don't want to catch screens with same width and different height if (screenSize.height() != area.height()) scaleFactor *= (float)area.width() / (float)(screenSize.width()); } } if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode // code is adapted from SceneOpenGL2::createProjectionMatrix() QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * std::tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; if (area.width() != fullRect.width()) { if (area.x() == 0) { // horizontal layout: left screen xmin *= (float)area.width() / (float)fullRect.width(); xmax *= (fullRect.width() - 0.5f * area.width()) / (0.5f * fullRect.width()); } else { // horizontal layout: right screen xmin *= (fullRect.width() - 0.5f * area.width()) / (0.5f * fullRect.width()); xmax *= (float)area.width() / (float)fullRect.width(); } } if (area.height() != fullRect.height()) { if (area.y() == 0) { // vertical layout: top screen ymin *= (fullRect.height() - 0.5f * area.height()) / (0.5f * fullRect.height()); ymax *= (float)area.height() / (float)fullRect.height(); } else { // vertical layout: bottom screen ymin *= (float)area.height() / (float)fullRect.height(); ymax *= (fullRect.height() - 0.5f * area.height()) / (0.5f * fullRect.height()); } } m_projectionMatrix = QMatrix4x4(); m_projectionMatrix.frustum(xmin, xmax, ymin, ymax, zNear, zFar); const float scaleFactor = 1.1f / zNear; // Create a second matrix that transforms screen coordinates // to world coordinates. QMatrix4x4 matrix; matrix.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); matrix.scale( (xmax - xmin) * scaleFactor / fullRect.width(), -(ymax - ymin) * scaleFactor / fullRect.height(), 0.001); // Combine the matrices m_projectionMatrix *= matrix; m_modelviewMatrix = QMatrix4x4(); m_modelviewMatrix.translate(area.x(), area.y(), 0.0); } // Setup caption frame geometry if (windowTitle) { QRect frameRect = QRect(area.width() * 0.25f + area.x(), area.height() * 0.9f + area.y(), area.width() * 0.5f, QFontMetrics(captionFont).height()); if (!captionFrame) { captionFrame = effects->effectFrame(EffectFrameStyled); captionFrame->setFont(captionFont); captionFrame->enableCrossFade(true); } captionFrame->setGeometry(frameRect); captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); // And initial contents updateCaption(); } effects->addRepaintFull(); } else { startRequested = true; } } } } void CoverSwitchEffect::slotTabBoxClosed() { if (mActivated) { if (animateStop) { if (!animation && !start) { stop = true; } else if (start && scheduled_directions.isEmpty()) { start = false; stop = true; timeLine.setCurrentTime(timeLine.duration() - timeLine.currentValue()); } else { stopRequested = true; } } else effects->setActiveFullScreenEffect(0); mActivated = false; effects->unrefTabBox(); effects->stopMouseInterception(this); effects->addRepaintFull(); } } void CoverSwitchEffect::slotTabBoxUpdated() { if (mActivated) { if (animateSwitch && currentWindowList.count() > 1) { // determine the switch direction if (selected_window != effects->currentTabBoxWindow()) { if (selected_window != NULL) { int old_index = currentWindowList.indexOf(selected_window); int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); Direction new_direction; int distance = new_index - old_index; if (distance > 0) new_direction = Left; if (distance < 0) new_direction = Right; if (effects->currentTabBoxWindowList().count() == 2) { new_direction = Left; distance = 1; } if (distance != 0) { distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; if (tempDistance < abs(distance)) { distance = tempDistance; if (new_direction == Left) new_direction = Right; else new_direction = Left; } if (!animation && !start) { animation = true; direction = new_direction; distance--; } for (int i = 0; i < distance; i++) { if (!scheduled_directions.isEmpty() && scheduled_directions.last() != new_direction) scheduled_directions.pop_back(); else scheduled_directions.enqueue(new_direction); if (scheduled_directions.count() == effects->currentTabBoxWindowList().count()) scheduled_directions.clear(); } } } selected_window = effects->currentTabBoxWindow(); currentWindowList = effects->currentTabBoxWindowList(); updateCaption(); } } effects->addRepaintFull(); } } void CoverSwitchEffect::paintWindowCover(EffectWindow* w, bool reflectedWindow, WindowPaintData& data) { QRect windowRect = w->geometry(); data.setYTranslation(area.height() - windowRect.y() - windowRect.height()); data.setZTranslation(-zPosition); if (start) { if (w->isMinimized()) { data.multiplyOpacity(timeLine.currentValue()); } else { const QVector3D translation = data.translation() * timeLine.currentValue(); data.setXTranslation(translation.x()); data.setYTranslation(translation.y()); data.setZTranslation(translation.z()); if (effects->numScreens() > 1) { QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); if (w->screen() == activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x() * (1.0f - timeLine.currentValue())); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y() * (1.0f - timeLine.currentValue())); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < area.x()) { data.translate(- clientRect.width() * (1.0f - timeLine.currentValue())); } if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { data.translate(0.0, - clientRect.height() * (1.0f - timeLine.currentValue())); } } } data.setRotationAngle(data.rotationAngle() * timeLine.currentValue()); } } if (stop) { if (w->isMinimized() && w != effects->activeWindow()) { data.multiplyOpacity((1.0 - timeLine.currentValue())); } else { const QVector3D translation = data.translation() * (1.0 - timeLine.currentValue()); data.setXTranslation(translation.x()); data.setYTranslation(translation.y()); data.setZTranslation(translation.z()); if (effects->numScreens() > 1) { QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect rect = effects->clientArea(FullScreenArea, activeScreen, effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); if (w->screen() == activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x() * timeLine.currentValue()); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y() * timeLine.currentValue()); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { data.translate(- clientRect.width() * timeLine.currentValue()); } if (clientRect.height() != fullRect.height() && clientRect.y() < area.y()) { data.translate(0.0, - clientRect.height() * timeLine.currentValue()); } } } data.setRotationAngle(data.rotationAngle() * (1.0 - timeLine.currentValue())); } } if (reflectedWindow) { QMatrix4x4 reflectionMatrix; reflectionMatrix.scale(1.0, -1.0, 1.0); data.setProjectionMatrix(data.screenProjectionMatrix()); data.setModelViewMatrix(reflectionMatrix); data.setYTranslation(- area.height() - windowRect.y() - windowRect.height()); if (start) { data.multiplyOpacity(timeLine.currentValue()); } else if (stop) { data.multiplyOpacity(1.0 - timeLine.currentValue()); } effects->drawWindow(w, PAINT_WINDOW_TRANSFORMED, infiniteRegion(), data); } else { effects->paintWindow(w, PAINT_WINDOW_TRANSFORMED, infiniteRegion(), data); } } void CoverSwitchEffect::paintFrontWindow(EffectWindow* frontWindow, int width, int leftWindows, int rightWindows, bool reflectedWindow) { if (frontWindow == NULL) return; bool specialHandlingForward = false; WindowPaintData data(frontWindow); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setXTranslation(area.width() * 0.5 - frontWindow->geometry().x() - frontWindow->geometry().width() * 0.5); if (leftWindows == 0) { leftWindows = 1; if (!start && !stop) specialHandlingForward = true; } if (rightWindows == 0) { rightWindows = 1; } if (animation) { float distance = 0.0; const QSize screenSize = effects->virtualScreenSize(); if (direction == Right) { // move to right distance = -frontWindow->geometry().width() * 0.5f + area.width() * 0.5f + (((float)screenSize.width() * 0.5 * scaleFactor) - (float)area.width() * 0.5f) / rightWindows; data.translate(distance * timeLine.currentValue()); data.setRotationAxis(Qt::YAxis); data.setRotationAngle(-angle * timeLine.currentValue()); data.setRotationOrigin(QVector3D(frontWindow->geometry().width(), 0.0, 0.0)); } else { // move to left distance = frontWindow->geometry().width() * 0.5f - area.width() * 0.5f + ((float)width * 0.5f - ((float)screenSize.width() * 0.5 * scaleFactor)) / leftWindows; float factor = 1.0; if (specialHandlingForward) factor = 2.0; data.translate(distance * timeLine.currentValue() * factor); data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle * timeLine.currentValue()); } } if (specialHandlingForward) { data.multiplyOpacity((1.0 - timeLine.currentValue() * 2.0)); paintWindowCover(frontWindow, reflectedWindow, data); } else paintWindowCover(frontWindow, reflectedWindow, data); } void CoverSwitchEffect::paintWindows(const EffectWindowList& windows, bool left, bool reflectedWindows, EffectWindow* additionalWindow) { int width = area.width(); int windowCount = windows.count(); EffectWindow* window; int rotateFactor = 1; if (!left) { rotateFactor = -1; } const QSize screenSize = effects->virtualScreenSize(); float xTranslate = -((float)(width) * 0.5f - ((float)screenSize.width() * 0.5 * scaleFactor)); if (!left) xTranslate = ((float)screenSize.width() * 0.5 * scaleFactor) - (float)width * 0.5f; // handling for additional window from other side // has to appear on this side after half of the time if (animation && timeLine.currentValue() >= 0.5 && additionalWindow != NULL) { WindowPaintData data(additionalWindow); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle * rotateFactor); if (left) { data.translate(-xTranslate - additionalWindow->geometry().x()); } else { data.translate(xTranslate + area.width() - additionalWindow->geometry().x() - additionalWindow->geometry().width()); data.setRotationOrigin(QVector3D(additionalWindow->geometry().width(), 0.0, 0.0)); } data.multiplyOpacity((timeLine.currentValue() - 0.5) * 2.0); paintWindowCover(additionalWindow, reflectedWindows, data); } // normal behaviour for (int i = 0; i < windows.count(); i++) { window = windows.at(i); if (window == NULL || window->isDeleted()) { continue; } WindowPaintData data(window); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(angle); if (left) data.translate(-xTranslate + xTranslate * i / windowCount - window->geometry().x()); else data.translate(xTranslate + width - xTranslate * i / windowCount - window->geometry().x() - window->geometry().width()); if (animation) { if (direction == Right) { if ((i == windowCount - 1) && left) { // right most window on left side -> move to front // have to move one window distance plus half the difference between the window and the desktop size data.translate((xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.currentValue()); data.setRotationAngle(angle - angle * timeLine.currentValue()); } // right most window does not have to be moved else if (!left && (i == 0)); // do nothing else { // all other windows - move to next position data.translate(xTranslate / windowCount * timeLine.currentValue()); } } else { if ((i == windowCount - 1) && !left) { // left most window on right side -> move to front data.translate(- (xTranslate / windowCount + (width - window->geometry().width()) * 0.5f) * timeLine.currentValue()); data.setRotationAngle(angle - angle * timeLine.currentValue()); } // left most window does not have to be moved else if (i == 0 && left); // do nothing else { // all other windows - move to next position data.translate(- xTranslate / windowCount * timeLine.currentValue()); } } } if (!left) data.setRotationOrigin(QVector3D(window->geometry().width(), 0.0, 0.0)); data.setRotationAngle(data.rotationAngle() * rotateFactor); // make window most to edge transparent if animation if (animation && i == 0 && ((direction == Left && left) || (direction == Right && !left))) { // only for the first half of the animation if (timeLine.currentValue() < 0.5) { data.multiplyOpacity((1.0 - timeLine.currentValue() * 2.0)); paintWindowCover(window, reflectedWindows, data); } } else { paintWindowCover(window, reflectedWindows, data); } } } void CoverSwitchEffect::windowInputMouseEvent(QEvent* e) { if (e->type() != QEvent::MouseButtonPress) return; // we don't want click events during animations if (animation) return; QMouseEvent* event = static_cast< QMouseEvent* >(e); switch (event->button()) { case Qt::XButton1: // wheel up selectPreviousWindow(); break; case Qt::XButton2: // wheel down selectNextWindow(); break; case Qt::LeftButton: case Qt::RightButton: case Qt::MidButton: default: QPoint pos = event->pos(); // determine if a window has been clicked // not interested in events above a fullscreen window (ignoring panel size) if (pos.y() < (area.height()*scaleFactor - area.height()) * 0.5f *(1.0f / scaleFactor)) return; // if there is no selected window (that is no window at all) we cannot click it if (!selected_window) return; if (pos.x() < (area.width()*scaleFactor - selected_window->width()) * 0.5f *(1.0f / scaleFactor)) { float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); for (int i = 0; i < leftWindows.count(); i++) { int windowPos = availableSize / leftWindows.count() * i; if (pos.x() < windowPos) continue; if (i + 1 < leftWindows.count()) { if (pos.x() > availableSize / leftWindows.count()*(i + 1)) continue; } effects->setTabBoxWindow(leftWindows[i]); return; } } if (pos.x() > area.width() - (area.width()*scaleFactor - selected_window->width()) * 0.5f *(1.0f / scaleFactor)) { float availableSize = (area.width() * scaleFactor - area.width()) * 0.5f * (1.0f / scaleFactor); for (int i = 0; i < rightWindows.count(); i++) { int windowPos = area.width() - availableSize / rightWindows.count() * i; if (pos.x() > windowPos) continue; if (i + 1 < rightWindows.count()) { if (pos.x() < area.width() - availableSize / rightWindows.count()*(i + 1)) continue; } effects->setTabBoxWindow(rightWindows[i]); return; } } break; } } void CoverSwitchEffect::abort() { // it's possible that abort is called after tabbox has been closed // in this case the cleanup is already done (see bug 207554) if (mActivated) { effects->unrefTabBox(); effects->stopMouseInterception(this); } effects->setActiveFullScreenEffect(0); mActivated = false; stop = false; stopRequested = false; effects->addRepaintFull(); captionFrame->free(); } void CoverSwitchEffect::slotWindowClosed(EffectWindow* c) { if (c == selected_window) selected_window = 0; // if the list is not empty, the effect is active if (!currentWindowList.isEmpty()) { c->refWindow(); referrencedWindows.append(c); currentWindowList.removeAll(c); leftWindows.removeAll(c); rightWindows.removeAll(c); } } bool CoverSwitchEffect::isActive() const { return (mActivated || stop || stopRequested) && !effects->isScreenLocked(); } void CoverSwitchEffect::updateCaption() { if (!selected_window || !windowTitle) { return; } if (selected_window->isDesktop()) { captionFrame->setText(i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop")); static QPixmap pix = QIcon::fromTheme(QStringLiteral("user-desktop")).pixmap(captionFrame->iconSize()); captionFrame->setIcon(pix); } else { captionFrame->setText(selected_window->caption()); captionFrame->setIcon(selected_window->icon()); } } void CoverSwitchEffect::slotTabBoxKeyEvent(QKeyEvent *event) { if (event->type() == QEvent::KeyPress) { switch (event->key()) { case Qt::Key_Left: selectPreviousWindow(); break; case Qt::Key_Right: selectNextWindow(); break; default: // nothing break; } } } void CoverSwitchEffect::selectNextOrPreviousWindow(bool forward) { if (!mActivated || !selected_window) { return; } const int index = effects->currentTabBoxWindowList().indexOf(selected_window); int newIndex = index; if (forward) { ++newIndex; } else { --newIndex; } if (newIndex == effects->currentTabBoxWindowList().size()) { newIndex = 0; } else if (newIndex < 0) { newIndex = effects->currentTabBoxWindowList().size() -1; } if (index == newIndex) { return; } effects->setTabBoxWindow(effects->currentTabBoxWindowList().at(newIndex)); } } // namespace diff --git a/effects/cube/cubeslide.cpp b/effects/cube/cubeslide.cpp index ae050b9b1..857062057 100644 --- a/effects/cube/cubeslide.cpp +++ b/effects/cube/cubeslide.cpp @@ -1,608 +1,608 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "cubeslide.h" // KConfigSkeleton #include "cubeslideconfig.h" #include #include #include #include namespace KWin { CubeSlideEffect::CubeSlideEffect() : windowMoving(false) , desktopChangedWhileMoving(false) , progressRestriction(0.0f) { connect(effects, SIGNAL(desktopChanged(int,int)), this, SLOT(slotDesktopChanged(int,int))); connect(effects, SIGNAL(windowStepUserMovedResized(KWin::EffectWindow*,QRect)), this, SLOT(slotWindowStepUserMovedResized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowFinishUserMovedResized(KWin::EffectWindow*)), this, SLOT(slotWindowFinishUserMovedResized(KWin::EffectWindow*))); reconfigure(ReconfigureAll); } CubeSlideEffect::~CubeSlideEffect() { } bool CubeSlideEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void CubeSlideEffect::reconfigure(ReconfigureFlags) { CubeSlideConfig::self()->read(); // TODO: rename rotationDuration to duration rotationDuration = animationTime(CubeSlideConfig::rotationDuration() != 0 ? CubeSlideConfig::rotationDuration() : 500); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); timeLine.setDuration(rotationDuration); dontSlidePanels = CubeSlideConfig::dontSlidePanels(); dontSlideStickyWindows = CubeSlideConfig::dontSlideStickyWindows(); usePagerLayout = CubeSlideConfig::usePagerLayout(); useWindowMoving = CubeSlideConfig::useWindowMoving(); } void CubeSlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (!slideRotations.empty()) { data.mask |= PAINT_SCREEN_TRANSFORMED | Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS | PAINT_SCREEN_BACKGROUND_FIRST; timeLine.setCurrentTime(timeLine.currentTime() + time); if (windowMoving && timeLine.currentTime() > progressRestriction * (qreal)timeLine.duration()) timeLine.setCurrentTime(progressRestriction * (qreal)timeLine.duration()); if (dontSlidePanels) panels.clear(); stickyWindows.clear(); } effects->prePaintScreen(data, time); } void CubeSlideEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { if (!slideRotations.empty()) { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); paintSlideCube(mask, region, data); glCullFace(GL_BACK); paintSlideCube(mask, region, data); glDisable(GL_CULL_FACE); if (dontSlidePanels) { foreach (EffectWindow * w, panels) { WindowPaintData wData(w); effects->paintWindow(w, 0, infiniteRegion(), wData); } } foreach (EffectWindow * w, stickyWindows) { WindowPaintData wData(w); effects->paintWindow(w, 0, infiniteRegion(), wData); } } else effects->paintScreen(mask, region, data); } void CubeSlideEffect::paintSlideCube(int mask, QRegion region, ScreenPaintData& data) { // slide cube only paints to desktops at a time // first the horizontal rotations followed by vertical rotations QRect rect = effects->clientArea(FullArea, effects->activeScreen(), effects->currentDesktop()); float point = rect.width() / 2 * tan(45.0f * M_PI / 180.0f); cube_painting = true; painting_desktop = front_desktop; ScreenPaintData firstFaceData = data; ScreenPaintData secondFaceData = data; RotationDirection direction = slideRotations.head(); int secondDesktop; switch(direction) { case Left: firstFaceData.setRotationAxis(Qt::YAxis); secondFaceData.setRotationAxis(Qt::YAxis); if (usePagerLayout) secondDesktop = effects->desktopToLeft(front_desktop, true); else { secondDesktop = front_desktop - 1; if (secondDesktop == 0) secondDesktop = effects->numberOfDesktops(); } firstFaceData.setRotationAngle(90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(-90.0f * (1.0f - timeLine.currentValue())); break; case Right: firstFaceData.setRotationAxis(Qt::YAxis); secondFaceData.setRotationAxis(Qt::YAxis); if (usePagerLayout) secondDesktop = effects->desktopToRight(front_desktop, true); else { secondDesktop = front_desktop + 1; if (secondDesktop > effects->numberOfDesktops()) secondDesktop = 1; } firstFaceData.setRotationAngle(-90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(90.0f * (1.0f - timeLine.currentValue())); break; case Upwards: firstFaceData.setRotationAxis(Qt::XAxis); secondFaceData.setRotationAxis(Qt::XAxis); secondDesktop = effects->desktopAbove(front_desktop, true); firstFaceData.setRotationAngle(-90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(90.0f * (1.0f - timeLine.currentValue())); point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); break; case Downwards: firstFaceData.setRotationAxis(Qt::XAxis); secondFaceData.setRotationAxis(Qt::XAxis); secondDesktop = effects->desktopBelow(front_desktop, true); firstFaceData.setRotationAngle(90.0f * timeLine.currentValue()); secondFaceData.setRotationAngle(-90.0f * (1.0f - timeLine.currentValue())); point = rect.height() / 2 * tan(45.0f * M_PI / 180.0f); break; default: // totally impossible return; } // front desktop firstFaceData.setRotationOrigin(QVector3D(rect.width() / 2, rect.height() / 2, -point)); other_desktop = secondDesktop; firstDesktop = true; effects->paintScreen(mask, region, firstFaceData); // second desktop other_desktop = painting_desktop; painting_desktop = secondDesktop; firstDesktop = false; secondFaceData.setRotationOrigin(QVector3D(rect.width() / 2, rect.height() / 2, -point)); effects->paintScreen(mask, region, secondFaceData); cube_painting = false; painting_desktop = effects->currentDesktop(); } void CubeSlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (!slideRotations.empty() && cube_painting) { QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); if (dontSlidePanels && w->isDock()) { w->setData(WindowForceBlurRole, QVariant(true)); panels.insert(w); } if (!w->isManaged()) { w->setData(WindowForceBlurRole, QVariant(true)); stickyWindows.insert(w); } else if (dontSlideStickyWindows && !w->isDock() && !w->isDesktop() && w->isOnAllDesktops()) { w->setData(WindowForceBlurRole, QVariant(true)); stickyWindows.insert(w); } if (w->isOnDesktop(painting_desktop)) { if (w->x() < rect.x()) { data.quads = data.quads.splitAtX(-w->x()); } if (w->x() + w->width() > rect.x() + rect.width()) { data.quads = data.quads.splitAtX(rect.width() - w->x()); } if (w->y() < rect.y()) { data.quads = data.quads.splitAtY(-w->y()); } if (w->y() + w->height() > rect.y() + rect.height()) { data.quads = data.quads.splitAtY(rect.height() - w->y()); } w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else if (w->isOnDesktop(other_desktop)) { RotationDirection direction = slideRotations.head(); bool enable = false; if (w->x() < rect.x() && (direction == Left || direction == Right)) { data.quads = data.quads.splitAtX(-w->x()); enable = true; } if (w->x() + w->width() > rect.x() + rect.width() && (direction == Left || direction == Right)) { data.quads = data.quads.splitAtX(rect.width() - w->x()); enable = true; } if (w->y() < rect.y() && (direction == Upwards || direction == Downwards)) { data.quads = data.quads.splitAtY(-w->y()); enable = true; } if (w->y() + w->height() > rect.y() + rect.height() && (direction == Upwards || direction == Downwards)) { data.quads = data.quads.splitAtY(rect.height() - w->y()); enable = true; } if (enable) { data.setTransformed(); data.setTranslucent(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } else w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } effects->prePaintWindow(w, data, time); } void CubeSlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (!slideRotations.empty() && cube_painting) { if (dontSlidePanels && w->isDock()) return; if (stickyWindows.contains(w)) return; // filter out quads overlapping the edges QRect rect = effects->clientArea(FullArea, effects->activeScreen(), painting_desktop); if (w->isOnDesktop(painting_desktop)) { if (w->x() < rect.x()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() > -w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->x() + w->width() > rect.x() + rect.width()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.right() <= rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() < rect.y()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() > -w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() + w->height() > rect.y() + rect.height()) { WindowQuadList new_quads; foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() <= rect.height() - w->y()) { new_quads.append(quad); } } data.quads = new_quads; } } // paint windows overlapping edges from other desktop if (w->isOnDesktop(other_desktop) && (mask & PAINT_WINDOW_TRANSFORMED)) { RotationDirection direction = slideRotations.head(); if (w->x() < rect.x() && (direction == Left || direction == Right)) { WindowQuadList new_quads; data.setXTranslation(rect.width()); foreach (const WindowQuad & quad, data.quads) { if (quad.right() <= -w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->x() + w->width() > rect.x() + rect.width() && (direction == Left || direction == Right)) { WindowQuadList new_quads; data.setXTranslation(-rect.width()); foreach (const WindowQuad & quad, data.quads) { if (quad.right() > rect.width() - w->x()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() < rect.y() && (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.setYTranslation(rect.height()); foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() <= -w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (w->y() + w->height() > rect.y() + rect.height() && (direction == Upwards || direction == Downwards)) { WindowQuadList new_quads; data.setYTranslation(-rect.height()); foreach (const WindowQuad & quad, data.quads) { if (quad.bottom() > rect.height() - w->y()) { new_quads.append(quad); } } data.quads = new_quads; } if (firstDesktop) data.multiplyOpacity(timeLine.currentValue()); else data.multiplyOpacity((1.0 - timeLine.currentValue())); } } effects->paintWindow(w, mask, region, data); } void CubeSlideEffect::postPaintScreen() { effects->postPaintScreen(); if (!slideRotations.empty()) { if (timeLine.currentValue() == 1.0) { RotationDirection direction = slideRotations.dequeue(); switch(direction) { case Left: if (usePagerLayout) front_desktop = effects->desktopToLeft(front_desktop, true); else { front_desktop--; if (front_desktop == 0) front_desktop = effects->numberOfDesktops(); } break; case Right: if (usePagerLayout) front_desktop = effects->desktopToRight(front_desktop, true); else { front_desktop++; if (front_desktop > effects->numberOfDesktops()) front_desktop = 1; } break; case Upwards: front_desktop = effects->desktopAbove(front_desktop, true); break; case Downwards: front_desktop = effects->desktopBelow(front_desktop, true); break; } timeLine.setCurrentTime(0); if (slideRotations.count() == 1) timeLine.setCurveShape(QTimeLine::EaseOutCurve); else timeLine.setCurveShape(QTimeLine::LinearCurve); if (slideRotations.empty()) { foreach (EffectWindow * w, panels) w->setData(WindowForceBlurRole, QVariant(false)); foreach (EffectWindow * w, stickyWindows) w->setData(WindowForceBlurRole, QVariant(false)); stickyWindows.clear(); panels.clear(); effects->setActiveFullScreenEffect(0); } } effects->addRepaintFull(); } } void CubeSlideEffect::slotDesktopChanged(int old, int current) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; if (old > effects->numberOfDesktops()) { // number of desktops has been reduced -> no animation return; } if (windowMoving) { desktopChangedWhileMoving = true; progressRestriction = 1.0 - progressRestriction; effects->addRepaintFull(); return; } bool activate = true; if (!slideRotations.empty()) { // last slide still in progress activate = false; RotationDirection direction = slideRotations.dequeue(); slideRotations.clear(); slideRotations.enqueue(direction); switch(direction) { case Left: if (usePagerLayout) old = effects->desktopToLeft(front_desktop, true); else { old = front_desktop - 1; if (old == 0) old = effects->numberOfDesktops(); } break; case Right: if (usePagerLayout) old = effects->desktopToRight(front_desktop, true); else { old = front_desktop + 1; if (old > effects->numberOfDesktops()) old = 1; } break; case Upwards: old = effects->desktopAbove(front_desktop, true); break; case Downwards: old = effects->desktopBelow(front_desktop, true); break; } } if (usePagerLayout) { // calculate distance in respect to pager QPoint diff = effects->desktopGridCoords(effects->currentDesktop()) - effects->desktopGridCoords(old); if (qAbs(diff.x()) > effects->desktopGridWidth() / 2) { int sign = -1 * (diff.x() / qAbs(diff.x())); diff.setX(sign *(effects->desktopGridWidth() - qAbs(diff.x()))); } if (diff.x() > 0) { for (int i = 0; i < diff.x(); i++) { slideRotations.enqueue(Right); } } else if (diff.x() < 0) { diff.setX(-diff.x()); for (int i = 0; i < diff.x(); i++) { slideRotations.enqueue(Left); } } if (qAbs(diff.y()) > effects->desktopGridHeight() / 2) { int sign = -1 * (diff.y() / qAbs(diff.y())); diff.setY(sign *(effects->desktopGridHeight() - qAbs(diff.y()))); } if (diff.y() > 0) { for (int i = 0; i < diff.y(); i++) { slideRotations.enqueue(Downwards); } } if (diff.y() < 0) { diff.setY(-diff.y()); for (int i = 0; i < diff.y(); i++) { slideRotations.enqueue(Upwards); } } } else { // ignore pager layout int left = old - current; if (left < 0) left = effects->numberOfDesktops() + left; int right = current - old; if (right < 0) right = effects->numberOfDesktops() + right; if (left < right) { for (int i = 0; i < left; i++) { slideRotations.enqueue(Left); } } else { for (int i = 0; i < right; i++) { slideRotations.enqueue(Right); } } } timeLine.setDuration((float)rotationDuration / (float)slideRotations.count()); if (activate) { if (slideRotations.count() == 1) timeLine.setCurveShape(QTimeLine::EaseInOutCurve); else timeLine.setCurveShape(QTimeLine::EaseInCurve); effects->setActiveFullScreenEffect(this); timeLine.setCurrentTime(0); front_desktop = old; effects->addRepaintFull(); } } void CubeSlideEffect::slotWindowStepUserMovedResized(EffectWindow* w) { if (!useWindowMoving) return; if (!effects->kwinOption(SwitchDesktopOnScreenEdgeMovingWindows).toBool()) return; if (w->isUserResize()) return; const QSize screenSize = effects->virtualScreenSize(); const QPoint cursor = effects->cursorPos(); const int horizontal = screenSize.width() * 0.1; const int vertical = screenSize.height() * 0.1; const QRect leftRect(0, screenSize.height() * 0.1, horizontal, screenSize.height() * 0.8); const QRect rightRect(screenSize.width() - horizontal, screenSize.height() * 0.1, horizontal, screenSize.height() * 0.8); const QRect topRect(horizontal, 0, screenSize.width() * 0.8, vertical); const QRect bottomRect(horizontal, screenSize.height() - vertical, screenSize.width() - horizontal * 2, vertical); if (leftRect.contains(cursor)) { if (effects->desktopToLeft(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(horizontal - cursor.x()) / (float)horizontal, Left); } else if (rightRect.contains(cursor)) { if (effects->desktopToRight(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(cursor.x() - screenSize.width() + horizontal) / (float)horizontal, Right); } else if (topRect.contains(cursor)) { if (effects->desktopAbove(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(vertical - cursor.y()) / (float)vertical, Upwards); } else if (bottomRect.contains(cursor)) { if (effects->desktopBelow(effects->currentDesktop()) != effects->currentDesktop()) windowMovingChanged(0.3 *(float)(cursor.y() - screenSize.height() + vertical) / (float)vertical, Downwards); } else { // not in one of the areas windowMoving = false; desktopChangedWhileMoving = false; timeLine.setCurrentTime(0); if (!slideRotations.isEmpty()) slideRotations.clear(); effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); } } void CubeSlideEffect::slotWindowFinishUserMovedResized(EffectWindow* w) { if (!useWindowMoving) return; if (!effects->kwinOption(SwitchDesktopOnScreenEdgeMovingWindows).toBool()) return; if (w->isUserResize()) return; if (!desktopChangedWhileMoving) { if (slideRotations.isEmpty()) return; const RotationDirection direction = slideRotations.dequeue(); switch(direction) { case Left: slideRotations.enqueue(Right); break; case Right: slideRotations.enqueue(Left); break; case Upwards: slideRotations.enqueue(Downwards); break; case Downwards: slideRotations.enqueue(Upwards); break; default: break; // impossible } timeLine.setCurrentTime(timeLine.duration() - timeLine.currentTime()); } desktopChangedWhileMoving = false; windowMoving = false; effects->addRepaintFull(); } void CubeSlideEffect::windowMovingChanged(float progress, RotationDirection direction) { if (desktopChangedWhileMoving) progressRestriction = 1.0 - progress; else progressRestriction = progress; front_desktop = effects->currentDesktop(); if (slideRotations.isEmpty()) { slideRotations.enqueue(direction); timeLine.setCurveShape(QTimeLine::EaseInOutCurve); windowMoving = true; effects->setActiveFullScreenEffect(this); } effects->addRepaintFull(); } bool CubeSlideEffect::isActive() const { return !slideRotations.isEmpty(); } } // namespace diff --git a/effects/fallapart/fallapart.cpp b/effects/fallapart/fallapart.cpp index 80ca51ef5..260a32b76 100644 --- a/effects/fallapart/fallapart.cpp +++ b/effects/fallapart/fallapart.cpp @@ -1,172 +1,172 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 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 "fallapart.h" #include #include #include namespace KWin { bool FallApartEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } FallApartEffect::FallApartEffect() { reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); } void FallApartEffect::reconfigure(ReconfigureFlags) { KConfigGroup conf = effects->effectConfig(QStringLiteral("FallApart")); blockSize = qBound(1, conf.readEntry("BlockSize", 40), 100000); } void FallApartEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); } void FallApartEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (windows.contains(w) && isRealWindow(w)) { if (windows[ w ] < 1) { windows[ w ] += time / animationTime(1000.); data.setTransformed(); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); // Request the window to be divided into cells data.quads = data.quads.makeGrid(blockSize); } else { windows.remove(w); w->unrefWindow(); } } effects->prePaintWindow(w, data, time); } void FallApartEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (windows.contains(w) && isRealWindow(w)) { WindowQuadList new_quads; int cnt = 0; foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach // make fragments move in various directions, based on where // they are (left pieces generally move to the left, etc.) QPointF p1(quad[ 0 ].x(), quad[ 0 ].y()); double xdiff = 0; if (p1.x() < w->width() / 2) xdiff = -(w->width() / 2 - p1.x()) / w->width() * 100; if (p1.x() > w->width() / 2) xdiff = (p1.x() - w->width() / 2) / w->width() * 100; double ydiff = 0; if (p1.y() < w->height() / 2) ydiff = -(w->height() / 2 - p1.y()) / w->height() * 100; if (p1.y() > w->height() / 2) ydiff = (p1.y() - w->height() / 2) / w->height() * 100; double modif = windows[ w ] * windows[ w ] * 64; srandom(cnt); // change direction randomly but consistently xdiff += (rand() % 21 - 10); ydiff += (rand() % 21 - 10); for (int j = 0; j < 4; ++j) { quad[ j ].move(quad[ j ].x() + xdiff * modif, quad[ j ].y() + ydiff * modif); } // also make the fragments rotate around their center QPointF center((quad[ 0 ].x() + quad[ 1 ].x() + quad[ 2 ].x() + quad[ 3 ].x()) / 4, (quad[ 0 ].y() + quad[ 1 ].y() + quad[ 2 ].y() + quad[ 3 ].y()) / 4); double adiff = (rand() % 720 - 360) / 360. * 2 * M_PI; // spin randomly for (int j = 0; j < 4; ++j) { double x = quad[ j ].x() - center.x(); double y = quad[ j ].y() - center.y(); double angle = atan2(y, x); angle += windows[ w ] * adiff; double dist = sqrt(x * x + y * y); x = dist * cos(angle); y = dist * sin(angle); quad[ j ].move(center.x() + x, center.y() + y); } new_quads.append(quad); ++cnt; } data.quads = new_quads; } effects->paintWindow(w, mask, region, data); } void FallApartEffect::postPaintScreen() { if (!windows.isEmpty()) effects->addRepaintFull(); effects->postPaintScreen(); } bool FallApartEffect::isRealWindow(EffectWindow* w) { // TODO: isSpecialWindow is rather generic, maybe tell windowtypes separately? /* qCDebug(KWINEFFECTS) << "--" << w->caption() << "--------------------------------"; qCDebug(KWINEFFECTS) << "Tooltip:" << w->isTooltip(); qCDebug(KWINEFFECTS) << "Toolbar:" << w->isToolbar(); qCDebug(KWINEFFECTS) << "Desktop:" << w->isDesktop(); qCDebug(KWINEFFECTS) << "Special:" << w->isSpecialWindow(); qCDebug(KWINEFFECTS) << "TopMenu:" << w->isTopMenu(); qCDebug(KWINEFFECTS) << "Notific:" << w->isNotification(); qCDebug(KWINEFFECTS) << "Splash:" << w->isSplash(); qCDebug(KWINEFFECTS) << "Normal:" << w->isNormalWindow(); */ if (!w->isNormalWindow()) return false; return true; } void FallApartEffect::slotWindowClosed(EffectWindow* c) { if (!isRealWindow(c)) return; if (!c->isVisible()) return; const void* e = c->data(WindowClosedGrabRole).value(); if (e && e != this) return; windows[ c ] = 0; c->refWindow(); } void FallApartEffect::slotWindowDeleted(EffectWindow* c) { windows.remove(c); } bool FallApartEffect::isActive() const { return !windows.isEmpty(); } } // namespace diff --git a/effects/flipswitch/flipswitch.cpp b/effects/flipswitch/flipswitch.cpp index 10aeae973..69a33822c 100644 --- a/effects/flipswitch/flipswitch.cpp +++ b/effects/flipswitch/flipswitch.cpp @@ -1,987 +1,987 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008, 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "flipswitch.h" // KConfigSkeleton #include "flipswitchconfig.h" #include #include #include #include #include #include #include #include #include #include namespace KWin { FlipSwitchEffect::FlipSwitchEffect() : m_currentAnimationShape(QTimeLine::EaseInOutCurve) , m_active(false) , m_start(false) , m_stop(false) , m_animation(false) , m_hasKeyboardGrab(false) , m_captionFrame(NULL) { reconfigure(ReconfigureAll); // Caption frame m_captionFont.setBold(true); m_captionFont.setPointSize(m_captionFont.pointSize() * 2); QAction* flipSwitchCurrentAction = new QAction(this); flipSwitchCurrentAction->setObjectName(QStringLiteral("FlipSwitchCurrent")); flipSwitchCurrentAction->setText(i18n("Toggle Flip Switch (Current desktop)")); KGlobalAccel::self()->setShortcut(flipSwitchCurrentAction, QList()); m_shortcutCurrent = KGlobalAccel::self()->shortcut(flipSwitchCurrentAction); effects->registerGlobalShortcut(QKeySequence(), flipSwitchCurrentAction); connect(flipSwitchCurrentAction, SIGNAL(triggered(bool)), this, SLOT(toggleActiveCurrent())); QAction* flipSwitchAllAction = new QAction(this); flipSwitchAllAction->setObjectName(QStringLiteral("FlipSwitchAll")); flipSwitchAllAction->setText(i18n("Toggle Flip Switch (All desktops)")); KGlobalAccel::self()->setShortcut(flipSwitchAllAction, QList()); effects->registerGlobalShortcut(QKeySequence(), flipSwitchAllAction); m_shortcutAll = KGlobalAccel::self()->shortcut(flipSwitchAllAction); connect(flipSwitchAllAction, SIGNAL(triggered(bool)), this, SLOT(toggleActiveAllDesktops())); connect(KGlobalAccel::self(), &KGlobalAccel::globalShortcutChanged, this, &FlipSwitchEffect::globalShortcutChanged); connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(tabBoxAdded(int)), this, SLOT(slotTabBoxAdded(int))); connect(effects, SIGNAL(tabBoxClosed()), this, SLOT(slotTabBoxClosed())); connect(effects, SIGNAL(tabBoxUpdated()), this, SLOT(slotTabBoxUpdated())); connect(effects, SIGNAL(tabBoxKeyEvent(QKeyEvent*)), this, SLOT(slotTabBoxKeyEvent(QKeyEvent*))); } FlipSwitchEffect::~FlipSwitchEffect() { delete m_captionFrame; } bool FlipSwitchEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void FlipSwitchEffect::reconfigure(ReconfigureFlags) { FlipSwitchConfig::self()->read(); m_tabbox = FlipSwitchConfig::tabBox(); m_tabboxAlternative = FlipSwitchConfig::tabBoxAlternative(); const int duration = animationTime(200); m_timeLine.setDuration(duration); m_startStopTimeLine.setDuration(duration); m_angle = FlipSwitchConfig::angle(); m_xPosition = FlipSwitchConfig::xPosition() / 100.0f; m_yPosition = FlipSwitchConfig::yPosition() / 100.0f; m_windowTitle = FlipSwitchConfig::windowTitle(); } void FlipSwitchEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (m_active) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; if (m_start) m_startStopTimeLine.setCurrentTime(m_startStopTimeLine.currentTime() + time); if (m_stop && m_scheduledDirections.isEmpty()) m_startStopTimeLine.setCurrentTime(m_startStopTimeLine.currentTime() - time); if (m_animation) m_timeLine.setCurrentTime(m_timeLine.currentTime() + time); } effects->prePaintScreen(data, time); } void FlipSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); if (m_active) { EffectWindowList tempList; if (m_mode == TabboxMode) tempList = effects->currentTabBoxWindowList(); else { // we have to setup the list // using stacking order directly is not possible // as not each window in stacking order is shown // TODO: store list instead of calculating in each frame? foreach (EffectWindow * w, effects->stackingOrder()) { if (m_windows.contains(w)) tempList.append(w); } } m_flipOrderedWindows.clear(); int index = tempList.indexOf(m_selectedWindow); int tabIndex = index; if (m_mode == TabboxMode) { foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach if (direction == DirectionBackward) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } tabIndex = index; EffectWindow* w = NULL; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index--; if (index < 0) index = tempList.count() + index; w = tempList.at(index); } for (int i = index - 1; i >= 0; i--) m_flipOrderedWindows.append(tempList.at(i)); for (int i = effects->currentTabBoxWindowList().count() - 1; i >= index; i--) m_flipOrderedWindows.append(tempList.at(i)); if (w) { m_flipOrderedWindows.removeAll(w); m_flipOrderedWindows.append(w); } } else { foreach (SwitchingDirection direction, m_scheduledDirections) { // krazy:exclude=foreach if (direction == DirectionForward) index++; else index--; if (index < 0) index = tempList.count() - 1; if (index >= tempList.count()) index = 0; } tabIndex = index; EffectWindow* w = NULL; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { index++; if (index >= tempList.count()) index = 0; } // sort from stacking order for (int i = index + 1; i < tempList.count(); i++) m_flipOrderedWindows.append(tempList.at(i)); for (int i = 0; i <= index; i++) m_flipOrderedWindows.append(tempList.at(i)); if (w) { m_flipOrderedWindows.removeAll(w); m_flipOrderedWindows.append(w); } } int winMask = PAINT_WINDOW_TRANSFORMED | PAINT_WINDOW_TRANSLUCENT; // fade in/out one window at the end of the stack during animation if (m_animation && !m_scheduledDirections.isEmpty()) { EffectWindow* w = m_flipOrderedWindows.last(); if (ItemInfo *info = m_windows.value(w,0)) { WindowPaintData data(w); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(m_angle * m_startStopTimeLine.currentValue()); data.setOpacity(info->opacity); data.setBrightness(info->brightness); data.setSaturation(info->saturation); int distance = tempList.count() - 1; float zDistance = 500.0f; data.translate(- (w->x() - m_screenArea.x() + data.xTranslation()) * m_startStopTimeLine.currentValue()); data.translate(m_screenArea.width() * m_xPosition * m_startStopTimeLine.currentValue(), (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslation())) * m_startStopTimeLine.currentValue()); data.translate(- (m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.currentValue(), - (m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.currentValue(), - (zDistance * distance) * m_startStopTimeLine.currentValue()); if (m_scheduledDirections.head() == DirectionForward) data.multiplyOpacity(0.8 * m_timeLine.currentValue()); else data.multiplyOpacity(0.8 * (1.0 - m_timeLine.currentValue())); if (effects->numScreens() > 1) { adjustWindowMultiScreen(w, data); } effects->drawWindow(w, winMask, infiniteRegion(), data); } } foreach (EffectWindow *w, m_flipOrderedWindows) { ItemInfo *info = m_windows.value(w,0); if (!info) continue; WindowPaintData data(w); if (effects->numScreens() > 1) { data.setProjectionMatrix(m_projectionMatrix); data.setModelViewMatrix(m_modelviewMatrix); } data.setRotationAxis(Qt::YAxis); data.setRotationAngle(m_angle * m_startStopTimeLine.currentValue()); data.setOpacity(info->opacity); data.setBrightness(info->brightness); data.setSaturation(info->saturation); int windowIndex = tempList.indexOf(w); int distance; if (m_mode == TabboxMode) { if (windowIndex < tabIndex) distance = tempList.count() - (tabIndex - windowIndex); else if (windowIndex > tabIndex) distance = windowIndex - tabIndex; else distance = 0; } else { distance = m_flipOrderedWindows.count() - m_flipOrderedWindows.indexOf(w) - 1; if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { distance--; } } if (!m_scheduledDirections.isEmpty() && m_scheduledDirections.head() == DirectionBackward) { if (w == m_flipOrderedWindows.last()) { distance = -1; data.multiplyOpacity(m_timeLine.currentValue()); } } float zDistance = 500.0f; data.translate(- (w->x() - m_screenArea.x() + data.xTranslation()) * m_startStopTimeLine.currentValue()); data.translate(m_screenArea.width() * m_xPosition * m_startStopTimeLine.currentValue(), (m_screenArea.y() + m_screenArea.height() * m_yPosition - (w->y() + w->height() + data.yTranslation())) * m_startStopTimeLine.currentValue()); data.translate(-(m_screenArea.width() * 0.25f) * distance * m_startStopTimeLine.currentValue(), -(m_screenArea.height() * 0.10f) * distance * m_startStopTimeLine.currentValue(), -(zDistance * distance) * m_startStopTimeLine.currentValue()); if (m_animation && !m_scheduledDirections.isEmpty()) { if (m_scheduledDirections.head() == DirectionForward) { data.translate((m_screenArea.width() * 0.25f) * m_timeLine.currentValue(), (m_screenArea.height() * 0.10f) * m_timeLine.currentValue(), zDistance * m_timeLine.currentValue()); if (distance == 0) data.multiplyOpacity((1.0 - m_timeLine.currentValue())); } else { data.translate(- (m_screenArea.width() * 0.25f) * m_timeLine.currentValue(), - (m_screenArea.height() * 0.10f) * m_timeLine.currentValue(), - zDistance * m_timeLine.currentValue()); } } data.multiplyOpacity((0.8 + 0.2 * (1.0 - m_startStopTimeLine.currentValue()))); if (effects->numScreens() > 1) { adjustWindowMultiScreen(w, data); } effects->drawWindow(w, winMask, infiniteRegion(), data); } if (m_windowTitle) { // Render the caption frame if (m_animation) { m_captionFrame->setCrossFadeProgress(m_timeLine.currentValue()); } m_captionFrame->render(region, m_startStopTimeLine.currentValue()); } } } void FlipSwitchEffect::postPaintScreen() { if (m_active) { if (m_start && m_startStopTimeLine.currentValue() == 1.0f) { m_start = false; if (!m_scheduledDirections.isEmpty()) { m_animation = true; m_timeLine.setCurrentTime(0); if (m_scheduledDirections.count() == 1) { m_currentAnimationShape = QTimeLine::EaseOutCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } else { m_currentAnimationShape = QTimeLine::LinearCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } } effects->addRepaintFull(); } if (m_stop && m_startStopTimeLine.currentValue() == 0.0f) { m_stop = false; m_active = false; m_captionFrame->free(); effects->setActiveFullScreenEffect(0); effects->addRepaintFull(); qDeleteAll(m_windows); m_windows.clear(); } if (m_animation && m_timeLine.currentValue() == 1.0f) { m_timeLine.setCurrentTime(0); m_scheduledDirections.dequeue(); if (m_scheduledDirections.isEmpty()) { m_animation = false; effects->addRepaintFull(); } else { if (m_scheduledDirections.count() == 1) { if (m_stop) m_currentAnimationShape = QTimeLine::LinearCurve; else m_currentAnimationShape = QTimeLine::EaseOutCurve; } else { m_currentAnimationShape = QTimeLine::LinearCurve; } m_timeLine.setCurveShape(m_currentAnimationShape); } } if (m_start || m_stop || m_animation) effects->addRepaintFull(); } effects->postPaintScreen(); } void FlipSwitchEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (m_active) { if (m_windows.contains(w)) { data.setTransformed(); data.setTranslucent(); if (!w->isOnCurrentDesktop()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); if (w->isMinimized()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); if (!w->isCurrentTab()) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_TAB_GROUP); } else { if ((m_start || m_stop) && !w->isDesktop() && w->isOnCurrentDesktop()) data.setTranslucent(); else if (!w->isDesktop()) w->disablePainting(EffectWindow::PAINT_DISABLED_BY_DESKTOP); } } effects->prePaintWindow(w, data, time); } void FlipSwitchEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (m_active) { ItemInfo *info = m_windows.value(w,0); if (info) { info->opacity = data.opacity(); info->brightness = data.brightness(); info->saturation = data.saturation(); } // fade out all windows not in window list except the desktops const bool isFader = (m_start || m_stop) && !info && !w->isDesktop(); if (isFader) data.multiplyOpacity((1.0 - m_startStopTimeLine.currentValue())); // if not a fader or the desktop, skip painting here to prevent flicker if (!(isFader || w->isDesktop())) return; } effects->paintWindow(w, mask, region, data); } //************************************************************* // Tabbox handling //************************************************************* void FlipSwitchEffect::slotTabBoxAdded(int mode) { if (effects->activeFullScreenEffect() && effects->activeFullScreenEffect() != this) return; // only for windows mode effects->setShowingDesktop(false); if (((mode == TabBoxWindowsMode && m_tabbox) || (mode == TabBoxWindowsAlternativeMode && m_tabboxAlternative) || (mode == TabBoxCurrentAppWindowsMode && m_tabbox) || (mode == TabBoxCurrentAppWindowsAlternativeMode && m_tabboxAlternative)) && (!m_active || (m_active && m_stop)) && !effects->currentTabBoxWindowList().isEmpty()) { setActive(true, TabboxMode); if (m_active) effects->refTabBox(); } } void FlipSwitchEffect::slotTabBoxClosed() { if (m_active) { setActive(false, TabboxMode); effects->unrefTabBox(); } } void FlipSwitchEffect::slotTabBoxUpdated() { if (m_active && !m_stop) { if (!effects->currentTabBoxWindowList().isEmpty()) { // determine the switch direction if (m_selectedWindow != effects->currentTabBoxWindow()) { if (m_selectedWindow != NULL) { int old_index = effects->currentTabBoxWindowList().indexOf(m_selectedWindow); int new_index = effects->currentTabBoxWindowList().indexOf(effects->currentTabBoxWindow()); SwitchingDirection new_direction; int distance = new_index - old_index; if (distance > 0) new_direction = DirectionForward; if (distance < 0) new_direction = DirectionBackward; if (effects->currentTabBoxWindowList().count() == 2) { new_direction = DirectionForward; distance = 1; } if (distance != 0) { distance = abs(distance); int tempDistance = effects->currentTabBoxWindowList().count() - distance; if (tempDistance < abs(distance)) { distance = tempDistance; if (new_direction == DirectionForward) new_direction = DirectionBackward; else new_direction = DirectionForward; } scheduleAnimation(new_direction, distance); } } m_selectedWindow = effects->currentTabBoxWindow(); updateCaption(); } } effects->addRepaintFull(); } } //************************************************************* // Window adding/removing handling //************************************************************* void FlipSwitchEffect::slotWindowAdded(EffectWindow* w) { if (m_active && isSelectableWindow(w)) { m_windows[ w ] = new ItemInfo; } } void FlipSwitchEffect::slotWindowClosed(EffectWindow* w) { if (m_selectedWindow == w) m_selectedWindow = 0; if (m_active) { QHash< const EffectWindow*, ItemInfo* >::iterator it = m_windows.find(w); if (it != m_windows.end()) { delete *it; m_windows.erase(it); } } } //************************************************************* // Activation //************************************************************* void FlipSwitchEffect::setActive(bool activate, FlipSwitchMode mode) { if (activate) { // effect already active, do some sanity checks if (m_active) { if (m_stop) { if (mode != m_mode) { // only the same mode may reactivate the effect return; } } else { // active, but not scheduled for closing -> abort return; } } m_mode = mode; foreach (EffectWindow * w, effects->stackingOrder()) { if (isSelectableWindow(w) && !m_windows.contains(w)) m_windows[ w ] = new ItemInfo; } if (m_windows.isEmpty()) return; effects->setActiveFullScreenEffect(this); m_active = true; m_start = true; m_startStopTimeLine.setCurveShape(QTimeLine::EaseInOutCurve); m_activeScreen = effects->activeScreen(); m_screenArea = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode // code is copied from Coverswitch QRect fullRect = effects->clientArea(FullArea, m_activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * std::tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; if (m_screenArea.width() != fullRect.width()) { if (m_screenArea.x() == 0) { // horizontal layout: left screen xmin *= (float)m_screenArea.width() / (float)fullRect.width(); xmax *= (fullRect.width() - 0.5f * m_screenArea.width()) / (0.5f * fullRect.width()); } else { // horizontal layout: right screen xmin *= (fullRect.width() - 0.5f * m_screenArea.width()) / (0.5f * fullRect.width()); xmax *= (float)m_screenArea.width() / (float)fullRect.width(); } } if (m_screenArea.height() != fullRect.height()) { if (m_screenArea.y() == 0) { // vertical layout: top screen ymin *= (fullRect.height() - 0.5f * m_screenArea.height()) / (0.5f * fullRect.height()); ymax *= (float)m_screenArea.height() / (float)fullRect.height(); } else { // vertical layout: bottom screen ymin *= (float)m_screenArea.height() / (float)fullRect.height(); ymax *= (fullRect.height() - 0.5f * m_screenArea.height()) / (0.5f * fullRect.height()); } } m_projectionMatrix = QMatrix4x4(); m_projectionMatrix.frustum(xmin, xmax, ymin, ymax, zNear, zFar); const float scaleFactor = 1.1f / zNear; // Create a second matrix that transforms screen coordinates // to world coordinates. QMatrix4x4 matrix; matrix.translate(xmin * scaleFactor, ymax * scaleFactor, -1.1); matrix.scale( (xmax - xmin) * scaleFactor / fullRect.width(), -(ymax - ymin) * scaleFactor / fullRect.height(), 0.001); // Combine the matrices m_projectionMatrix *= matrix; m_modelviewMatrix = QMatrix4x4(); m_modelviewMatrix.translate(m_screenArea.x(), m_screenArea.y(), 0.0); } if (m_stop) { // effect is still closing from last usage m_stop = false; } else { // things to do only when there is no closing animation m_scheduledDirections.clear(); } switch(m_mode) { case TabboxMode: m_selectedWindow = effects->currentTabBoxWindow(); effects->startMouseInterception(this, Qt::ArrowCursor); break; case CurrentDesktopMode: m_selectedWindow = effects->activeWindow(); effects->startMouseInterception(this, Qt::BlankCursor); m_hasKeyboardGrab = effects->grabKeyboard(this); break; case AllDesktopsMode: m_selectedWindow = effects->activeWindow(); effects->startMouseInterception(this, Qt::BlankCursor); m_hasKeyboardGrab = effects->grabKeyboard(this); break; } // Setup caption frame geometry QRect frameRect = QRect(m_screenArea.width() * 0.25f + m_screenArea.x(), m_screenArea.height() * 0.1f + m_screenArea.y() - QFontMetrics(m_captionFont).height(), m_screenArea.width() * 0.5f, QFontMetrics(m_captionFont).height()); if (!m_captionFrame) { m_captionFrame = effects->effectFrame(EffectFrameStyled); m_captionFrame->setFont(m_captionFont); m_captionFrame->enableCrossFade(true); } m_captionFrame->setGeometry(frameRect); m_captionFrame->setIconSize(QSize(frameRect.height(), frameRect.height())); updateCaption(); effects->addRepaintFull(); } else { // only deactivate if mode is current mode if (mode != m_mode) return; if (m_start && m_scheduledDirections.isEmpty()) { m_start = false; } m_stop = true; if (m_animation) { m_startStopTimeLine.setCurveShape(QTimeLine::EaseOutCurve); if (m_scheduledDirections.count() == 1) { if (m_currentAnimationShape == QTimeLine::EaseInOutCurve) m_currentAnimationShape = QTimeLine::EaseInCurve; else if (m_currentAnimationShape == QTimeLine::EaseOutCurve) m_currentAnimationShape = QTimeLine::LinearCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } } else m_startStopTimeLine.setCurveShape(QTimeLine::EaseInOutCurve); effects->stopMouseInterception(this); if (m_hasKeyboardGrab) { effects->ungrabKeyboard(); m_hasKeyboardGrab = false; } effects->addRepaintFull(); } } void FlipSwitchEffect::toggleActiveAllDesktops() { if (m_active) { if (m_stop) { // reactivate if stopping setActive(true, AllDesktopsMode); } else { // deactivate if not stopping setActive(false, AllDesktopsMode); } } else { setActive(true, AllDesktopsMode); } } void FlipSwitchEffect::toggleActiveCurrent() { if (m_active) { if (m_stop) { // reactivate if stopping setActive(true, CurrentDesktopMode); } else { // deactivate if not stopping setActive(false, CurrentDesktopMode); } } else { setActive(true, CurrentDesktopMode); } } //************************************************************* // Helper function //************************************************************* bool FlipSwitchEffect::isSelectableWindow(EffectWindow* w) const { // desktop windows might be included if ((w->isSpecialWindow() && !w->isDesktop()) || w->isUtility()) return false; if (w->isDesktop()) return (m_mode == TabboxMode && effects->currentTabBoxWindowList().contains(w)); if (w->isDeleted()) return false; if (!w->acceptsFocus()) return false; switch(m_mode) { case TabboxMode: return effects->currentTabBoxWindowList().contains(w); case CurrentDesktopMode: return w->isOnCurrentDesktop(); case AllDesktopsMode: //nothing special break; } return true; } void FlipSwitchEffect::scheduleAnimation(const SwitchingDirection& direction, int distance) { if (m_start) { // start is still active so change the shape to have a nice transition m_startStopTimeLine.setCurveShape(QTimeLine::EaseInCurve); } if (!m_animation && !m_start) { m_animation = true; m_scheduledDirections.enqueue(direction); distance--; // reset shape just to make sure m_currentAnimationShape = QTimeLine::EaseInOutCurve; m_timeLine.setCurveShape(m_currentAnimationShape); } for (int i = 0; i < distance; i++) { if (m_scheduledDirections.count() > 1 && m_scheduledDirections.last() != direction) m_scheduledDirections.pop_back(); else m_scheduledDirections.enqueue(direction); if (m_scheduledDirections.count() == m_windows.count() + 1) { SwitchingDirection temp = m_scheduledDirections.dequeue(); m_scheduledDirections.clear(); m_scheduledDirections.enqueue(temp); } } if (m_scheduledDirections.count() > 1) { QTimeLine::CurveShape newShape = QTimeLine::EaseInOutCurve; switch(m_currentAnimationShape) { case QTimeLine::EaseInOutCurve: newShape = QTimeLine::EaseInCurve; break; case QTimeLine::EaseOutCurve: newShape = QTimeLine::LinearCurve; break; default: newShape = m_currentAnimationShape; } if (newShape != m_currentAnimationShape) { m_currentAnimationShape = newShape; m_timeLine.setCurveShape(m_currentAnimationShape); } } } void FlipSwitchEffect::adjustWindowMultiScreen(const KWin::EffectWindow* w, WindowPaintData& data) { if (effects->numScreens() <= 1) return; QRect clientRect = effects->clientArea(FullScreenArea, w->screen(), effects->currentDesktop()); QRect rect = effects->clientArea(ScreenArea, m_activeScreen, effects->currentDesktop()); QRect fullRect = effects->clientArea(FullArea, m_activeScreen, effects->currentDesktop()); if (w->screen() == m_activeScreen) { if (clientRect.width() != fullRect.width() && clientRect.x() != fullRect.x()) { data.translate(- clientRect.x()); } if (clientRect.height() != fullRect.height() && clientRect.y() != fullRect.y()) { data.translate(0.0, - clientRect.y()); } } else { if (clientRect.width() != fullRect.width() && clientRect.x() < rect.x()) { data.translate(- (m_screenArea.x() - clientRect.x())); } if (clientRect.height() != fullRect.height() && clientRect.y() < m_screenArea.y()) { data.translate(0.0, - (m_screenArea.y() - clientRect.y())); } } } void FlipSwitchEffect::selectNextOrPreviousWindow(bool forward) { if (!m_active || !m_selectedWindow) { return; } const int index = effects->currentTabBoxWindowList().indexOf(m_selectedWindow); int newIndex = index; if (forward) { ++newIndex; } else { --newIndex; } if (newIndex == effects->currentTabBoxWindowList().size()) { newIndex = 0; } else if (newIndex < 0) { newIndex = effects->currentTabBoxWindowList().size() -1; } if (index == newIndex) { return; } effects->setTabBoxWindow(effects->currentTabBoxWindowList().at(newIndex)); } //************************************************************* // Keyboard handling //************************************************************* void FlipSwitchEffect::globalShortcutChanged(QAction *action, QKeySequence shortcut) { if (action->objectName() == QStringLiteral("FlipSwitchAll")) { m_shortcutAll.clear(); m_shortcutAll.append(shortcut); } else if (action->objectName() == QStringLiteral("FlipSwitchCurrent")) { m_shortcutCurrent.clear(); m_shortcutCurrent.append(shortcut); } } void FlipSwitchEffect::grabbedKeyboardEvent(QKeyEvent* e) { if (e->type() == QEvent::KeyPress) { // check for global shortcuts // HACK: keyboard grab disables the global shortcuts so we have to check for global shortcut (bug 156155) if (m_mode == CurrentDesktopMode && m_shortcutCurrent.contains(e->key() + e->modifiers())) { toggleActiveCurrent(); return; } if (m_mode == AllDesktopsMode && m_shortcutAll.contains(e->key() + e->modifiers())) { toggleActiveAllDesktops(); return; } switch(e->key()) { case Qt::Key_Escape: setActive(false, m_mode); return; case Qt::Key_Tab: { // find next window if (m_windows.isEmpty()) return; // sanity check bool found = false; for (int i = effects->stackingOrder().indexOf(m_selectedWindow) - 1; i >= 0; i--) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } if (!found) { for (int i = effects->stackingOrder().count() - 1; i > effects->stackingOrder().indexOf(m_selectedWindow); i--) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } } if (found) { updateCaption(); scheduleAnimation(DirectionForward); } break; } case Qt::Key_Backtab: { // find previous window if (m_windows.isEmpty()) return; // sanity check bool found = false; for (int i = effects->stackingOrder().indexOf(m_selectedWindow) + 1; i < effects->stackingOrder().count(); i++) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } if (!found) { for (int i = 0; i < effects->stackingOrder().indexOf(m_selectedWindow); i++) { if (isSelectableWindow(effects->stackingOrder().at(i))) { m_selectedWindow = effects->stackingOrder().at(i); found = true; break; } } } if (found) { updateCaption(); scheduleAnimation(DirectionBackward); } break; } case Qt::Key_Return: case Qt::Key_Enter: case Qt::Key_Space: if (m_selectedWindow) effects->activateWindow(m_selectedWindow); setActive(false, m_mode); break; default: break; } effects->addRepaintFull(); } } void FlipSwitchEffect::slotTabBoxKeyEvent(QKeyEvent *event) { if (event->type() == QEvent::KeyPress) { switch (event->key()) { case Qt::Key_Up: case Qt::Key_Left: selectPreviousWindow(); break; case Qt::Key_Down: case Qt::Key_Right: selectNextWindow(); break; default: // nothing break; } } } bool FlipSwitchEffect::isActive() const { return m_active && !effects->isScreenLocked(); } void FlipSwitchEffect::updateCaption() { if (!m_selectedWindow) { return; } if (m_selectedWindow->isDesktop()) { m_captionFrame->setText(i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop")); static QPixmap pix = QIcon::fromTheme(QStringLiteral("user-desktop")).pixmap(m_captionFrame->iconSize()); m_captionFrame->setIcon(pix); } else { m_captionFrame->setText(m_selectedWindow->caption()); m_captionFrame->setIcon(m_selectedWindow->icon()); } } //************************************************************* // Mouse handling //************************************************************* void FlipSwitchEffect::windowInputMouseEvent(QEvent* e) { if (e->type() != QEvent::MouseButtonPress) return; // we don't want click events during animations if (m_animation) return; QMouseEvent* event = static_cast< QMouseEvent* >(e); switch (event->button()) { case Qt::XButton1: // wheel up selectPreviousWindow(); break; case Qt::XButton2: // wheel down selectNextWindow(); break; case Qt::LeftButton: case Qt::RightButton: case Qt::MidButton: default: // TODO: Change window on mouse button click break; } } //************************************************************* // Item Info //************************************************************* FlipSwitchEffect::ItemInfo::ItemInfo() : deleted(false) , opacity(0.0) , brightness(0.0) , saturation(0.0) { } FlipSwitchEffect::ItemInfo::~ItemInfo() { } } // namespace diff --git a/effects/glide/glide.cpp b/effects/glide/glide.cpp index 76016b05d..954ab913e 100644 --- a/effects/glide/glide.cpp +++ b/effects/glide/glide.cpp @@ -1,245 +1,245 @@ /******************************************************************** 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 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 "glide.h" // KConfigSkeleton #include "glideconfig.h" #include // Effect is based on fade effect by Philip Falkner namespace KWin { static const int IsGlideWindow = 0x22A982D4; GlideEffect::GlideEffect() : Effect() , m_atom(QByteArrayLiteral("_KDE_SLIDE")) { if (m_atom.isValid()) { effects->registerPropertyType( m_atom, true ); } reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); } GlideEffect::~GlideEffect() { if (m_atom.isValid()) { effects->registerPropertyType( m_atom, false ); } } bool GlideEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void GlideEffect::reconfigure(ReconfigureFlags) { // Fetch config with KConfigXT GlideConfig::self()->read(); duration = animationTime(350); effect = (EffectStyle) GlideConfig::glideEffect(); angle = GlideConfig::glideAngle(); } void GlideEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (!windows.isEmpty()) data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); } void GlideEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { InfoHash::iterator info = windows.find(w); if (info != windows.end()) { data.setTransformed(); if (info->added) info->timeLine->setCurrentTime(info->timeLine->currentTime() + time); else if (info->closed) { info->timeLine->setCurrentTime(info->timeLine->currentTime() - time); if (info->deleted) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } } effects->prePaintWindow(w, data, time); // if the window isn't to be painted, then let's make sure // to track its progress if (info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect()) w->addRepaintFull(); } void GlideEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { InfoHash::const_iterator info = windows.constFind(w); if (info != windows.constEnd()) { const double progress = info->timeLine->currentValue(); data.setRotationAxis(Qt::XAxis); data.setRotationAngle(angle * (1 - progress)); data.multiplyOpacity(progress); switch(effect) { default: case GlideInOut: if (info->added) glideIn(w, data, info); else if (info->closed) glideOut(w, data, info); break; case GlideOutIn: if (info->added) glideOut(w, data, info); if (info->closed) glideIn(w, data, info); break; case GlideIn: glideIn(w, data, info); break; case GlideOut: glideOut(w, data, info); break; } } effects->paintWindow(w, mask, region, data); } void GlideEffect::glideIn(EffectWindow* w, WindowPaintData& data, const InfoHash::const_iterator &info) { const double progress = info->timeLine->currentValue(); data *= progress; data.translate(int(w->width() / 2 * (1 - progress)), int(w->height() / 2 * (1 - progress))); } void GlideEffect::glideOut(EffectWindow* w, WindowPaintData& data, const InfoHash::const_iterator &info) { const double progress = info->timeLine->currentValue(); data *= (2 - progress); data.translate(- int(w->width() / 2 * (1 - progress)), - int(w->height() / 2 * (1 - progress))); } void GlideEffect::postPaintWindow(EffectWindow* w) { InfoHash::iterator info = windows.find(w); if (info != windows.end()) { if (info->added && info->timeLine->currentValue() == 1.0) { windows.remove(w); effects->addRepaintFull(); } else if (info->closed && info->timeLine->currentValue() == 0.0) { info->closed = false; if (info->deleted) { windows.remove(w); w->unrefWindow(); } effects->addRepaintFull(); } if (info->added || info->closed) w->addRepaintFull(); } effects->postPaintWindow(w); } void GlideEffect::slotWindowAdded(EffectWindow* w) { if (!isGlideWindow(w)) return; w->setData(IsGlideWindow, true); const void *addGrab = w->data(WindowAddedGrabRole).value(); if (addGrab && addGrab != this) return; w->setData(WindowAddedGrabRole, QVariant::fromValue(static_cast(this))); InfoHash::iterator it = windows.find(w); WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = true; info->closed = false; info->deleted = false; delete info->timeLine; info->timeLine = new QTimeLine(duration); info->timeLine->setCurveShape(QTimeLine::EaseOutCurve); w->addRepaintFull(); } void GlideEffect::slotWindowClosed(EffectWindow* w) { if (!isGlideWindow(w)) return; const void *closeGrab = w->data(WindowClosedGrabRole).value(); if (closeGrab && closeGrab != this) return; w->refWindow(); w->setData(WindowClosedGrabRole, QVariant::fromValue(static_cast(this))); InfoHash::iterator it = windows.find(w); WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = false; info->closed = true; info->deleted = true; delete info->timeLine; info->timeLine = new QTimeLine(duration); info->timeLine->setCurveShape(QTimeLine::EaseInCurve); info->timeLine->setCurrentTime(info->timeLine->duration()); w->addRepaintFull(); } void GlideEffect::slotWindowDeleted(EffectWindow* w) { windows.remove(w); } bool GlideEffect::isGlideWindow(EffectWindow* w) { if (effects->activeFullScreenEffect()) return false; if (w->data(IsGlideWindow).toBool()) return true; if (m_atom.isValid() && !w->readProperty( m_atom, m_atom, 32 ).isNull()) return false; if (w->hasDecoration()) return true; if (!w->isManaged() || w->isMenu() || w->isNotification() || w->isDesktop() || w->isDock() || w->isSplash() || w->isToolbar()) return false; return true; } bool GlideEffect::isActive() const { return !windows.isEmpty(); } GlideEffect::WindowInfo::WindowInfo() : deleted(false) , added(false) , closed(false) , timeLine(0) { } GlideEffect::WindowInfo::~WindowInfo() { delete timeLine; } } // namespace diff --git a/effects/magiclamp/magiclamp.cpp b/effects/magiclamp/magiclamp.cpp index e530b43ff..4983862f4 100644 --- a/effects/magiclamp/magiclamp.cpp +++ b/effects/magiclamp/magiclamp.cpp @@ -1,378 +1,378 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ // based on minimize animation by Rivo Laks #include "magiclamp.h" // KConfigSkeleton #include "magiclampconfig.h" #include #include #include #include namespace KWin { MagicLampEffect::MagicLampEffect() { mActiveAnimations = 0; reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); connect(effects, SIGNAL(windowMinimized(KWin::EffectWindow*)), this, SLOT(slotWindowMinimized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowUnminimized(KWin::EffectWindow*)), this, SLOT(slotWindowUnminimized(KWin::EffectWindow*))); } bool MagicLampEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void MagicLampEffect::reconfigure(ReconfigureFlags) { MagicLampConfig::self()->read(); // TODO: rename animationDuration to duration mAnimationDuration = animationTime(MagicLampConfig::animationDuration() != 0 ? MagicLampConfig::animationDuration() : 250); KConfigGroup conf = effects->effectConfig(QStringLiteral("MagicLamp")); conf = effects->effectConfig(QStringLiteral("Shadow")); int v = conf.readEntry("Size", 5); v += conf.readEntry("Fuzzyness", 10); mShadowOffset[0] = mShadowOffset[1] = -v; mShadowOffset[2] = mShadowOffset[3] = v; v = conf.readEntry("XOffset", 0); mShadowOffset[0] -= v; mShadowOffset[2] += v; v = conf.readEntry("YOffset", 3); mShadowOffset[1] -= v; mShadowOffset[3] += v; } void MagicLampEffect::prePaintScreen(ScreenPrePaintData& data, int time) { QHash< EffectWindow*, QTimeLine* >::iterator entry = mTimeLineWindows.begin(); bool erase = false; while (entry != mTimeLineWindows.end()) { QTimeLine *timeline = entry.value(); if (entry.key()->isMinimized()) { timeline->setCurrentTime(timeline->currentTime() + time); erase = (timeline->currentValue() >= 1.0f); } else { timeline->setCurrentTime(timeline->currentTime() - time); erase = (timeline->currentValue() <= 0.0f); } if (erase) { delete timeline; entry = mTimeLineWindows.erase(entry); } else ++entry; } mActiveAnimations = mTimeLineWindows.count(); if (mActiveAnimations > 0) // We need to mark the screen windows as transformed. Otherwise the // whole screen won't be repainted, resulting in artefacts data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; effects->prePaintScreen(data, time); } void MagicLampEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { // Schedule window for transformation if the animation is still in // progress if (mTimeLineWindows.contains(w)) { // We'll transform this window data.setTransformed(); data.quads = data.quads.makeGrid(40); w->enablePainting(EffectWindow::PAINT_DISABLED_BY_MINIMIZE); } effects->prePaintWindow(w, data, time); } void MagicLampEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (mTimeLineWindows.contains(w)) { // 0 = not minimized, 1 = fully minimized float progress = mTimeLineWindows[w]->currentValue(); QRect geo = w->geometry(); QRect icon = w->iconGeometry(); IconPosition position = Top; // If there's no icon geometry, minimize to the center of the screen if (!icon.isValid()) { QRect extG = geo.adjusted(mShadowOffset[0], mShadowOffset[1], mShadowOffset[2], mShadowOffset[3]); QPoint pt = cursorPos(); // focussing inside the window is no good, leads to ugly artefacts, find nearest border if (extG.contains(pt)) { const int d[2][2] = { {pt.x() - extG.x(), extG.right() - pt.x()}, {pt.y() - extG.y(), extG.bottom() - pt.y()} }; int di = d[1][0]; position = Top; if (d[0][0] < di) { di = d[0][0]; position = Left; } if (d[1][1] < di) { di = d[1][1]; position = Bottom; } if (d[0][1] < di) position = Right; switch(position) { case Top: pt.setY(extG.y()); break; case Left: pt.setX(extG.x()); break; case Bottom: pt.setY(extG.bottom()); break; case Right: pt.setX(extG.right()); break; } } else { if (pt.y() < geo.y()) position = Top; else if (pt.x() < geo.x()) position = Left; else if (pt.y() > geo.bottom()) position = Bottom; else if (pt.x() > geo.right()) position = Right; } icon = QRect(pt, QSize(0, 0)); } else { // Assumption: there is a panel containing the icon position EffectWindow* panel = NULL; foreach (EffectWindow * window, effects->stackingOrder()) { if (!window->isDock()) continue; // we have to use intersects as there seems to be a Plasma bug // the published icon geometry might be bigger than the panel if (window->geometry().intersects(icon)) { panel = window; break; } } if (panel) { // Assumption: width of horizonal panel is greater than its height and vice versa // The panel has to border one screen edge, so get it's screen area QRect panelScreen = effects->clientArea(ScreenArea, panel); if (panel->width() >= panel->height()) { // horizontal panel if (panel->y() == panelScreen.y()) position = Top; else position = Bottom; } else { // vertical panel if (panel->x() == panelScreen.x()) position = Left; else position = Right; } } else { // we did not find a panel, so it might be autohidden QRect iconScreen = effects->clientArea(ScreenArea, icon.topLeft(), effects->currentDesktop()); // as the icon geometry could be overlap a screen edge we use an intersection QRect rect = iconScreen.intersected(icon); // here we need a different assumption: icon geometry borders one screen edge // this assumption might be wrong for e.g. task applet being the only applet in panel // in this case the icon borders two screen edges // there might be a wrong animation, but not distorted if (rect.x() == iconScreen.x()) { position = Left; } else if (rect.x() + rect.width() == iconScreen.x() + iconScreen.width()) { position = Right; } else if (rect.y() == iconScreen.y()) { position = Top; } else { position = Bottom; } } } #define SANITIZE_PROGRESS if (p_progress[0] < 0)\ p_progress[0] = -p_progress[0];\ if (p_progress[1] < 0)\ p_progress[1] = -p_progress[1] #define SET_QUADS(_SET_A_, _A_, _DA_, _SET_B_, _B_, _O0_, _O1_, _O2_, _O3_) quad[0]._SET_A_((icon._A_() + icon._DA_()*(quad[0]._A_() / geo._DA_()) - (quad[0]._A_() + geo._A_()))*p_progress[_O0_] + quad[0]._A_());\ quad[1]._SET_A_((icon._A_() + icon._DA_()*(quad[1]._A_() / geo._DA_()) - (quad[1]._A_() + geo._A_()))*p_progress[_O1_] + quad[1]._A_());\ quad[2]._SET_A_((icon._A_() + icon._DA_()*(quad[2]._A_() / geo._DA_()) - (quad[2]._A_() + geo._A_()))*p_progress[_O2_] + quad[2]._A_());\ quad[3]._SET_A_((icon._A_() + icon._DA_()*(quad[3]._A_() / geo._DA_()) - (quad[3]._A_() + geo._A_()))*p_progress[_O3_] + quad[3]._A_());\ \ quad[0]._SET_B_(quad[0]._B_() + offset[_O0_]);\ quad[1]._SET_B_(quad[1]._B_() + offset[_O1_]);\ quad[2]._SET_B_(quad[2]._B_() + offset[_O2_]);\ quad[3]._SET_B_(quad[3]._B_() + offset[_O3_]) WindowQuadList newQuads; float quadFactor; // defines how fast a quad is vertically moved: y coordinates near to window top are slowed down // it is used as quadFactor^3/windowHeight^3 // quadFactor is the y position of the quad but is changed towards becomming the window height // by that the factor becomes 1 and has no influence any more float offset[2] = {0,0}; // how far has a quad to be moved? Distance between icon and window multiplied by the progress and by the quadFactor float p_progress[2] = {0,0}; // the factor which defines how far the x values have to be changed // factor is the current moved y value diveded by the distance between icon and window WindowQuad lastQuad(WindowQuadError); lastQuad[0].setX(-1); lastQuad[0].setY(-1); lastQuad[1].setX(-1); lastQuad[1].setY(-1); lastQuad[2].setX(-1); lastQuad[2].setY(-1); if (position == Bottom) { float height_cube = float(geo.height()) * float(geo.height()) * float(geo.height()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].y() != lastQuad[0].y() || quad[2].y() != lastQuad[2].y()) { quadFactor = quad[0].y() + (geo.height() - quad[0].y()) * progress; offset[0] = (icon.y() + quad[0].y() - geo.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); quadFactor = quad[2].y() + (geo.height() - quad[2].y()) * progress; offset[1] = (icon.y() + quad[2].y() - geo.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); p_progress[1] = qMin(offset[1] / (icon.y() + icon.height() - geo.y() - float(quad[2].y())), 1.0f); p_progress[0] = qMin(offset[0] / (icon.y() + icon.height() - geo.y() - float(quad[0].y())), 1.0f); } else lastQuad = quad; SANITIZE_PROGRESS; // x values are moved towards the center of the icon SET_QUADS(setX, x, width, setY, y, 0,0,1,1); newQuads.append(quad); } } else if (position == Top) { float height_cube = float(geo.height()) * float(geo.height()) * float(geo.height()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].y() != lastQuad[0].y() || quad[2].y() != lastQuad[2].y()) { quadFactor = geo.height() - quad[0].y() + (quad[0].y()) * progress; offset[0] = (geo.y() - icon.height() + geo.height() + quad[0].y() - icon.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); quadFactor = geo.height() - quad[2].y() + (quad[2].y()) * progress; offset[1] = (geo.y() - icon.height() + geo.height() + quad[2].y() - icon.y()) * progress * ((quadFactor * quadFactor * quadFactor) / height_cube); p_progress[0] = qMin(offset[0] / (geo.y() - icon.height() + geo.height() - icon.y() - float(geo.height() - quad[0].y())), 1.0f); p_progress[1] = qMin(offset[1] / (geo.y() - icon.height() + geo.height() - icon.y() - float(geo.height() - quad[2].y())), 1.0f); } else lastQuad = quad; offset[0] = -offset[0]; offset[1] = -offset[1]; SANITIZE_PROGRESS; // x values are moved towards the center of the icon SET_QUADS(setX, x, width, setY, y, 0,0,1,1); newQuads.append(quad); } } else if (position == Left) { float width_cube = float(geo.width()) * float(geo.width()) * float(geo.width()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].x() != lastQuad[0].x() || quad[1].x() != lastQuad[1].x()) { quadFactor = geo.width() - quad[0].x() + (quad[0].x()) * progress; offset[0] = (geo.x() - icon.width() + geo.width() + quad[0].x() - icon.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); quadFactor = geo.width() - quad[1].x() + (quad[1].x()) * progress; offset[1] = (geo.x() - icon.width() + geo.width() + quad[1].x() - icon.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); p_progress[0] = qMin(offset[0] / (geo.x() - icon.width() + geo.width() - icon.x() - float(geo.width() - quad[0].x())), 1.0f); p_progress[1] = qMin(offset[1] / (geo.x() - icon.width() + geo.width() - icon.x() - float(geo.width() - quad[1].x())), 1.0f); } else lastQuad = quad; offset[0] = -offset[0]; offset[1] = -offset[1]; SANITIZE_PROGRESS; // y values are moved towards the center of the icon SET_QUADS(setY, y, height, setX, x, 0,1,1,0); newQuads.append(quad); } } else if (position == Right) { float width_cube = float(geo.width()) * float(geo.width()) * float(geo.width()); foreach (WindowQuad quad, data.quads) { // krazy:exclude=foreach if (quad[0].x() != lastQuad[0].x() || quad[1].x() != lastQuad[1].x()) { quadFactor = quad[0].x() + (geo.width() - quad[0].x()) * progress; offset[0] = (icon.x() + quad[0].x() - geo.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); quadFactor = quad[1].x() + (geo.width() - quad[1].x()) * progress; offset[1] = (icon.x() + quad[1].x() - geo.x()) * progress * ((quadFactor * quadFactor * quadFactor) / width_cube); p_progress[0] = qMin(offset[0] / (icon.x() + icon.width() - geo.x() - float(quad[0].x())), 1.0f); p_progress[1] = qMin(offset[1] / (icon.x() + icon.width() - geo.x() - float(quad[1].x())), 1.0f); } else lastQuad = quad; SANITIZE_PROGRESS; // y values are moved towards the center of the icon SET_QUADS(setY, y, height, setX, x, 0,1,1,0); newQuads.append(quad); } } data.quads = newQuads; } // Call the next effect. effects->paintWindow(w, mask, region, data); } void MagicLampEffect::postPaintScreen() { if (mActiveAnimations > 0) // Repaint the workspace so that everything would be repainted next time effects->addRepaintFull(); mActiveAnimations = mTimeLineWindows.count(); // Call the next effect. effects->postPaintScreen(); } void MagicLampEffect::slotWindowDeleted(EffectWindow* w) { delete mTimeLineWindows.take(w); } void MagicLampEffect::slotWindowMinimized(EffectWindow* w) { if (effects->activeFullScreenEffect()) return; if (!mTimeLineWindows.contains(w)) { mTimeLineWindows.insert(w, new QTimeLine(mAnimationDuration, this)); mTimeLineWindows[w]->setCurveShape(QTimeLine::LinearCurve); } mTimeLineWindows[w]->setCurrentTime(0); } void MagicLampEffect::slotWindowUnminimized(EffectWindow* w) { if (effects->activeFullScreenEffect()) return; if (!mTimeLineWindows.contains(w)) { mTimeLineWindows.insert(w, new QTimeLine(mAnimationDuration, this)); mTimeLineWindows[w]->setCurveShape(QTimeLine::LinearCurve); } mTimeLineWindows[w]->setCurrentTime(mAnimationDuration); } bool MagicLampEffect::isActive() const { return !mTimeLineWindows.isEmpty(); } } // namespace diff --git a/effects/sheet/sheet.cpp b/effects/sheet/sheet.cpp index 78b056f68..84c1bc339 100644 --- a/effects/sheet/sheet.cpp +++ b/effects/sheet/sheet.cpp @@ -1,205 +1,205 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2007 Philip Falkner Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "sheet.h" #include "sheetconfig.h" #include #include #include // Effect is based on fade effect by Philip Falkner namespace KWin { static const int IsSheetWindow = 0x22A982D5; SheetEffect::SheetEffect() { reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(windowDeleted(KWin::EffectWindow*)), this, SLOT(slotWindowDeleted(KWin::EffectWindow*))); } bool SheetEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void SheetEffect::reconfigure(ReconfigureFlags) { SheetConfig::self()->read(); duration = animationTime(SheetConfig::animationTime() != 0 ? SheetConfig::animationTime() : 500); } void SheetEffect::prePaintScreen(ScreenPrePaintData& data, int time) { if (!windows.isEmpty()) { data.mask |= PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS; screenTime = time; } effects->prePaintScreen(data, time); } void SheetEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { InfoMap::iterator info = windows.find(w); if (info != windows.end()) { data.setTransformed(); if (info->added) info->timeLine->setCurrentTime(info->timeLine->currentTime() + screenTime); else if (info->closed) { info->timeLine->setCurrentTime(info->timeLine->currentTime() - screenTime); if (info->deleted) w->enablePainting(EffectWindow::PAINT_DISABLED_BY_DELETE); } } effects->prePaintWindow(w, data, time); // if the window isn't to be painted, then let's make sure // to track its progress if (info != windows.end() && !w->isPaintingEnabled() && !effects->activeFullScreenEffect()) w->addRepaintFull(); } void SheetEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { InfoMap::const_iterator info = windows.constFind(w); if (info != windows.constEnd()) { const double progress = info->timeLine->currentValue(); QGraphicsRotation rot; data.setRotationAxis(Qt::XAxis); data.setRotationAngle(60.0 * (1.0 - progress)); data *= QVector3D(1.0, progress, progress); data.translate(0.0, - (w->y() - info->parentY) * (1.0 - progress)); } effects->paintWindow(w, mask, region, data); } void SheetEffect::postPaintWindow(EffectWindow* w) { InfoMap::iterator info = windows.find(w); if (info != windows.end()) { if (info->added && info->timeLine->currentValue() == 1.0) { windows.remove(w); effects->addRepaintFull(); } else if (info->closed && info->timeLine->currentValue() == 0.0) { info->closed = false; if (info->deleted) { windows.remove(w); w->unrefWindow(); } effects->addRepaintFull(); } if (info->added || info->closed) w->addRepaintFull(); } effects->postPaintWindow(w); } void SheetEffect::slotWindowAdded(EffectWindow* w) { if (!isSheetWindow(w)) return; w->setData(IsSheetWindow, true); InfoMap::iterator it = windows.find(w); WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = true; info->closed = false; info->deleted = false; delete info->timeLine; info->timeLine = new QTimeLine(duration); const EffectWindowList stack = effects->stackingOrder(); // find parent foreach (EffectWindow * window, stack) { if (window->findModal() == w) { info->parentY = window->y(); break; } } w->addRepaintFull(); } void SheetEffect::slotWindowClosed(EffectWindow* w) { if (!isSheetWindow(w)) return; w->refWindow(); InfoMap::iterator it = windows.find(w); WindowInfo *info = (it == windows.end()) ? &windows[w] : &it.value(); info->added = false; info->closed = true; info->deleted = true; delete info->timeLine; info->timeLine = new QTimeLine(duration); info->timeLine->setCurrentTime(duration); bool found = false; // find parent const EffectWindowList stack = effects->stackingOrder(); foreach (EffectWindow * window, stack) { if (window->findModal() == w) { info->parentY = window->y(); found = true; break; } } if (!found) info->parentY = 0; w->addRepaintFull(); } void SheetEffect::slotWindowDeleted(EffectWindow* w) { windows.remove(w); } bool SheetEffect::isSheetWindow(EffectWindow* w) { return (w->isModal() || w->data(IsSheetWindow).toBool()); } bool SheetEffect::isActive() const { return !windows.isEmpty(); } SheetEffect::WindowInfo::WindowInfo() : deleted(false) , added(false) , closed(false) , timeLine(0) , parentY(0) { } SheetEffect::WindowInfo::~WindowInfo() { delete timeLine; } } // namespace diff --git a/effects/wobblywindows/wobblywindows.cpp b/effects/wobblywindows/wobblywindows.cpp index 6c92b8f2a..7e3ddcea8 100644 --- a/effects/wobblywindows/wobblywindows.cpp +++ b/effects/wobblywindows/wobblywindows.cpp @@ -1,1209 +1,1209 @@ /***************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2008 Cédric Borgese You can Freely distribute this program under the GNU General Public License. See the file "COPYING" for the exact licensing terms. ******************************************************************/ #include "wobblywindows.h" #include "wobblywindowsconfig.h" #include #define USE_ASSERT #ifdef USE_ASSERT #define ASSERT1 assert #else #define ASSERT1 #endif //#define COMPUTE_STATS // if you enable it and run kwin in a terminal from the session it manages, // be sure to redirect the output of kwin in a file or // you'll propably get deadlocks. //#define VERBOSE_MODE #if defined COMPUTE_STATS && !defined VERBOSE_MODE # ifdef __GNUC__ # warning "You enable COMPUTE_STATS without VERBOSE_MODE, computed stats will not be printed." # endif #endif namespace KWin { struct ParameterSet { qreal stiffness; qreal drag; qreal move_factor; qreal xTesselation; qreal yTesselation; qreal minVelocity; qreal maxVelocity; qreal stopVelocity; qreal minAcceleration; qreal maxAcceleration; qreal stopAcceleration; bool moveEffectEnabled; bool openEffectEnabled; bool closeEffectEnabled; }; static const ParameterSet set_0 = { 0.15, 0.80, 0.10, 20.0, 20.0, 0.0, 1000.0, 0.5, 0.0, 1000.0, 0.5, true, false, false }; static const ParameterSet set_1 = { 0.10, 0.85, 0.10, 20.0, 20.0, 0.0, 1000.0, 0.5, 0.0, 1000.0, 0.5, true, false, false }; static const ParameterSet set_2 = { 0.06, 0.90, 0.10, 20.0, 20.0, 0.0, 1000.0, 0.5, 0.0, 1000.0, 0.5, true, false, false }; static const ParameterSet set_3 = { 0.03, 0.92, 0.20, 20.0, 20.0, 0.0, 1000.0, 0.5, 0.0, 1000.0, 0.5, true, false, false }; static const ParameterSet set_4 = { 0.01, 0.97, 0.25, 20.0, 20.0, 0.0, 1000.0, 0.5, 0.0, 1000.0, 0.5, true, false, false }; static const ParameterSet pset[5] = { set_0, set_1, set_2, set_3, set_4 }; WobblyWindowsEffect::WobblyWindowsEffect() { reconfigure(ReconfigureAll); connect(effects, SIGNAL(windowAdded(KWin::EffectWindow*)), this, SLOT(slotWindowAdded(KWin::EffectWindow*))); connect(effects, SIGNAL(windowClosed(KWin::EffectWindow*)), this, SLOT(slotWindowClosed(KWin::EffectWindow*))); connect(effects, SIGNAL(windowStartUserMovedResized(KWin::EffectWindow*)), this, SLOT(slotWindowStartUserMovedResized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowStepUserMovedResized(KWin::EffectWindow*,QRect)), this, SLOT(slotWindowStepUserMovedResized(KWin::EffectWindow*,QRect))); connect(effects, SIGNAL(windowFinishUserMovedResized(KWin::EffectWindow*)), this, SLOT(slotWindowFinishUserMovedResized(KWin::EffectWindow*))); connect(effects, SIGNAL(windowMaximizedStateChanged(KWin::EffectWindow*,bool,bool)), this, SLOT(slotWindowMaximizeStateChanged(KWin::EffectWindow*,bool,bool))); } WobblyWindowsEffect::~WobblyWindowsEffect() { if (!windows.empty()) { // we should be empty at this point... // emit a warning and clean the list. qCDebug(KWINEFFECTS) << "Windows list not empty. Left items : " << windows.count(); QHash< const EffectWindow*, WindowWobblyInfos >::iterator i; for (i = windows.begin(); i != windows.end(); ++i) { freeWobblyInfo(i.value()); } } } void WobblyWindowsEffect::reconfigure(ReconfigureFlags) { WobblyWindowsConfig::self()->read(); QString settingsMode = WobblyWindowsConfig::settings(); if (settingsMode != QStringLiteral("Custom")) { unsigned int wobblynessLevel = WobblyWindowsConfig::wobblynessLevel(); if (wobblynessLevel > 4) { qCDebug(KWINEFFECTS) << "Wrong value for \"WobblynessLevel\" : " << wobblynessLevel; wobblynessLevel = 4; } setParameterSet(pset[wobblynessLevel]); if (WobblyWindowsConfig::advancedMode()) { m_stiffness = WobblyWindowsConfig::stiffness() / 100.0; m_drag = WobblyWindowsConfig::drag() / 100.0; m_move_factor = WobblyWindowsConfig::moveFactor() / 100.0; } } else { // Custom method, read all values from config file. m_stiffness = WobblyWindowsConfig::stiffness() / 100.0; m_drag = WobblyWindowsConfig::drag() / 100.0; m_move_factor = WobblyWindowsConfig::moveFactor() / 100.0; m_xTesselation = WobblyWindowsConfig::xTesselation(); m_yTesselation = WobblyWindowsConfig::yTesselation(); m_minVelocity = WobblyWindowsConfig::minVelocity(); m_maxVelocity = WobblyWindowsConfig::maxVelocity(); m_stopVelocity = WobblyWindowsConfig::stopVelocity(); m_minAcceleration = WobblyWindowsConfig::minAcceleration(); m_maxAcceleration = WobblyWindowsConfig::maxAcceleration(); m_stopAcceleration = WobblyWindowsConfig::stopAcceleration(); m_moveEffectEnabled = WobblyWindowsConfig::moveEffect(); m_openEffectEnabled = WobblyWindowsConfig::openEffect(); // disable close effect by default for now as it doesn't do what I want. m_closeEffectEnabled = WobblyWindowsConfig::closeEffect(); } m_moveWobble = WobblyWindowsConfig::moveWobble(); m_resizeWobble = WobblyWindowsConfig::resizeWobble(); #if defined VERBOSE_MODE qCDebug(KWINEFFECTS) << "Parameters :\n" << "move : " << m_moveEffectEnabled << ", open : " << m_openEffectEnabled << ", close : " << m_closeEffectEnabled << "\n" "grid(" << m_stiffness << ", " << m_drag << ", " << m_move_factor << ")\n" << "velocity(" << m_minVelocity << ", " << m_maxVelocity << ", " << m_stopVelocity << ")\n" << "acceleration(" << m_minAcceleration << ", " << m_maxAcceleration << ", " << m_stopAcceleration << ")\n" << "tesselation(" << m_xTesselation << ", " << m_yTesselation << ")"; #endif } bool WobblyWindowsEffect::supported() { - return effects->isOpenGLCompositing(); + return effects->isOpenGLCompositing() && effects->animationsSupported(); } void WobblyWindowsEffect::setParameterSet(const ParameterSet& pset) { m_stiffness = pset.stiffness; m_drag = pset.drag; m_move_factor = pset.move_factor; m_xTesselation = pset.xTesselation; m_yTesselation = pset.yTesselation; m_minVelocity = pset.minVelocity; m_maxVelocity = pset.maxVelocity; m_stopVelocity = pset.stopVelocity; m_minAcceleration = pset.minAcceleration; m_maxAcceleration = pset.maxAcceleration; m_stopAcceleration = pset.stopAcceleration; m_moveEffectEnabled = pset.moveEffectEnabled; m_openEffectEnabled = pset.openEffectEnabled; m_closeEffectEnabled = pset.closeEffectEnabled; } void WobblyWindowsEffect::setVelocityThreshold(qreal m_minVelocity) { this->m_minVelocity = m_minVelocity; } void WobblyWindowsEffect::setMoveFactor(qreal factor) { m_move_factor = factor; } void WobblyWindowsEffect::setStiffness(qreal stiffness) { m_stiffness = stiffness; } void WobblyWindowsEffect::setDrag(qreal drag) { m_drag = drag; } void WobblyWindowsEffect::prePaintScreen(ScreenPrePaintData& data, int time) { // We need to mark the screen windows as transformed. Otherwise the whole // screen won't be repainted, resulting in artefacts. // Could we just set a subset of the screen to be repainted ? if (windows.count() != 0) { m_updateRegion = QRegion(); } effects->prePaintScreen(data, time); } const qreal maxTime = 10.0; void WobblyWindowsEffect::prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) { if (windows.contains(w)) { data.setTransformed(); data.quads = data.quads.makeRegularGrid(m_xTesselation, m_yTesselation); bool stop = false; qreal updateTime = time; while (!stop && (updateTime > maxTime)) { #if defined VERBOSE_MODE qCDebug(KWINEFFECTS) << "loop time " << updateTime << " / " << time; #endif stop = !updateWindowWobblyDatas(w, maxTime); updateTime -= maxTime; } if (!stop && updateTime > 0) { updateWindowWobblyDatas(w, updateTime); } } effects->prePaintWindow(w, data, time); } void WobblyWindowsEffect::paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) { if (!(mask & PAINT_SCREEN_TRANSFORMED) && windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; int tx = w->geometry().x(); int ty = w->geometry().y(); double left = 0.0; double top = 0.0; double right = w->width(); double bottom = w->height(); for (int i = 0; i < data.quads.count(); ++i) { for (int j = 0; j < 4; ++j) { WindowVertex& v = data.quads[i][j]; Pair oldPos = {tx + v.x(), ty + v.y()}; Pair newPos = computeBezierPoint(wwi, oldPos); v.move(newPos.x - tx, newPos.y - ty); } left = qMin(left, data.quads[i].left()); top = qMin(top, data.quads[i].top()); right = qMax(right, data.quads[i].right()); bottom = qMax(bottom, data.quads[i].bottom()); } m_updateRegion = m_updateRegion.united(QRect(w->x() + left, w->y() + top, right - left + 2, bottom - top + 2)); } // Call the next effect. effects->paintWindow(w, mask, region, data); } void WobblyWindowsEffect::postPaintScreen() { if (!windows.isEmpty()) { effects->addRepaint(m_updateRegion); } // Call the next effect. effects->postPaintScreen(); } void WobblyWindowsEffect::slotWindowStartUserMovedResized(EffectWindow *w) { if (!m_moveEffectEnabled || w->isSpecialWindow()) return; if ((w->isUserMove() && m_moveWobble) || (w->isUserResize() && m_resizeWobble)) { startMovedResized(w); } } void WobblyWindowsEffect::slotWindowStepUserMovedResized(EffectWindow *w, const QRect &geometry) { Q_UNUSED(geometry) if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; QRect rect = w->geometry(); if (rect.y() != wwi.resize_original_rect.y()) wwi.can_wobble_top = true; if (rect.x() != wwi.resize_original_rect.x()) wwi.can_wobble_left = true; if (rect.right() != wwi.resize_original_rect.right()) wwi.can_wobble_right = true; if (rect.bottom() != wwi.resize_original_rect.bottom()) wwi.can_wobble_bottom = true; } } void WobblyWindowsEffect::slotWindowFinishUserMovedResized(EffectWindow *w) { if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; wwi.status = Free; QRect rect = w->geometry(); if (rect.y() != wwi.resize_original_rect.y()) wwi.can_wobble_top = true; if (rect.x() != wwi.resize_original_rect.x()) wwi.can_wobble_left = true; if (rect.right() != wwi.resize_original_rect.right()) wwi.can_wobble_right = true; if (rect.bottom() != wwi.resize_original_rect.bottom()) wwi.can_wobble_bottom = true; } } void WobblyWindowsEffect::slotWindowMaximizeStateChanged(EffectWindow *w, bool horizontal, bool vertical) { Q_UNUSED(horizontal) Q_UNUSED(vertical) if (w->isUserMove() || !m_moveEffectEnabled || w->isSpecialWindow()) return; if (m_moveWobble && m_resizeWobble) { stepMovedResized(w); } if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; QRect rect = w->geometry(); if (rect.y() != wwi.resize_original_rect.y()) wwi.can_wobble_top = true; if (rect.x() != wwi.resize_original_rect.x()) wwi.can_wobble_left = true; if (rect.right() != wwi.resize_original_rect.right()) wwi.can_wobble_right = true; if (rect.bottom() != wwi.resize_original_rect.bottom()) wwi.can_wobble_bottom = true; } } void WobblyWindowsEffect::startMovedResized(EffectWindow* w) { if (!windows.contains(w)) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); windows[w] = new_wwi; } WindowWobblyInfos& wwi = windows[w]; wwi.status = Moving; const QRectF& rect = w->geometry(); qreal x_increment = rect.width() / (wwi.width - 1.0); qreal y_increment = rect.height() / (wwi.height - 1.0); Pair picked = {static_cast(cursorPos().x()), static_cast(cursorPos().y())}; int indx = (picked.x - rect.x()) / x_increment + 0.5; int indy = (picked.y - rect.y()) / y_increment + 0.5; int pickedPointIndex = indy * wwi.width + indx; if (pickedPointIndex < 0) { qCDebug(KWINEFFECTS) << "Picked index == " << pickedPointIndex << " with (" << cursorPos().x() << "," << cursorPos().y() << ")"; pickedPointIndex = 0; } else if (static_cast(pickedPointIndex) > wwi.count - 1) { qCDebug(KWINEFFECTS) << "Picked index == " << pickedPointIndex << " with (" << cursorPos().x() << "," << cursorPos().y() << ")"; pickedPointIndex = wwi.count - 1; } #if defined VERBOSE_MODE qCDebug(KWINEFFECTS) << "Original Picked point -- x : " << picked.x << " - y : " << picked.y; #endif wwi.constraint[pickedPointIndex] = true; if (w->isUserResize()) { // on a resize, do not allow any edges to wobble until it has been moved from // its original location wwi.can_wobble_top = wwi.can_wobble_left = wwi.can_wobble_right = wwi.can_wobble_bottom = false; wwi.resize_original_rect = w->geometry(); } else { wwi.can_wobble_top = wwi.can_wobble_left = wwi.can_wobble_right = wwi.can_wobble_bottom = true; } } void WobblyWindowsEffect::stepMovedResized(EffectWindow* w) { QRect new_geometry = w->geometry(); if (!windows.contains(w)) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, new_geometry); windows[w] = new_wwi; } WindowWobblyInfos& wwi = windows[w]; wwi.status = Free; QRect maximized_area = effects->clientArea(MaximizeArea, w); bool throb_direction_out = (new_geometry.top() == maximized_area.top() && new_geometry.bottom() == maximized_area.bottom()) || (new_geometry.left() == maximized_area.left() && new_geometry.right() == maximized_area.right()); qreal magnitude = throb_direction_out ? 10 : -30; // a small throb out when maximized, a larger throb inwards when restored for (unsigned int j = 0; j < wwi.height; ++j) { for (unsigned int i = 0; i < wwi.width; ++i) { Pair v = { magnitude*(i / qreal(wwi.width - 1) - 0.5), magnitude*(j / qreal(wwi.height - 1) - 0.5) }; wwi.velocity[j*wwi.width+i] = v; } } // constrain the middle of the window, so that any asymetry wont cause it to drift off-center for (unsigned int j = 1; j < wwi.height - 1; ++j) { for (unsigned int i = 1; i < wwi.width - 1; ++i) { wwi.constraint[j*wwi.width+i] = true; } } } void WobblyWindowsEffect::slotWindowAdded(EffectWindow* w) { if (m_openEffectEnabled && w->data(WindowAddedGrabRole).value() != this) { if (windows.contains(w)) { // could this happen ?? WindowWobblyInfos& wwi = windows[w]; wobblyOpenInit(wwi); } else { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); wobblyOpenInit(new_wwi); windows[w] = new_wwi; } } } void WobblyWindowsEffect::slotWindowClosed(EffectWindow* w) { if (windows.contains(w)) { WindowWobblyInfos& wwi = windows[w]; if (m_closeEffectEnabled) { wobblyCloseInit(wwi, w); w->refWindow(); } else { freeWobblyInfo(wwi); windows.remove(w); if (windows.isEmpty()) effects->addRepaintFull(); } } else if (m_closeEffectEnabled && w->data(WindowAddedGrabRole).value() != this) { WindowWobblyInfos new_wwi; initWobblyInfo(new_wwi, w->geometry()); wobblyCloseInit(new_wwi, w); windows[w] = new_wwi; w->refWindow(); } } void WobblyWindowsEffect::wobblyOpenInit(WindowWobblyInfos& wwi) const { Pair middle = { (wwi.origin[0].x + wwi.origin[15].x) / 2, (wwi.origin[0].y + wwi.origin[15].y) / 2 }; for (unsigned int j = 0; j < 4; ++j) { for (unsigned int i = 0; i < 4; ++i) { unsigned int idx = j * 4 + i; wwi.constraint[idx] = false; wwi.position[idx].x = (wwi.position[idx].x + 3 * middle.x) / 4; wwi.position[idx].y = (wwi.position[idx].y + 3 * middle.y) / 4; } } wwi.status = Openning; wwi.can_wobble_top = wwi.can_wobble_left = wwi.can_wobble_right = wwi.can_wobble_bottom = true; } void WobblyWindowsEffect::wobblyCloseInit(WindowWobblyInfos& wwi, EffectWindow* w) const { const QRectF& rect = w->geometry(); QPointF center = rect.center(); int x1 = (rect.x() + 3 * center.x()) / 4; int x2 = (rect.x() + rect.width() + 3 * center.x()) / 4; int y1 = (rect.y() + 3 * center.y()) / 4; int y2 = (rect.y() + rect.height() + 3 * center.y()) / 4; wwi.closeRect.setCoords(x1, y1, x2, y2); // for closing, not yet used... for (unsigned int j = 0; j < 4; ++j) { for (unsigned int i = 0; i < 4; ++i) { unsigned int idx = j * 4 + i; wwi.constraint[idx] = false; } } wwi.status = Closing; } void WobblyWindowsEffect::initWobblyInfo(WindowWobblyInfos& wwi, QRect geometry) const { wwi.count = 4 * 4; wwi.width = 4; wwi.height = 4; wwi.bezierWidth = m_xTesselation; wwi.bezierHeight = m_yTesselation; wwi.bezierCount = m_xTesselation * m_yTesselation; wwi.origin = new Pair[wwi.count]; wwi.position = new Pair[wwi.count]; wwi.velocity = new Pair[wwi.count]; wwi.acceleration = new Pair[wwi.count]; wwi.buffer = new Pair[wwi.count]; wwi.constraint = new bool[wwi.count]; wwi.bezierSurface = new Pair[wwi.bezierCount]; wwi.status = Moving; qreal x = geometry.x(), y = geometry.y(); qreal width = geometry.width(), height = geometry.height(); Pair initValue = {x, y}; static const Pair nullPair = {0.0, 0.0}; qreal x_increment = width / (wwi.width - 1.0); qreal y_increment = height / (wwi.height - 1.0); for (unsigned int j = 0; j < 4; ++j) { for (unsigned int i = 0; i < 4; ++i) { unsigned int idx = j * 4 + i; wwi.origin[idx] = initValue; wwi.position[idx] = initValue; wwi.velocity[idx] = nullPair; wwi.constraint[idx] = false; if (i != 4 - 2) { // x grid count - 2, i.e. not the last point initValue.x += x_increment; } else { initValue.x = width + x; } initValue.x = initValue.x; } initValue.x = x; initValue.x = initValue.x; if (j != 4 - 2) { // y grid count - 2, i.e. not the last point initValue.y += y_increment; } else { initValue.y = height + y; } initValue.y = initValue.y; } } void WobblyWindowsEffect::freeWobblyInfo(WindowWobblyInfos& wwi) const { delete[] wwi.origin; delete[] wwi.position; delete[] wwi.velocity; delete[] wwi.acceleration; delete[] wwi.buffer; delete[] wwi.constraint; delete[] wwi.bezierSurface; } WobblyWindowsEffect::Pair WobblyWindowsEffect::computeBezierPoint(const WindowWobblyInfos& wwi, Pair point) const { // compute the input value Pair topleft = wwi.origin[0]; Pair bottomright = wwi.origin[wwi.count-1]; // ASSERT1(point.x >= topleft.x); // ASSERT1(point.y >= topleft.y); // ASSERT1(point.x <= bottomright.x); // ASSERT1(point.y <= bottomright.y); qreal tx = (point.x - topleft.x) / (bottomright.x - topleft.x); qreal ty = (point.y - topleft.y) / (bottomright.y - topleft.y); // ASSERT1(tx >= 0); // ASSERT1(tx <= 1); // ASSERT1(ty >= 0); // ASSERT1(ty <= 1); // compute polynomial coeff qreal px[4]; px[0] = (1 - tx) * (1 - tx) * (1 - tx); px[1] = 3 * (1 - tx) * (1 - tx) * tx; px[2] = 3 * (1 - tx) * tx * tx; px[3] = tx * tx * tx; qreal py[4]; py[0] = (1 - ty) * (1 - ty) * (1 - ty); py[1] = 3 * (1 - ty) * (1 - ty) * ty; py[2] = 3 * (1 - ty) * ty * ty; py[3] = ty * ty * ty; Pair res = {0.0, 0.0}; for (unsigned int j = 0; j < 4; ++j) { for (unsigned int i = 0; i < 4; ++i) { // this assume the grid is 4*4 res.x += px[i] * py[j] * wwi.position[i + j * wwi.width].x; res.y += px[i] * py[j] * wwi.position[i + j * wwi.width].y; } } return res; } namespace { static inline void fixVectorBounds(WobblyWindowsEffect::Pair& vec, qreal min, qreal max) { if (fabs(vec.x) < min) { vec.x = 0.0; } else if (fabs(vec.x) > max) { if (vec.x > 0.0) { vec.x = max; } else { vec.x = -max; } } if (fabs(vec.y) < min) { vec.y = 0.0; } else if (fabs(vec.y) > max) { if (vec.y > 0.0) { vec.y = max; } else { vec.y = -max; } } } static inline void computeVectorBounds(WobblyWindowsEffect::Pair& vec, WobblyWindowsEffect::Pair& bound) { if (fabs(vec.x) < bound.x) { bound.x = fabs(vec.x); } else if (fabs(vec.x) > bound.y) { bound.y = fabs(vec.x); } if (fabs(vec.y) < bound.x) { bound.x = fabs(vec.y); } else if (fabs(vec.y) > bound.y) { bound.y = fabs(vec.y); } } } // close the anonymous namespace bool WobblyWindowsEffect::updateWindowWobblyDatas(EffectWindow* w, qreal time) { QRectF rect = w->geometry(); WindowWobblyInfos& wwi = windows[w]; if (wwi.status == Closing) { rect = wwi.closeRect; } qreal x_length = rect.width() / (wwi.width - 1.0); qreal y_length = rect.height() / (wwi.height - 1.0); #if defined VERBOSE_MODE qCDebug(KWINEFFECTS) << "time " << time; qCDebug(KWINEFFECTS) << "increment x " << x_length << " // y" << y_length; #endif Pair origine = {rect.x(), rect.y()}; for (unsigned int j = 0; j < wwi.height; ++j) { for (unsigned int i = 0; i < wwi.width; ++i) { wwi.origin[wwi.width*j + i] = origine; if (i != wwi.width - 2) { origine.x += x_length; } else { origine.x = rect.width() + rect.x(); } } origine.x = rect.x(); if (j != wwi.height - 2) { origine.y += y_length; } else { origine.y = rect.height() + rect.y(); } } Pair neibourgs[4]; Pair acceleration; qreal acc_sum = 0.0; qreal vel_sum = 0.0; // compute acceleration, velocity and position for each point // for corners // top-left if (wwi.constraint[0]) { Pair window_pos = wwi.origin[0]; Pair current_pos = wwi.position[0]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[0] = accel; } else { Pair& pos = wwi.position[0]; neibourgs[0] = wwi.position[1]; neibourgs[1] = wwi.position[wwi.width]; acceleration.x = ((neibourgs[0].x - pos.x) - x_length) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness; acceleration.y = ((neibourgs[1].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 2; acceleration.y /= 2; wwi.acceleration[0] = acceleration; } // top-right if (wwi.constraint[wwi.width-1]) { Pair window_pos = wwi.origin[wwi.width-1]; Pair current_pos = wwi.position[wwi.width-1]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[wwi.width-1] = accel; } else { Pair& pos = wwi.position[wwi.width-1]; neibourgs[0] = wwi.position[wwi.width-2]; neibourgs[1] = wwi.position[2*wwi.width-1]; acceleration.x = (x_length - (pos.x - neibourgs[0].x)) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness; acceleration.y = ((neibourgs[1].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 2; acceleration.y /= 2; wwi.acceleration[wwi.width-1] = acceleration; } // bottom-left if (wwi.constraint[wwi.width*(wwi.height-1)]) { Pair window_pos = wwi.origin[wwi.width*(wwi.height-1)]; Pair current_pos = wwi.position[wwi.width*(wwi.height-1)]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[wwi.width*(wwi.height-1)] = accel; } else { Pair& pos = wwi.position[wwi.width*(wwi.height-1)]; neibourgs[0] = wwi.position[wwi.width*(wwi.height-1)+1]; neibourgs[1] = wwi.position[wwi.width*(wwi.height-2)]; acceleration.x = ((neibourgs[0].x - pos.x) - x_length) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[1].y)) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 2; acceleration.y /= 2; wwi.acceleration[wwi.width*(wwi.height-1)] = acceleration; } // bottom-right if (wwi.constraint[wwi.count-1]) { Pair window_pos = wwi.origin[wwi.count-1]; Pair current_pos = wwi.position[wwi.count-1]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[wwi.count-1] = accel; } else { Pair& pos = wwi.position[wwi.count-1]; neibourgs[0] = wwi.position[wwi.count-2]; neibourgs[1] = wwi.position[wwi.width*(wwi.height-1)-1]; acceleration.x = (x_length - (pos.x - neibourgs[0].x)) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[1].y)) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 2; acceleration.y /= 2; wwi.acceleration[wwi.count-1] = acceleration; } // for borders // top border for (unsigned int i = 1; i < wwi.width - 1; ++i) { if (wwi.constraint[i]) { Pair window_pos = wwi.origin[i]; Pair current_pos = wwi.position[i]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[i] = accel; } else { Pair& pos = wwi.position[i]; neibourgs[0] = wwi.position[i-1]; neibourgs[1] = wwi.position[i+1]; neibourgs[2] = wwi.position[i+wwi.width]; acceleration.x = (x_length - (pos.x - neibourgs[0].x)) * m_stiffness + ((neibourgs[1].x - pos.x) - x_length) * m_stiffness + (neibourgs[2].x - pos.x) * m_stiffness; acceleration.y = ((neibourgs[2].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness + (neibourgs[1].y - pos.y) * m_stiffness; acceleration.x /= 3; acceleration.y /= 3; wwi.acceleration[i] = acceleration; } } // bottom border for (unsigned int i = wwi.width * (wwi.height - 1) + 1; i < wwi.count - 1; ++i) { if (wwi.constraint[i]) { Pair window_pos = wwi.origin[i]; Pair current_pos = wwi.position[i]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[i] = accel; } else { Pair& pos = wwi.position[i]; neibourgs[0] = wwi.position[i-1]; neibourgs[1] = wwi.position[i+1]; neibourgs[2] = wwi.position[i-wwi.width]; acceleration.x = (x_length - (pos.x - neibourgs[0].x)) * m_stiffness + ((neibourgs[1].x - pos.x) - x_length) * m_stiffness + (neibourgs[2].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[2].y)) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness + (neibourgs[1].y - pos.y) * m_stiffness; acceleration.x /= 3; acceleration.y /= 3; wwi.acceleration[i] = acceleration; } } // left border for (unsigned int i = wwi.width; i < wwi.width*(wwi.height - 1); i += wwi.width) { if (wwi.constraint[i]) { Pair window_pos = wwi.origin[i]; Pair current_pos = wwi.position[i]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[i] = accel; } else { Pair& pos = wwi.position[i]; neibourgs[0] = wwi.position[i+1]; neibourgs[1] = wwi.position[i-wwi.width]; neibourgs[2] = wwi.position[i+wwi.width]; acceleration.x = ((neibourgs[0].x - pos.x) - x_length) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness + (neibourgs[2].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[1].y)) * m_stiffness + ((neibourgs[2].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 3; acceleration.y /= 3; wwi.acceleration[i] = acceleration; } } // right border for (unsigned int i = 2 * wwi.width - 1; i < wwi.count - 1; i += wwi.width) { if (wwi.constraint[i]) { Pair window_pos = wwi.origin[i]; Pair current_pos = wwi.position[i]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[i] = accel; } else { Pair& pos = wwi.position[i]; neibourgs[0] = wwi.position[i-1]; neibourgs[1] = wwi.position[i-wwi.width]; neibourgs[2] = wwi.position[i+wwi.width]; acceleration.x = (x_length - (pos.x - neibourgs[0].x)) * m_stiffness + (neibourgs[1].x - pos.x) * m_stiffness + (neibourgs[2].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[1].y)) * m_stiffness + ((neibourgs[2].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness; acceleration.x /= 3; acceleration.y /= 3; wwi.acceleration[i] = acceleration; } } // for the inner points for (unsigned int j = 1; j < wwi.height - 1; ++j) { for (unsigned int i = 1; i < wwi.width - 1; ++i) { unsigned int index = i + j * wwi.width; if (wwi.constraint[index]) { Pair window_pos = wwi.origin[index]; Pair current_pos = wwi.position[index]; Pair move = {window_pos.x - current_pos.x, window_pos.y - current_pos.y}; Pair accel = {move.x*m_stiffness, move.y*m_stiffness}; wwi.acceleration[index] = accel; } else { Pair& pos = wwi.position[index]; neibourgs[0] = wwi.position[index-1]; neibourgs[1] = wwi.position[index+1]; neibourgs[2] = wwi.position[index-wwi.width]; neibourgs[3] = wwi.position[index+wwi.width]; acceleration.x = ((neibourgs[0].x - pos.x) - x_length) * m_stiffness + (x_length - (pos.x - neibourgs[1].x)) * m_stiffness + (neibourgs[2].x - pos.x) * m_stiffness + (neibourgs[3].x - pos.x) * m_stiffness; acceleration.y = (y_length - (pos.y - neibourgs[2].y)) * m_stiffness + ((neibourgs[3].y - pos.y) - y_length) * m_stiffness + (neibourgs[0].y - pos.y) * m_stiffness + (neibourgs[1].y - pos.y) * m_stiffness; acceleration.x /= 4; acceleration.y /= 4; wwi.acceleration[index] = acceleration; } } } heightRingLinearMean(&wwi.acceleration, wwi); #if defined COMPUTE_STATS Pair accBound = {m_maxAcceleration, m_minAcceleration}; Pair velBound = {m_maxVelocity, m_minVelocity}; #endif // compute the new velocity of each vertex. for (unsigned int i = 0; i < wwi.count; ++i) { Pair acc = wwi.acceleration[i]; fixVectorBounds(acc, m_minAcceleration, m_maxAcceleration); #if defined COMPUTE_STATS computeVectorBounds(acc, accBound); #endif Pair& vel = wwi.velocity[i]; vel.x = acc.x * time + vel.x * m_drag; vel.y = acc.y * time + vel.y * m_drag; acc_sum += fabs(acc.x) + fabs(acc.y); } heightRingLinearMean(&wwi.velocity, wwi); // compute the new pos of each vertex. for (unsigned int i = 0; i < wwi.count; ++i) { Pair& pos = wwi.position[i]; Pair& vel = wwi.velocity[i]; fixVectorBounds(vel, m_minVelocity, m_maxVelocity); #if defined COMPUTE_STATS computeVectorBounds(vel, velBound); #endif pos.x += vel.x * time * m_move_factor; pos.y += vel.y * time * m_move_factor; vel_sum += fabs(vel.x) + fabs(vel.y); #if defined VERBOSE_MODE if (wwi.constraint[i]) { qCDebug(KWINEFFECTS) << "Constraint point ** vel : " << vel.x << "," << vel.y << " ** move : " << vel.x*time << "," << vel.y*time; } #endif } if (!wwi.can_wobble_top) { for (unsigned int i = 0; i < wwi.width; ++i) for (unsigned j = 0; j < wwi.width - 1; ++j) wwi.position[i+wwi.width*j].y = wwi.origin[i+wwi.width*j].y; } if (!wwi.can_wobble_bottom) { for (unsigned int i = wwi.width * (wwi.height - 1); i < wwi.count; ++i) for (unsigned j = 0; j < wwi.width - 1; ++j) wwi.position[i-wwi.width*j].y = wwi.origin[i-wwi.width*j].y; } if (!wwi.can_wobble_left) { for (unsigned int i = 0; i < wwi.count; i += wwi.width) for (unsigned j = 0; j < wwi.width - 1; ++j) wwi.position[i+j].x = wwi.origin[i+j].x; } if (!wwi.can_wobble_right) { for (unsigned int i = wwi.width - 1; i < wwi.count; i += wwi.width) for (unsigned j = 0; j < wwi.width - 1; ++j) wwi.position[i-j].x = wwi.origin[i-j].x; } #if defined VERBOSE_MODE # if defined COMPUTE_STATS qCDebug(KWINEFFECTS) << "Acceleration bounds (" << accBound.x << ", " << accBound.y << ")"; qCDebug(KWINEFFECTS) << "Velocity bounds (" << velBound.x << ", " << velBound.y << ")"; # endif qCDebug(KWINEFFECTS) << "sum_acc : " << acc_sum << " *** sum_vel :" << vel_sum; #endif if (wwi.status != Moving && acc_sum < m_stopAcceleration && vel_sum < m_stopVelocity) { if (wwi.status == Closing) { w->unrefWindow(); } freeWobblyInfo(wwi); windows.remove(w); if (windows.isEmpty()) effects->addRepaintFull(); return false; } return true; } void WobblyWindowsEffect::heightRingLinearMean(Pair** data_pointer, WindowWobblyInfos& wwi) { Pair* data = *data_pointer; Pair neibourgs[8]; // for corners // top-left { Pair& res = wwi.buffer[0]; Pair vit = data[0]; neibourgs[0] = data[1]; neibourgs[1] = data[wwi.width]; neibourgs[2] = data[wwi.width+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // top-right { Pair& res = wwi.buffer[wwi.width-1]; Pair vit = data[wwi.width-1]; neibourgs[0] = data[wwi.width-2]; neibourgs[1] = data[2*wwi.width-1]; neibourgs[2] = data[2*wwi.width-2]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // bottom-left { Pair& res = wwi.buffer[wwi.width*(wwi.height-1)]; Pair vit = data[wwi.width*(wwi.height-1)]; neibourgs[0] = data[wwi.width*(wwi.height-1)+1]; neibourgs[1] = data[wwi.width*(wwi.height-2)]; neibourgs[2] = data[wwi.width*(wwi.height-2)+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // bottom-right { Pair& res = wwi.buffer[wwi.count-1]; Pair vit = data[wwi.count-1]; neibourgs[0] = data[wwi.count-2]; neibourgs[1] = data[wwi.width*(wwi.height-1)-1]; neibourgs[2] = data[wwi.width*(wwi.height-1)-2]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + 3.0 * vit.x) / 6.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + 3.0 * vit.y) / 6.0; } // for borders // top border for (unsigned int i = 1; i < wwi.width - 1; ++i) { Pair& res = wwi.buffer[i]; Pair vit = data[i]; neibourgs[0] = data[i-1]; neibourgs[1] = data[i+1]; neibourgs[2] = data[i+wwi.width]; neibourgs[3] = data[i+wwi.width-1]; neibourgs[4] = data[i+wwi.width+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + neibourgs[3].x + neibourgs[4].x + 5.0 * vit.x) / 10.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + neibourgs[3].y + neibourgs[4].y + 5.0 * vit.y) / 10.0; } // bottom border for (unsigned int i = wwi.width * (wwi.height - 1) + 1; i < wwi.count - 1; ++i) { Pair& res = wwi.buffer[i]; Pair vit = data[i]; neibourgs[0] = data[i-1]; neibourgs[1] = data[i+1]; neibourgs[2] = data[i-wwi.width]; neibourgs[3] = data[i-wwi.width-1]; neibourgs[4] = data[i-wwi.width+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + neibourgs[3].x + neibourgs[4].x + 5.0 * vit.x) / 10.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + neibourgs[3].y + neibourgs[4].y + 5.0 * vit.y) / 10.0; } // left border for (unsigned int i = wwi.width; i < wwi.width*(wwi.height - 1); i += wwi.width) { Pair& res = wwi.buffer[i]; Pair vit = data[i]; neibourgs[0] = data[i+1]; neibourgs[1] = data[i-wwi.width]; neibourgs[2] = data[i+wwi.width]; neibourgs[3] = data[i-wwi.width+1]; neibourgs[4] = data[i+wwi.width+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + neibourgs[3].x + neibourgs[4].x + 5.0 * vit.x) / 10.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + neibourgs[3].y + neibourgs[4].y + 5.0 * vit.y) / 10.0; } // right border for (unsigned int i = 2 * wwi.width - 1; i < wwi.count - 1; i += wwi.width) { Pair& res = wwi.buffer[i]; Pair vit = data[i]; neibourgs[0] = data[i-1]; neibourgs[1] = data[i-wwi.width]; neibourgs[2] = data[i+wwi.width]; neibourgs[3] = data[i-wwi.width-1]; neibourgs[4] = data[i+wwi.width-1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + neibourgs[3].x + neibourgs[4].x + 5.0 * vit.x) / 10.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + neibourgs[3].y + neibourgs[4].y + 5.0 * vit.y) / 10.0; } // for the inner points for (unsigned int j = 1; j < wwi.height - 1; ++j) { for (unsigned int i = 1; i < wwi.width - 1; ++i) { unsigned int index = i + j * wwi.width; Pair& res = wwi.buffer[index]; Pair& vit = data[index]; neibourgs[0] = data[index-1]; neibourgs[1] = data[index+1]; neibourgs[2] = data[index-wwi.width]; neibourgs[3] = data[index+wwi.width]; neibourgs[4] = data[index-wwi.width-1]; neibourgs[5] = data[index-wwi.width+1]; neibourgs[6] = data[index+wwi.width-1]; neibourgs[7] = data[index+wwi.width+1]; res.x = (neibourgs[0].x + neibourgs[1].x + neibourgs[2].x + neibourgs[3].x + neibourgs[4].x + neibourgs[5].x + neibourgs[6].x + neibourgs[7].x + 8.0 * vit.x) / 16.0; res.y = (neibourgs[0].y + neibourgs[1].y + neibourgs[2].y + neibourgs[3].y + neibourgs[4].y + neibourgs[5].y + neibourgs[6].y + neibourgs[7].y + 8.0 * vit.y) / 16.0; } } Pair* tmp = data; *data_pointer = wwi.buffer; wwi.buffer = tmp; } bool WobblyWindowsEffect::isActive() const { return !windows.isEmpty(); } } // namespace KWin diff --git a/libkwineffects/CMakeLists.txt b/libkwineffects/CMakeLists.txt index 661d56161..d22c1db90 100644 --- a/libkwineffects/CMakeLists.txt +++ b/libkwineffects/CMakeLists.txt @@ -1,127 +1,127 @@ ########### next target ############### include(ECMSetupVersion) ecm_setup_version(${PROJECT_VERSION} VARIABLE_PREFIX KWINEFFECTS VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kwineffects_version.h" PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KWinEffectsConfigVersion.cmake" - SOVERSION 8 + SOVERSION 9 ) ### xrenderutils lib ### set(kwin_XRENDERUTILS_SRCS kwinxrenderutils.cpp logging.cpp ) add_library(kwinxrenderutils SHARED ${kwin_XRENDERUTILS_SRCS}) generate_export_header(kwinxrenderutils EXPORT_FILE_NAME kwinxrenderutils_export.h) target_link_libraries(kwinxrenderutils PUBLIC Qt5::Core Qt5::Gui XCB::XCB XCB::XFIXES XCB::RENDER KF5::WaylandServer ) set_target_properties(kwinxrenderutils PROPERTIES VERSION ${KWINEFFECTS_VERSION_STRING} SOVERSION ${KWINEFFECTS_SOVERSION} ) set_target_properties(kwinxrenderutils PROPERTIES OUTPUT_NAME ${KWIN_NAME}xrenderutils) install(TARGETS kwinxrenderutils EXPORT kdeworkspaceLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) ### effects lib ### set(kwin_EFFECTSLIB_SRCS kwineffects.cpp anidata.cpp kwinanimationeffect.cpp logging.cpp ) set(kwineffects_QT_LIBS Qt5::DBus Qt5::Widgets Qt5::X11Extras ) set(kwineffects_KDE_LIBS KF5::ConfigCore KF5::CoreAddons KF5::WindowSystem ) set(kwineffects_XCB_LIBS XCB::XCB ) add_library(kwineffects SHARED ${kwin_EFFECTSLIB_SRCS}) generate_export_header(kwineffects EXPORT_FILE_NAME kwineffects_export.h) target_link_libraries(kwineffects PUBLIC ${kwineffects_QT_LIBS} ${kwineffects_KDE_LIBS} ${kwineffects_XCB_LIBS} ) if( KWIN_HAVE_XRENDER_COMPOSITING ) target_link_libraries(kwineffects PRIVATE kwinxrenderutils XCB::XFIXES) endif() set_target_properties(kwineffects PROPERTIES VERSION ${KWINEFFECTS_VERSION_STRING} SOVERSION ${KWINEFFECTS_SOVERSION} ) set_target_properties(kwineffects PROPERTIES OUTPUT_NAME ${KWIN_NAME}effects) install(TARGETS kwineffects EXPORT kdeworkspaceLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) # kwingl(es)utils library set(kwin_GLUTILSLIB_SRCS kwinglutils.cpp kwingltexture.cpp kwinglutils_funcs.cpp kwinglplatform.cpp kwinglcolorcorrection.cpp logging.cpp ) macro( KWIN4_ADD_GLUTILS_BACKEND name glinclude ) include_directories(${glinclude}) add_library(${name} SHARED ${kwin_GLUTILSLIB_SRCS}) generate_export_header(${name} BASE_NAME kwinglutils EXPORT_FILE_NAME kwinglutils_export.h) target_link_libraries(${name} PUBLIC Qt5::DBus Qt5::X11Extras XCB::XCB KF5::CoreAddons KF5::WindowSystem) set_target_properties(${name} PROPERTIES VERSION ${KWINEFFECTS_VERSION_STRING} SOVERSION ${KWINEFFECTS_SOVERSION} ) target_link_libraries(${name} PUBLIC ${ARGN}) install(TARGETS ${name} EXPORT kdeworkspaceLibraryTargets ${INSTALL_TARGETS_DEFAULT_ARGS}) endmacro() kwin4_add_glutils_backend(kwinglutils ${epoxy_INCLUDE_DIR} ${epoxy_LIBRARY}) set_target_properties(kwinglutils PROPERTIES OUTPUT_NAME ${KWIN_NAME}glutils) target_link_libraries(kwinglutils PUBLIC ${epoxy_LIBRARY}) # -ldl used by OpenGL code find_library(DL_LIBRARY dl) if (DL_LIBRARY) target_link_libraries(kwinglutils PRIVATE ${DL_LIBRARY}) endif() install( FILES kwinglobals.h kwineffects.h kwinanimationeffect.h kwinglplatform.h kwinglutils.h kwinglutils_funcs.h kwingltexture.h kwinxrenderutils.h ${CMAKE_CURRENT_BINARY_DIR}/kwinconfig.h ${CMAKE_CURRENT_BINARY_DIR}/kwineffects_export.h ${CMAKE_CURRENT_BINARY_DIR}/kwinglutils_export.h ${CMAKE_CURRENT_BINARY_DIR}/kwinxrenderutils_export.h DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel) diff --git a/libkwineffects/kwineffects.h b/libkwineffects/kwineffects.h index 555bef821..721084cf4 100644 --- a/libkwineffects/kwineffects.h +++ b/libkwineffects/kwineffects.h @@ -1,3213 +1,3223 @@ /******************************************************************** 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 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 class KConfigGroup; class QFont; class QGraphicsScale; class QKeyEvent; class QMatrix4x4; /** * Logging category to be used inside the KWin effects. * Do not use in this library. **/ Q_DECLARE_LOGGING_CATEGORY(KWINEFFECTS) namespace KWayland { namespace Server { class SurfaceInterface; class Display; } } namespace KWin { class PaintDataPrivate; class WindowPaintDataPrivate; class EffectWindow; class EffectWindowGroup; class EffectFrame; class EffectFramePrivate; class Effect; class WindowQuad; class GLShader; class XRenderPicture; class WindowQuadList; class WindowPrePaintData; class WindowPaintData; class ScreenPrePaintData; class ScreenPaintData; typedef QPair< QString, Effect* > EffectPair; typedef QList< KWin::EffectWindow* > EffectWindowList; /** @defgroup kwineffects KWin effects library * KWin effects library contains necessary classes for creating new KWin * compositing effects. * * @section creating Creating new effects * This example will demonstrate the basics of creating an effect. We'll use * CoolEffect as the class name, cooleffect as internal name and * "Cool Effect" as user-visible name of the effect. * * This example doesn't demonstrate how to write the effect's code. For that, * see the documentation of the Effect class. * * @subsection creating-class CoolEffect class * First you need to create CoolEffect class which has to be a subclass of * @ref KWin::Effect. In that class you can reimplement various virtual * methods to control how and where the windows are drawn. * * @subsection creating-macro KWIN_EFFECT_FACTORY macro * This library provides a specialized KPluginFactory subclass and macros to * create a sub class. This subclass of KPluginFactory has to be used, otherwise * KWin won't load the plugin. Use the @ref KWIN_EFFECT_FACTORY macro to create the * plugin factory. * * @subsection creating-buildsystem Buildsystem * To build the effect, you can use the KWIN_ADD_EFFECT() cmake macro which * can be found in effects/CMakeLists.txt file in KWin's source. First * argument of the macro is the name of the library that will contain * your effect. Although not strictly required, it is usually a good idea to * use the same name as your effect's internal name there. Following arguments * to the macro are the files containing your effect's source. If our effect's * source is in cooleffect.cpp, we'd use following: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * @endcode * * This macro takes care of compiling your effect. You'll also need to install * your effect's .desktop file, so the example CMakeLists.txt file would be * as follows: * @code * KWIN_ADD_EFFECT(cooleffect cooleffect.cpp) * install( FILES cooleffect.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kwin ) * @endcode * * @subsection creating-desktop Effect's .desktop file * You will also need to create .desktop file to set name, description, icon * and other properties of your effect. Important fields of the .desktop file * are: * @li Name User-visible name of your effect * @li Icon Name of the icon of the effect * @li Comment Short description of the effect * @li Type must be "Service" * @li X-KDE-ServiceTypes must be "KWin/Effect" * @li X-KDE-PluginInfo-Name effect's internal name as passed to the KWIN_EFFECT macro plus "kwin4_effect_" prefix * @li X-KDE-PluginInfo-Category effect's category. Should be one of Appearance, Accessibility, Window Management, Demos, Tests, Misc * @li X-KDE-PluginInfo-EnabledByDefault whether the effect should be enabled by default (use sparingly). Default is false * @li X-KDE-Library name of the library containing the effect. This is the first argument passed to the KWIN_ADD_EFFECT macro in cmake file plus "kwin4_effect_" prefix. * * Example cooleffect.desktop file follows: * @code [Desktop Entry] Name=Cool Effect Comment=The coolest effect you've ever seen Icon=preferences-system-windows-effect-cooleffect Type=Service X-KDE-ServiceTypes=KWin/Effect X-KDE-PluginInfo-Author=My Name X-KDE-PluginInfo-Email=my@email.here X-KDE-PluginInfo-Name=kwin4_effect_cooleffect X-KDE-PluginInfo-Category=Misc X-KDE-Library=kwin4_effect_cooleffect * @endcode * * * @section accessing Accessing windows and workspace * Effects can gain access to the properties of windows and workspace via * EffectWindow and EffectsHandler classes. * * There is one global EffectsHandler object which you can access using the * @ref effects pointer. * For each window, there is an EffectWindow object which can be used to read * window properties such as position and also to change them. * * For more information about this, see the documentation of the corresponding * classes. * * @{ **/ #define KWIN_EFFECT_API_MAKE_VERSION( major, minor ) (( major ) << 8 | ( minor )) #define KWIN_EFFECT_API_VERSION_MAJOR 0 #define KWIN_EFFECT_API_VERSION_MINOR 224 #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, ScreenInversion, Blur, Contrast }; /** * Constructs new Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is constructed. **/ Effect(); /** * Destructs the Effect object. * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is destroyed. **/ virtual ~Effect(); /** * Flags describing which parts of configuration have changed. */ enum ReconfigureFlag { ReconfigureAll = 1 << 0 /// Everything needs to be reconfigured. }; Q_DECLARE_FLAGS(ReconfigureFlags, ReconfigureFlag) /** * Called when configuration changes (either the effect's or KWin's global). * * In OpenGL based compositing, the frameworks ensures that the context is current * when the Effect is reconfigured. If this method is called from within the Effect it is * required to ensure that the context is current if the implementation does OpenGL calls. */ virtual void reconfigure(ReconfigureFlags flags); /** * Called when another effect requests the proxy for this effect. */ virtual void* proxy(); /** * Called before starting to paint the screen. * In this method you can: * @li set whether the windows or the entire screen will be transformed * @li change the region of the screen that will be painted * @li do various housekeeping tasks such as initing your effect's variables for the upcoming paint pass or updating animation's progress * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintScreen(ScreenPrePaintData& data, int time); /** * In this method you can: * @li paint something on top of the windows (by painting after calling * effects->paintScreen()) * @li paint multiple desktops and/or multiple copies of the same desktop * by calling effects->paintScreen() multiple times * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data); /** * Called after all the painting has been finished. * In this method you can: * @li schedule next repaint in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintScreen(); /** * Called for every window before the actual paint pass * In this method you can: * @li enable or disable painting of the window (e.g. enable paiting of minimized window) * @li set window to be painted with translucency * @li set window to be transformed * @li request the window to be divided into multiple parts * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time); /** * This is the main method for painting windows. * In this method you can: * @li do various transformations * @li change opacity of the window * @li change brightness and/or saturation, if it's supported * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Called for every window after all painting has been finished. * In this method you can: * @li schedule next repaint for individual window(s) in case of animations * You shouldn't paint anything here. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void postPaintWindow(EffectWindow* w); /** * This method is called directly before painting an @ref EffectFrame. * You can implement this method if you need to bind a shader or perform * other operations before the frame is rendered. * @param frame The EffectFrame which will be rendered * @param region Region to restrict painting to * @param opacity Opacity of text/icon * @param frameOpacity Opacity of background * @since 4.6 * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity); /** * Called on Transparent resizes. * return true if your effect substitutes questioned feature */ virtual bool provides(Feature); /** * Can be called to draw multiple copies (e.g. thumbnails) of a window. * You can change window's opacity/brightness/etc here, but you can't * do any transformations. * * In OpenGL based compositing, the frameworks ensures that the context is current * when this method is invoked. **/ virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data); /** * Define new window quads so that they can be transformed by other effects. * It's up to the effect to keep track of them. **/ virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList); virtual void windowInputMouseEvent(QEvent* e); virtual void grabbedKeyboardEvent(QKeyEvent* e); /** * Overwrite this method to indicate whether your effect will be doing something in * the next frame to be rendered. If the method returns @c false the effect will be * excluded from the chained methods in the next rendered frame. * * This method is called always directly before the paint loop begins. So it is totally * fine to e.g. react on a window event, issue a repaint to trigger an animation and * change a flag to indicate that this method returns @c true. * * As the method is called each frame, you should not perform complex calculations. * Best use just a boolean flag. * * The default implementation of this method returns @c true. * @since 4.8 **/ virtual bool isActive() const; /** * Reimplement this method to provide online debugging. * This could be as trivial as printing specific detail informations 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; 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; }; /** * Prefer the KWIN_EFFECT_FACTORY macros. */ class KWINEFFECTS_EXPORT EffectPluginFactory : public KPluginFactory { Q_OBJECT public: EffectPluginFactory(); virtual ~EffectPluginFactory(); /** * Returns whether the Effect is supported. * * An Effect can implement this method to determine at runtime whether the Effect is supported. * * If the current compositing backend is not supported it should return @c false. * * This method is optional, by default @c true is returned. */ virtual bool isSupported() const; /** * Returns whether the Effect should get enabled by default. * * This function provides a way for an effect to override the default at runtime, * e.g. based on the capabilities of the hardware. * * This method is optional; the effect doesn't have to provide it. * * Note that this function is only called if the supported() function returns true, * and if X-KDE-PluginInfo-EnabledByDefault is set to true in the .desktop file. * * This method is optional, by default @c true is returned. */ virtual bool enabledByDefault() const; /** * This method returns the created Effect. */ virtual KWin::Effect *createEffect() const = 0; }; /** * Defines an EffectPluginFactory sub class with customized isSupported and enabledByDefault methods. * * If the Effect to be created does not need the isSupported or enabledByDefault methods prefer * the simplified KWIN_EFFECT_FACTORY, KWIN_EFFECT_FACTORY_SUPPORTED or KWIN_EFFECT_FACTORY_ENABLED * macros which create an EffectPluginFactory with a useable default value. * * The macro also adds a useable K_EXPORT_PLUGIN_VERSION to the definition. KWin will not load * any Effect with a non-matching plugin version. This API is not providing binary compatibility * and thus the effect plugin must be compiled against the same kwineffects library version as * KWin. * * @param factoryName The name to be used for the EffectPluginFactory * @param className The class name of the Effect sub class which is to be created by the factory * @param jsonFile Name of the json file to be compiled into the plugin as metadata * @param supported Source code to go into the isSupported() method, must return a boolean * @param enabled Source code to go into the enabledByDefault() method, must return a boolean **/ #define KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, enabled ) \ class factoryName : public KWin::EffectPluginFactory \ { \ Q_OBJECT \ Q_PLUGIN_METADATA(IID KPluginFactory_iid FILE jsonFile) \ Q_INTERFACES(KPluginFactory) \ public: \ explicit factoryName() {} \ ~factoryName() {} \ bool isSupported() const override { \ supported \ } \ bool enabledByDefault() const override { \ enabled \ } \ KWin::Effect *createEffect() const override { \ return new className(); \ } \ }; \ K_EXPORT_PLUGIN_VERSION(quint32(KWIN_EFFECT_API_VERSION)) #define KWIN_EFFECT_FACTORY_ENABLED( factoryName, className, jsonFile, enabled ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, enabled ) #define KWIN_EFFECT_FACTORY_SUPPORTED( factoryName, classname, jsonFile, supported ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, supported, return true; ) #define KWIN_EFFECT_FACTORY( factoryName, classname, jsonFile ) \ KWIN_EFFECT_FACTORY_SUPPORTED_ENABLED( factoryName, className, jsonFile, return true;, return true; ) /** * @short Manager class that handles all the effects. * * This class creates Effect objects and calls it's appropriate methods. * * Effect objects can call methods of this class to interact with the * workspace, e.g. to activate or move a specific window, change current * desktop or create a special input window to receive mouse and keyboard * events. **/ class KWINEFFECTS_EXPORT EffectsHandler : public QObject { Q_OBJECT Q_PROPERTY(int currentDesktop READ currentDesktop WRITE setCurrentDesktop NOTIFY desktopChanged) Q_PROPERTY(QString currentActivity READ currentActivity NOTIFY currentActivityChanged) Q_PROPERTY(KWin::EffectWindow *activeWindow READ activeWindow WRITE activateWindow NOTIFY windowActivated) Q_PROPERTY(QSize desktopGridSize READ desktopGridSize) Q_PROPERTY(int desktopGridWidth READ desktopGridWidth) Q_PROPERTY(int desktopGridHeight READ desktopGridHeight) Q_PROPERTY(int workspaceWidth READ workspaceWidth) Q_PROPERTY(int workspaceHeight READ workspaceHeight) /** * The number of desktops currently used. Minimum number of desktops is 1, maximum 20. **/ Q_PROPERTY(int desktops READ numberOfDesktops WRITE setNumberOfDesktops NOTIFY numberDesktopsChanged) Q_PROPERTY(bool optionRollOverDesktops READ optionRollOverDesktops) Q_PROPERTY(int activeScreen READ activeScreen) Q_PROPERTY(int numScreens READ numScreens NOTIFY numberScreensChanged) /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ Q_PROPERTY(qreal animationTimeFactor READ animationTimeFactor) Q_PROPERTY(QList< KWin::EffectWindow* > stackingOrder READ stackingOrder) /** * Whether window decorations use the alpha channel. **/ Q_PROPERTY(bool decorationsHaveAlpha READ decorationsHaveAlpha) /** * Whether the window decorations support blurring behind the decoration. **/ Q_PROPERTY(bool decorationSupportsBlurBehind READ decorationSupportsBlurBehind) Q_PROPERTY(CompositingType compositingType READ compositingType CONSTANT) Q_PROPERTY(QPoint cursorPos READ cursorPos) Q_PROPERTY(QSize virtualScreenSize READ virtualScreenSize NOTIFY virtualScreenSizeChanged) Q_PROPERTY(QRect virtualScreenGeometry READ virtualScreenGeometry NOTIFY virtualScreenGeometryChanged) friend class Effect; public: explicit EffectsHandler(CompositingType type); virtual ~EffectsHandler(); // for use by effects virtual void prePaintScreen(ScreenPrePaintData& data, int time) = 0; virtual void paintScreen(int mask, QRegion region, ScreenPaintData& data) = 0; virtual void postPaintScreen() = 0; virtual void prePaintWindow(EffectWindow* w, WindowPrePaintData& data, int time) = 0; virtual void paintWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void postPaintWindow(EffectWindow* w) = 0; virtual void paintEffectFrame(EffectFrame* frame, QRegion region, double opacity, double frameOpacity) = 0; virtual void drawWindow(EffectWindow* w, int mask, QRegion region, WindowPaintData& data) = 0; virtual void buildQuads(EffectWindow* w, WindowQuadList& quadList) = 0; virtual QVariant kwinOption(KWinOption kwopt) = 0; /** * Sets the cursor while the mouse is intercepted. * @see startMouseInterception * @since 4.11 **/ virtual void defineCursor(Qt::CursorShape shape) = 0; virtual QPoint cursorPos() const = 0; virtual bool grabKeyboard(Effect* effect) = 0; virtual void ungrabKeyboard() = 0; /** * Ensures that all mouse events are sent to the @p effect. * No window will get the mouse events. Only fullscreen effects providing a custom user interface should * be using this method. The input events are delivered to Effect::windowInputMouseEvent. * * NOTE: this method does not perform an X11 mouse grab. On X11 a fullscreen input window is raised above * all other windows, but no grab is performed. * * @param shape Sets the cursor to be used while the mouse is intercepted * @see stopMouseInterception * @see Effect::windowInputMouseEvent * @since 4.11 **/ virtual void startMouseInterception(Effect *effect, Qt::CursorShape shape) = 0; /** * Releases the hold mouse interception for @p effect * @see startMouseInterception * @since 4.11 **/ virtual void stopMouseInterception(Effect *effect) = 0; /** * @brief Registers a global shortcut with the provided @p action. * * @param shortcut The global shortcut which should trigger the action * @param action The action which gets triggered when the shortcut matches */ virtual void registerGlobalShortcut(const QKeySequence &shortcut, QAction *action) = 0; /** * @brief Registers a global pointer shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param pointerButtons The pointer buttons which need to be pressed * @param action The action which gets triggered when the shortcut matches **/ virtual void registerPointerShortcut(Qt::KeyboardModifiers modifiers, Qt::MouseButton pointerButtons, QAction *action) = 0; /** * @brief Registers a global axis shortcut with the provided @p action. * * @param modifiers The keyboard modifiers which need to be holded * @param axis The direction in which the axis needs to be moved * @param action The action which gets triggered when the shortcut matches **/ virtual void registerAxisShortcut(Qt::KeyboardModifiers modifiers, PointerAxisDirection axis, QAction *action) = 0; /** * 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; // 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; Q_SCRIPTABLE virtual void windowToDesktop(KWin::EffectWindow* w, int desktop) = 0; Q_SCRIPTABLE virtual void windowToScreen(KWin::EffectWindow* w, int screen) = 0; virtual void setShowingDesktop(bool showing) = 0; // Activities /** * @returns The ID of the current activity. */ virtual QString currentActivity() const = 0; // Desktops /** * @returns The ID of the current desktop. */ virtual int currentDesktop() const = 0; /** * @returns Total number of desktops currently in existence. */ virtual int numberOfDesktops() const = 0; /** * Set the current desktop to @a desktop. */ virtual void setCurrentDesktop(int desktop) = 0; /** * Sets the total number of desktops to @a desktops. */ virtual void setNumberOfDesktops(int desktops) = 0; /** * @returns The size of desktop layout in grid units. */ virtual QSize desktopGridSize() const = 0; /** * @returns The width of desktop layout in grid units. */ virtual int desktopGridWidth() const = 0; /** * @returns The height of desktop layout in grid units. */ virtual int desktopGridHeight() const = 0; /** * @returns The width of desktop layout in pixels. */ virtual int workspaceWidth() const = 0; /** * @returns The height of desktop layout in pixels. */ virtual int workspaceHeight() const = 0; /** * @returns The ID of the desktop at the point @a coords or 0 if no desktop exists at that * point. @a coords is to be in grid units. */ virtual int desktopAtCoords(QPoint coords) const = 0; /** * @returns The coords of desktop @a id in grid units. */ virtual QPoint desktopGridCoords(int id) const = 0; /** * @returns The coords of the top-left corner of desktop @a id in pixels. */ virtual QPoint desktopCoords(int id) const = 0; /** * @returns The ID of the desktop above desktop @a id. Wraps around to the bottom of * the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopAbove(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the right of desktop @a id. Wraps around to the * left of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToRight(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop below desktop @a id. Wraps around to the top of the * layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopBelow(int desktop = 0, bool wrap = true) const = 0; /** * @returns The ID of the desktop to the left of desktop @a id. Wraps around to the * right of the layout if @a wrap is set. If @a id is not set use the current one. */ Q_SCRIPTABLE virtual int desktopToLeft(int desktop = 0, bool wrap = true) const = 0; Q_SCRIPTABLE virtual QString desktopName(int desktop) const = 0; virtual bool optionRollOverDesktops() const = 0; virtual int activeScreen() const = 0; // Xinerama virtual int numScreens() const = 0; // Xinerama Q_SCRIPTABLE virtual int screenNumber(const QPoint& pos) const = 0; // Xinerama virtual QRect clientArea(clientAreaOption, int screen, int desktop) const = 0; virtual QRect clientArea(clientAreaOption, const EffectWindow* c) const = 0; virtual QRect clientArea(clientAreaOption, const QPoint& p, int desktop) const = 0; /** * The bounding size of all screens combined. Overlapping areas * are not counted multiple times. * * @see virtualScreenGeometry() * @see virtualScreenSizeChanged() * @since 5.0 **/ virtual QSize virtualScreenSize() const = 0; /** * The bounding geometry of all outputs combined. Always starts at (0,0) and has * virtualScreenSize as it's size. * * @see virtualScreenSize() * @see virtualScreenGeometryChanged() * @since 5.0 **/ virtual QRect virtualScreenGeometry() const = 0; /** * Factor by which animation speed in the effect should be modified (multiplied). * If configurable in the effect itself, the option should have also 'default' * animation speed. The actual value should be determined using animationTime(). * Note: The factor can be also 0, so make sure your code can cope with 0ms time * if used manually. */ virtual double animationTimeFactor() const = 0; virtual WindowQuadType newWindowQuadType() = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(WId id) const = 0; Q_SCRIPTABLE virtual KWin::EffectWindow* findWindow(KWayland::Server::SurfaceInterface *surf) const = 0; virtual EffectWindowList stackingOrder() const = 0; // window will be temporarily painted as if being at the top of the stack Q_SCRIPTABLE virtual void setElevatedWindow(KWin::EffectWindow* w, bool set) = 0; virtual void setTabBoxWindow(EffectWindow*) = 0; virtual void setTabBoxDesktop(int) = 0; virtual EffectWindowList currentTabBoxWindowList() const = 0; virtual void refTabBox() = 0; virtual void unrefTabBox() = 0; virtual void closeTabBox() = 0; virtual QList< int > currentTabBoxDesktopList() const = 0; virtual int currentTabBoxDesktop() const = 0; virtual EffectWindow* currentTabBoxWindow() const = 0; virtual void setActiveFullScreenEffect(Effect* e) = 0; virtual Effect* activeFullScreenEffect() const = 0; /** * Schedules the entire workspace to be repainted next time. * If you call it during painting (including prepaint) then it does not * affect the current painting. **/ Q_SCRIPTABLE virtual void addRepaintFull() = 0; Q_SCRIPTABLE virtual void addRepaint(const QRect& r) = 0; Q_SCRIPTABLE virtual void addRepaint(const QRegion& r) = 0; Q_SCRIPTABLE virtual void addRepaint(int x, int y, int w, int h) = 0; CompositingType compositingType() const; /** * @brief Whether the Compositor is OpenGL based (either GL 1 or 2). * * @return bool @c true in case of OpenGL based Compositor, @c false otherwise **/ bool isOpenGLCompositing() const; virtual unsigned long xrenderBufferPicture() = 0; /** * @brief Provides access to the QPainter which is rendering to the back buffer. * * Only relevant for CompositingType QPainterCompositing. For all other compositing types * @c null is returned. * * @return QPainter* The Scene's QPainter or @c null. */ virtual QPainter *scenePainter() = 0; virtual void reconfigure() = 0; /** Makes KWin core watch PropertyNotify events for the given atom, or stops watching if reg is false (must be called the same number of times as registering). Events are sent using Effect::propertyNotify(). Note that even events that haven't been registered for can be received. */ virtual void registerPropertyType(long atom, bool reg) = 0; virtual QByteArray readRootProperty(long atom, long type, int format) const = 0; virtual void deleteRootProperty(long atom) const = 0; /** * @brief Announces support for the feature with the given name. If no other Effect * has announced support for this feature yet, an X11 property will be installed on * the root window. * * The Effect will be notified for events through the signal propertyNotify(). * * To remove the support again use @link removeSupportProperty. When an Effect is * destroyed it is automatically taken care of removing the support. It is not * required to call @link removeSupportProperty in the Effect's cleanup handling. * * @param propertyName The name of the property to announce support for * @param effect The effect which announces support * @return xcb_atom_t The created X11 atom * @see removeSupportProperty * @since 4.11 **/ virtual xcb_atom_t announceSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * @brief Removes support for the feature with the given name. If there is no other Effect left * which has announced support for the given property, the property will be removed from the * root window. * * In case the Effect had not registered support, calling this function does not change anything. * * @param propertyName The name of the property to remove support for * @param effect The effect which had registered the property. * @see announceSupportProperty * @since 4.11 **/ virtual void removeSupportProperty(const QByteArray &propertyName, Effect *effect) = 0; /** * Returns @a true if the active window decoration has shadow API hooks. */ virtual bool hasDecorationShadows() const = 0; /** * Returns @a true if the window decorations use the alpha channel, and @a false otherwise. * @since 4.5 */ virtual bool decorationsHaveAlpha() const = 0; /** * Returns @a true if the window decorations support blurring behind the decoration, and @a false otherwise * @since 4.6 */ virtual bool decorationSupportsBlurBehind() const = 0; /** * Creates a new frame object. If the frame does not have a static size * then it will be located at @a position with @a alignment. A * non-static frame will automatically adjust its size to fit the contents. * @returns A new @ref EffectFrame. It is the responsibility of the caller to delete the * EffectFrame. * @since 4.6 */ virtual EffectFrame* effectFrame(EffectFrameStyle style, bool staticSize = true, const QPoint& position = QPoint(-1, -1), Qt::Alignment alignment = Qt::AlignCenter) const = 0; /** * Allows an effect to trigger a reload of itself. * This can be used by an effect which needs to be reloaded when screen geometry changes. * It is possible that the effect cannot be loaded again as it's supported method does no longer * hold. * @param effect The effect to reload * @since 4.8 **/ virtual void reloadEffect(Effect *effect) = 0; /** * Whether the screen is currently considered as locked. * Note for technical reasons this is not always possible to detect. The screen will only * be considered as locked if the screen locking process implements the * org.freedesktop.ScreenSaver interface. * * @returns @c true if the screen is currently locked, @c false otherwise * @see screenLockingChanged * @since 4.11 **/ virtual bool isScreenLocked() const = 0; /** * @brief Makes the OpenGL compositing context current. * * If the compositing backend is not using OpenGL, this method returns @c false. * * @return bool @c true if the context became current, @c false otherwise. */ virtual bool makeOpenGLContextCurrent() = 0; /** * @brief Makes a null OpenGL context current resulting in no context * being current. * * If the compositing backend is not OpenGL based, this method is a noop. * * There is normally no reason for an Effect to call this method. */ virtual void doneOpenGLContextCurrent() = 0; virtual xcb_connection_t *xcbConnection() const = 0; virtual xcb_window_t x11RootWindow() const = 0; /** * Interface to the Wayland display: this is relevant only * on Wayland, on X11 it will be nullptr * @since 5.5 */ virtual KWayland::Server::Display *waylandDisplay() const = 0; + /** + * Whether animations are supported by the Scene. + * If this method returns @c false Effects are supposed to not + * animate transitions. + * + * @returns Whether the Scene can drive animations + * @since 5.8 + **/ + virtual bool animationsSupported() const = 0; + /** * @return @ref KConfigGroup which holds given effect's config options **/ static KConfigGroup effectConfig(const QString& effectname); Q_SIGNALS: /** * Signal emitted when the current desktop changed. * @param oldDesktop The previously current desktop * @param newDesktop The new current desktop * @param with The window which is taken over to the new desktop, can be NULL * @since 4.9 */ void desktopChanged(int oldDesktop, int newDesktop, KWin::EffectWindow *with); /** * @since 4.7 * @deprecated */ void desktopChanged(int oldDesktop, int newDesktop); /** * Signal emitted when a window moved to another desktop * NOTICE that this does NOT imply that the desktop has changed * The @param window which is moved to the new desktop * @param oldDesktop The previous desktop of the window * @param newDesktop The new desktop of the window * @since 4.11.4 */ void desktopPresenceChanged(KWin::EffectWindow *window, int oldDesktop, int newDesktop); /** * Signal emitted when the number of currently existing desktops is changed. * @param old The previous number of desktops in used. * @see EffectsHandler::numberOfDesktops. * @since 4.7 */ void numberDesktopsChanged(uint old); /** * Signal emitted when the number of screens changed. * @since 5.0 **/ void numberScreensChanged(); /** * Signal emitted when the desktop showing ("dashboard") state changed * The desktop is risen to the keepAbove layer, you may want to elevate * windows or such. * @since 5.3 **/ void showingDesktopChanged(bool); /** * Signal emitted when a new window has been added to the Workspace. * @param w The added window * @since 4.7 **/ void windowAdded(KWin::EffectWindow *w); /** * Signal emitted when a window is being removed from the Workspace. * An effect which wants to animate the window closing should connect * to this signal and reference the window by using * @link EffectWindow::refWindow * @param w The window which is being closed * @since 4.7 **/ void windowClosed(KWin::EffectWindow *w); /** * Signal emitted when a window get's activated. * @param w The new active window, or @c NULL if there is no active window. * @since 4.7 **/ void windowActivated(KWin::EffectWindow *w); /** * Signal emitted when a window is deleted. * This means that a closed window is not referenced any more. * An effect bookkeeping the closed windows should connect to this * signal to clean up the internal references. * @param w The window which is going to be deleted. * @see EffectWindow::refWindow * @see EffectWindow::unrefWindow * @see windowClosed * @since 4.7 **/ void windowDeleted(KWin::EffectWindow *w); /** * Signal emitted when a user begins a window move or resize operation. * To figure out whether the user resizes or moves the window use * @link EffectWindow::isUserMove or @link EffectWindow::isUserResize. * Whenever the geometry is updated the signal @link windowStepUserMovedResized * is emitted with the current geometry. * The move/resize operation ends with the signal @link windowFinishUserMovedResized. * Only one window can be moved/resized by the user at the same time! * @param w The window which is being moved/resized * @see windowStepUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStartUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted during a move/resize operation when the user changed the geometry. * Please note: KWin supports two operation modes. In one mode all changes are applied * instantly. This means the window's geometry matches the passed in @p geometry. In the * other mode the geometry is changed after the user ended the move/resize mode. * The @p geometry differs from the window's geometry. Also the window's pixmap still has * the same size as before. Depending what the effect wants to do it would be recommended * to scale/translate the window. * @param w The window which is being moved/resized * @param geometry The geometry of the window in the current move/resize step. * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @see EffectWindow::isUserMove * @see EffectWindow::isUserResize * @since 4.7 **/ void windowStepUserMovedResized(KWin::EffectWindow *w, const QRect &geometry); /** * Signal emitted when the user finishes move/resize of window @p w. * @param w The window which has been moved/resized * @see windowStartUserMovedResized * @see windowFinishUserMovedResized * @since 4.7 **/ void windowFinishUserMovedResized(KWin::EffectWindow *w); /** * Signal emitted when the maximized state of the window @p w changed. * A window can be in one of four states: * @li restored: both @p horizontal and @p vertical are @c false * @li horizontally maximized: @p horizontal is @c true and @p vertical is @c false * @li vertically maximized: @p horizontal is @c false and @p vertical is @c true * @li completely maximized: both @p horizontal and @p vertical are @C true * @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 an area of a window is scheduled for repainting. * Use this signal in an effect if another area needs to be synced as well. * @param w The window which is scheduled for repainting * @param r Always empty. * @since 4.7 **/ void windowDamaged(KWin::EffectWindow *w, const QRect &r); /** * Signal emitted when a tabbox is added. * An effect who wants to replace the tabbox with itself should use @link refTabBox. * @param mode The TabBoxMode. * @see refTabBox * @see tabBoxClosed * @see tabBoxUpdated * @see tabBoxKeyEvent * @since 4.7 **/ void tabBoxAdded(int mode); /** * Signal emitted when the TabBox was closed by KWin core. * An effect which referenced the TabBox should use @link unrefTabBox to unref again. * @see unrefTabBox * @see tabBoxAdded * @since 4.7 **/ void tabBoxClosed(); /** * Signal emitted when the selected TabBox window changed or the TabBox List changed. * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. * @see refTabBox * @see currentTabBoxWindowList * @see currentTabBoxDesktopList * @see currentTabBoxWindow * @see currentTabBoxDesktop * @since 4.7 **/ void tabBoxUpdated(); /** * Signal emitted when a key event, which is not handled by TabBox directly is, happens while * TabBox is active. An effect might use the key event to e.g. change the selected window. * An effect should only response to this signal if it referenced the TabBox with @link refTabBox. * @param event The key event not handled by TabBox directly * @see refTabBox * @since 4.7 **/ void tabBoxKeyEvent(QKeyEvent* event); void currentTabAboutToChange(KWin::EffectWindow* from, KWin::EffectWindow* to); void tabAdded(KWin::EffectWindow* from, KWin::EffectWindow* to); // from merged with to void tabRemoved(KWin::EffectWindow* c, KWin::EffectWindow* group); // c removed from group /** * Signal emitted when mouse changed. * If an effect needs to get updated mouse positions, it needs to first call @link startMousePolling. * For a fullscreen effect it is better to use an input window and react on @link windowInputMouseEvent. * @param pos The new mouse position * @param oldpos The previously mouse position * @param buttons The pressed mouse buttons * @param oldbuttons The previously pressed mouse buttons * @param modifiers Pressed keyboard modifiers * @param oldmodifiers Previously pressed keyboard modifiers. * @see startMousePolling * @since 4.7 **/ void mouseChanged(const QPoint& pos, const QPoint& oldpos, Qt::MouseButtons buttons, Qt::MouseButtons oldbuttons, Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers oldmodifiers); /** * Signal emitted when the cursor shape changed. * You'll likely want to query the current cursor as reaction: xcb_xfixes_get_cursor_image_unchecked * Connection to this signal is tracked, so if you don't need it anymore, disconnect from it to stop cursor event filtering */ void cursorShapeChanged(); /** * Receives events registered for using @link registerPropertyType. * Use readProperty() to get the property data. * Note that the property may be already set on the window, so doing the same * processing from windowAdded() (e.g. simply calling propertyNotify() from it) * is usually needed. * @param w The window whose property changed, is @c null if it is a root window property * @param atom The property * @since 4.7 */ void propertyNotify(KWin::EffectWindow* w, long atom); /** * Signal emitted after the screen geometry changed (e.g. add of a monitor). * Effects using displayWidth()/displayHeight() to cache information should * react on this signal and update the caches. * @param size The new screen size * @since 4.8 **/ void screenGeometryChanged(const QSize &size); /** * This signal is emitted when the global * activity is changed * @param id id of the new current activity * @since 4.9 **/ void currentActivityChanged(const QString &id); /** * This signal is emitted when a new activity is added * @param id id of the new activity * @since 4.9 */ void activityAdded(const QString &id); /** * This signal is emitted when the activity * is removed * @param id id of the removed activity * @since 4.9 */ void activityRemoved(const QString &id); /** * This signal is emitted when the screen got locked or unlocked. * @param locked @c true if the screen is now locked, @c false if it is now unlocked * @since 4.11 **/ void screenLockingChanged(bool locked); /** * This signels is emitted when ever the stacking order is change, ie. a window is risen * or lowered * @since 4.10 */ void stackingOrderChanged(); /** * This signal is emitted when the user starts to approach the @p border with the mouse. * The @p factor describes how far away the mouse is in a relative mean. The values are in * [0.0, 1.0] with 0.0 being emitted when first entered and on leaving. The value 1.0 means that * the @p border is reached with the mouse. So the values are well suited for animations. * The signal is always emitted when the mouse cursor position changes. * @param border The screen edge which is being approached * @param factor Value in range [0.0,1.0] to describe how close the mouse is to the border * @param geometry The geometry of the edge which is being approached * @since 4.11 **/ void screenEdgeApproaching(ElectricBorder border, qreal factor, const QRect &geometry); /** * Emitted whenever the virtualScreenSize changes. * @see virtualScreenSize() * @since 5.0 **/ void virtualScreenSizeChanged(); /** * Emitted whenever the virtualScreenGeometry changes. * @see virtualScreenGeometry() * @since 5.0 **/ void virtualScreenGeometryChanged(); /** * The window @p w gets shown again. The window was previously * initially shown with @link{windowAdded} and hidden with @link{windowHidden}. * * @see windowHidden * @see windowAdded * @since 5.8 **/ void windowShown(KWin::EffectWindow *w); /** * The window @p w got hidden but not yet closed. * This can happen when a window is still being used and is supposed to be shown again * with @link{windowShown}. On X11 an example is autohiding panels. On Wayland every * window first goes through the window hidden state and might get shown again, or might * get closed the normal way. * * @see windowShown * @see windowClosed * @since 5.8 **/ void windowHidden(KWin::EffectWindow *w); protected: QVector< EffectPair > loaded_effects; //QHash< QString, EffectFactory* > effect_factories; CompositingType compositing_type; }; /** * @short Representation of a window used by/for Effect classes. * * The purpose is to hide internal data and also to serve as a single * representation for the case when Client/Unmanaged becomes Deleted. **/ class KWINEFFECTS_EXPORT EffectWindow : public QObject { Q_OBJECT Q_PROPERTY(bool alpha READ hasAlpha CONSTANT) Q_PROPERTY(QRect geometry READ geometry) Q_PROPERTY(QRect expandedGeometry READ expandedGeometry) Q_PROPERTY(int height READ height) Q_PROPERTY(qreal opacity READ opacity) Q_PROPERTY(QPoint pos READ pos) Q_PROPERTY(int screen READ screen) Q_PROPERTY(QSize size READ size) Q_PROPERTY(int width READ width) Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int desktop READ desktop) Q_PROPERTY(bool onAllDesktops READ isOnAllDesktops) Q_PROPERTY(bool onCurrentDesktop READ isOnCurrentDesktop) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QString windowClass READ windowClass) Q_PROPERTY(QString windowRole READ windowRole) /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool desktopWindow READ isDesktop) /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dock READ isDock) /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool toolbar READ isToolbar) /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool menu READ isMenu) /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool normalWindow READ isNormalWindow) /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dialog READ isDialog) /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool splash READ isSplash) /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool utility READ isUtility) /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dropdownMenu READ isDropdownMenu) /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool popupMenu READ isPopupMenu) /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool tooltip READ isTooltip) /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool notification READ isNotification) /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ Q_PROPERTY(bool onScreenDisplay READ isOnScreenDisplay) /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool comboBox READ isComboBox) /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(bool dndIcon READ isDNDIcon) /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ Q_PROPERTY(int windowType READ windowType) /** * Whether this EffectWindow is managed by KWin (it has control over its placement and other * aspects, as opposed to override-redirect windows that are entirely handled by the application). **/ Q_PROPERTY(bool managed READ isManaged) /** * Whether this EffectWindow represents an already deleted window and only kept for the compositor for animations. **/ Q_PROPERTY(bool deleted READ isDeleted) /** * Whether the window has an own shape **/ Q_PROPERTY(bool shaped READ hasOwnShape) /** * The Window's shape **/ Q_PROPERTY(QRegion shape READ shape) /** * The Caption of the window. Read from WM_NAME property together with a suffix for hostname and shortcut. **/ Q_PROPERTY(QString caption READ caption) /** * Whether the window is set to be kept above other windows. **/ Q_PROPERTY(bool keepAbove READ keepAbove) /** * Whether the window is minimized. **/ Q_PROPERTY(bool minimized READ isMinimized WRITE setMinimized) /** * Whether the window represents a modal window. **/ Q_PROPERTY(bool modal READ isModal) /** * Whether the window is moveable. Even if it is not moveable, it might be possible to move * it to another screen. * @see moveableAcrossScreens **/ Q_PROPERTY(bool moveable READ isMovable) /** * Whether the window can be moved to another screen. * @see moveable **/ Q_PROPERTY(bool moveableAcrossScreens READ isMovableAcrossScreens) /** * By how much the window wishes to grow/shrink at least. Usually QSize(1,1). * MAY BE DISOBEYED BY THE WM! It's only for information, do NOT rely on it at all. */ Q_PROPERTY(QSize basicUnit READ basicUnit) /** * Whether the window is currently being moved by the user. **/ Q_PROPERTY(bool move READ isUserMove) /** * Whether the window is currently being resized by the user. **/ Q_PROPERTY(bool resize READ isUserResize) /** * The optional geometry representing the minimized Client in e.g a taskbar. * See _NET_WM_ICON_GEOMETRY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . **/ Q_PROPERTY(QRect iconGeometry READ iconGeometry) /** * Returns whether the window is any of special windows types (desktop, dock, splash, ...), * i.e. window types that usually don't have a window frame and the user does not use window * management (moving, raising,...) on them. **/ Q_PROPERTY(bool specialWindow READ isSpecialWindow) Q_PROPERTY(QIcon icon READ icon) /** * Whether the window should be excluded from window switching effects. **/ Q_PROPERTY(bool skipSwitcher READ isSkipSwitcher) /** * Geometry of the actual window contents inside the whole (including decorations) window. */ Q_PROPERTY(QRect contentsRect READ contentsRect) /** * Geometry of the transparent rect in the decoration. * May be different from contentsRect if the decoration is extended into the client area. */ Q_PROPERTY(QRect decorationInnerRect READ decorationInnerRect) Q_PROPERTY(bool hasDecoration READ hasDecoration) Q_PROPERTY(QStringList activities READ activities) Q_PROPERTY(bool onCurrentActivity READ isOnCurrentActivity) Q_PROPERTY(bool onAllActivities READ isOnAllActivities) /** * Whether the decoration currently uses an alpha channel. * @since 4.10 **/ Q_PROPERTY(bool decorationHasAlpha READ decorationHasAlpha) /** * Whether the window is currently visible to the user, that is: *
    *
  • Not minimized
  • *
  • On current desktop
  • *
  • On current activity
  • *
* @since 4.11 **/ Q_PROPERTY(bool visible READ isVisible) /** * Whether the window does not want to be animated on window close. * In case this property is @c true it is not useful to start an animation on window close. * The window will not be visible, but the animation hooks are executed. * @since 5.0 **/ Q_PROPERTY(bool skipsCloseAnimation READ skipsCloseAnimation) /** * Interface to the corresponding wayland surface. * relevant only in Wayland, on X11 it will be nullptr */ Q_PROPERTY(KWayland::Server::SurfaceInterface *surface READ surface) /** * Whether the window is fullscreen. * @since 5.6 **/ Q_PROPERTY(bool fullScreen READ isFullScreen) public: /** Flags explaining why painting should be disabled */ enum { /** Window will not be painted */ PAINT_DISABLED = 1 << 0, /** Window will not be painted because it is deleted */ PAINT_DISABLED_BY_DELETE = 1 << 1, /** Window will not be painted because of which desktop it's on */ PAINT_DISABLED_BY_DESKTOP = 1 << 2, /** Window will not be painted because it is minimized */ PAINT_DISABLED_BY_MINIMIZE = 1 << 3, /** Window will not be painted because it is not the active window in a client group */ PAINT_DISABLED_BY_TAB_GROUP = 1 << 4, /** Window will not be painted because it's not on the current activity */ PAINT_DISABLED_BY_ACTIVITY = 1 << 5 }; explicit EffectWindow(QObject *parent = nullptr); virtual ~EffectWindow(); virtual void enablePainting(int reason) = 0; virtual void disablePainting(int reason) = 0; virtual bool isPaintingEnabled() = 0; Q_SCRIPTABLE void addRepaint(const QRect& r); Q_SCRIPTABLE void addRepaint(int x, int y, int w, int h); Q_SCRIPTABLE void addRepaintFull(); Q_SCRIPTABLE void addLayerRepaint(const QRect& r); Q_SCRIPTABLE void addLayerRepaint(int x, int y, int w, int h); virtual void refWindow() = 0; virtual void unrefWindow() = 0; bool isDeleted() const; bool isMinimized() const; double opacity() const; bool hasAlpha() const; bool isOnCurrentActivity() const; Q_SCRIPTABLE bool isOnActivity(QString id) const; bool isOnAllActivities() const; QStringList activities() const; bool isOnDesktop(int d) const; bool isOnCurrentDesktop() const; bool isOnAllDesktops() const; int desktop() const; // prefer isOnXXX() int x() const; int y() const; int width() const; int height() const; /** * 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. */ QSize basicUnit() const; QRect geometry() const; /** * Geometry of the window including decoration and potentially shadows. * May be different from geometry() if the window has a shadow. * @since 4.9 */ QRect expandedGeometry() const; virtual QRegion shape() const = 0; int screen() const; /** @internal Do not use */ bool hasOwnShape() const; // only for shadow effect, for now QPoint pos() const; QSize size() const; QRect rect() const; bool isMovable() const; bool isMovableAcrossScreens() const; bool isUserMove() const; bool isUserResize() const; QRect iconGeometry() const; /** * Geometry of the actual window contents inside the whole (including decorations) window. */ QRect contentsRect() const; /** * 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; bool decorationHasAlpha() const; virtual QByteArray readProperty(long atom, long type, int format) const = 0; virtual void deleteProperty(long atom) const = 0; QString caption() const; QIcon icon() const; QString windowClass() const; QString windowRole() const; virtual const EffectWindowGroup* group() const = 0; /** * Returns whether the window is a desktop background window (the one with wallpaper). * See _NET_WM_WINDOW_TYPE_DESKTOP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDesktop() const; /** * Returns whether the window is a dock (i.e. a panel). * See _NET_WM_WINDOW_TYPE_DOCK at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDock() const; /** * Returns whether the window is a standalone (detached) toolbar window. * See _NET_WM_WINDOW_TYPE_TOOLBAR at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isToolbar() const; /** * Returns whether the window is a torn-off menu. * See _NET_WM_WINDOW_TYPE_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isMenu() const; /** * Returns whether the window is a "normal" window, i.e. an application or any other window * for which none of the specialized window types fit. * See _NET_WM_WINDOW_TYPE_NORMAL at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isNormalWindow() const; // 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. */ bool isSpecialWindow() const; /** * Returns whether the window is a dialog window. * See _NET_WM_WINDOW_TYPE_DIALOG at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDialog() const; /** * Returns whether the window is a splashscreen. Note that many (especially older) applications * do not support marking their splash windows with this type. * See _NET_WM_WINDOW_TYPE_SPLASH at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isSplash() const; /** * Returns whether the window is a utility window, such as a tool window. * See _NET_WM_WINDOW_TYPE_UTILITY at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isUtility() const; /** * Returns whether the window is a dropdown menu (i.e. a popup directly or indirectly open * from the applications menubar). * See _NET_WM_WINDOW_TYPE_DROPDOWN_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDropdownMenu() const; /** * Returns whether the window is a popup menu (that is not a torn-off or dropdown menu). * See _NET_WM_WINDOW_TYPE_POPUP_MENU at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isPopupMenu() const; // a context popup, not dropdown, not torn-off /** * Returns whether the window is a tooltip. * See _NET_WM_WINDOW_TYPE_TOOLTIP at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isTooltip() const; /** * Returns whether the window is a window with a notification. * See _NET_WM_WINDOW_TYPE_NOTIFICATION at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isNotification() const; /** * Returns whether the window is an on screen display window * using the non-standard _KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY */ bool isOnScreenDisplay() const; /** * Returns whether the window is a combobox popup. * See _NET_WM_WINDOW_TYPE_COMBO at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isComboBox() const; /** * Returns whether the window is a Drag&Drop icon. * See _NET_WM_WINDOW_TYPE_DND at http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ bool isDNDIcon() const; /** * Returns the NETWM window type * See http://standards.freedesktop.org/wm-spec/wm-spec-latest.html . */ NET::WindowType windowType() const; /** * 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). */ bool isManaged() const; // whether it's managed or override-redirect /** * Returns whether or not the window can accept keyboard focus. */ bool acceptsFocus() const; /** * Returns whether or not the window is kept above all other windows. */ bool keepAbove() const; bool isModal() const; 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 */ bool isSkipSwitcher() const; /** * 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); void minimize(); void unminimize(); Q_SCRIPTABLE void closeWindow() const; bool isCurrentTab() const; /** * @since 4.11 **/ bool isVisible() const; /** * @since 5.0 **/ bool skipsCloseAnimation() const; /** * @since 5.5 */ KWayland::Server::SurfaceInterface *surface() const; /** * @since 5.6 **/ bool isFullScreen() const; /** * Can be used to by effects to store arbitrary data in the EffectWindow. */ Q_SCRIPTABLE virtual void setData(int role, const QVariant &data) = 0; Q_SCRIPTABLE virtual QVariant data(int role) const = 0; /** * @brief References the previous window pixmap to prevent discarding. * * This method allows to reference the previous window pixmap in case that a window changed * its size, which requires a new window pixmap. By referencing the previous (and then outdated) * window pixmap an effect can for example cross fade the current window pixmap with the previous * one. This allows for smoother transitions for window geometry changes. * * If an effect calls this method on a window it also needs to call @link unreferencePreviousWindowPixmap * once it does no longer need the previous window pixmap. * * Note: the window pixmap is not kept forever even when referenced. If the geometry changes again, so that * a new window pixmap is created, the previous window pixmap will be exchanged with the current one. This * means it's still possible to have rendering glitches. An effect is supposed to track for itself the changes * to the window's geometry and decide how the transition should continue in such a situation. * * @see unreferencePreviousWindowPixmap * @since 4.11 */ virtual void referencePreviousWindowPixmap() = 0; /** * @brief Unreferences the previous window pixmap. Only relevant after @link referencePreviousWindowPixmap had * been called. * * @see referencePreviousWindowPixmap * @since 4.11 */ virtual void unreferencePreviousWindowPixmap() = 0; }; 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(double x, double y, double tx, double ty); double x() const { return px; } double y() const { return py; } double u() const { return tx; } double v() const { return ty; } double originalX() const { return ox; } double originalY() const { return oy; } double textureX() const { return tx; } double textureY() const { return ty; } void move(double x, double y); void setX(double x); void setY(double y); private: friend class WindowQuad; friend class WindowQuadList; double px, py; // position double ox, oy; // origional position double tx, ty; // texture coords }; /** * @short Class representing one area of a window. * * WindowQuads consists of four WindowVertex objects and represents one part of a window. */ // NOTE: This class expects the (original) vertices to be in the clockwise order starting from topleft. class KWINEFFECTS_EXPORT WindowQuad { public: explicit WindowQuad(WindowQuadType type, int id = -1); WindowQuad makeSubQuad(double x1, double y1, double x2, double y2) const; WindowVertex& operator[](int index); const WindowVertex& operator[](int index) const; WindowQuadType type() const; void setUVAxisSwapped(bool value) { uvSwapped = value; } bool uvAxisSwapped() const { return uvSwapped; } int id() const; bool decoration() const; bool effect() const; double left() const; double right() const; double top() const; double bottom() const; double originalLeft() const; double originalRight() const; double originalTop() const; double originalBottom() const; bool smoothNeeded() const; bool isTransformed() const; private: friend class WindowQuadList; WindowVertex verts[ 4 ]; WindowQuadType quadType; // 0 - contents, 1 - decoration bool uvSwapped; int quadID; }; class KWINEFFECTS_EXPORT WindowQuadList : public QList< WindowQuad > { public: WindowQuadList splitAtX(double x) const; WindowQuadList splitAtY(double y) const; WindowQuadList makeGrid(int maxquadsize) const; WindowQuadList makeRegularGrid(int xSubdivisions, int ySubdivisions) const; WindowQuadList select(WindowQuadType type) const; WindowQuadList filterOut(WindowQuadType type) const; bool smoothNeeded() const; void makeInterleavedArrays(unsigned int type, GLVertex2D *vertices, const QMatrix4x4 &matrix) const; void makeArrays(float** vertices, float** texcoords, const QSizeF &size, bool yInverted) const; bool isTransformed() const; }; class KWINEFFECTS_EXPORT WindowPrePaintData { public: int mask; /** * Region that will be painted, in screen coordinates. **/ QRegion paint; /** * The clip region will be subtracted from paint region of following windows. * I.e. window will definitely cover it's clip region **/ QRegion clip; WindowQuadList quads; /** * Simple helper that sets data to say the window will be painted as non-opaque. * Takes also care of changing the regions. */ void setTranslucent(); /** * Helper to mark that this window will be transformed **/ void setTransformed(); }; class KWINEFFECTS_EXPORT PaintData { public: virtual ~PaintData(); /** * @returns scale factor in X direction. * @since 4.10 **/ qreal xScale() const; /** * @returns scale factor in Y direction. * @since 4.10 **/ qreal yScale() const; /** * @returns scale factor in Z direction. * @since 4.10 **/ qreal zScale() const; /** * Sets the scale factor in X direction to @p scale * @param scale The scale factor in X direction * @since 4.10 **/ void setXScale(qreal scale); /** * Sets the scale factor in Y direction to @p scale * @param scale The scale factor in Y direction * @since 4.10 **/ void setYScale(qreal scale); /** * Sets the scale factor in Z direction to @p scale * @param scale The scale factor in Z direction * @since 4.10 **/ void setZScale(qreal scale); /** * Sets the scale factor in X and Y direction. * @param scale The scale factor for X and Y direction * @since 4.10 **/ void setScale(const QVector2D &scale); /** * Sets the scale factor in X, Y and Z direction * @param scale The scale factor for X, Y and Z direction * @since 4.10 **/ void setScale(const QVector3D &scale); const QGraphicsScale &scale() const; const QVector3D &translation() const; /** * @returns the translation in X direction. * @since 4.10 **/ qreal xTranslation() const; /** * @returns the translation in Y direction. * @since 4.10 **/ qreal yTranslation() const; /** * @returns the translation in Z direction. * @since 4.10 **/ qreal zTranslation() const; /** * Sets the translation in X direction to @p translate. * @since 4.10 **/ void setXTranslation(qreal translate); /** * Sets the translation in Y direction to @p translate. * @since 4.10 **/ void setYTranslation(qreal translate); /** * Sets the translation in Z direction to @p translate. * @since 4.10 **/ void setZTranslation(qreal translate); /** * Performs a translation by adding the values component wise. * @param x Translation in X direction * @param y Translation in Y direction * @param z Translation in Z direction * @since 4.10 **/ void translate(qreal x, qreal y = 0.0, qreal z = 0.0); /** * Performs a translation by adding the values component wise. * Overloaded method for convenience. * @param translate The translation * @since 4.10 **/ void translate(const QVector3D &translate); /** * Sets the rotation angle. * @param angle The new rotation angle. * @since 4.10 * @see rotationAngle() **/ void setRotationAngle(qreal angle); /** * Returns the rotation angle. * Initially 0.0. * @returns The current rotation angle. * @since 4.10 * @see setRotationAngle **/ qreal rotationAngle() const; /** * Sets the rotation origin. * @param origin The new rotation origin. * @since 4.10 * @see rotationOrigin() **/ void setRotationOrigin(const QVector3D &origin); /** * Returns the rotation origin. That is the point in space which is fixed during the rotation. * Initially this is 0/0/0. * @returns The rotation's origin * @since 4.10 * @see setRotationOrigin() **/ QVector3D rotationOrigin() const; /** * Sets the rotation axis. * Set a component to 1.0 to rotate around this axis and to 0.0 to disable rotation around the * axis. * @param axis A vector holding information on which axis to rotate * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(const QVector3D &axis); /** * Sets the rotation axis. * Overloaded method for convenience. * @param axis The axis around which should be rotated. * @since 4.10 * @see rotationAxis() **/ void setRotationAxis(Qt::Axis axis); /** * The current rotation axis. * By default the rotation is (0/0/1) which means a rotation around the z axis. * @returns The current rotation axis. * @since 4.10 * @see setRotationAxis **/ QVector3D rotationAxis() const; protected: PaintData(); PaintData(const PaintData &other); private: PaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT WindowPaintData : public PaintData { public: explicit WindowPaintData(EffectWindow* w); explicit WindowPaintData(EffectWindow* w, const QMatrix4x4 &screenProjectionMatrix); WindowPaintData(const WindowPaintData &other); virtual ~WindowPaintData(); /** * Scales the window by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ WindowPaintData& operator*=(qreal scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ WindowPaintData& operator*=(const QVector2D &scale); /** * Scales the window by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ WindowPaintData& operator*=(const QVector3D &scale); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ WindowPaintData& operator+=(const QPointF &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QPoint &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector2D &translation); /** * Translates the window by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ WindowPaintData& operator+=(const QVector3D &translation); /** * Window opacity, in range 0 = transparent to 1 = fully opaque * @see setOpacity * @since 4.10 */ qreal opacity() const; /** * Sets the window opacity to the new @p opacity. * If you want to modify the existing opacity level consider using multiplyOpacity. * @param opacity The new opacity level * @since 4.10 **/ void setOpacity(qreal opacity); /** * Multiplies the current opacity with the @p factor. * @param factor Factor with which the opacity should be multiplied * @return New opacity level * @since 4.10 **/ qreal multiplyOpacity(qreal factor); /** * Saturation of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * unsaturated (greyscale). 0.5 would make the colors less intense, * but not completely grey * Use EffectsHandler::saturationSupported() to find out whether saturation * is supported by the system, otherwise this value has no effect. * @return The current saturation * @see setSaturation() * @since 4.10 **/ qreal saturation() const; /** * Sets the window saturation level to @p saturation. * If you want to modify the existing saturation level consider using multiplySaturation. * @param saturation The new saturation level * @since 4.10 **/ void setSaturation(qreal saturation) const; /** * Multiplies the current saturation with @p factor. * @param factor with which the saturation should be multiplied * @return New saturation level * @since 4.10 **/ qreal multiplySaturation(qreal factor); /** * Brightness of the window, in range [0; 1] * 1 means that the window is unchanged, 0 means that it's completely * black. 0.5 would make it 50% darker than usual **/ qreal brightness() const; /** * Sets the window brightness level to @p brightness. * If you want to modify the existing brightness level consider using multiplyBrightness. * @param brightness The new brightness level **/ void setBrightness(qreal brightness); /** * Multiplies the current brightness level with @p factor. * @param factor with which the brightness should be multiplied. * @return New brightness level * @since 4.10 **/ qreal multiplyBrightness(qreal factor); /** * The screen number for which the painting should be done. * This affects color correction (different screens may need different * color correction lookup tables because they have different ICC profiles). * @return screen for which painting should be done */ int screen() const; /** * @param screen New screen number * A value less than 0 will indicate that a default profile should be done. */ void setScreen(int screen) const; /** * @brief Sets the cross fading @p factor to fade over with previously sized window. * If @c 1.0 only the current window is used, if @c 0.0 only the previous window is used. * * By default only the current window is used. This factor can only make any visual difference * if the previous window get referenced. * * @param factor The cross fade factor between @c 0.0 (previous window) and @c 1.0 (current window) * @see crossFadeProgress */ void setCrossFadeProgress(qreal factor); /** * @see setCrossFadeProgress */ qreal crossFadeProgress() const; /** * Sets the projection matrix that will be used when painting the window. * * The default projection matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setProjectionMatrix(const QMatrix4x4 &matrix); /** * Returns the current projection matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 projectionMatrix() const; /** * Returns a reference to the projection matrix. */ QMatrix4x4 &rprojectionMatrix(); /** * Sets the model-view matrix that will be used when painting the window. * * The default model-view matrix can be overridden by setting this matrix * to a non-identity matrix. */ void setModelViewMatrix(const QMatrix4x4 &matrix); /** * Returns the current model-view matrix. * * The default value for this matrix is the identity matrix. */ QMatrix4x4 modelViewMatrix() const; /** * Returns a reference to the model-view matrix. */ QMatrix4x4 &rmodelViewMatrix(); /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * @since 5.6 **/ QMatrix4x4 screenProjectionMatrix() const; WindowQuadList quads; /** * Shader to be used for rendering, if any. */ GLShader* shader; private: WindowPaintDataPrivate * const d; }; class KWINEFFECTS_EXPORT ScreenPaintData : public PaintData { public: ScreenPaintData(); ScreenPaintData(const QMatrix4x4 &projectionMatrix); ScreenPaintData(const ScreenPaintData &other); virtual ~ScreenPaintData(); /** * Scales the screen by @p scale factor. * Multiplies all three components by the given factor. * @since 4.10 **/ ScreenPaintData& operator*=(qreal scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication on x and y components. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector2D &scale); /** * Scales the screen by @p scale factor. * Performs a component wise multiplication. * @since 4.10 **/ ScreenPaintData& operator*=(const QVector3D &scale); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * @since 4.10 **/ ScreenPaintData& operator+=(const QPointF &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QPoint &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector2D &translation); /** * Translates the screen by the given @p translation and returns a reference to the ScreenPaintData. * Overloaded method for convenience. * @since 4.10 **/ ScreenPaintData& operator+=(const QVector3D &translation); ScreenPaintData& operator=(const ScreenPaintData &rhs); /** * The projection matrix used by the scene for the current rendering pass. * On non-OpenGL compositors it's set to Identity matrix. * @since 5.6 **/ QMatrix4x4 projectionMatrix() const; private: class Private; QScopedPointer d; }; class KWINEFFECTS_EXPORT ScreenPrePaintData { public: int mask; QRegion paint; }; /** * @short Helper class for restricting painting area only to allowed area. * * This helper class helps specifying areas that should be painted, clipping * out the rest. The simplest usage is creating an object on the stack * and giving it the area that is allowed to be painted to. When the object * is destroyed, the restriction will be removed. * Note that all painting code must use paintArea() to actually perform the clipping. */ class KWINEFFECTS_EXPORT PaintClipper { public: /** * Calls push(). */ explicit PaintClipper(const QRegion& allowed_area); /** * Calls pop(). */ ~PaintClipper(); /** * Allows painting only in the given area. When areas have been already * specified, painting is allowed only in the intersection of all areas. */ static void push(const QRegion& allowed_area); /** * Removes the given area. It must match the top item in the stack. */ static void pop(const QRegion& allowed_area); /** * Returns true if any clipping should be performed. */ static bool clip(); /** * If clip() returns true, this function gives the resulting area in which * painting is allowed. It is usually simpler to use the helper Iterator class. */ static QRegion paintArea(); /** * Helper class to perform the clipped painting. The usage is: * @code * for ( PaintClipper::Iterator iterator; * !iterator.isDone(); * iterator.next()) * { // do the painting, possibly use iterator.boundingRect() * } * @endcode */ class KWINEFFECTS_EXPORT Iterator { public: Iterator(); ~Iterator(); bool isDone(); void next(); QRect boundingRect() const; private: struct Data; Data* data; }; private: QRegion area; static QStack< QRegion >* areas; }; /** * @internal */ template class KWINEFFECTS_EXPORT Motion { public: /** * Creates a new motion object. "Strength" is the amount of * acceleration that is applied to the object when the target * changes and "smoothness" relates to how fast the object * can change its direction and speed. */ explicit Motion(T initial, double strength, double smoothness); /** * Creates an exact copy of another motion object, including * position, target and velocity. */ Motion(const Motion &other); ~Motion(); inline T value() const { return m_value; } inline void setValue(const T value) { m_value = value; } inline T target() const { return m_target; } inline void setTarget(const T target) { m_start = m_value; m_target = target; } inline T velocity() const { return m_velocity; } inline void setVelocity(const T velocity) { m_velocity = velocity; } inline double strength() const { return m_strength; } inline void setStrength(const double strength) { m_strength = strength; } inline double smoothness() const { return m_smoothness; } inline void setSmoothness(const double smoothness) { m_smoothness = smoothness; } inline T startValue() { return m_start; } /** * The distance between the current position and the target. */ inline T distance() const { return m_target - m_value; } /** * Calculates the new position if not at the target. Called * once per frame only. */ void calculate(const int msec); /** * Place the object on top of the target immediately, * bypassing all movement calculation. */ void finish(); private: T m_value; T m_start; T m_target; T m_velocity; double m_strength; double m_smoothness; }; /** * @short A single 1D motion dynamics object. * * This class represents a single object that can be moved around a * 1D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion1D : public Motion { public: explicit Motion1D(double initial = 0.0, double strength = 0.08, double smoothness = 4.0); Motion1D(const Motion1D &other); ~Motion1D(); }; /** * @short A single 2D motion dynamics object. * * This class represents a single object that can be moved around a * 2D space. Although it can be used directly by itself it is * recommended to use a motion manager instead. */ class KWINEFFECTS_EXPORT Motion2D : public Motion { public: explicit Motion2D(QPointF initial = QPointF(), double strength = 0.08, double smoothness = 4.0); Motion2D(const Motion2D &other); ~Motion2D(); }; /** * @short Helper class for motion dynamics in KWin effects. * * This motion manager class is intended to help KWin effect authors * move windows across the screen smoothly and naturally. Once * windows are registered by the manager the effect can issue move * commands with the moveWindow() methods. The position of any * managed window can be determined in realtime by the * transformedGeometry() method. As the manager knows if any windows * are moving at any given time it can also be used as a notifier as * to see whether the effect is active or not. */ class KWINEFFECTS_EXPORT WindowMotionManager { public: /** * Creates a new window manager object. */ explicit WindowMotionManager(bool useGlobalAnimationModifier = true); ~WindowMotionManager(); /** * Register a window for managing. */ void manage(EffectWindow *w); /** * Register a list of windows for managing. */ inline void manage(EffectWindowList list) { for (int i = 0; i < list.size(); i++) manage(list.at(i)); } /** * Deregister a window. All transformations applied to the * window will be permanently removed and cannot be recovered. */ void unmanage(EffectWindow *w); /** * Deregister all windows, returning the manager to its * originally initiated state. */ void unmanageAll(); /** * Determine the new positions for windows that have not * reached their target. Called once per frame, usually in * prePaintScreen(). Remember to set the * Effect::PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS flag. */ void calculate(int time); /** * Modify a registered window's paint data to make it appear * at its real location on the screen. Usually called in * paintWindow(). Remember to flag the window as having been * transformed in prePaintWindow() by calling * WindowPrePaintData::setTransformed() */ void apply(EffectWindow *w, WindowPaintData &data); /** * Set all motion targets and values back to where the * windows were before transformations. The same as * unmanaging then remanaging all windows. */ void reset(); /** * Resets the motion target and current value of a single * window. */ void reset(EffectWindow *w); /** * Ask the manager to move the window to the target position * with the specified scale. If `yScale` is not provided or * set to 0.0, `scale` will be used as the scale in the * vertical direction as well as in the horizontal direction. */ void moveWindow(EffectWindow *w, QPoint target, double scale = 1.0, double yScale = 0.0); /** * This is an overloaded method, provided for convenience. * * Ask the manager to move the window to the target rectangle. * Automatically determines scale. */ inline void moveWindow(EffectWindow *w, QRect target) { // TODO: Scale might be slightly different in the comparison due to rounding moveWindow(w, target.topLeft(), target.width() / double(w->width()), target.height() / double(w->height())); } /** * Retrieve the current tranformed geometry of a registered * window. */ QRectF transformedGeometry(EffectWindow *w) const; /** * Sets the current transformed geometry of a registered window to the given geometry. * @see transformedGeometry * @since 4.5 */ void setTransformedGeometry(EffectWindow *w, const QRectF &geometry); /** * Retrieve the current target geometry of a registered * window. */ QRectF targetGeometry(EffectWindow *w) const; /** * Return the window that has its transformed geometry under * the specified point. It is recommended to use the stacking * order as it's what the user sees, but it is slightly * slower to process. */ EffectWindow* windowAtPoint(QPoint point, bool useStackingOrder = true) const; /** * Return a list of all currently registered windows. */ inline EffectWindowList managedWindows() const { return m_managedWindows.keys(); } /** * Returns whether or not a specified window is being managed * by this manager object. */ inline bool isManaging(EffectWindow *w) const { return m_managedWindows.contains(w); } /** * Returns whether or not this manager object is actually * managing any windows or not. */ inline bool managingWindows() const { return !m_managedWindows.empty(); } /** * Returns whether all windows have reached their targets yet * or not. Can be used to see if an effect should be * processed and displayed or not. */ inline bool areWindowsMoving() const { return !m_movingWindowsSet.isEmpty(); } /** * Returns whether a window has reached its targets yet * or not. */ inline bool isWindowMoving(EffectWindow *w) const { return m_movingWindowsSet.contains(w); } private: bool m_useGlobalAnimationModifier; struct WindowMotion { // TODO: Rotation, etc? Motion2D translation; // Absolute position Motion2D scale; // xScale and yScale }; QHash m_managedWindows; QSet m_movingWindowsSet; }; /** * @short Helper class for displaying text and icons in frames. * * Paints text and/or and icon with an optional frame around them. The * available frames includes one that follows the default Plasma theme and * another that doesn't. * It is recommended to use this class whenever displaying text. */ class KWINEFFECTS_EXPORT EffectFrame { public: EffectFrame(); virtual ~EffectFrame(); /** * Delete any existing textures to free up graphics memory. They will * be automatically recreated the next time they are required. */ virtual void free() = 0; /** * Render the frame. */ virtual void render(QRegion region = infiniteRegion(), double opacity = 1.0, double frameOpacity = 1.0) = 0; virtual void setPosition(const QPoint& point) = 0; /** * Set the text alignment for static frames and the position alignment * for non-static. */ virtual void setAlignment(Qt::Alignment alignment) = 0; virtual Qt::Alignment alignment() const = 0; virtual void setGeometry(const QRect& geometry, bool force = false) = 0; virtual const QRect& geometry() const = 0; virtual void setText(const QString& text) = 0; virtual const QString& text() const = 0; virtual void setFont(const QFont& font) = 0; virtual const QFont& font() const = 0; /** * Set the icon that will appear on the left-hand size of the frame. */ virtual void setIcon(const QIcon& icon) = 0; virtual const QIcon& icon() const = 0; virtual void setIconSize(const QSize& size) = 0; virtual const QSize& iconSize() const = 0; /** * Sets the geometry of a selection. * To remove the selection set a null rect. * @param selection The geometry of the selection in screen coordinates. **/ virtual void setSelection(const QRect& selection) = 0; /** * @param shader The GLShader for rendering. **/ virtual void setShader(GLShader* shader) = 0; /** * @returns The GLShader used for rendering or null if none. **/ virtual GLShader* shader() const = 0; /** * @returns The style of this EffectFrame. **/ virtual EffectFrameStyle style() const = 0; /** * If @p enable is @c true cross fading between icons and text is enabled * By default disabled. Use setCrossFadeProgress to cross fade. * Cross Fading is currently only available if OpenGL is used. * @param enable @c true enables cross fading, @c false disables it again * @see isCrossFade * @see setCrossFadeProgress * @since 4.6 **/ void enableCrossFade(bool enable); /** * @returns @c true if cross fading is enabled, @c false otherwise * @see enableCrossFade * @since 4.6 **/ bool isCrossFade() const; /** * Sets the current progress for cross fading the last used icon/text * with current icon/text to @p progress. * A value of 0.0 means completely old icon/text, a value of 1.0 means * completely current icon/text. * Default value is 1.0. You have to enable cross fade before using it. * Cross Fading is currently only available if OpenGL is used. * @see enableCrossFade * @see isCrossFade * @see crossFadeProgress * @since 4.6 **/ void setCrossFadeProgress(qreal progress); /** * @returns The current progress for cross fading * @see setCrossFadeProgress * @see enableCrossFade * @see isCrossFade * @since 4.6 **/ qreal crossFadeProgress() const; /** * Returns The projection matrix as used by the current screen painting pass * including screen transformations. * * This matrix is only valid during a rendering pass started by render. * * @since 5.6 * @see render * @see EffectsHandler::paintEffectFrame * @see Effect::paintEffectFrame **/ QMatrix4x4 screenProjectionMatrix() const; protected: void setScreenProjectionMatrix(const QMatrix4x4 &projection); private: EffectFramePrivate* const d; }; /** * Pointer to the global EffectsHandler object. **/ extern KWINEFFECTS_EXPORT EffectsHandler* effects; /*************************************************************** WindowVertex ***************************************************************/ inline WindowVertex::WindowVertex() : px(0), py(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 void WindowVertex::move(double x, double y) { px = x; py = y; } inline void WindowVertex::setX(double x) { px = x; } inline void WindowVertex::setY(double y) { py = y; } /*************************************************************** WindowQuad ***************************************************************/ inline WindowQuad::WindowQuad(WindowQuadType t, int id) : quadType(t) , uvSwapped(false) , quadID(id) { } inline WindowVertex& WindowQuad::operator[](int index) { assert(index >= 0 && index < 4); return verts[ index ]; } inline const WindowVertex& WindowQuad::operator[](int index) const { assert(index >= 0 && index < 4); return verts[ index ]; } inline WindowQuadType WindowQuad::type() const { assert(quadType != WindowQuadError); return quadType; } inline int WindowQuad::id() const { return quadID; } inline bool WindowQuad::decoration() const { assert(quadType != WindowQuadError); return quadType == WindowQuadDecoration; } inline bool WindowQuad::effect() const { assert(quadType != WindowQuadError); return quadType >= EFFECT_QUAD_TYPE_START; } inline bool WindowQuad::isTransformed() const { return !(verts[ 0 ].px == verts[ 0 ].ox && verts[ 0 ].py == verts[ 0 ].oy && verts[ 1 ].px == verts[ 1 ].ox && verts[ 1 ].py == verts[ 1 ].oy && verts[ 2 ].px == verts[ 2 ].ox && verts[ 2 ].py == verts[ 2 ].oy && verts[ 3 ].px == verts[ 3 ].ox && verts[ 3 ].py == verts[ 3 ].oy); } inline double WindowQuad::left() const { return qMin(verts[ 0 ].px, qMin(verts[ 1 ].px, qMin(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::right() const { return qMax(verts[ 0 ].px, qMax(verts[ 1 ].px, qMax(verts[ 2 ].px, verts[ 3 ].px))); } inline double WindowQuad::top() const { return qMin(verts[ 0 ].py, qMin(verts[ 1 ].py, qMin(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::bottom() const { return qMax(verts[ 0 ].py, qMax(verts[ 1 ].py, qMax(verts[ 2 ].py, verts[ 3 ].py))); } inline double WindowQuad::originalLeft() const { return verts[ 0 ].ox; } inline double WindowQuad::originalRight() const { return verts[ 2 ].ox; } inline double WindowQuad::originalTop() const { return verts[ 0 ].oy; } inline double WindowQuad::originalBottom() const { return verts[ 2 ].oy; } /*************************************************************** Motion ***************************************************************/ template Motion::Motion(T initial, double strength, double smoothness) : m_value(initial) , m_start(initial) , m_target(initial) , m_velocity() , m_strength(strength) , m_smoothness(smoothness) { } template Motion::Motion(const Motion &other) : m_value(other.value()) , m_start(other.target()) , m_target(other.target()) , m_velocity(other.velocity()) , m_strength(other.strength()) , m_smoothness(other.smoothness()) { } template Motion::~Motion() { } template void Motion::calculate(const int msec) { if (m_value == m_target && m_velocity == T()) // At target and not moving return; // Poor man's time independent calculation int steps = qMax(1, msec / 5); for (int i = 0; i < steps; i++) { T diff = m_target - m_value; T strength = diff * m_strength; m_velocity = (m_smoothness * m_velocity + strength) / (m_smoothness + 1.0); m_value += m_velocity; } } template void Motion::finish() { m_value = m_target; m_velocity = T(); } /*************************************************************** Effect ***************************************************************/ template int Effect::animationTime(int defaultDuration) { return animationTime(T::duration() != 0 ? T::duration() : defaultDuration); } } // namespace Q_DECLARE_METATYPE(KWin::EffectWindow*) Q_DECLARE_METATYPE(QList) /** @} */ #endif // KWINEFFECTS_H diff --git a/scene.h b/scene.h index c5ee8655e..2b4896971 100644 --- a/scene.h +++ b/scene.h @@ -1,630 +1,638 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCENE_H #define KWIN_SCENE_H #include "toplevel.h" #include "utils.h" #include "kwineffects.h" #include #include class QOpenGLFramebufferObject; namespace KWayland { namespace Server { class BufferInterface; class SubSurfaceInterface; } } namespace KWin { namespace Decoration { class DecoratedClientImpl; class Renderer; } class AbstractThumbnailItem; class Deleted; class EffectFrameImpl; class EffectWindowImpl; class OverlayWindow; class Shadow; class WindowPixmap; // The base class for compositing backends. class KWIN_EXPORT Scene : public QObject { Q_OBJECT public: explicit Scene(QObject *parent = nullptr); virtual ~Scene() = 0; class EffectFrame; class Window; // Returns true if the ctor failed to properly initialize. virtual bool initFailed() const = 0; virtual CompositingType compositingType() const = 0; virtual bool hasPendingFlush() const { return false; } // Repaints the given screen areas, windows provides the stacking order. // The entry point for the main part of the painting pass. // returns the time since the last vblank signal - if there's one // ie. "what of this frame is lost to painting" virtual qint64 paint(QRegion damage, ToplevelList windows) = 0; // Notification function - KWin core informs about changes. // Used to mainly discard cached data. // a new window has been created void windowAdded(Toplevel*); /** * @brief Creates the Scene backend of an EffectFrame. * * @param frame The EffectFrame this Scene::EffectFrame belongs to. */ virtual Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame) = 0; /** * @brief Creates the Scene specific Shadow subclass. * * An implementing class has to create a proper instance. It is not allowed to * return @c null. * * @param toplevel The Toplevel for which the Shadow needs to be created. */ virtual Shadow *createShadow(Toplevel *toplevel) = 0; /** * Method invoked when the screen geometry is changed. * Reimplementing classes should also invoke the parent method * as it takes care of resizing the overlay window. * @param size The new screen geometry size **/ virtual void screenGeometryChanged(const QSize &size); // Flags controlling how painting is done. enum { // Window (or at least part of it) will be painted opaque. PAINT_WINDOW_OPAQUE = 1 << 0, // Window (or at least part of it) will be painted translucent. PAINT_WINDOW_TRANSLUCENT = 1 << 1, // Window will be painted with transformed geometry. PAINT_WINDOW_TRANSFORMED = 1 << 2, // Paint only a region of the screen (can be optimized, cannot // be used together with TRANSFORMED flags). PAINT_SCREEN_REGION = 1 << 3, // Whole screen will be painted with transformed geometry. PAINT_SCREEN_TRANSFORMED = 1 << 4, // At least one window will be painted with transformed geometry. PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS = 1 << 5, // Clear whole background as the very first step, without optimizing it PAINT_SCREEN_BACKGROUND_FIRST = 1 << 6, // PAINT_DECORATION_ONLY = 1 << 7 has been removed // Window will be painted with a lanczos filter. PAINT_WINDOW_LANCZOS = 1 << 8 // PAINT_SCREEN_WITH_TRANSFORMED_WINDOWS_WITHOUT_FULL_REPAINTS = 1 << 9 has been removed }; // types of filtering available enum ImageFilterType { ImageFilterFast, ImageFilterGood }; // there's nothing to paint (adjust time_diff later) virtual void idle(); virtual bool blocksForRetrace() const; virtual bool syncsToVBlank() const; virtual OverlayWindow* overlayWindow() = 0; virtual bool makeOpenGLContextCurrent(); virtual void doneOpenGLContextCurrent(); virtual QMatrix4x4 screenProjectionMatrix() const; /** * Whether the Scene uses an X11 overlay window to perform compositing. */ virtual bool usesOverlayWindow() const = 0; virtual void triggerFence(); virtual Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *) = 0; + /** + * Whether the Scene is able to drive animations. + * This is used as a hint to the effects system which effects can be supported. + * If the Scene performs software rendering it is supposed to return @c false, + * if rendering is hardware accelerated it should return @c true. + **/ + virtual bool animationsSupported() const = 0; + Q_SIGNALS: void frameRendered(); public Q_SLOTS: // a window has been destroyed void windowDeleted(KWin::Deleted*); // shape/size of a window changed void windowGeometryShapeChanged(KWin::Toplevel* c); // a window has been closed void windowClosed(KWin::Toplevel* c, KWin::Deleted* deleted); protected: virtual Window *createWindow(Toplevel *toplevel) = 0; void createStackingOrder(ToplevelList toplevels); void clearStackingOrder(); // shared implementation, starts painting the screen void paintScreen(int *mask, const QRegion &damage, const QRegion &repaint, QRegion *updateRegion, QRegion *validRegion, const QMatrix4x4 &projection = QMatrix4x4()); friend class EffectsHandlerImpl; // called after all effects had their paintScreen() called void finalPaintScreen(int mask, QRegion region, ScreenPaintData& data); // shared implementation of painting the screen in the generic // (unoptimized) way virtual void paintGenericScreen(int mask, ScreenPaintData data); // shared implementation of painting the screen in an optimized way virtual void paintSimpleScreen(int mask, QRegion region); // paint the background (not the desktop background - the whole background) virtual void paintBackground(QRegion region) = 0; // called after all effects had their paintWindow() called void finalPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); // shared implementation, starts painting the window virtual void paintWindow(Window* w, int mask, QRegion region, WindowQuadList quads); // called after all effects had their drawWindow() called virtual void finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); // let the scene decide whether it's better to paint more of the screen, eg. in order to allow a buffer swap // the default is NOOP virtual void extendPaintRegion(QRegion ®ion, bool opaqueFullscreen); virtual void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data); // compute time since the last repaint void updateTimeDiff(); // saved data for 2nd pass of optimized screen painting struct Phase2Data { Phase2Data(Window* w, QRegion r, QRegion c, int m, const WindowQuadList& q) : window(w), region(r), clip(c), mask(m), quads(q) {} Phase2Data() { window = 0; mask = 0; } Window* window; QRegion region; QRegion clip; int mask; WindowQuadList quads; }; // The region which actually has been painted by paintScreen() and should be // copied from the buffer to the screen. I.e. the region returned from Scene::paintScreen(). // Since prePaintWindow() can extend areas to paint, these changes would have to propagate // up all the way from paintSimpleScreen() up to paintScreen(), so save them here rather // than propagate them up in arguments. QRegion painted_region; // Additional damage that needs to be repaired to bring a reused back buffer up to date QRegion repaint_region; // The dirty region before it was unioned with repaint_region QRegion damaged_region; // time since last repaint int time_diff; QElapsedTimer last_time; private: void paintWindowThumbnails(Scene::Window *w, QRegion region, qreal opacity, qreal brightness, qreal saturation); void paintDesktopThumbnails(Scene::Window *w); QHash< Toplevel*, Window* > m_windows; // windows in their stacking order QVector< Window* > stacking_order; }; // The base class for windows representations in composite backends class Scene::Window { public: Window(Toplevel* c); virtual ~Window(); // perform the actual painting of the window virtual void performPaint(int mask, QRegion region, WindowPaintData data) = 0; // do any cleanup needed when the window's composite pixmap is discarded void pixmapDiscarded(); int x() const; int y() const; int width() const; int height() const; QRect geometry() const; QPoint pos() const; QSize size() const; QRect rect() const; // access to the internal window class // TODO eventually get rid of this Toplevel* window() const; // should the window be painted bool isPaintingEnabled() const; void resetPaintingEnabled(); // Flags explaining why painting should be disabled enum { // Window will not be painted PAINT_DISABLED = 1 << 0, // Window will not be painted because it is deleted PAINT_DISABLED_BY_DELETE = 1 << 1, // Window will not be painted because of which desktop it's on PAINT_DISABLED_BY_DESKTOP = 1 << 2, // Window will not be painted because it is minimized PAINT_DISABLED_BY_MINIMIZE = 1 << 3, // Window will not be painted because it is not the active window in a client group PAINT_DISABLED_BY_TAB_GROUP = 1 << 4, // Window will not be painted because it's not on the current activity PAINT_DISABLED_BY_ACTIVITY = 1 << 5 }; void enablePainting(int reason); void disablePainting(int reason); // is the window visible at all bool isVisible() const; // is the window fully opaque bool isOpaque() const; // shape of the window const QRegion &shape() const; QRegion clientShape() const; void discardShape(); void updateToplevel(Toplevel* c); // creates initial quad list for the window virtual WindowQuadList buildQuads(bool force = false) const; void updateShadow(Shadow* shadow); const Shadow* shadow() const; Shadow* shadow(); void referencePreviousPixmap(); void unreferencePreviousPixmap(); protected: WindowQuadList makeQuads(WindowQuadType type, const QRegion& reg, const QPoint &textureOffset = QPoint(0, 0)) const; WindowQuadList makeDecorationQuads(const QRect *rects, const QRegion ®ion) const; /** * @brief Returns the WindowPixmap for this Window. * * If the WindowPixmap does not yet exist, this method will invoke @link createWindowPixmap. * If the WindowPixmap is not valid it tries to create it, in case this succeeds the WindowPixmap is * returned. In case it fails, the previous (and still valid) WindowPixmap is returned. * * Note: this method can return @c NULL as there might neither be a valid previous nor current WindowPixmap * around. * * The WindowPixmap gets casted to the type passed in as a template parameter. That way this class does not * need to know the actual WindowPixmap subclass used by the concrete Scene implementations. * * @return The WindowPixmap casted to T* or @c NULL if there is no valid window pixmap. */ template T *windowPixmap(); template T *previousWindowPixmap(); /** * @brief Factory method to create a WindowPixmap. * * The inheriting classes need to implement this method to create a new instance of their WindowPixmap subclass. * Note: do not use @link WindowPixmap::create on the created instance. The Scene will take care of that. */ virtual WindowPixmap *createWindowPixmap() = 0; Toplevel* toplevel; ImageFilterType filter; Shadow *m_shadow; private: QScopedPointer m_currentPixmap; QScopedPointer m_previousPixmap; int m_referencePixmapCounter; int disable_painting; mutable QRegion shape_region; mutable bool shape_valid; mutable QScopedPointer cached_quad_list; Q_DISABLE_COPY(Window) }; /** * @brief Wrapper for a pixmap of the @link Scene::Window. * * This class encapsulates the functionality to get the pixmap for a window. When initialized the pixmap is not yet * mapped to the window and @link isValid will return @c false. The pixmap mapping to the window can be established * through @link create. If it succeeds @link isValid will return @c true, otherwise it will keep in the non valid * state and it can be tried to create the pixmap mapping again (e.g. in the next frame). * * This class is not intended to be updated when the pixmap is no longer valid due to e.g. resizing the window. * Instead a new instance of this class should be instantiated. The idea behind this is that a valid pixmap does not * get destroyed, but can continue to be used. To indicate that a newer pixmap should in generally be around, one can * use @link markAsDiscarded. * * This class is intended to be inherited for the needs of the compositor backends which need further mapping from * the native pixmap to the respective rendering format. */ class WindowPixmap { public: virtual ~WindowPixmap(); /** * @brief Tries to create the mapping between the Window and the pixmap. * * In case this method succeeds in creating the pixmap for the window, @link isValid will return @c true otherwise * @c false. * * Inheriting classes should re-implement this method in case they need to add further functionality for mapping the * native pixmap to the rendering format. */ virtual void create(); /** * @return @c true if the pixmap has been created and is valid, @c false otherwise */ bool isValid() const; /** * @return The native X11 pixmap handle */ xcb_pixmap_t pixmap() const; /** * @return The Wayland BufferInterface for this WindowPixmap. **/ QPointer buffer() const; const QSharedPointer &fbo() const; /** * @brief Whether this WindowPixmap is considered as discarded. This means the window has changed in a way that a new * WindowPixmap should have been created already. * * @return @c true if this WindowPixmap is considered as discarded, @c false otherwise. * @see markAsDiscarded */ bool isDiscarded() const; /** * @brief Marks this WindowPixmap as discarded. From now on @link isDiscarded will return @c true. This method should * only be used by the Window when it changes in a way that a new pixmap is required. * * @see isDiscarded */ void markAsDiscarded(); /** * The size of the pixmap. */ const QSize &size() const; /** * The geometry of the Client's content inside the pixmap. In case of a decorated Client the * pixmap also contains the decoration which is not rendered into this pixmap, though. This * contentsRect tells where inside the complete pixmap the real content is. */ const QRect &contentsRect() const; /** * @brief Returns the Toplevel this WindowPixmap belongs to. * Note: the Toplevel can change over the lifetime of the WindowPixmap in case the Toplevel is copied to Deleted. */ Toplevel *toplevel() const; /** * @returns the parent WindowPixmap in the sub-surface tree **/ WindowPixmap *parent() const { return m_parent; } /** * @returns the current sub-surface tree **/ QVector children() const { return m_children; } /** * @returns the subsurface this WindowPixmap is for if it is not for a root window **/ QPointer subSurface() const { return m_subSurface; } /** * @returns the surface this WindowPixmap references, might be @c null. **/ KWayland::Server::SurfaceInterface *surface() const; protected: explicit WindowPixmap(Scene::Window *window); explicit WindowPixmap(const QPointer &subSurface, WindowPixmap *parent); virtual WindowPixmap *createChild(const QPointer &subSurface); /** * @return The Window this WindowPixmap belongs to */ Scene::Window *window(); /** * Should be called by the implementing subclasses when the Wayland Buffer changed and needs * updating. **/ virtual void updateBuffer(); /** * Sets the sub-surface tree to @p children. **/ void setChildren(const QVector &children) { m_children = children; } private: Scene::Window *m_window; xcb_pixmap_t m_pixmap; QSize m_pixmapSize; bool m_discarded; QRect m_contentsRect; QPointer m_buffer; QSharedPointer m_fbo; WindowPixmap *m_parent = nullptr; QVector m_children; QPointer m_subSurface; }; class Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame); virtual ~EffectFrame(); virtual void render(QRegion region, double opacity, double frameOpacity) = 0; virtual void free() = 0; virtual void freeIconFrame() = 0; virtual void freeTextFrame() = 0; virtual void freeSelection() = 0; virtual void crossFadeIcon() = 0; virtual void crossFadeText() = 0; protected: EffectFrameImpl* m_effectFrame; }; inline int Scene::Window::x() const { return toplevel->x(); } inline int Scene::Window::y() const { return toplevel->y(); } inline int Scene::Window::width() const { return toplevel->width(); } inline int Scene::Window::height() const { return toplevel->height(); } inline QRect Scene::Window::geometry() const { return toplevel->geometry(); } inline QSize Scene::Window::size() const { return toplevel->size(); } inline QPoint Scene::Window::pos() const { return toplevel->pos(); } inline QRect Scene::Window::rect() const { return toplevel->rect(); } inline Toplevel* Scene::Window::window() const { return toplevel; } inline void Scene::Window::updateToplevel(Toplevel* c) { toplevel = c; } inline void Scene::Window::updateShadow(Shadow* shadow) { m_shadow = shadow; } inline const Shadow* Scene::Window::shadow() const { return m_shadow; } inline Shadow* Scene::Window::shadow() { return m_shadow; } inline QPointer WindowPixmap::buffer() const { return m_buffer; } inline const QSharedPointer &WindowPixmap::fbo() const { return m_fbo; } template inline T* Scene::Window::windowPixmap() { if (m_currentPixmap.isNull()) { m_currentPixmap.reset(createWindowPixmap()); } if (m_currentPixmap->isValid()) { return static_cast(m_currentPixmap.data()); } m_currentPixmap->create(); if (m_currentPixmap->isValid()) { return static_cast(m_currentPixmap.data()); } else { return static_cast(m_previousPixmap.data()); } } template inline T* Scene::Window::previousWindowPixmap() { return static_cast(m_previousPixmap.data()); } inline Toplevel* WindowPixmap::toplevel() const { return m_window->window(); } inline xcb_pixmap_t WindowPixmap::pixmap() const { return m_pixmap; } inline bool WindowPixmap::isDiscarded() const { return m_discarded; } inline void WindowPixmap::markAsDiscarded() { m_discarded = true; m_window->referencePreviousPixmap(); } inline const QRect &WindowPixmap::contentsRect() const { return m_contentsRect; } inline const QSize &WindowPixmap::size() const { return m_pixmapSize; } } // namespace #endif diff --git a/scene_opengl.cpp b/scene_opengl.cpp index 7d81eab21..0118999bf 100644 --- a/scene_opengl.cpp +++ b/scene_opengl.cpp @@ -1,2583 +1,2588 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 2010, 2011 Martin Gräßlin Based on glcompmgr code by Felix Bellaby. Using code from Compiz and Beryl. Explicit command stream synchronization based on the sample implementation by James Jones , Copyright © 2011 NVIDIA Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "scene_opengl.h" #include "platform.h" #include "wayland_server.h" #include #include #include "utils.h" #include "client.h" #include "composite.h" #include "deleted.h" #include "effects.h" #include "lanczosfilter.h" #include "main.h" #include "overlaywindow.h" #include "screens.h" #include "decorations/decoratedclient.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // HACK: workaround for libepoxy < 1.3 #ifndef GL_GUILTY_CONTEXT_RESET #define GL_GUILTY_CONTEXT_RESET 0x8253 #endif #ifndef GL_INNOCENT_CONTEXT_RESET #define GL_INNOCENT_CONTEXT_RESET 0x8254 #endif #ifndef GL_UNKNOWN_CONTEXT_RESET #define GL_UNKNOWN_CONTEXT_RESET 0x8255 #endif namespace KWin { extern int currentRefreshRate(); /** * SyncObject represents a fence used to synchronize operations in * the kwin command stream with operations in the X command stream. */ class SyncObject { public: enum State { Ready, TriggerSent, Waiting, Done, Resetting }; SyncObject(); ~SyncObject(); State state() const { return m_state; } void trigger(); void wait(); bool finish(); void reset(); void finishResetting(); private: State m_state; GLsync m_sync; xcb_sync_fence_t m_fence; xcb_get_input_focus_cookie_t m_reset_cookie; }; SyncObject::SyncObject() { m_state = Ready; xcb_connection_t * const c = connection(); m_fence = xcb_generate_id(c); xcb_sync_create_fence(c, rootWindow(), m_fence, false); xcb_flush(c); m_sync = glImportSyncEXT(GL_SYNC_X11_FENCE_EXT, m_fence, 0); } SyncObject::~SyncObject() { // If glDeleteSync is called before the xcb fence is signalled // the nvidia driver (the only one to implement GL_SYNC_X11_FENCE_EXT) // deadlocks waiting for the fence to be signalled. // To avoid this, make sure the fence is signalled before // deleting the sync. if (m_state == Resetting || m_state == Ready){ trigger(); // The flush is necessary! // The trigger command needs to be sent to the X server. xcb_flush(connection()); } xcb_sync_destroy_fence(connection(), m_fence); glDeleteSync(m_sync); if (m_state == Resetting) xcb_discard_reply(connection(), m_reset_cookie.sequence); } void SyncObject::trigger() { assert(m_state == Ready || m_state == Resetting); // Finish resetting the fence if necessary if (m_state == Resetting) finishResetting(); xcb_sync_trigger_fence(connection(), m_fence); m_state = TriggerSent; } void SyncObject::wait() { if (m_state != TriggerSent) return; glWaitSync(m_sync, 0, GL_TIMEOUT_IGNORED); m_state = Waiting; } bool SyncObject::finish() { if (m_state == Done) return true; // Note: It is possible that we never inserted a wait for the fence. // This can happen if we ended up not rendering the damaged // window because it is fully occluded. assert(m_state == TriggerSent || m_state == Waiting); // Check if the fence is signaled GLint value; glGetSynciv(m_sync, GL_SYNC_STATUS, 1, nullptr, &value); if (value != GL_SIGNALED) { qCDebug(KWIN_CORE) << "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_CORE) << "Timeout while waiting for X fence"; return false; case GL_WAIT_FAILED: qCWarning(KWIN_CORE) << "glClientWaitSync() failed"; return false; } } m_state = Done; return true; } void SyncObject::reset() { assert(m_state == Done); xcb_connection_t * const c = connection(); // Send the reset request along with a sync request. // We use the cookie to ensure that the server has processed the reset // request before we trigger the fence and call glWaitSync(). // Otherwise there is a race condition between the reset finishing and // the glWaitSync() call. xcb_sync_reset_fence(c, m_fence); m_reset_cookie = xcb_get_input_focus(c); xcb_flush(c); m_state = Resetting; } void SyncObject::finishResetting() { assert(m_state == Resetting); free(xcb_get_input_focus_reply(connection(), m_reset_cookie, nullptr)); m_state = Ready; } // ----------------------------------------------------------------------- /** * SyncManager manages a set of fences used for explicit synchronization * with the X command stream. */ class SyncManager { public: enum { MaxFences = 4 }; SyncManager(); ~SyncManager(); SyncObject *nextFence(); bool updateFences(); private: std::array m_fences; int m_next; }; SyncManager::SyncManager() : m_next(0) { } SyncManager::~SyncManager() { } SyncObject *SyncManager::nextFence() { SyncObject *fence = &m_fences[m_next]; m_next = (m_next + 1) % MaxFences; return fence; } bool SyncManager::updateFences() { for (int i = 0; i < qMin(2, MaxFences - 1); i++) { const int index = (m_next + i) % MaxFences; SyncObject &fence = m_fences[index]; switch (fence.state()) { case SyncObject::Ready: break; case SyncObject::TriggerSent: case SyncObject::Waiting: if (!fence.finish()) return false; fence.reset(); break; // Should not happen in practice since we always reset the fence // after finishing it case SyncObject::Done: fence.reset(); break; case SyncObject::Resetting: fence.finishResetting(); break; } } return true; } // ----------------------------------------------------------------------- //**************************************** // SceneOpenGL //**************************************** OpenGLBackend::OpenGLBackend() : m_syncsToVBlank(false) , m_blocksForRetrace(false) , m_directRendering(false) , m_haveBufferAge(false) , m_failed(false) { } OpenGLBackend::~OpenGLBackend() { } void OpenGLBackend::setFailed(const QString &reason) { qCWarning(KWIN_CORE) << "Creating the OpenGL rendering failed: " << reason; m_failed = true; } void OpenGLBackend::idle() { if (hasPendingFlush()) { effects->makeOpenGLContextCurrent(); present(); } } void OpenGLBackend::addToDamageHistory(const QRegion ®ion) { if (m_damageHistory.count() > 10) m_damageHistory.removeLast(); m_damageHistory.prepend(region); } QRegion OpenGLBackend::accumulatedDamageHistory(int bufferAge) const { QRegion region; // Note: An age of zero means the buffer contents are undefined if (bufferAge > 0 && bufferAge <= m_damageHistory.count()) { for (int i = 0; i < bufferAge - 1; i++) region |= m_damageHistory[i]; } else { const QSize &s = screens()->size(); region = QRegion(0, 0, s.width(), s.height()); } return region; } OverlayWindow* OpenGLBackend::overlayWindow() { return NULL; } QRegion OpenGLBackend::prepareRenderingForScreen(int screenId) { // fallback to repaint complete screen return screens()->geometry(screenId); } void OpenGLBackend::endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion) { Q_UNUSED(screenId) Q_UNUSED(damage) Q_UNUSED(damagedRegion) } bool OpenGLBackend::perScreenRendering() const { return false; } /************************************************ * 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_CORE) << "GL_ARB_texture_non_power_of_two and GL_ARB_texture_rectangle missing"; init_ok = false; return; // error } if (glPlatform->isMesaDriver() && glPlatform->mesaVersion() < kVersionNumber(8, 0)) { qCCritical(KWIN_CORE) << "KWin requires at least Mesa 8.0 for OpenGL compositing."; init_ok = false; return; } if (!glPlatform->isGLES() && !m_backend->isSurfaceLessContext()) { glDrawBuffer(GL_BACK); } m_debug = qstrcmp(qgetenv("KWIN_GL_DEBUG"), "1") == 0; initDebugOutput(); // set strict binding if (options->isGlStrictBindingFollowsDriver()) { options->setGlStrictBinding(!glPlatform->supports(LooseBinding)); } bool haveSyncObjects = glPlatform->isGLES() ? hasGLVersion(3, 0) : hasGLVersion(3, 2) || hasGLExtension("GL_ARB_sync"); if (hasGLExtension("GL_EXT_x11_sync_object") && haveSyncObjects) { const QByteArray useExplicitSync = qgetenv("KWIN_EXPLICIT_SYNC"); if (useExplicitSync != "0") { qCDebug(KWIN_CORE) << "Initializing fences for synchronization with the X command stream"; m_syncManager = new SyncManager; } else { qCDebug(KWIN_CORE) << "Explicit synchronization with the X command stream disabled by environment variable"; } } } static SceneOpenGL *gs_debuggedScene = nullptr; SceneOpenGL::~SceneOpenGL() { // do cleanup after initBuffer() gs_debuggedScene = nullptr; SceneOpenGL::EffectFrame::cleanup(); if (init_ok) { delete m_syncManager; // backend might be still needed for a different scene delete m_backend; } } static void scheduleVboReInit() { if (!gs_debuggedScene) return; static QPointer timer; if (!timer) { delete timer; timer = new QTimer(gs_debuggedScene); timer->setSingleShot(true); QObject::connect(timer.data(), &QTimer::timeout, gs_debuggedScene, []() { GLVertexBuffer::cleanup(); GLVertexBuffer::initStatic(); }); } timer->start(250); } void SceneOpenGL::initDebugOutput() { const bool have_KHR_debug = hasGLExtension(QByteArrayLiteral("GL_KHR_debug")); const bool have_ARB_debug = hasGLExtension(QByteArrayLiteral("GL_ARB_debug_output")); if (!have_KHR_debug && !have_ARB_debug) return; if (!have_ARB_debug) { // if we don't have ARB debug, but only KHR debug we need to verify whether the context is a debug context // it should work without as well, but empirical tests show: no it doesn't if (GLPlatform::instance()->isGLES()) { if (!hasGLVersion(3, 2)) { // empirical data shows extension doesn't work return; } } else if (!hasGLVersion(3, 0)) { return; } // can only be queried with either OpenGL >= 3.0 or OpenGL ES of at least 3.1 GLint value = 0; glGetIntegerv(GL_CONTEXT_FLAGS, &value); if (!(value & GL_CONTEXT_FLAG_DEBUG_BIT)) { return; } } gs_debuggedScene = this; // Set the callback function auto callback = [](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *userParam) { Q_UNUSED(source) Q_UNUSED(severity) Q_UNUSED(userParam) while (message[length] == '\n' || message[length] == '\r') --length; switch (type) { case GL_DEBUG_TYPE_ERROR: case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: qCWarning(KWIN_CORE, "%#x: %.*s", id, length, message); break; case GL_DEBUG_TYPE_OTHER: // at least the nvidia driver seems prone to end up with invalid VBOs after // transferring them between system heap and VRAM // so we re-init them whenever this happens (typically when switching VT, resuming // from STR and XRandR events - #344326 if (strstr(message, "Buffer detailed info:") && strstr(message, "has been updated")) scheduleVboReInit(); // fall through! for general message printing case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: case GL_DEBUG_TYPE_PORTABILITY: case GL_DEBUG_TYPE_PERFORMANCE: default: qCDebug(KWIN_CORE, "%#x: %.*s", id, length, message); break; } }; glDebugMessageCallback(callback, nullptr); // This state exists only in GL_KHR_debug if (have_KHR_debug) glEnable(GL_DEBUG_OUTPUT); #ifndef NDEBUG // Enable all debug messages glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); #else // Enable error messages glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR, GL_DONT_CARE, 0, nullptr, GL_TRUE); glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DONT_CARE, 0, nullptr, GL_TRUE); #endif // Insert a test message const QByteArray message = QByteArrayLiteral("OpenGL debug output initialized"); glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0, GL_DEBUG_SEVERITY_LOW, message.length(), message.constData()); } SceneOpenGL *SceneOpenGL::createScene(QObject *parent) { OpenGLBackend *backend = kwinApp()->platform()->createOpenGLBackend(); if (!backend) { return nullptr; } if (!backend->isFailed()) { backend->init(); } if (backend->isFailed()) { delete backend; return NULL; } SceneOpenGL *scene = NULL; // first let's try an OpenGL 2 scene if (SceneOpenGL2::supported(backend)) { scene = new SceneOpenGL2(backend, parent); if (scene->initFailed()) { delete scene; scene = NULL; } else { return scene; } } if (!scene) { if (GLPlatform::instance()->recommendedCompositor() == XRenderCompositing) { qCCritical(KWIN_CORE) << "OpenGL driver recommends XRender based compositing. Falling back to XRender."; qCCritical(KWIN_CORE) << "To overwrite the detection use the environment variable KWIN_COMPOSE"; qCCritical(KWIN_CORE) << "For more information see http://community.kde.org/KWin/Environment_Variables#KWIN_COMPOSE"; QTimer::singleShot(0, Compositor::self(), SLOT(fallbackToXRenderCompositing())); } delete backend; } return scene; } OverlayWindow *SceneOpenGL::overlayWindow() { return m_backend->overlayWindow(); } bool SceneOpenGL::syncsToVBlank() const { return m_backend->syncsToVBlank(); } bool SceneOpenGL::blocksForRetrace() const { return m_backend->blocksForRetrace(); } void SceneOpenGL::idle() { m_backend->idle(); Scene::idle(); } bool SceneOpenGL::initFailed() const { return !init_ok; } void SceneOpenGL::copyPixels(const QRegion ®ion) { const int height = screens()->size().height(); foreach (const QRect &r, region.rects()) { const int x0 = r.x(); const int y0 = height - r.y() - r.height(); const int x1 = r.x() + r.width(); const int y1 = height - r.y(); glBlitFramebuffer(x0, y0, x1, y1, x0, y0, x1, y1, GL_COLOR_BUFFER_BIT, GL_NEAREST); } } void SceneOpenGL::handleGraphicsReset(GLenum status) { switch (status) { case GL_GUILTY_CONTEXT_RESET: qCDebug(KWIN_CORE) << "A graphics reset attributable to the current GL context occurred."; break; case GL_INNOCENT_CONTEXT_RESET: qCDebug(KWIN_CORE) << "A graphics reset not attributable to the current GL context occurred."; break; case GL_UNKNOWN_CONTEXT_RESET: qCDebug(KWIN_CORE) << "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_CORE) << "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(); } } qint64 SceneOpenGL::paint(QRegion damage, ToplevelList toplevels) { // actually paint the frame, flushed with the NEXT frame createStackingOrder(toplevels); // After this call, updateRegion will contain the damaged region in the // back buffer. This is the region that needs to be posted to repair // the front buffer. It doesn't include the additional damage returned // by prepareRenderingFrame(). validRegion is the region that has been // repainted, and may be larger than updateRegion. QRegion updateRegion, validRegion; if (m_backend->perScreenRendering()) { // trigger start render timer m_backend->prepareRenderingFrame(); for (int i = 0; i < screens()->count(); ++i) { const QRect &geo = screens()->geometry(i); QRegion update; QRegion valid; // prepare rendering makes context current on the output QRegion repaint = m_backend->prepareRenderingForScreen(i); 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()); // call generic implementation 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; } 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); 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_CORE) << "Aborting explicit synchronization with the X command stream."; qCDebug(KWIN_CORE) << "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 foreach (const QRect &r, region.rects()) { // 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()); } } SceneOpenGL::Texture *SceneOpenGL::createTexture() { return new Texture(m_backend); } bool SceneOpenGL::viewportLimitsMatched(const QSize &size) const { GLint limit[2]; glGetIntegerv(GL_MAX_VIEWPORT_DIMS, limit); if (limit[0] < size.width() || limit[1] < size.height()) { QMetaObject::invokeMethod(Compositor::self(), "suspend", Qt::QueuedConnection, Q_ARG(Compositor::SuspendReason, Compositor::AllReasonSuspend)); const QString message = i18n("

OpenGL desktop effects not possible

" "Your system cannot perform OpenGL Desktop Effects at the " "current resolution

" "You can try to select the XRender backend, but it " "might be very slow for this resolution as well.
" "Alternatively, lower the combined resolution of all screens " "to %1x%2 ", limit[0], limit[1]); const QString details = i18n("The demanded resolution exceeds the GL_MAX_VIEWPORT_DIMS " "limitation of your GPU and is therefore not compatible " "with the OpenGL compositor.
" "XRender does not know such limitation, but the performance " "will usually be impacted by the hardware limitations that " "restrict the OpenGL viewport size."); const int oldTimeout = QDBusConnection::sessionBus().interface()->timeout(); QDBusConnection::sessionBus().interface()->setTimeout(500); if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QStringLiteral("org.kde.kwinCompositingDialog")).value()) { QDBusInterface dialog( QStringLiteral("org.kde.kwinCompositingDialog"), QStringLiteral("/CompositorSettings"), QStringLiteral("org.kde.kwinCompositingDialog") ); dialog.asyncCall(QStringLiteral("warn"), message, details, QString()); } else { const QString args = QLatin1String("warn ") + QString::fromUtf8(message.toLocal8Bit().toBase64()) + QLatin1String(" details ") + QString::fromUtf8(details.toLocal8Bit().toBase64()); KProcess::startDetached(QStringLiteral("kcmshell5"), QStringList() << QStringLiteral("kwincompositing") << QStringLiteral("--args") << args); } QDBusConnection::sessionBus().interface()->setTimeout(oldTimeout); return false; } glGetIntegerv(GL_MAX_TEXTURE_SIZE, limit); if (limit[0] < size.width() || limit[0] < size.height()) { KConfig cfg(QStringLiteral("kwin_dialogsrc")); if (!KConfigGroup(&cfg, "Notification Messages").readEntry("max_tex_warning", true)) return true; const QString message = i18n("

OpenGL desktop effects might be unusable

" "OpenGL Desktop Effects at the current resolution are supported " "but might be exceptionally slow.
" "Also large windows will turn entirely black.

" "Consider to suspend compositing, switch to the XRender backend " "or lower the resolution to %1x%1." , limit[0]); const QString details = i18n("The demanded resolution exceeds the GL_MAX_TEXTURE_SIZE " "limitation of your GPU, thus windows of that size cannot be " "assigned to textures and will be entirely black.
" "Also this limit will often be a performance level barrier despite " "below GL_MAX_VIEWPORT_DIMS, because the driver might fall back to " "software rendering in this case."); const int oldTimeout = QDBusConnection::sessionBus().interface()->timeout(); QDBusConnection::sessionBus().interface()->setTimeout(500); if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QStringLiteral("org.kde.kwinCompositingDialog")).value()) { QDBusInterface dialog( QStringLiteral("org.kde.kwinCompositingDialog"), QStringLiteral("/CompositorSettings"), QStringLiteral("org.kde.kwinCompositingDialog") ); dialog.asyncCall(QStringLiteral("warn"), message, details, QStringLiteral("kwin_dialogsrc:max_tex_warning")); } else { const QString args = QLatin1String("warn ") + QString::fromUtf8(message.toLocal8Bit().toBase64()) + QLatin1String(" details ") + QString::fromUtf8(details.toLocal8Bit().toBase64()) + QLatin1String(" dontagain kwin_dialogsrc:max_tex_warning"); KProcess::startDetached(QStringLiteral("kcmshell5"), QStringList() << QStringLiteral("kwincompositing") << QStringLiteral("--args") << args); } QDBusConnection::sessionBus().interface()->setTimeout(oldTimeout); } 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); GLVertexBuffer::setVirtualScreenSize(size); } void SceneOpenGL::paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data) { const QRect r = region.boundingRect(); glEnable(GL_SCISSOR_TEST); glScissor(r.x(), screens()->size().height() - r.y() - r.height(), r.width(), r.height()); KWin::Scene::paintDesktop(desktop, mask, region, data); glDisable(GL_SCISSOR_TEST); } bool SceneOpenGL::makeOpenGLContextCurrent() { return m_backend->makeCurrent(); } void SceneOpenGL::doneOpenGLContextCurrent() { m_backend->doneCurrent(); } Scene::EffectFrame *SceneOpenGL::createEffectFrame(EffectFrameImpl *frame) { return new SceneOpenGL::EffectFrame(frame, this); } Shadow *SceneOpenGL::createShadow(Toplevel *toplevel) { return new SceneOpenGLShadow(toplevel); } Decoration::Renderer *SceneOpenGL::createDecorationRenderer(Decoration::DecoratedClientImpl *impl) { return new SceneOpenGLDecorationRenderer(impl); } +bool SceneOpenGL::animationsSupported() const +{ + return !GLPlatform::instance()->isSoftwareEmulation(); +} + //**************************************** // 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_CORE) << "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_CORE) << "Driver does not recommend OpenGL 2 compositing"; return false; } return true; } SceneOpenGL2::SceneOpenGL2(OpenGLBackend *backend, QObject *parent) : SceneOpenGL(backend, parent) , m_lanczosFilter(NULL) , m_colorCorrection() { 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_CORE) << "OpenGL 2.0 is not supported"; init_ok = false; return; } // Initialize color correction before the shaders slotColorCorrectedChanged(false); connect(options, SIGNAL(colorCorrectedChanged()), this, SLOT(slotColorCorrectedChanged()), Qt::QueuedConnection); const QSize &s = screens()->size(); GLRenderTarget::setVirtualScreenSize(s); GLVertexBuffer::setVirtualScreenSize(s); // push one shader on the stack so that one is always bound ShaderManager::instance()->pushShader(ShaderTrait::MapTexture); if (checkGLError("Init")) { qCCritical(KWIN_CORE) << "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_CORE) << "ShaderManager self test failed"; init_ok = false; return; } qCDebug(KWIN_CORE) << "OpenGL 2 compositing successfully initialized"; init_ok = true; } SceneOpenGL2::~SceneOpenGL2() { } QMatrix4x4 SceneOpenGL2::createProjectionMatrix() const { // Create a perspective projection with a 60° field-of-view, // and an aspect ratio of 1.0. const float fovY = 60.0f; const float aspect = 1.0f; const float zNear = 0.1f; const float zFar = 100.0f; const float yMax = zNear * std::tan(fovY * M_PI / 360.0f); const float yMin = -yMax; const float xMin = yMin * aspect; const float xMax = yMax * aspect; QMatrix4x4 projection; projection.frustum(xMin, xMax, yMin, yMax, zNear, zFar); // Create a second matrix that transforms screen coordinates // to world coordinates. const float scaleFactor = 1.1 * std::tan(fovY * M_PI / 360.0f) / yMax; const QSize size = screens()->size(); QMatrix4x4 matrix; matrix.translate(xMin * scaleFactor, yMax * scaleFactor, -1.1); matrix.scale( (xMax - xMin) * scaleFactor / size.width(), -(yMax - yMin) * scaleFactor / size.height(), 0.001); // Combine the matrices return projection * matrix; } void SceneOpenGL2::updateProjectionMatrix() { m_projectionMatrix = createProjectionMatrix(); } void SceneOpenGL2::paintSimpleScreen(int mask, QRegion region) { m_screenProjectionMatrix = m_projectionMatrix; Scene::paintSimpleScreen(mask, region); } void SceneOpenGL2::paintGenericScreen(int mask, ScreenPaintData data) { const QMatrix4x4 screenMatrix = transformation(mask, data); m_screenProjectionMatrix = m_projectionMatrix * screenMatrix; Scene::paintGenericScreen(mask, data); } void SceneOpenGL2::doPaintBackground(const QVector< float >& vertices) { GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setUseColor(true); vbo->setData(vertices.count() / 2, 2, vertices.data(), NULL); ShaderBinder binder(ShaderTrait::UniformColor); binder.shader()->setUniform(GLShader::ModelViewProjectionMatrix, m_projectionMatrix); vbo->render(GL_TRIANGLES); } Scene::Window *SceneOpenGL2::createWindow(Toplevel *t) { SceneOpenGL2Window *w = new SceneOpenGL2Window(t); w->setScene(this); return w; } void SceneOpenGL2::finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data) { if (waylandServer() && waylandServer()->isScreenLocked() && !w->window()->isLockScreen() && !w->window()->isInputMethod()) { return; } if (!m_colorCorrection.isNull() && m_colorCorrection->isEnabled()) { // Split the painting for separate screens const int numScreens = screens()->count(); for (int screen = 0; screen < numScreens; ++ screen) { QRegion regionForScreen(region); if (numScreens > 1) regionForScreen = region.intersected(screens()->geometry(screen)); data.setScreen(screen); performPaintWindow(w, mask, regionForScreen, data); } } else { 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); // recreate the lanczos filter when the screen gets resized connect(screens(), SIGNAL(changed()), SLOT(resetLanczosFilter())); } m_lanczosFilter->performPaint(w, mask, region, data); } else w->sceneWindow()->performPaint(mask, region, data); } void SceneOpenGL2::resetLanczosFilter() { // TODO: Qt5 - replace by a lambda slot delete m_lanczosFilter; m_lanczosFilter = NULL; } ColorCorrection *SceneOpenGL2::colorCorrection() { return m_colorCorrection.data(); } void SceneOpenGL2::slotColorCorrectedChanged(bool recreateShaders) { qCDebug(KWIN_CORE) << "Color correction:" << options->isColorCorrected(); if (options->isColorCorrected() && m_colorCorrection.isNull()) { m_colorCorrection.reset(new ColorCorrection(this)); if (!m_colorCorrection->setEnabled(true)) { m_colorCorrection.reset(); return; } connect(m_colorCorrection.data(), SIGNAL(changed()), Compositor::self(), SLOT(addRepaintFull())); connect(m_colorCorrection.data(), SIGNAL(errorOccured()), options, SLOT(setColorCorrected()), Qt::QueuedConnection); if (recreateShaders) { // Reload all shaders ShaderManager::cleanup(); ShaderManager::instance(); } } else { m_colorCorrection.reset(); } Compositor::self()->addRepaintFull(); } //**************************************** // SceneOpenGL::Texture //**************************************** SceneOpenGL::Texture::Texture(OpenGLBackend *backend) : GLTexture(*backend->createBackendTexture(this)) { } SceneOpenGL::Texture::~Texture() { } SceneOpenGL::Texture& SceneOpenGL::Texture::operator = (const SceneOpenGL::Texture& tex) { d_ptr = tex.d_ptr; return *this; } void SceneOpenGL::Texture::discard() { d_ptr = d_func()->backend()->createBackendTexture(this); } bool SceneOpenGL::Texture::load(WindowPixmap *pixmap) { if (!pixmap->isValid()) { return false; } // decrease the reference counter for the old texture d_ptr = d_func()->backend()->createBackendTexture(this); //new TexturePrivate(); Q_D(Texture); return d->loadTexture(pixmap); } void SceneOpenGL::Texture::updateFromPixmap(WindowPixmap *pixmap) { Q_D(Texture); d->updateTexture(pixmap); } //**************************************** // SceneOpenGL::Texture //**************************************** SceneOpenGL::TexturePrivate::TexturePrivate() { } SceneOpenGL::TexturePrivate::~TexturePrivate() { } void SceneOpenGL::TexturePrivate::updateTexture(WindowPixmap *pixmap) { Q_UNUSED(pixmap) } //**************************************** // SceneOpenGL::Window //**************************************** SceneOpenGL::Window::Window(Toplevel* c) : Scene::Window(c) , m_scene(NULL) { } SceneOpenGL::Window::~Window() { } static SceneOpenGL::Texture *s_frameTexture = NULL; // Bind the window pixmap to an OpenGL texture. bool SceneOpenGL::Window::bindTexture() { s_frameTexture = NULL; OpenGLWindowPixmap *pixmap = windowPixmap(); if (!pixmap) { return false; } s_frameTexture = pixmap->texture(); if (pixmap->isDiscarded()) { return !pixmap->texture()->isNull(); } if (!window()->damage().isEmpty()) m_scene->insertWait(); return pixmap->bind(); } QMatrix4x4 SceneOpenGL::Window::transformation(int mask, const WindowPaintData &data) const { QMatrix4x4 matrix; matrix.translate(x(), y()); if (!(mask & PAINT_WINDOW_TRANSFORMED)) return matrix; matrix.translate(data.translation()); data.scale().applyTo(&matrix); if (data.rotationAngle() == 0.0) return matrix; // Apply the rotation // cannot use data.rotation.applyTo(&matrix) as QGraphicsRotation uses projectedRotate to map back to 2D matrix.translate(data.rotationOrigin()); const QVector3D axis = data.rotationAxis(); matrix.rotate(data.rotationAngle(), axis.x(), axis.y(), axis.z()); matrix.translate(-data.rotationOrigin()); return matrix; } bool SceneOpenGL::Window::beginRenderWindow(int mask, const QRegion ®ion, WindowPaintData &data) { if (region.isEmpty()) return false; m_hardwareClipping = region != infiniteRegion() && (mask & PAINT_WINDOW_TRANSFORMED) && !(mask & PAINT_SCREEN_TRANSFORMED); if (region != infiniteRegion() && !m_hardwareClipping) { WindowQuadList quads; quads.reserve(data.quads.count()); const QRegion filterRegion = region.translated(-x(), -y()); // split all quads in bounding rect with the actual rects in the region foreach (const WindowQuad &quad, data.quads) { foreach (const QRect &r, filterRegion.rects()) { const QRectF rf(r); const QRectF quadRect(QPointF(quad.left(), quad.top()), QPointF(quad.right(), quad.bottom())); const QRectF &intersected = rf.intersected(quadRect); if (intersected.isValid()) { if (quadRect == intersected) { // case 1: completely contains, include and do not check other rects quads << quad; break; } // case 2: intersection quads << quad.makeSubQuad(intersected.left(), intersected.top(), intersected.right(), intersected.bottom()); } } } data.quads = quads; } if (data.quads.isEmpty()) return false; if (!bindTexture() || !s_frameTexture) { return false; } if (m_hardwareClipping) { glEnable(GL_SCISSOR_TEST); } // Update the texture filter if (options->glSmoothScale() != 0 && (mask & (PAINT_WINDOW_TRANSFORMED | PAINT_SCREEN_TRANSFORMED))) filter = ImageFilterGood; else filter = ImageFilterFast; s_frameTexture->setFilter(filter == ImageFilterGood ? GL_LINEAR : GL_NEAREST); const GLVertexAttrib attribs[] = { { VA_Position, 2, GL_FLOAT, offsetof(GLVertex2D, position) }, { VA_TexCoord, 2, GL_FLOAT, offsetof(GLVertex2D, texcoord) }, }; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setAttribLayout(attribs, 2, sizeof(GLVertex2D)); return true; } void SceneOpenGL::Window::endRenderWindow() { if (m_hardwareClipping) { glDisable(GL_SCISSOR_TEST); } } GLTexture *SceneOpenGL::Window::getDecorationTexture() const { if (AbstractClient *client = dynamic_cast(toplevel)) { if (client->noBorder()) { return nullptr; } if (!client->isDecorated()) { return nullptr; } if (SceneOpenGLDecorationRenderer *renderer = static_cast(client->decoratedClient()->renderer())) { renderer->render(); return renderer->texture(); } } else if (toplevel->isDeleted()) { Deleted *deleted = static_cast(toplevel); if (!deleted->wasClient() || deleted->noBorder()) { return nullptr; } if (const SceneOpenGLDecorationRenderer *renderer = static_cast(deleted->decorationRenderer())) { return renderer->texture(); } } return nullptr; } WindowPixmap* SceneOpenGL::Window::createWindowPixmap() { return new OpenGLWindowPixmap(this, m_scene); } //*************************************** // SceneOpenGL2Window //*************************************** SceneOpenGL2Window::SceneOpenGL2Window(Toplevel *c) : SceneOpenGL::Window(c) , m_blendingEnabled(false) { } SceneOpenGL2Window::~SceneOpenGL2Window() { } QVector4D SceneOpenGL2Window::modulate(float opacity, float brightness) const { const float a = opacity; const float rgb = opacity * brightness; return QVector4D(rgb, rgb, rgb, a); } void SceneOpenGL2Window::setBlendEnabled(bool enabled) { if (enabled && !m_blendingEnabled) glEnable(GL_BLEND); else if (!enabled && m_blendingEnabled) glDisable(GL_BLEND); m_blendingEnabled = enabled; } void SceneOpenGL2Window::setupLeafNodes(LeafNode *nodes, const WindowQuadList *quads, const WindowPaintData &data) { if (!quads[ShadowLeaf].isEmpty()) { nodes[ShadowLeaf].texture = static_cast(m_shadow)->shadowTexture(); nodes[ShadowLeaf].opacity = data.opacity(); nodes[ShadowLeaf].hasAlpha = true; nodes[ShadowLeaf].coordinateType = NormalizedCoordinates; } if (!quads[DecorationLeaf].isEmpty()) { nodes[DecorationLeaf].texture = getDecorationTexture(); nodes[DecorationLeaf].opacity = data.opacity(); nodes[DecorationLeaf].hasAlpha = true; nodes[DecorationLeaf].coordinateType = UnnormalizedCoordinates; } nodes[ContentLeaf].texture = s_frameTexture; nodes[ContentLeaf].hasAlpha = !isOpaque(); // TODO: ARGB crsoofading is atm. a hack, playing on opacities for two dumb SrcOver operations // Should be a shader if (data.crossFadeProgress() != 1.0 && (data.opacity() < 0.95 || toplevel->hasAlpha())) { const float opacity = 1.0 - data.crossFadeProgress(); nodes[ContentLeaf].opacity = data.opacity() * (1 - pow(opacity, 1.0f + 2.0f * data.opacity())); } else { nodes[ContentLeaf].opacity = data.opacity(); } nodes[ContentLeaf].coordinateType = UnnormalizedCoordinates; if (data.crossFadeProgress() != 1.0) { OpenGLWindowPixmap *previous = previousWindowPixmap(); nodes[PreviousContentLeaf].texture = previous ? previous->texture() : NULL; nodes[PreviousContentLeaf].hasAlpha = !isOpaque(); nodes[PreviousContentLeaf].opacity = data.opacity() * (1.0 - data.crossFadeProgress()); nodes[PreviousContentLeaf].coordinateType = NormalizedCoordinates; } } QMatrix4x4 SceneOpenGL2Window::modelViewProjectionMatrix(int mask, const WindowPaintData &data) const { SceneOpenGL2 *scene = static_cast(m_scene); const QMatrix4x4 pMatrix = data.projectionMatrix(); const QMatrix4x4 mvMatrix = data.modelViewMatrix(); // An effect may want to override the default projection matrix in some cases, // such as when it is rendering a window on a render target that doesn't have // the same dimensions as the default framebuffer. // // Note that the screen transformation is not applied here. if (!pMatrix.isIdentity()) return pMatrix * mvMatrix; // If an effect has specified a model-view matrix, we multiply that matrix // with the default projection matrix. If the effect hasn't specified a // model-view matrix, mvMatrix will be the identity matrix. if (mask & Scene::PAINT_SCREEN_TRANSFORMED) return scene->screenProjectionMatrix() * mvMatrix; return scene->projectionMatrix() * mvMatrix; } static void renderSubSurface(GLShader *shader, const QMatrix4x4 &mvp, const QMatrix4x4 &windowMatrix, OpenGLWindowPixmap *pixmap) { QMatrix4x4 newWindowMatrix = windowMatrix; newWindowMatrix.translate(pixmap->subSurface()->position().x(), pixmap->subSurface()->position().y()); if (!pixmap->texture()->isNull()) { // render this texture shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp * newWindowMatrix); auto texture = pixmap->texture(); texture->bind(); texture->render(QRegion(), QRect(0, 0, texture->width(), texture->height())); 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)); } } void SceneOpenGL2Window::performPaint(int mask, QRegion region, WindowPaintData data) { if (!beginRenderWindow(mask, region, data)) return; SceneOpenGL2 *scene = static_cast(m_scene); QMatrix4x4 windowMatrix = transformation(mask, data); const QMatrix4x4 modelViewProjection = modelViewProjectionMatrix(mask, data); const QMatrix4x4 mvpMatrix = modelViewProjection * windowMatrix; GLShader *shader = data.shader; if (!shader) { ShaderTraits traits = ShaderTrait::MapTexture; if (data.opacity() != 1.0 || data.brightness() != 1.0 || data.crossFadeProgress() != 1.0) traits |= ShaderTrait::Modulate; if (data.saturation() != 1.0) traits |= ShaderTrait::AdjustSaturation; shader = ShaderManager::instance()->pushShader(traits); } shader->setUniform(GLShader::ModelViewProjectionMatrix, mvpMatrix); if (ColorCorrection *cc = scene->colorCorrection()) { cc->setupForOutput(data.screen()); } shader->setUniform(GLShader::Saturation, data.saturation()); const GLenum filter = (mask & (Effect::PAINT_WINDOW_TRANSFORMED | Effect::PAINT_SCREEN_TRANSFORMED)) && options->glSmoothScale() != 0 ? GL_LINEAR : GL_NEAREST; WindowQuadList quads[LeafCount]; // Split the quads into separate lists for each type foreach (const WindowQuad &quad, data.quads) { switch (quad.type()) { case WindowQuadDecoration: quads[DecorationLeaf].append(quad); continue; case WindowQuadContents: quads[ContentLeaf].append(quad); continue; case WindowQuadShadow: quads[ShadowLeaf].append(quad); continue; default: continue; } } if (data.crossFadeProgress() != 1.0) { OpenGLWindowPixmap *previous = previousWindowPixmap(); if (previous) { const QRect &oldGeometry = previous->contentsRect(); for (const WindowQuad &quad : quads[ContentLeaf]) { // we need to create new window quads with normalize texture coordinates // normal quads divide the x/y position by width/height. This would not work as the texture // is larger than the visible content in case of a decorated Client resulting in garbage being shown. // So we calculate the normalized texture coordinate in the Client's new content space and map it to // the previous Client's content space. WindowQuad newQuad(WindowQuadContents); for (int i = 0; i < 4; ++i) { const qreal xFactor = qreal(quad[i].textureX() - toplevel->clientPos().x())/qreal(toplevel->clientSize().width()); const qreal yFactor = qreal(quad[i].textureY() - toplevel->clientPos().y())/qreal(toplevel->clientSize().height()); WindowVertex vertex(quad[i].x(), quad[i].y(), (xFactor * oldGeometry.width() + oldGeometry.x())/qreal(previous->size().width()), (yFactor * oldGeometry.height() + oldGeometry.y())/qreal(previous->size().height())); newQuad[i] = vertex; } quads[PreviousContentLeaf].append(newQuad); } } } const bool indexedQuads = GLVertexBuffer::supportsIndexedQuads(); const GLenum primitiveType = indexedQuads ? GL_QUADS : GL_TRIANGLES; const int verticesPerQuad = indexedQuads ? 4 : 6; const size_t size = verticesPerQuad * (quads[0].count() + quads[1].count() + quads[2].count() + quads[3].count()) * sizeof(GLVertex2D); GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); GLVertex2D *map = (GLVertex2D *) vbo->map(size); LeafNode nodes[LeafCount]; setupLeafNodes(nodes, quads, data); for (int i = 0, v = 0; i < LeafCount; i++) { if (quads[i].isEmpty() || !nodes[i].texture) continue; nodes[i].firstVertex = v; nodes[i].vertexCount = quads[i].count() * verticesPerQuad; const QMatrix4x4 matrix = nodes[i].texture->matrix(nodes[i].coordinateType); quads[i].makeInterleavedArrays(primitiveType, &map[v], matrix); v += quads[i].count() * verticesPerQuad; } vbo->unmap(); vbo->bindArrays(); // Make sure the blend function is set up correctly in case we will be doing blending glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); float opacity = -1.0; for (int i = 0; i < LeafCount; i++) { if (nodes[i].vertexCount == 0) continue; setBlendEnabled(nodes[i].hasAlpha || nodes[i].opacity < 1.0); if (opacity != nodes[i].opacity) { shader->setUniform(GLShader::ModulationConstant, modulate(nodes[i].opacity, data.brightness())); opacity = nodes[i].opacity; } nodes[i].texture->setFilter(filter); nodes[i].texture->setWrapMode(GL_CLAMP_TO_EDGE); nodes[i].texture->bind(); vbo->draw(region, primitiveType, nodes[i].firstVertex, nodes[i].vertexCount, m_hardwareClipping); } vbo->unbindArrays(); setBlendEnabled(false); // render sub-surfaces auto wp = windowPixmap(); const auto &children = wp ? wp->children() : QVector(); windowMatrix.translate(toplevel->clientPos().x(), toplevel->clientPos().y()); for (auto pixmap : children) { if (pixmap->subSurface().isNull() || pixmap->subSurface()->surface().isNull() || !pixmap->subSurface()->surface()->isMapped()) { continue; } renderSubSurface(shader, modelViewProjection, windowMatrix, static_cast(pixmap)); } if (!data.shader) ShaderManager::instance()->popShader(); endRenderWindow(); } //**************************************** // OpenGLWindowPixmap //**************************************** OpenGLWindowPixmap::OpenGLWindowPixmap(Scene::Window *window, SceneOpenGL* scene) : WindowPixmap(window) , m_texture(scene->createTexture()) , m_scene(scene) { } OpenGLWindowPixmap::OpenGLWindowPixmap(const QPointer &subSurface, WindowPixmap *parent, SceneOpenGL *scene) : WindowPixmap(subSurface, parent) , m_texture(scene->createTexture()) , m_scene(scene) { } OpenGLWindowPixmap::~OpenGLWindowPixmap() { } bool OpenGLWindowPixmap::bind() { if (!m_texture->isNull()) { // always call updateBuffer to get the sub-surface tree updated if (subSurface().isNull() && !toplevel()->damage().isEmpty()) { updateBuffer(); } auto s = surface(); if (s && !s->trackedDamage().isEmpty()) { m_texture->updateFromPixmap(this); // mipmaps need to be updated m_texture->setDirty(); } if (subSurface().isNull()) { toplevel()->resetDamage(); } // also bind all children for (auto it = children().constBegin(); it != children().constEnd(); ++it) { static_cast(*it)->bind(); } return true; } // also bind all children, needs to be done before checking isValid // as there might be valid children to render, see https://bugreports.qt.io/browse/QTBUG-52192 if (subSurface().isNull()) { updateBuffer(); } for (auto it = children().constBegin(); it != children().constEnd(); ++it) { static_cast(*it)->bind(); } if (!isValid()) { return false; } bool success = m_texture->load(this); if (success) { if (subSurface().isNull()) { toplevel()->resetDamage(); } } else qCDebug(KWIN_CORE) << "Failed to bind window"; return success; } WindowPixmap *OpenGLWindowPixmap::createChild(const QPointer &subSurface) { return new OpenGLWindowPixmap(subSurface, this, m_scene); } //**************************************** // SceneOpenGL::EffectFrame //**************************************** GLTexture* SceneOpenGL::EffectFrame::m_unstyledTexture = NULL; QPixmap* SceneOpenGL::EffectFrame::m_unstyledPixmap = NULL; SceneOpenGL::EffectFrame::EffectFrame(EffectFrameImpl* frame, SceneOpenGL *scene) : Scene::EffectFrame(frame) , m_texture(NULL) , m_textTexture(NULL) , m_oldTextTexture(NULL) , m_textPixmap(NULL) , m_iconTexture(NULL) , m_oldIconTexture(NULL) , m_selectionTexture(NULL) , m_unstyledVBO(NULL) , m_scene(scene) { if (m_effectFrame->style() == EffectFrameUnstyled && !m_unstyledTexture) { updateUnstyledTexture(); } } SceneOpenGL::EffectFrame::~EffectFrame() { delete m_texture; delete m_textTexture; delete m_textPixmap; delete m_oldTextTexture; delete m_iconTexture; delete m_oldIconTexture; delete m_selectionTexture; delete m_unstyledVBO; } void SceneOpenGL::EffectFrame::free() { glFlush(); delete m_texture; m_texture = NULL; delete m_textTexture; m_textTexture = NULL; delete m_textPixmap; m_textPixmap = NULL; delete m_iconTexture; m_iconTexture = NULL; delete m_selectionTexture; m_selectionTexture = NULL; delete m_unstyledVBO; m_unstyledVBO = NULL; delete m_oldIconTexture; m_oldIconTexture = NULL; delete m_oldTextTexture; m_oldTextTexture = NULL; } void SceneOpenGL::EffectFrame::freeIconFrame() { delete m_iconTexture; m_iconTexture = NULL; } void SceneOpenGL::EffectFrame::freeTextFrame() { delete m_textTexture; m_textTexture = NULL; delete m_textPixmap; m_textPixmap = NULL; } void SceneOpenGL::EffectFrame::freeSelection() { delete m_selectionTexture; m_selectionTexture = NULL; } void SceneOpenGL::EffectFrame::crossFadeIcon() { delete m_oldIconTexture; m_oldIconTexture = m_iconTexture; m_iconTexture = NULL; } void SceneOpenGL::EffectFrame::crossFadeText() { delete m_oldTextTexture; m_oldTextTexture = m_textTexture; m_textTexture = NULL; } void SceneOpenGL::EffectFrame::render(QRegion region, double opacity, double frameOpacity) { if (m_effectFrame->geometry().isEmpty()) return; // Nothing to display region = infiniteRegion(); // TODO: Old region doesn't seem to work with OpenGL GLShader* shader = m_effectFrame->shader(); if (!shader) { shader = ShaderManager::instance()->pushShader(ShaderTrait::MapTexture | ShaderTrait::Modulate); } else if (shader) { ShaderManager::instance()->pushShader(shader); } if (shader) { shader->setUniform(GLShader::ModulationConstant, QVector4D(1.0, 1.0, 1.0, 1.0)); shader->setUniform(GLShader::Saturation, 1.0f); } const QMatrix4x4 projection = m_scene->projectionMatrix(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Render the actual frame if (m_effectFrame->style() == EffectFrameUnstyled) { if (!m_unstyledVBO) { m_unstyledVBO = new GLVertexBuffer(GLVertexBuffer::Static); QRect area = m_effectFrame->geometry(); area.moveTo(0, 0); area.adjust(-5, -5, 5, 5); const int roundness = 5; QVector verts, texCoords; verts.reserve(84); texCoords.reserve(84); // top left verts << area.left() << area.top(); texCoords << 0.0f << 0.0f; verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; // top verts << area.left() + roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.left() + roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; // top right verts << area.right() - roundness << area.top(); texCoords << 0.5f << 0.0f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() << area.top(); texCoords << 1.0f << 0.0f; verts << area.right() - roundness << area.top() + roundness; texCoords << 0.5f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; verts << area.right() << area.top(); texCoords << 1.0f << 0.0f; // bottom left verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.left() << area.bottom(); texCoords << 0.0f << 1.0f; verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.left() << area.bottom(); texCoords << 0.0f << 1.0f; verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; // bottom verts << area.left() + roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.left() + roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; // bottom right verts << area.right() - roundness << area.bottom() - roundness; texCoords << 0.5f << 0.5f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; verts << area.right() - roundness << area.bottom(); texCoords << 0.5f << 1.0f; verts << area.right() << area.bottom(); texCoords << 1.0f << 1.0f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; // center verts << area.left() << area.top() + roundness; texCoords << 0.0f << 0.5f; verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; verts << area.left() << area.bottom() - roundness; texCoords << 0.0f << 0.5f; verts << area.right() << area.bottom() - roundness; texCoords << 1.0f << 0.5f; verts << area.right() << area.top() + roundness; texCoords << 1.0f << 0.5f; m_unstyledVBO->setData(verts.count() / 2, 2, verts.data(), texCoords.data()); } if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_unstyledTexture->bind(); const QPoint pt = m_effectFrame->geometry().topLeft(); QMatrix4x4 mvp(projection); mvp.translate(pt.x(), pt.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_unstyledVBO->render(region, GL_TRIANGLES); m_unstyledTexture->unbind(); } else if (m_effectFrame->style() == EffectFrameStyled) { if (!m_texture) // Lazy creation updateTexture(); if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_texture->bind(); qreal left, top, right, bottom; m_effectFrame->frame().getMargins(left, top, right, bottom); // m_geometry is the inner geometry const QRect rect = m_effectFrame->geometry().adjusted(-left, -top, right, bottom); QMatrix4x4 mvp(projection); mvp.translate(rect.x(), rect.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); m_texture->render(region, rect); m_texture->unbind(); } if (!m_effectFrame->selection().isNull()) { if (!m_selectionTexture) { // Lazy creation QPixmap pixmap = m_effectFrame->selectionFrame().framePixmap(); if (!pixmap.isNull()) m_selectionTexture = new GLTexture(pixmap); } if (m_selectionTexture) { if (shader) { const float a = opacity * frameOpacity; shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } QMatrix4x4 mvp(projection); mvp.translate(m_effectFrame->selection().x(), m_effectFrame->selection().y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); m_selectionTexture->bind(); m_selectionTexture->render(region, m_effectFrame->selection()); m_selectionTexture->unbind(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } // Render icon if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) { QPoint topLeft(m_effectFrame->geometry().x(), m_effectFrame->geometry().center().y() - m_effectFrame->iconSize().height() / 2); QMatrix4x4 mvp(projection); mvp.translate(topLeft.x(), topLeft.y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); if (m_effectFrame->isCrossFade() && m_oldIconTexture) { if (shader) { const float a = opacity * (1.0 - m_effectFrame->crossFadeProgress()); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_oldIconTexture->bind(); m_oldIconTexture->render(region, QRect(topLeft, m_effectFrame->iconSize())); m_oldIconTexture->unbind(); if (shader) { const float a = opacity * m_effectFrame->crossFadeProgress(); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } } else { if (shader) { const QVector4D constant(opacity, opacity, opacity, opacity); shader->setUniform(GLShader::ModulationConstant, constant); } } if (!m_iconTexture) { // lazy creation m_iconTexture = new GLTexture(m_effectFrame->icon().pixmap(m_effectFrame->iconSize())); } m_iconTexture->bind(); m_iconTexture->render(region, QRect(topLeft, m_effectFrame->iconSize())); m_iconTexture->unbind(); } // Render text if (!m_effectFrame->text().isEmpty()) { QMatrix4x4 mvp(projection); mvp.translate(m_effectFrame->geometry().x(), m_effectFrame->geometry().y()); shader->setUniform(GLShader::ModelViewProjectionMatrix, mvp); if (m_effectFrame->isCrossFade() && m_oldTextTexture) { if (shader) { const float a = opacity * (1.0 - m_effectFrame->crossFadeProgress()); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } m_oldTextTexture->bind(); m_oldTextTexture->render(region, m_effectFrame->geometry()); m_oldTextTexture->unbind(); if (shader) { const float a = opacity * m_effectFrame->crossFadeProgress(); shader->setUniform(GLShader::ModulationConstant, QVector4D(a, a, a, a)); } } else { if (shader) { const QVector4D constant(opacity, opacity, opacity, opacity); shader->setUniform(GLShader::ModulationConstant, constant); } } if (!m_textTexture) // Lazy creation updateTextTexture(); if (m_textTexture) { m_textTexture->bind(); m_textTexture->render(region, m_effectFrame->geometry()); m_textTexture->unbind(); } } if (shader) { ShaderManager::instance()->popShader(); } glDisable(GL_BLEND); } void SceneOpenGL::EffectFrame::updateTexture() { delete m_texture; m_texture = 0L; if (m_effectFrame->style() == EffectFrameStyled) { QPixmap pixmap = m_effectFrame->frame().framePixmap(); m_texture = new GLTexture(pixmap); } } void SceneOpenGL::EffectFrame::updateTextTexture() { delete m_textTexture; m_textTexture = 0L; delete m_textPixmap; m_textPixmap = 0L; if (m_effectFrame->text().isEmpty()) return; // Determine position on texture to paint text QRect rect(QPoint(0, 0), m_effectFrame->geometry().size()); if (!m_effectFrame->icon().isNull() && !m_effectFrame->iconSize().isEmpty()) rect.setLeft(m_effectFrame->iconSize().width()); // If static size elide text as required QString text = m_effectFrame->text(); if (m_effectFrame->isStatic()) { QFontMetrics metrics(m_effectFrame->font()); text = metrics.elidedText(text, Qt::ElideRight, rect.width()); } m_textPixmap = new QPixmap(m_effectFrame->geometry().size()); m_textPixmap->fill(Qt::transparent); QPainter p(m_textPixmap); p.setFont(m_effectFrame->font()); if (m_effectFrame->style() == EffectFrameStyled) p.setPen(m_effectFrame->styledTextColor()); else // TODO: What about no frame? Custom color setting required p.setPen(Qt::white); p.drawText(rect, m_effectFrame->alignment(), text); p.end(); m_textTexture = new GLTexture(*m_textPixmap); } void SceneOpenGL::EffectFrame::updateUnstyledTexture() { delete m_unstyledTexture; m_unstyledTexture = 0L; delete m_unstyledPixmap; m_unstyledPixmap = 0L; // Based off circle() from kwinxrenderutils.cpp #define CS 8 m_unstyledPixmap = new QPixmap(2 * CS, 2 * CS); m_unstyledPixmap->fill(Qt::transparent); QPainter p(m_unstyledPixmap); p.setRenderHint(QPainter::Antialiasing); p.setPen(Qt::NoPen); p.setBrush(Qt::black); p.drawEllipse(m_unstyledPixmap->rect()); p.end(); #undef CS m_unstyledTexture = new GLTexture(*m_unstyledPixmap); } void SceneOpenGL::EffectFrame::cleanup() { delete m_unstyledTexture; m_unstyledTexture = NULL; delete m_unstyledPixmap; m_unstyledPixmap = NULL; } //**************************************** // SceneOpenGL::Shadow //**************************************** class DecorationShadowTextureCache { public: ~DecorationShadowTextureCache(); DecorationShadowTextureCache(const DecorationShadowTextureCache&) = delete; static DecorationShadowTextureCache &instance(); void unregister(SceneOpenGLShadow *shadow); QSharedPointer getTexture(SceneOpenGLShadow *shadow); private: DecorationShadowTextureCache() = default; struct Data { QSharedPointer texture; QVector shadows; }; QHash m_cache; }; DecorationShadowTextureCache &DecorationShadowTextureCache::instance() { static DecorationShadowTextureCache s_instance; return s_instance; } DecorationShadowTextureCache::~DecorationShadowTextureCache() { Q_ASSERT(m_cache.isEmpty()); } void DecorationShadowTextureCache::unregister(SceneOpenGLShadow *shadow) { auto it = m_cache.begin(); while (it != m_cache.end()) { auto &d = it.value(); // check whether the Vector of Shadows contains our shadow and remove all of them auto glIt = d.shadows.begin(); while (glIt != d.shadows.end()) { if (*glIt == shadow) { glIt = d.shadows.erase(glIt); } else { glIt++; } } // if there are no shadows any more we can erase the cache entry if (d.shadows.isEmpty()) { it = m_cache.erase(it); } else { it++; } } } QSharedPointer DecorationShadowTextureCache::getTexture(SceneOpenGLShadow *shadow) { Q_ASSERT(shadow->hasDecorationShadow()); unregister(shadow); const auto &decoShadow = shadow->decorationShadow(); Q_ASSERT(!decoShadow.isNull()); auto it = m_cache.find(decoShadow.data()); if (it != m_cache.end()) { Q_ASSERT(!it.value().shadows.contains(shadow)); it.value().shadows << shadow; return it.value().texture; } Data d; d.shadows << shadow; d.texture = QSharedPointer::create(shadow->decorationShadowImage()); m_cache.insert(decoShadow.data(), d); return d.texture; } SceneOpenGLShadow::SceneOpenGLShadow(Toplevel *toplevel) : Shadow(toplevel) { } SceneOpenGLShadow::~SceneOpenGLShadow() { if (effects) { effects->makeOpenGLContextCurrent(); DecorationShadowTextureCache::instance().unregister(this); m_texture.reset(); } } void SceneOpenGLShadow::buildQuads() { // prepare window quads m_shadowQuads.clear(); 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)); if ((left.width() - leftOffset() > topLevel()->width()) || (right.width() - rightOffset() > topLevel()->width()) || (top.height() - topOffset() > topLevel()->height()) || (bottom.height() - bottomOffset() > topLevel()->height())) { // if our shadow is bigger than the window, we don't render the shadow setShadowRegion(QRegion()); return; } const QRectF outerRect(QPointF(-leftOffset(), -topOffset()), QPointF(topLevel()->width() + rightOffset(), topLevel()->height() + bottomOffset())); const int width = qMax(topLeft.width(), bottomLeft.width()) + qMax(top.width(), bottom.width()) + qMax(topRight.width(), bottomRight.width()); const int height = qMax(topLeft.height(), topRight.height()) + qMax(left.height(), right.height()) + qMax(bottomLeft.height(), bottomRight.height()); qreal tx1(0.0), tx2(0.0), ty1(0.0), ty2(0.0); tx2 = topLeft.width()/width; ty2 = topLeft.height()/height; WindowQuad topLeftQuad(WindowQuadShadow); topLeftQuad[ 0 ] = WindowVertex(outerRect.x(), outerRect.y(), tx1, ty1); topLeftQuad[ 1 ] = WindowVertex(outerRect.x() + topLeft.width(), outerRect.y(), tx2, ty1); topLeftQuad[ 2 ] = WindowVertex(outerRect.x() + topLeft.width(), outerRect.y() + topLeft.height(), tx2, ty2); topLeftQuad[ 3 ] = WindowVertex(outerRect.x(), outerRect.y() + topLeft.height(), tx1, ty2); m_shadowQuads.append(topLeftQuad); tx1 = tx2; tx2 = (topLeft.width() + top.width())/width; ty2 = top.height()/height; WindowQuad topQuad(WindowQuadShadow); topQuad[ 0 ] = WindowVertex(outerRect.x() + topLeft.width(), outerRect.y(), tx1, ty1); topQuad[ 1 ] = WindowVertex(outerRect.right() - topRight.width(), outerRect.y(), tx2, ty1); topQuad[ 2 ] = WindowVertex(outerRect.right() - topRight.width(), outerRect.y() + top.height(),tx2, ty2); topQuad[ 3 ] = WindowVertex(outerRect.x() + topLeft.width(), outerRect.y() + top.height(), tx1, ty2); m_shadowQuads.append(topQuad); tx1 = tx2; tx2 = 1.0; ty2 = topRight.height()/height; WindowQuad topRightQuad(WindowQuadShadow); topRightQuad[ 0 ] = WindowVertex(outerRect.right() - topRight.width(), outerRect.y(), tx1, ty1); topRightQuad[ 1 ] = WindowVertex(outerRect.right(), outerRect.y(), tx2, ty1); topRightQuad[ 2 ] = WindowVertex(outerRect.right(), outerRect.y() + topRight.height(), tx2, ty2); topRightQuad[ 3 ] = WindowVertex(outerRect.right() - topRight.width(), outerRect.y() + topRight.height(), tx1, ty2); m_shadowQuads.append(topRightQuad); tx1 = (width - right.width())/width; ty1 = topRight.height()/height; ty2 = (topRight.height() + right.height())/height; WindowQuad rightQuad(WindowQuadShadow); rightQuad[ 0 ] = WindowVertex(outerRect.right() - right.width(), outerRect.y() + topRight.height(), tx1, ty1); rightQuad[ 1 ] = WindowVertex(outerRect.right(), outerRect.y() + topRight.height(), tx2, ty1); rightQuad[ 2 ] = WindowVertex(outerRect.right(), outerRect.bottom() - bottomRight.height(), tx2, ty2); rightQuad[ 3 ] = WindowVertex(outerRect.right() - right.width(), outerRect.bottom() - bottomRight.height(), tx1, ty2); m_shadowQuads.append(rightQuad); tx1 = (width - bottomRight.width())/width; ty1 = ty2; ty2 = 1.0; WindowQuad bottomRightQuad(WindowQuadShadow); bottomRightQuad[ 0 ] = WindowVertex(outerRect.right() - bottomRight.width(), outerRect.bottom() - bottomRight.height(), tx1, ty1); bottomRightQuad[ 1 ] = WindowVertex(outerRect.right(), outerRect.bottom() - bottomRight.height(), tx2, ty1); bottomRightQuad[ 2 ] = WindowVertex(outerRect.right(), outerRect.bottom(), tx2, ty2); bottomRightQuad[ 3 ] = WindowVertex(outerRect.right() - bottomRight.width(), outerRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomRightQuad); tx2 = tx1; tx1 = bottomLeft.width()/width; ty1 = (height - bottom.height())/height; WindowQuad bottomQuad(WindowQuadShadow); bottomQuad[ 0 ] = WindowVertex(outerRect.x() + bottomLeft.width(), outerRect.bottom() - bottom.height(), tx1, ty1); bottomQuad[ 1 ] = WindowVertex(outerRect.right() - bottomRight.width(), outerRect.bottom() - bottom.height(), tx2, ty1); bottomQuad[ 2 ] = WindowVertex(outerRect.right() - bottomRight.width(), outerRect.bottom(), tx2, ty2); bottomQuad[ 3 ] = WindowVertex(outerRect.x() + bottomLeft.width(), outerRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomQuad); tx1 = 0.0; tx2 = bottomLeft.width()/width; ty1 = (height - bottomLeft.height())/height; WindowQuad bottomLeftQuad(WindowQuadShadow); bottomLeftQuad[ 0 ] = WindowVertex(outerRect.x(), outerRect.bottom() - bottomLeft.height(), tx1, ty1); bottomLeftQuad[ 1 ] = WindowVertex(outerRect.x() + bottomLeft.width(), outerRect.bottom() - bottomLeft.height(), tx2, ty1); bottomLeftQuad[ 2 ] = WindowVertex(outerRect.x() + bottomLeft.width(), outerRect.bottom(), tx2, ty2); bottomLeftQuad[ 3 ] = WindowVertex(outerRect.x(), outerRect.bottom(), tx1, ty2); m_shadowQuads.append(bottomLeftQuad); tx2 = left.width()/width; ty2 = ty1; ty1 = topLeft.height()/height; WindowQuad leftQuad(WindowQuadShadow); leftQuad[ 0 ] = WindowVertex(outerRect.x(), outerRect.y() + topLeft.height(), tx1, ty1); leftQuad[ 1 ] = WindowVertex(outerRect.x() + left.width(), outerRect.y() + topLeft.height(), tx2, ty1); leftQuad[ 2 ] = WindowVertex(outerRect.x() + left.width(), outerRect.bottom() - bottomLeft.height(), tx2, ty2); leftQuad[ 3 ] = WindowVertex(outerRect.x(), outerRect.bottom() - bottomLeft.height(), tx1, ty2); m_shadowQuads.append(leftQuad); } bool SceneOpenGLShadow::prepareBackend() { if (hasDecorationShadow()) { // simplifies a lot by going directly to effects->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 = qMax(topLeft.width(), bottomLeft.width()) + qMax(top.width(), bottom.width()) + qMax(topRight.width(), bottomRight.width()); const int height = qMax(topRight.height(), topLeft.height()) + qMax(left.height(), right.height()) + qMax(bottomLeft.height(), bottomRight.height()); if (width == 0 || height == 0) { return false; } QImage image(width, height, QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter p; p.begin(&image); p.drawPixmap(0, 0, shadowPixmap(ShadowElementTopLeft)); p.drawPixmap(topLeft.width(), 0, shadowPixmap(ShadowElementTop)); p.drawPixmap(topLeft.width() + top.width(), 0, shadowPixmap(ShadowElementTopRight)); p.drawPixmap(0, topLeft.height(), shadowPixmap(ShadowElementLeft)); p.drawPixmap(width - right.width(), topRight.height(), shadowPixmap(ShadowElementRight)); p.drawPixmap(0, topLeft.height() + left.height(), shadowPixmap(ShadowElementBottomLeft)); p.drawPixmap(bottomLeft.width(), height - bottom.height(), shadowPixmap(ShadowElementBottom)); p.drawPixmap(bottomLeft.width() + bottom.width(), topRight.height() + right.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; } } effects->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; } SwapProfiler::SwapProfiler() { init(); } void SwapProfiler::init() { m_time = 2 * 1000*1000; // we start with a long time mean of 2ms ... m_counter = 0; } void SwapProfiler::begin() { m_timer.start(); } char SwapProfiler::end() { // .. and blend in actual values. // this way we prevent extremes from killing our long time mean m_time = (10*m_time + m_timer.nsecsElapsed())/11; if (++m_counter > 500) { const bool blocks = m_time > 1000 * 1000; // 1ms, i get ~250µs and ~7ms w/o triple buffering... qCDebug(KWIN_CORE) << "Triple buffering detection:" << QString(blocks ? QStringLiteral("NOT available") : QStringLiteral("Available")) << " - Mean block time:" << m_time/(1000.0*1000.0) << "ms"; return blocks ? 'd' : 't'; } return 0; } SceneOpenGLDecorationRenderer::SceneOpenGLDecorationRenderer(Decoration::DecoratedClientImpl *client) : Renderer(client) , m_texture() { connect(this, &Renderer::renderScheduled, client->client(), static_cast(&AbstractClient::addRepaint)); } SceneOpenGLDecorationRenderer::~SceneOpenGLDecorationRenderer() = default; // Rotates the given source rect 90° counter-clockwise, // and flips it vertically static QImage rotate(const QImage &srcImage, const QRect &srcRect) { QImage image(srcRect.height(), srcRect.width(), srcImage.format()); 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 + (srcRect.y() + x) * srcImage.width() + srcRect.x(); uint32_t *d = dst + x; for (int y = 0; y < image.height(); y++) { *d = s[y]; d += image.width(); } } return image; } void SceneOpenGLDecorationRenderer::render() { const QRegion scheduled = getScheduled(); if (scheduled.isEmpty()) { return; } if (areImageSizesDirty()) { 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 = scheduled.boundingRect(); auto renderPart = [this](const QRect &geo, const QRect &partRect, const QPoint &offset, bool rotated = false) { if (geo.isNull()) { return; } QImage image = renderToImage(geo); if (rotated) { // TODO: get this done directly when rendering to the image image = rotate(image, QRect(geo.topLeft() - partRect.topLeft(), geo.size())); } m_texture->update(image, geo.topLeft() - partRect.topLeft() + offset); }; renderPart(left.intersected(geometry), left, QPoint(0, top.height() + bottom.height() + 2), true); renderPart(top.intersected(geometry), top, QPoint(0, 0)); renderPart(right.intersected(geometry), right, QPoint(0, top.height() + bottom.height() + left.width() + 3), true); renderPart(bottom.intersected(geometry), bottom, QPoint(0, top.height() + 1)); } static int align(int value, int align) { return (value + align - 1) & ~(align - 1); } void SceneOpenGLDecorationRenderer::resizeTexture() { QRect left, top, right, bottom; client()->client()->layoutDecorationRects(left, top, right, bottom); QSize size; size.rwidth() = qMax(qMax(top.width(), bottom.width()), qMax(left.height(), right.height())); size.rheight() = top.height() + bottom.height() + left.width() + right.width() + 3; size.rwidth() = align(size.width(), 128); 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); } } // namespace diff --git a/scene_opengl.h b/scene_opengl.h index 0d0c8c047..716203839 100644 --- a/scene_opengl.h +++ b/scene_opengl.h @@ -1,668 +1,669 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak Copyright (C) 2009, 2010, 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCENE_OPENGL_H #define KWIN_SCENE_OPENGL_H #include "scene.h" #include "shadow.h" #include "kwinglutils.h" #include "kwingltexture_p.h" #include "decorations/decorationrenderer.h" namespace KWin { class ColorCorrection; class LanczosFilter; class OpenGLBackend; class SyncManager; class SyncObject; class KWIN_EXPORT SceneOpenGL : public Scene { Q_OBJECT public: class EffectFrame; class Texture; class TexturePrivate; class Window; virtual ~SceneOpenGL(); virtual bool initFailed() const; virtual bool hasPendingFlush() const; virtual qint64 paint(QRegion damage, ToplevelList windows); virtual Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame); virtual Shadow *createShadow(Toplevel *toplevel); virtual void screenGeometryChanged(const QSize &size); virtual OverlayWindow *overlayWindow(); virtual bool usesOverlayWindow() const; virtual bool blocksForRetrace() const; virtual bool syncsToVBlank() const; virtual bool makeOpenGLContextCurrent() override; virtual void doneOpenGLContextCurrent() override; Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *impl) override; virtual void triggerFence() override; virtual QMatrix4x4 projectionMatrix() const = 0; + bool animationsSupported() const override; void insertWait(); void idle(); bool debug() const { return m_debug; } void initDebugOutput(); /** * @brief Factory method to create a backend specific texture. * * @return :SceneOpenGL::Texture* **/ Texture *createTexture(); OpenGLBackend *backend() const { return m_backend; } /** * Copy a region of pixels from the current read to the current draw buffer */ static void copyPixels(const QRegion ®ion); static SceneOpenGL *createScene(QObject *parent); protected: SceneOpenGL(OpenGLBackend *backend, QObject *parent = nullptr); virtual void paintBackground(QRegion region); virtual void extendPaintRegion(QRegion ®ion, bool opaqueFullscreen); QMatrix4x4 transformation(int mask, const ScreenPaintData &data) const; virtual void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data); void handleGraphicsReset(GLenum status); virtual void doPaintBackground(const QVector &vertices) = 0; virtual void updateProjectionMatrix() = 0; Q_SIGNALS: void resetCompositing(); protected: bool init_ok; private: bool viewportLimitsMatched(const QSize &size) const; private: bool m_debug; OpenGLBackend *m_backend; SyncManager *m_syncManager; SyncObject *m_currentFence; }; class SceneOpenGL2 : public SceneOpenGL { Q_OBJECT public: explicit SceneOpenGL2(OpenGLBackend *backend, QObject *parent = nullptr); virtual ~SceneOpenGL2(); virtual CompositingType compositingType() const { return OpenGL2Compositing; } static bool supported(OpenGLBackend *backend); ColorCorrection *colorCorrection(); QMatrix4x4 projectionMatrix() const override { return m_projectionMatrix; } QMatrix4x4 screenProjectionMatrix() const override { return m_screenProjectionMatrix; } protected: virtual void paintSimpleScreen(int mask, QRegion region); virtual void paintGenericScreen(int mask, ScreenPaintData data); virtual void doPaintBackground(const QVector< float >& vertices); virtual Scene::Window *createWindow(Toplevel *t); virtual void finalDrawWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); virtual void updateProjectionMatrix() override; private Q_SLOTS: void slotColorCorrectedChanged(bool recreateShaders = true); void resetLanczosFilter(); private: void performPaintWindow(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data); QMatrix4x4 createProjectionMatrix() const; private: LanczosFilter *m_lanczosFilter; QScopedPointer m_colorCorrection; QMatrix4x4 m_projectionMatrix; QMatrix4x4 m_screenProjectionMatrix; GLuint vao; }; class SceneOpenGL::TexturePrivate : public GLTexturePrivate { public: virtual ~TexturePrivate(); virtual bool loadTexture(WindowPixmap *pixmap) = 0; virtual void updateTexture(WindowPixmap *pixmap); virtual OpenGLBackend *backend() = 0; protected: TexturePrivate(); private: Q_DISABLE_COPY(TexturePrivate) }; class SceneOpenGL::Texture : public GLTexture { public: Texture(OpenGLBackend *backend); virtual ~Texture(); Texture & operator = (const Texture& tex); void discard() override final; protected: bool load(WindowPixmap *pixmap); void updateFromPixmap(WindowPixmap *pixmap); Texture(TexturePrivate& dd); private: Q_DECLARE_PRIVATE(Texture) friend class OpenGLWindowPixmap; }; class SceneOpenGL::Window : public Scene::Window { public: virtual ~Window(); bool beginRenderWindow(int mask, const QRegion ®ion, WindowPaintData &data); virtual void performPaint(int mask, QRegion region, WindowPaintData data) = 0; void endRenderWindow(); bool bindTexture(); void setScene(SceneOpenGL *scene) { m_scene = scene; } protected: virtual WindowPixmap* createWindowPixmap(); Window(Toplevel* c); enum TextureType { Content, Decoration, Shadow }; QMatrix4x4 transformation(int mask, const WindowPaintData &data) const; GLTexture *getDecorationTexture() const; protected: SceneOpenGL *m_scene; bool m_hardwareClipping; }; class SceneOpenGL2Window : public SceneOpenGL::Window { public: enum Leaf { ShadowLeaf = 0, DecorationLeaf, ContentLeaf, PreviousContentLeaf, LeafCount }; struct LeafNode { LeafNode() : texture(0), firstVertex(0), vertexCount(0), opacity(1.0), hasAlpha(false), coordinateType(UnnormalizedCoordinates) { } GLTexture *texture; int firstVertex; int vertexCount; float opacity; bool hasAlpha; TextureCoordinateType coordinateType; }; explicit SceneOpenGL2Window(Toplevel *c); virtual ~SceneOpenGL2Window(); protected: QMatrix4x4 modelViewProjectionMatrix(int mask, const WindowPaintData &data) const; QVector4D modulate(float opacity, float brightness) const; void setBlendEnabled(bool enabled); void setupLeafNodes(LeafNode *nodes, const WindowQuadList *quads, const WindowPaintData &data); virtual void performPaint(int mask, QRegion region, WindowPaintData data); private: /** * Whether prepareStates enabled blending and restore states should disable again. **/ bool m_blendingEnabled; }; class OpenGLWindowPixmap : public WindowPixmap { public: explicit OpenGLWindowPixmap(Scene::Window *window, SceneOpenGL *scene); virtual ~OpenGLWindowPixmap(); SceneOpenGL::Texture *texture() const; bool bind(); protected: WindowPixmap *createChild(const QPointer &subSurface) override; private: explicit OpenGLWindowPixmap(const QPointer &subSurface, WindowPixmap *parent, SceneOpenGL *scene); QScopedPointer m_texture; SceneOpenGL *m_scene; }; class SceneOpenGL::EffectFrame : public Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame, SceneOpenGL *scene); virtual ~EffectFrame(); virtual void free(); virtual void freeIconFrame(); virtual void freeTextFrame(); virtual void freeSelection(); virtual void render(QRegion region, double opacity, double frameOpacity); virtual void crossFadeIcon(); virtual void crossFadeText(); static void cleanup(); private: void updateTexture(); void updateTextTexture(); GLTexture *m_texture; GLTexture *m_textTexture; GLTexture *m_oldTextTexture; QPixmap *m_textPixmap; // need to keep the pixmap around to workaround some driver problems GLTexture *m_iconTexture; GLTexture *m_oldIconTexture; GLTexture *m_selectionTexture; GLVertexBuffer *m_unstyledVBO; SceneOpenGL *m_scene; static GLTexture* m_unstyledTexture; static QPixmap* m_unstyledPixmap; // need to keep the pixmap around to workaround some driver problems static void updateUnstyledTexture(); // Update OpenGL unstyled frame texture }; /** * @short OpenGL implementation of Shadow. * * This class extends Shadow by the Elements required for OpenGL rendering. * @author Martin Gräßlin **/ class SceneOpenGLShadow : public Shadow { public: explicit SceneOpenGLShadow(Toplevel *toplevel); virtual ~SceneOpenGLShadow(); GLTexture *shadowTexture() { return m_texture.data(); } protected: virtual void buildQuads(); virtual bool prepareBackend(); private: QSharedPointer m_texture; }; /** * @short Profiler to detect whether we have triple buffering * The strategy is to start setBlocksForRetrace(false) but assume blocking and have the system prove that assumption wrong **/ class KWIN_EXPORT SwapProfiler { public: SwapProfiler(); void init(); void begin(); /** * @return char being 'd' for double, 't' for triple (or more - but non-blocking) buffering and * 0 (NOT '0') otherwise, so you can act on "if (char result = SwapProfiler::end()) { fooBar(); } **/ char end(); private: QElapsedTimer m_timer; qint64 m_time; int m_counter; }; /** * @brief The OpenGLBackend creates and holds the OpenGL context and is responsible for Texture from Pixmap. * * The OpenGLBackend is an abstract base class used by the SceneOpenGL to abstract away the differences * between various OpenGL windowing systems such as GLX and EGL. * * A concrete implementation has to create and release the OpenGL context in a way so that the * SceneOpenGL does not have to care about it. * * In addition a major task for this class is to generate the SceneOpenGL::TexturePrivate which is * able to perform the texture from pixmap operation in the given backend. * * @author Martin Gräßlin **/ class KWIN_EXPORT OpenGLBackend { public: OpenGLBackend(); virtual ~OpenGLBackend(); virtual void init() = 0; /** * @return Time passes since start of rendering current frame. * @see startRenderTimer **/ qint64 renderTime() { return m_renderTimer.nsecsElapsed(); } virtual void screenGeometryChanged(const QSize &size) = 0; virtual SceneOpenGL::TexturePrivate *createBackendTexture(SceneOpenGL::Texture *texture) = 0; /** * @brief Backend specific code to prepare the rendering of a frame including flushing the * previously rendered frame to the screen if the backend works this way. * * @return A region that if not empty will be repainted in addition to the damaged region **/ virtual QRegion prepareRenderingFrame() = 0; /** * @brief Backend specific code to handle the end of rendering a frame. * * @param renderedRegion The possibly larger region that has been rendered * @param damagedRegion The damaged region that should be posted **/ virtual void endRenderingFrame(const QRegion &damage, const QRegion &damagedRegion) = 0; virtual void endRenderingFrameForScreen(int screenId, const QRegion &damage, const QRegion &damagedRegion); virtual bool makeCurrent() = 0; virtual void doneCurrent() = 0; virtual bool usesOverlayWindow() const = 0; /** * Whether the rendering needs to be split per screen. * Default implementation returns @c false. **/ virtual bool perScreenRendering() const; virtual QRegion prepareRenderingForScreen(int screenId); /** * @brief Compositor is going into idle mode, flushes any pending paints. **/ void idle(); /** * @return bool Whether the scene needs to flush a frame. **/ bool hasPendingFlush() const { return !m_lastDamage.isEmpty(); } /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* **/ virtual OverlayWindow *overlayWindow(); /** * @brief Whether the creation of the Backend failed. * * The SceneOpenGL should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneOpenGL should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. **/ bool isFailed() const { return m_failed; } /** * @brief Whether the Backend provides VSync. * * Currently only the GLX backend can provide VSync. * * @return bool @c true if VSync support is available, @c false otherwise **/ bool syncsToVBlank() const { return m_syncsToVBlank; } /** * @brief Whether VSync blocks execution until the screen is in the retrace * * Case for waitVideoSync and non triple buffering buffer swaps * **/ bool blocksForRetrace() const { return m_blocksForRetrace; } /** * @brief Whether the backend uses direct rendering. * * Some OpenGLScene modes require direct rendering. E.g. the OpenGL 2 should not be used * if direct rendering is not supported by the Scene. * * @return bool @c true if the GL context is direct, @c false if indirect **/ bool isDirectRendering() const { return m_directRendering; } bool supportsBufferAge() const { return m_haveBufferAge; } /** * @returns whether the context is surfaceless **/ bool isSurfaceLessContext() const { return m_surfaceLessContext; } /** * Returns the damage that has accumulated since a buffer of the given age was presented. */ QRegion accumulatedDamageHistory(int bufferAge) const; /** * Saves the given region to damage history. */ void addToDamageHistory(const QRegion ®ion); protected: /** * @brief Backend specific flushing of frame to screen. **/ virtual void present() = 0; /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. **/ void setFailed(const QString &reason); /** * @brief Sets whether the backend provides VSync. * * Should be called by the concrete subclass once it is determined whether VSync is supported. * If the subclass does not call this method, the backend defaults to @c false. * @param enabled @c true if VSync support available, @c false otherwise. **/ void setSyncsToVBlank(bool enabled) { m_syncsToVBlank = enabled; } /** * @brief Sets whether the VSync iplementation blocks * * Should be called by the concrete subclass once it is determined how VSync works. * If the subclass does not call this method, the backend defaults to @c false. * @param enabled @c true if VSync blocks, @c false otherwise. **/ void setBlocksForRetrace(bool enabled) { m_blocksForRetrace = enabled; } /** * @brief Sets whether the OpenGL context is direct. * * Should be called by the concrete subclass once it is determined whether the OpenGL context is * direct or indirect. * If the subclass does not call this method, the backend defaults to @c false. * * @param direct @c true if the OpenGL context is direct, @c false if indirect **/ void setIsDirectRendering(bool direct) { m_directRendering = direct; } void setSupportsBufferAge(bool value) { m_haveBufferAge = value; } /** * @return const QRegion& Damage of previously rendered frame **/ const QRegion &lastDamage() const { return m_lastDamage; } void setLastDamage(const QRegion &damage) { m_lastDamage = damage; } /** * @brief Starts the timer for how long it takes to render the frame. * * @see renderTime **/ void startRenderTimer() { m_renderTimer.start(); } /** * @param set whether the context is surface less **/ void setSurfaceLessContext(bool set) { m_surfaceLessContext = set; } SwapProfiler m_swapProfiler; private: /** * @brief Whether VSync is available and used, defaults to @c false. **/ bool m_syncsToVBlank; /** * @brief Whether present() will block execution until the next vertical retrace @c false. **/ bool m_blocksForRetrace; /** * @brief Whether direct rendering is used, defaults to @c false. **/ bool m_directRendering; /** * @brief Whether the backend supports GLX_EXT_buffer_age / EGL_EXT_buffer_age. */ bool m_haveBufferAge; /** * @brief Whether the initialization failed, of course default to @c false. **/ bool m_failed; /** * @brief Damaged region of previously rendered frame. **/ QRegion m_lastDamage; /** * @brief The damage history for the past 10 frames. */ QList m_damageHistory; /** * @brief Timer to measure how long a frame renders. **/ QElapsedTimer m_renderTimer; bool m_surfaceLessContext = false; }; class SceneOpenGLDecorationRenderer : public Decoration::Renderer { Q_OBJECT public: enum class DecorationPart : int { Left, Top, Right, Bottom, Count }; explicit SceneOpenGLDecorationRenderer(Decoration::DecoratedClientImpl *client); virtual ~SceneOpenGLDecorationRenderer(); void render() override; void reparent(Deleted *deleted) override; GLTexture *texture() { return m_texture.data(); } GLTexture *texture() const { return m_texture.data(); } private: void resizeTexture(); QScopedPointer m_texture; }; inline bool SceneOpenGL::hasPendingFlush() const { return m_backend->hasPendingFlush(); } inline bool SceneOpenGL::usesOverlayWindow() const { return m_backend->usesOverlayWindow(); } inline SceneOpenGL::Texture* OpenGLWindowPixmap::texture() const { return m_texture.data(); } } // namespace #endif diff --git a/scene_qpainter.h b/scene_qpainter.h index 37ccac9a8..439e79074 100644 --- a/scene_qpainter.h +++ b/scene_qpainter.h @@ -1,263 +1,267 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2013 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCENE_QPAINTER_H #define KWIN_SCENE_QPAINTER_H #include "scene.h" #include "shadow.h" #include "decorations/decorationrenderer.h" namespace KWin { class KWIN_EXPORT QPainterBackend { public: virtual ~QPainterBackend(); virtual void present(int mask, const QRegion &damage) = 0; /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* **/ virtual OverlayWindow *overlayWindow(); virtual bool usesOverlayWindow() const = 0; virtual void prepareRenderingFrame() = 0; /** * @brief Shows the Overlay Window * * Default implementation does nothing. */ virtual void showOverlay(); /** * @brief React on screen geometry changes. * * Default implementation does nothing. Override if specific functionality is required. * * @param size The new screen size */ virtual void screenGeometryChanged(const QSize &size); /** * @brief Whether the creation of the Backend failed. * * The SceneQPainter should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneQPainter should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. **/ bool isFailed() const { return m_failed; } virtual QImage *buffer() = 0; /** * Overload for the case that there is a different buffer per screen. * Default implementation just calls buffer. * @param screenId The id of the screen as used in Screens * @todo Get a better identifier for screen then a counter variable **/ virtual QImage *bufferForScreen(int screenId); virtual bool needsFullRepaint() const = 0; /** * Whether the rendering needs to be split per screen. * Default implementation returns @c false. **/ virtual bool perScreenRendering() const; protected: QPainterBackend(); /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. **/ void setFailed(const QString &reason); private: bool m_failed; }; class KWIN_EXPORT SceneQPainter : public Scene { Q_OBJECT public: virtual ~SceneQPainter(); virtual bool usesOverlayWindow() const override; virtual OverlayWindow* overlayWindow() override; virtual qint64 paint(QRegion damage, ToplevelList windows) override; virtual void paintGenericScreen(int mask, ScreenPaintData data) override; virtual CompositingType compositingType() const override; virtual bool initFailed() const override; virtual EffectFrame *createEffectFrame(EffectFrameImpl *frame) override; virtual Shadow *createShadow(Toplevel *toplevel) override; Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *impl) override; void screenGeometryChanged(const QSize &size) override; + bool animationsSupported() const override { + return false; + } + QPainter *painter(); QPainterBackend *backend() const { return m_backend.data(); } static SceneQPainter *createScene(QObject *parent); protected: virtual void paintBackground(QRegion region) override; virtual Scene::Window *createWindow(Toplevel *toplevel) override; private: explicit SceneQPainter(QPainterBackend *backend, QObject *parent = nullptr); void paintCursor(); QScopedPointer m_backend; QScopedPointer m_painter; class Window; }; class SceneQPainter::Window : public Scene::Window { public: Window(SceneQPainter *scene, Toplevel *c); virtual ~Window(); virtual void performPaint(int mask, QRegion region, WindowPaintData data) override; protected: virtual WindowPixmap *createWindowPixmap() override; private: void renderShadow(QPainter *painter); void renderWindowDecorations(QPainter *painter); SceneQPainter *m_scene; }; class QPainterWindowPixmap : public WindowPixmap { public: explicit QPainterWindowPixmap(Scene::Window *window); virtual ~QPainterWindowPixmap(); virtual void create() override; void updateBuffer() override; const QImage &image(); protected: WindowPixmap *createChild(const QPointer &subSurface) override; private: explicit QPainterWindowPixmap(const QPointer &subSurface, WindowPixmap *parent); QImage m_image; }; class QPainterEffectFrame : public Scene::EffectFrame { public: QPainterEffectFrame(EffectFrameImpl *frame, SceneQPainter *scene); virtual ~QPainterEffectFrame(); virtual void crossFadeIcon() override {} virtual void crossFadeText() override {} virtual void free() override {} virtual void freeIconFrame() override {} virtual void freeTextFrame() override {} virtual void freeSelection() override {} virtual void render(QRegion region, double opacity, double frameOpacity) override; private: SceneQPainter *m_scene; }; class SceneQPainterShadow : public Shadow { public: SceneQPainterShadow(Toplevel* toplevel); virtual ~SceneQPainterShadow(); using Shadow::ShadowElements; using Shadow::ShadowElementTop; using Shadow::ShadowElementTopRight; using Shadow::ShadowElementRight; using Shadow::ShadowElementBottomRight; using Shadow::ShadowElementBottom; using Shadow::ShadowElementBottomLeft; using Shadow::ShadowElementLeft; using Shadow::ShadowElementTopLeft; using Shadow::ShadowElementsCount; using Shadow::shadowPixmap; using Shadow::topOffset; using Shadow::leftOffset; using Shadow::rightOffset; using Shadow::bottomOffset; protected: virtual bool prepareBackend() override; }; class SceneQPainterDecorationRenderer : public Decoration::Renderer { Q_OBJECT public: enum class DecorationPart : int { Left, Top, Right, Bottom, Count }; explicit SceneQPainterDecorationRenderer(Decoration::DecoratedClientImpl *client); virtual ~SceneQPainterDecorationRenderer(); void render() override; void reparent(Deleted *deleted) override; QImage image(DecorationPart part) const; private: void resizeImages(); QImage m_images[int(DecorationPart::Count)]; }; inline bool SceneQPainter::usesOverlayWindow() const { return m_backend->usesOverlayWindow(); } inline OverlayWindow* SceneQPainter::overlayWindow() { return m_backend->overlayWindow(); } inline QPainter* SceneQPainter::painter() { return m_painter.data(); } inline const QImage &QPainterWindowPixmap::image() { return m_image; } } // KWin #endif // KWIN_SCENEQPAINTER_H diff --git a/scene_xrender.h b/scene_xrender.h index ba96f95d0..6138f29b6 100644 --- a/scene_xrender.h +++ b/scene_xrender.h @@ -1,344 +1,348 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2006 Lubos Lunak This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCENE_XRENDER_H #define KWIN_SCENE_XRENDER_H #include "scene.h" #include "shadow.h" #include "decorations/decorationrenderer.h" #ifdef KWIN_HAVE_XRENDER_COMPOSITING namespace KWin { namespace Xcb { class Shm; } /** * @brief Backend for the SceneXRender to hold the compositing buffer and take care of buffer * swapping. * * This class is intended as a small abstraction to support multiple compositing backends in the * SceneXRender. * */ class XRenderBackend { public: virtual ~XRenderBackend(); virtual void present(int mask, const QRegion &damage) = 0; /** * @brief Returns the OverlayWindow used by the backend. * * A backend does not have to use an OverlayWindow, this is mostly for the X world. * In case the backend does not use an OverlayWindow it is allowed to return @c null. * It's the task of the caller to check whether it is @c null. * * @return :OverlayWindow* **/ virtual OverlayWindow *overlayWindow(); virtual bool usesOverlayWindow() const = 0; /** * @brief Shows the Overlay Window * * Default implementation does nothing. */ virtual void showOverlay(); /** * @brief React on screen geometry changes. * * Default implementation does nothing. Override if specific functionality is required. * * @param size The new screen size */ virtual void screenGeometryChanged(const QSize &size); /** * @brief The compositing buffer hold by this backend. * * The Scene composites the new frame into this buffer. * * @return xcb_render_picture_t */ xcb_render_picture_t buffer() const { return m_buffer; } /** * @brief Whether the creation of the Backend failed. * * The SceneXRender should test whether the Backend got constructed correctly. If this method * returns @c true, the SceneXRender should not try to start the rendering. * * @return bool @c true if the creation of the Backend failed, @c false otherwise. **/ bool isFailed() const { return m_failed; } protected: XRenderBackend(); /** * @brief A subclass needs to call this method once it created the compositing back buffer. * * @param buffer The buffer to use for compositing * @return void */ void setBuffer(xcb_render_picture_t buffer); /** * @brief Sets the backend initialization to failed. * * This method should be called by the concrete subclass in case the initialization failed. * The given @p reason is logged as a warning. * * @param reason The reason why the initialization failed. **/ void setFailed(const QString &reason); private: // Create the compositing buffer. The root window is not double-buffered, // so it is done manually using this buffer, xcb_render_picture_t m_buffer; bool m_failed; }; /** * @brief XRenderBackend using an X11 Overlay Window as compositing target. * */ class X11XRenderBackend : public XRenderBackend { public: X11XRenderBackend(); ~X11XRenderBackend(); virtual void present(int mask, const QRegion &damage); virtual OverlayWindow* overlayWindow(); virtual void showOverlay(); virtual void screenGeometryChanged(const QSize &size); virtual bool usesOverlayWindow() const; private: void init(bool createOverlay); void createBuffer(); QScopedPointer m_overlayWindow; xcb_render_picture_t m_front; xcb_render_pictformat_t m_format; }; class SceneXrender : public Scene { Q_OBJECT public: class EffectFrame; virtual ~SceneXrender(); virtual bool initFailed() const; virtual CompositingType compositingType() const { return XRenderCompositing; } virtual qint64 paint(QRegion damage, ToplevelList windows); virtual Scene::EffectFrame *createEffectFrame(EffectFrameImpl *frame); virtual Shadow *createShadow(Toplevel *toplevel); virtual void screenGeometryChanged(const QSize &size); xcb_render_picture_t bufferPicture(); virtual OverlayWindow *overlayWindow() { return m_backend->overlayWindow(); } virtual bool usesOverlayWindow() const { return m_backend->usesOverlayWindow(); } Decoration::Renderer *createDecorationRenderer(Decoration::DecoratedClientImpl *client); + bool animationsSupported() const override { + return true; + } + static SceneXrender *createScene(QObject *parent); protected: virtual Scene::Window *createWindow(Toplevel *toplevel); virtual void paintBackground(QRegion region); virtual void paintGenericScreen(int mask, ScreenPaintData data); virtual void paintDesktop(int desktop, int mask, const QRegion ®ion, ScreenPaintData &data); private: explicit SceneXrender(XRenderBackend *backend, QObject *parent = nullptr); static ScreenPaintData screen_paint; class Window; QScopedPointer m_backend; }; class SceneXrender::Window : public Scene::Window { public: Window(Toplevel* c, SceneXrender *scene); virtual ~Window(); virtual void performPaint(int mask, QRegion region, WindowPaintData data); QRegion transformedShape() const; void setTransformedShape(const QRegion& shape); static void cleanup(); protected: virtual WindowPixmap* createWindowPixmap(); private: QRect mapToScreen(int mask, const WindowPaintData &data, const QRect &rect) const; QPoint mapToScreen(int mask, const WindowPaintData &data, const QPoint &point) const; void prepareTempPixmap(); void setPictureFilter(xcb_render_picture_t pic, ImageFilterType filter); SceneXrender *m_scene; xcb_render_pictformat_t format; double alpha_cached_opacity; QRegion transformed_shape; static QRect temp_visibleRect; static XRenderPicture *s_tempPicture; static XRenderPicture *s_fadeAlphaPicture; }; class XRenderWindowPixmap : public WindowPixmap { public: explicit XRenderWindowPixmap(Scene::Window *window, xcb_render_pictformat_t format); virtual ~XRenderWindowPixmap(); xcb_render_picture_t picture() const; virtual void create(); private: xcb_render_picture_t m_picture; xcb_render_pictformat_t m_format; }; class SceneXrender::EffectFrame : public Scene::EffectFrame { public: EffectFrame(EffectFrameImpl* frame); virtual ~EffectFrame(); virtual void free(); virtual void freeIconFrame(); virtual void freeTextFrame(); virtual void freeSelection(); virtual void crossFadeIcon(); virtual void crossFadeText(); virtual void render(QRegion region, double opacity, double frameOpacity); static void cleanup(); private: void updatePicture(); void updateTextPicture(); void renderUnstyled(xcb_render_picture_t pict, const QRect &rect, qreal opacity); XRenderPicture* m_picture; XRenderPicture* m_textPicture; XRenderPicture* m_iconPicture; XRenderPicture* m_selectionPicture; static XRenderPicture* s_effectFrameCircle; }; inline xcb_render_picture_t SceneXrender::bufferPicture() { return m_backend->buffer(); } inline QRegion SceneXrender::Window::transformedShape() const { return transformed_shape; } inline void SceneXrender::Window::setTransformedShape(const QRegion& shape) { transformed_shape = shape; } inline xcb_render_picture_t XRenderWindowPixmap::picture() const { return m_picture; } /** * @short XRender implementation of Shadow. * * This class extends Shadow by the elements required for XRender rendering. * @author Jacopo De Simoi **/ class SceneXRenderShadow : public Shadow { public: explicit SceneXRenderShadow(Toplevel *toplevel); using Shadow::ShadowElements; using Shadow::ShadowElementTop; using Shadow::ShadowElementTopRight; using Shadow::ShadowElementRight; using Shadow::ShadowElementBottomRight; using Shadow::ShadowElementBottom; using Shadow::ShadowElementBottomLeft; using Shadow::ShadowElementLeft; using Shadow::ShadowElementTopLeft; using Shadow::ShadowElementsCount; using Shadow::shadowPixmap; virtual ~SceneXRenderShadow(); void layoutShadowRects(QRect& top, QRect& topRight, QRect& right, QRect& bottomRight, QRect& bottom, QRect& bottomLeft, QRect& Left, QRect& topLeft); xcb_render_picture_t picture(ShadowElements element) const; protected: virtual void buildQuads(); virtual bool prepareBackend(); private: XRenderPicture* m_pictures[ShadowElementsCount]; }; class SceneXRenderDecorationRenderer : public Decoration::Renderer { Q_OBJECT public: enum class DecorationPart : int { Left, Top, Right, Bottom, Count }; explicit SceneXRenderDecorationRenderer(Decoration::DecoratedClientImpl *client); virtual ~SceneXRenderDecorationRenderer(); void render() override; void reparent(Deleted *deleted) override; xcb_render_picture_t picture(DecorationPart part) const; private: void resizePixmaps(); QSize m_sizes[int(DecorationPart::Count)]; xcb_pixmap_t m_pixmaps[int(DecorationPart::Count)]; xcb_gcontext_t m_gc; XRenderPicture* m_pictures[int(DecorationPart::Count)]; }; } // namespace #endif #endif diff --git a/scripting/scriptedeffect.cpp b/scripting/scriptedeffect.cpp index 7073792a8..0aa9a8b96 100644 --- a/scripting/scriptedeffect.cpp +++ b/scripting/scriptedeffect.cpp @@ -1,633 +1,638 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2012 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #include "scriptedeffect.h" #include "meta.h" #include "scriptingutils.h" #include "workspace_wrapper.h" #include "../screenedge.h" #include "scripting_logging.h" // KDE #include #include #include // Qt #include #include #include #include typedef KWin::EffectWindow* KEffectWindowRef; namespace KWin { QScriptValue kwinEffectScriptPrint(QScriptContext *context, QScriptEngine *engine) { ScriptedEffect *script = qobject_cast(context->callee().data().toQObject()); QString result; for (int i = 0; i < context->argumentCount(); ++i) { if (i > 0) { result.append(QLatin1Char(' ')); } result.append(context->argument(i).toString()); } qCDebug(KWIN_SCRIPTING) << script->scriptFile() << ":" << result; return engine->undefinedValue(); } QScriptValue kwinEffectScriptAnimationTime(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { return engine->undefinedValue(); } if (!context->argument(0).isNumber()) { return engine->undefinedValue(); } return Effect::animationTime(context->argument(0).toInteger()); } QScriptValue kwinEffectDisplayWidth(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(context) Q_UNUSED(engine) return displayWidth(); } QScriptValue kwinEffectDisplayHeight(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(context) Q_UNUSED(engine) return displayHeight(); } QScriptValue kwinScriptGlobalShortcut(QScriptContext *context, QScriptEngine *engine) { return globalShortcut(context, engine); } QScriptValue kwinScriptScreenEdge(QScriptContext *context, QScriptEngine *engine) { return registerScreenEdge(context, engine); } struct AnimationSettings { enum { Type = 1<<0, Curve = 1<<1, Delay = 1<<2, Duration = 1<<3 }; AnimationEffect::Attribute type; QEasingCurve::Type curve; FPx2 from; FPx2 to; int delay; uint duration; uint set; uint metaData; }; AnimationSettings animationSettingsFromObject(QScriptValue &object) { AnimationSettings settings; settings.set = 0; settings.metaData = 0; settings.to = qscriptvalue_cast(object.property(QStringLiteral("to"))); settings.from = qscriptvalue_cast(object.property(QStringLiteral("from"))); QScriptValue duration = object.property(QStringLiteral("duration")); if (duration.isValid() && duration.isNumber()) { settings.duration = duration.toUInt32(); settings.set |= AnimationSettings::Duration; } else { settings.duration = 0; } QScriptValue delay = object.property(QStringLiteral("delay")); if (delay.isValid() && delay.isNumber()) { settings.delay = delay.toInt32(); settings.set |= AnimationSettings::Delay; } else { settings.delay = 0; } QScriptValue curve = object.property(QStringLiteral("curve")); if (curve.isValid() && curve.isNumber()) { settings.curve = static_cast(curve.toInt32()); settings.set |= AnimationSettings::Curve; } else { settings.curve = QEasingCurve::Linear; } QScriptValue type = object.property(QStringLiteral("type")); if (type.isValid() && type.isNumber()) { settings.type = static_cast(type.toInt32()); settings.set |= AnimationSettings::Type; } else { settings.type = static_cast(-1); } return settings; } QList animationSettings(QScriptContext *context, ScriptedEffect *effect, EffectWindow **window) { QList settings; if (!effect) { context->throwError(QScriptContext::ReferenceError, QStringLiteral("Internal Scripted KWin Effect error")); return settings; } if (context->argumentCount() != 1) { context->throwError(QScriptContext::SyntaxError, QStringLiteral("Exactly one argument expected")); return settings; } if (!context->argument(0).isObject()) { context->throwError(QScriptContext::TypeError, QStringLiteral("Argument needs to be an object")); return settings; } QScriptValue object = context->argument(0); QScriptValue windowProperty = object.property(QStringLiteral("window")); if (!windowProperty.isValid() || !windowProperty.isObject()) { context->throwError(QScriptContext::TypeError, QStringLiteral("Window property missing in animation options")); return settings; } *window = qobject_cast(windowProperty.toQObject()); settings << animationSettingsFromObject(object); // global QScriptValue animations = object.property(QStringLiteral("animations")); // array if (animations.isValid()) { if (!animations.isArray()) { context->throwError(QScriptContext::TypeError, QStringLiteral("Animations provided but not an array")); settings.clear(); return settings; } const int length = static_cast(animations.property(QStringLiteral("length")).toInteger()); for (int i=0; ithrowError(QScriptContext::TypeError, QStringLiteral("Type property missing in animation options")); continue; } if (!(set & AnimationSettings::Duration)) { context->throwError(QScriptContext::TypeError, QStringLiteral("Duration property missing in animation options")); continue; } // Complete local animations from global settings if (!(s.set & AnimationSettings::Duration)) { s.duration = settings.at(0).duration; } if (!(s.set & AnimationSettings::Curve)) { s.curve = settings.at(0).curve; } if (!(s.set & AnimationSettings::Delay)) { s.delay = settings.at(0).delay; } s.metaData = 0; typedef QMap MetaTypeMap; static MetaTypeMap metaTypes({ {AnimationEffect::SourceAnchor, QStringLiteral("sourceAnchor")}, {AnimationEffect::TargetAnchor, QStringLiteral("targetAnchor")}, {AnimationEffect::RelativeSourceX, QStringLiteral("relativeSourceX")}, {AnimationEffect::RelativeSourceY, QStringLiteral("relativeSourceY")}, {AnimationEffect::RelativeTargetX, QStringLiteral("relativeTargetX")}, {AnimationEffect::RelativeTargetY, QStringLiteral("relativeTargetY")}, {AnimationEffect::Axis, QStringLiteral("axis")} }); for (MetaTypeMap::const_iterator it = metaTypes.constBegin(), end = metaTypes.constEnd(); it != end; ++it) { QScriptValue metaVal = value.property(*it); if (metaVal.isValid() && metaVal.isNumber()) { AnimationEffect::setMetaData(it.key(), metaVal.toInt32(), s.metaData); } } settings << s; } } } if (settings.count() == 1) { const uint set = settings.at(0).set; if (!(set & AnimationSettings::Type)) { context->throwError(QScriptContext::TypeError, QStringLiteral("Type property missing in animation options")); settings.clear(); } if (!(set & AnimationSettings::Duration)) { context->throwError(QScriptContext::TypeError, QStringLiteral("Duration property missing in animation options")); settings.clear(); } } else if (!(settings.at(0).set & AnimationSettings::Type)) { // invalid global settings.removeAt(0); // -> get rid of it, only used to complete the others } return settings; } QScriptValue kwinEffectAnimate(QScriptContext *context, QScriptEngine *engine) { ScriptedEffect *effect = qobject_cast(context->callee().data().toQObject()); EffectWindow *window; QList settings = animationSettings(context, effect, &window); if (settings.empty()) { context->throwError(QScriptContext::TypeError, QStringLiteral("No animations provided")); return engine->undefinedValue(); } if (!window) { context->throwError(QScriptContext::TypeError, QStringLiteral("Window property does not contain an EffectWindow")); return engine->undefinedValue(); } QScriptValue array = engine->newArray(settings.length()); int i = 0; foreach (const AnimationSettings &setting, settings) { array.setProperty(i, (uint)effect->animate(window, setting.type, setting.duration, setting.to, setting.from, setting.metaData, setting.curve, setting.delay)); ++i; } return array; } QScriptValue kwinEffectSet(QScriptContext *context, QScriptEngine *engine) { ScriptedEffect *effect = qobject_cast(context->callee().data().toQObject()); EffectWindow *window; QList settings = animationSettings(context, effect, &window); if (settings.empty()) { context->throwError(QScriptContext::TypeError, QStringLiteral("No animations provided")); return engine->undefinedValue(); } if (!window) { context->throwError(QScriptContext::TypeError, QStringLiteral("Window property does not contain an EffectWindow")); return engine->undefinedValue(); } QList animIds; foreach (const AnimationSettings &setting, settings) { animIds << QVariant(effect->set(window, setting.type, setting.duration, setting.to, setting.from, setting.metaData, setting.curve, setting.delay)); } return engine->newVariant(animIds); } QList animations(const QVariant &v, bool *ok) { QList animIds; *ok = false; if (v.isValid()) { quint64 animId = v.toULongLong(ok); if (*ok) animIds << animId; } if (!*ok) { // may still be a variantlist of variants being quint64 QList list = v.toList(); if (!list.isEmpty()) { foreach (const QVariant &vv, list) { quint64 animId = vv.toULongLong(ok); if (*ok) animIds << animId; } *ok = !animIds.isEmpty(); } } return animIds; } QScriptValue fpx2ToScriptValue(QScriptEngine *eng, const KWin::FPx2 &fpx2) { QScriptValue val = eng->newObject(); val.setProperty(QStringLiteral("value1"), fpx2[0]); val.setProperty(QStringLiteral("value2"), fpx2[1]); return val; } void fpx2FromScriptValue(const QScriptValue &value, KWin::FPx2 &fpx2) { if (value.isNull()) { fpx2 = FPx2(); return; } if (value.isNumber()) { fpx2 = FPx2(value.toNumber()); return; } if (value.isObject()) { QScriptValue value1 = value.property(QStringLiteral("value1")); QScriptValue value2 = value.property(QStringLiteral("value2")); if (!value1.isValid() || !value2.isValid() || !value1.isNumber() || !value2.isNumber()) { qCDebug(KWIN_SCRIPTING) << "Cannot cast scripted FPx2 to C++"; fpx2 = FPx2(); return; } fpx2 = FPx2(value1.toNumber(), value2.toNumber()); } } QScriptValue kwinEffectRetarget(QScriptContext *context, QScriptEngine *engine) { ScriptedEffect *effect = qobject_cast(context->callee().data().toQObject()); if (context->argumentCount() < 2 || context->argumentCount() > 3) { context->throwError(QScriptContext::SyntaxError, QStringLiteral("2 or 3 arguments expected")); return engine->undefinedValue(); } QVariant v = context->argument(0).toVariant(); bool ok = false; QList animIds = animations(v, &ok); if (!ok) { context->throwError(QScriptContext::TypeError, QStringLiteral("Argument needs to be one or several quint64")); return engine->undefinedValue(); } FPx2 target; fpx2FromScriptValue(context->argument(1), target); ok = false; const int remainingTime = context->argumentCount() == 3 ? context->argument(2).toVariant().toInt() : -1; foreach (const quint64 &animId, animIds) { ok = effect->retarget(animId, target, remainingTime); if (!ok) { break; } } return QScriptValue(ok); } QScriptValue kwinEffectCancel(QScriptContext *context, QScriptEngine *engine) { ScriptedEffect *effect = qobject_cast(context->callee().data().toQObject()); if (context->argumentCount() != 1) { context->throwError(QScriptContext::SyntaxError, QStringLiteral("Exactly one argument expected")); return engine->undefinedValue(); } QVariant v = context->argument(0).toVariant(); bool ok = false; QList animIds = animations(v, &ok); if (!ok) { context->throwError(QScriptContext::TypeError, QStringLiteral("Argument needs to be one or several quint64")); return engine->undefinedValue(); } foreach (const quint64 &animId, animIds) { ok |= engine->newVariant(effect->cancel(animId)).toBool(); } return engine->newVariant(ok); } QScriptValue effectWindowToScriptValue(QScriptEngine *eng, const KEffectWindowRef &window) { return eng->newQObject(window, QScriptEngine::QtOwnership, QScriptEngine::ExcludeChildObjects | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject); } void effectWindowFromScriptValue(const QScriptValue &value, EffectWindow* &window) { window = qobject_cast(value.toQObject()); } ScriptedEffect *ScriptedEffect::create(const KPluginMetaData &effect) { const QString name = effect.pluginId(); const QString scriptName = effect.value(QStringLiteral("X-Plasma-MainScript")); if (scriptName.isEmpty()) { qCDebug(KWIN_SCRIPTING) << "X-Plasma-MainScript not set"; return nullptr; } const QString scriptFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String(KWIN_NAME "/effects/") + name + QLatin1String("/contents/") + scriptName); if (scriptFile.isNull()) { qCDebug(KWIN_SCRIPTING) << "Could not locate the effect script"; return nullptr; } return ScriptedEffect::create(name, scriptFile, effect.value(QStringLiteral("X-KDE-Ordering")).toInt()); } ScriptedEffect *ScriptedEffect::create(const QString& effectName, const QString& pathToScript, int chainPosition) { ScriptedEffect *effect = new ScriptedEffect(); if (!effect->init(effectName, pathToScript)) { delete effect; return nullptr; } effect->m_chainPosition = chainPosition; return effect; } +bool ScriptedEffect::supported() +{ + return effects->animationsSupported(); +} + ScriptedEffect::ScriptedEffect() : AnimationEffect() , m_engine(new QScriptEngine(this)) , m_scriptFile(QString()) , m_config(nullptr) , m_chainPosition(0) { connect(m_engine, SIGNAL(signalHandlerException(QScriptValue)), SLOT(signalHandlerException(QScriptValue))); } ScriptedEffect::~ScriptedEffect() { } bool ScriptedEffect::init(const QString &effectName, const QString &pathToScript) { QFile scriptFile(pathToScript); if (!scriptFile.open(QIODevice::ReadOnly)) { qCDebug(KWIN_SCRIPTING) << "Could not open script file: " << pathToScript; return false; } m_effectName = effectName; m_scriptFile = pathToScript; // does the effect contain an KConfigXT file? const QString kconfigXTFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String(KWIN_NAME "/effects/") + m_effectName + QLatin1String("/contents/config/main.xml")); if (!kconfigXTFile.isNull()) { KConfigGroup cg = effects->effectConfig(m_effectName); QFile xmlFile(kconfigXTFile); m_config = new KConfigLoader(cg, &xmlFile, this); m_config->load(); } QScriptValue effectsObject = m_engine->newQObject(effects, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater); m_engine->globalObject().setProperty(QStringLiteral("effects"), effectsObject, QScriptValue::Undeletable); m_engine->globalObject().setProperty(QStringLiteral("Effect"), m_engine->newQMetaObject(&ScriptedEffect::staticMetaObject)); #ifndef KWIN_UNIT_TEST m_engine->globalObject().setProperty(QStringLiteral("KWin"), m_engine->newQMetaObject(&WorkspaceWrapper::staticMetaObject)); #endif m_engine->globalObject().setProperty(QStringLiteral("QEasingCurve"), m_engine->newQMetaObject(&QEasingCurve::staticMetaObject)); m_engine->globalObject().setProperty(QStringLiteral("effect"), m_engine->newQObject(this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeDeleteLater), QScriptValue::Undeletable); MetaScripting::registration(m_engine); qScriptRegisterMetaType(m_engine, effectWindowToScriptValue, effectWindowFromScriptValue); qScriptRegisterMetaType(m_engine, fpx2ToScriptValue, fpx2FromScriptValue); qScriptRegisterSequenceMetaType >(m_engine); // add our print QScriptValue printFunc = m_engine->newFunction(kwinEffectScriptPrint); printFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("print"), printFunc); // add our animationTime QScriptValue animationTimeFunc = m_engine->newFunction(kwinEffectScriptAnimationTime); animationTimeFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("animationTime"), animationTimeFunc); // add displayWidth and displayHeight QScriptValue displayWidthFunc = m_engine->newFunction(kwinEffectDisplayWidth); m_engine->globalObject().setProperty(QStringLiteral("displayWidth"), displayWidthFunc); QScriptValue displayHeightFunc = m_engine->newFunction(kwinEffectDisplayHeight); m_engine->globalObject().setProperty(QStringLiteral("displayHeight"), displayHeightFunc); // add global Shortcut registerGlobalShortcutFunction(this, m_engine, kwinScriptGlobalShortcut); registerScreenEdgeFunction(this, m_engine, kwinScriptScreenEdge); // add the animate method QScriptValue animateFunc = m_engine->newFunction(kwinEffectAnimate); animateFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("animate"), animateFunc); // and the set variant QScriptValue setFunc = m_engine->newFunction(kwinEffectSet); setFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("set"), setFunc); // retarget QScriptValue retargetFunc = m_engine->newFunction(kwinEffectRetarget); retargetFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("retarget"), retargetFunc); // cancel... QScriptValue cancelFunc = m_engine->newFunction(kwinEffectCancel); cancelFunc.setData(m_engine->newQObject(this)); m_engine->globalObject().setProperty(QStringLiteral("cancel"), cancelFunc); QScriptValue ret = m_engine->evaluate(QString::fromUtf8(scriptFile.readAll())); if (ret.isError()) { signalHandlerException(ret); return false; } scriptFile.close(); return true; } void ScriptedEffect::animationEnded(KWin::EffectWindow *w, Attribute a, uint meta) { AnimationEffect::animationEnded(w, a, meta); emit animationEnded(w, 0); } void ScriptedEffect::signalHandlerException(const QScriptValue &value) { if (value.isError()) { qCDebug(KWIN_SCRIPTING) << "KWin Effect script encountered an error at [Line " << m_engine->uncaughtExceptionLineNumber() << "]"; qCDebug(KWIN_SCRIPTING) << "Message: " << value.toString(); QScriptValueIterator iter(value); while (iter.hasNext()) { iter.next(); qCDebug(KWIN_SCRIPTING) << " " << iter.name() << ": " << iter.value().toString(); } } } quint64 ScriptedEffect::animate(KWin::EffectWindow* w, KWin::AnimationEffect::Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from, uint metaData, QEasingCurve::Type curve, int delay) { QEasingCurve qec; if (curve < QEasingCurve::Custom) qec.setType(curve); else if (static_cast(curve) == static_cast(GaussianCurve)) qec.setCustomType(qecGaussian); return AnimationEffect::animate(w, a, metaData, ms, to, qec, delay, from); } quint64 ScriptedEffect::set(KWin::EffectWindow* w, KWin::AnimationEffect::Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from, uint metaData, QEasingCurve::Type curve, int delay) { QEasingCurve qec; if (curve < QEasingCurve::Custom) qec.setType(curve); else if (static_cast(curve) == static_cast(GaussianCurve)) qec.setCustomType(qecGaussian); return AnimationEffect::set(w, a, metaData, ms, to, qec, delay, from); } bool ScriptedEffect::retarget(quint64 animationId, KWin::FPx2 newTarget, int newRemainingTime) { return AnimationEffect::retarget(animationId, newTarget, newRemainingTime); } bool ScriptedEffect::isGrabbed(EffectWindow* w, ScriptedEffect::DataRole grabRole) { void *e = w->data(static_cast(grabRole)).value(); if (e) { return e != this; } else { return false; } } void ScriptedEffect::reconfigure(ReconfigureFlags flags) { AnimationEffect::reconfigure(flags); if (m_config) { m_config->read(); } emit configChanged(); } void ScriptedEffect::registerShortcut(QAction *a, QScriptValue callback) { m_shortcutCallbacks.insert(a, callback); connect(a, SIGNAL(triggered(bool)), SLOT(globalShortcutTriggered())); } void ScriptedEffect::globalShortcutTriggered() { callGlobalShortcutCallback(this, sender()); } bool ScriptedEffect::borderActivated(ElectricBorder edge) { screenEdgeActivated(this, edge); return true; } QVariant ScriptedEffect::readConfig(const QString &key, const QVariant defaultValue) { if (!m_config) { return defaultValue; } return m_config->property(key); } } // namespace diff --git a/scripting/scriptedeffect.h b/scripting/scriptedeffect.h index fb97896f8..cd7a3da1b 100644 --- a/scripting/scriptedeffect.h +++ b/scripting/scriptedeffect.h @@ -1,127 +1,128 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2012 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_SCRIPTEDEFFECT_H #define KWIN_SCRIPTEDEFFECT_H #include class KConfigLoader; class KPluginMetaData; class QScriptEngine; class QScriptValue; namespace KWin { class KWIN_EXPORT ScriptedEffect : public KWin::AnimationEffect { Q_OBJECT Q_ENUMS(DataRole) Q_ENUMS(Qt::Axis) Q_ENUMS(Anchor) Q_ENUMS(MetaType) Q_ENUMS(EasingCurve) public: // copied from kwineffects.h enum DataRole { // Grab roles are used to force all other animations to ignore the window. // The value of the data is set to the Effect's `this` value. WindowAddedGrabRole = 1, WindowClosedGrabRole, WindowMinimizedGrabRole, WindowUnminimizedGrabRole, WindowForceBlurRole, ///< For fullscreen effects to enforce blurring of windows, WindowBlurBehindRole, ///< For single windows to blur behind WindowForceBackgroundContrastRole, ///< For fullscreen effects to enforce the background contrast, WindowBackgroundContrastRole, ///< For single windows to enable Background contrast LanczosCacheRole }; enum EasingCurve { GaussianCurve = 128 }; const QString &scriptFile() const { return m_scriptFile; } virtual void reconfigure(ReconfigureFlags flags); int requestedEffectChainPosition() const override { return m_chainPosition; } QString activeConfig() const; void setActiveConfig(const QString &name); static ScriptedEffect *create(const QString &effectName, const QString &pathToScript, int chainPosition); static ScriptedEffect *create(const KPluginMetaData &effect); + static bool supported(); virtual ~ScriptedEffect(); /** * Whether another effect has grabbed the @p w with the given @p grabRole. * @param w The window to check * @param grabRole The grab role to check * @returns @c true if another window has grabbed the effect, @c false otherwise **/ Q_SCRIPTABLE bool isGrabbed(KWin::EffectWindow *w, DataRole grabRole); /** * Reads the value from the configuration data for the given key. * @param key The key to search for * @param defaultValue The value to return if the key is not found * @returns The config value if present **/ Q_SCRIPTABLE QVariant readConfig(const QString &key, const QVariant defaultValue = QVariant()); void registerShortcut(QAction *a, QScriptValue callback); const QHash &shortcutCallbacks() const { return m_shortcutCallbacks; } QHash > &screenEdgeCallbacks() { return m_screenEdgeCallbacks; } public Q_SLOTS: quint64 animate(KWin::EffectWindow *w, Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from = KWin::FPx2(), uint metaData = 0, QEasingCurve::Type curve = QEasingCurve::Linear, int delay = 0); quint64 set(KWin::EffectWindow *w, Attribute a, int ms, KWin::FPx2 to, KWin::FPx2 from = KWin::FPx2(), uint metaData = 0, QEasingCurve::Type curve = QEasingCurve::Linear, int delay = 0); bool retarget(quint64 animationId, KWin::FPx2 newTarget, int newRemainingTime = -1); bool cancel(quint64 animationId) { return AnimationEffect::cancel(animationId); } virtual bool borderActivated(ElectricBorder border); Q_SIGNALS: /** * Signal emitted whenever the effect's config changed. **/ void configChanged(); void animationEnded(KWin::EffectWindow *w, quint64 animationId); protected: void animationEnded(KWin::EffectWindow *w, Attribute a, uint meta); private Q_SLOTS: void signalHandlerException(const QScriptValue &value); void globalShortcutTriggered(); private: ScriptedEffect(); bool init(const QString &effectName, const QString &pathToScript); QScriptEngine *m_engine; QString m_effectName; QString m_scriptFile; QHash m_shortcutCallbacks; QHash > m_screenEdgeCallbacks; KConfigLoader *m_config; int m_chainPosition; }; } #endif // KWIN_SCRIPTEDEFFECT_H