diff --git a/autotests/kstartupinfo_unittest.cpp b/autotests/kstartupinfo_unittest.cpp index dc3d859..862a9c9 100644 --- a/autotests/kstartupinfo_unittest.cpp +++ b/autotests/kstartupinfo_unittest.cpp @@ -1,310 +1,310 @@ /* This file is part of the KDE libraries Copyright 2012 David Faure Copyright 2012 Kai Dombrowe This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include "netwm.h" #include #include #include #include Q_DECLARE_METATYPE(KStartupInfoId) Q_DECLARE_METATYPE(KStartupInfoData) class KStartupInfo_UnitTest : public QObject { Q_OBJECT public: KStartupInfo_UnitTest() : m_listener(KStartupInfo::CleanOnCantDetect, this), m_receivedCount(0) { qRegisterMetaType(); qRegisterMetaType(); connect(&m_listener, SIGNAL(gotNewStartup(KStartupInfoId,KStartupInfoData)), this, SLOT(slotNewStartup(KStartupInfoId,KStartupInfoData))); } protected Q_SLOTS: void slotNewStartup(const KStartupInfoId &id, const KStartupInfoData &data) { ++m_receivedCount; m_receivedId = id; m_receivedData = data; emit ready(); } Q_SIGNALS: void ready(); private Q_SLOTS: void testStart(); void dontCrashCleanup_data(); void dontCrashCleanup(); void checkCleanOnCantDetectTest(); void checkStartupTest_data(); void checkStartupTest(); void createNewStartupIdTest(); void createNewStartupIdForTimestampTest(); private: KStartupInfo m_listener; int m_receivedCount; KStartupInfoId m_receivedId; KStartupInfoData m_receivedData; }; void KStartupInfo_UnitTest::testStart() { KStartupInfoId id; id.initId(KStartupInfo::createNewStartupId()); KStartupInfoData data; const QString appId = "/dir with space/kstartupinfo_unittest.desktop"; data.setApplicationId(appId); const QString iconPath = "/dir with space/kstartupinfo_unittest.png"; data.setIcon(iconPath); const QString description = "A description"; data.setDescription(description); const QString name = "A name"; data.setName(name); const int pid = 12345; data.addPid(pid); const QString bin = "dir with space/kstartupinfo_unittest"; data.setBin(bin); QSignalSpy removedSpy(&m_listener, SIGNAL(gotRemoveStartup(KStartupInfoId,KStartupInfoData))); QVERIFY(removedSpy.isValid()); KStartupInfo::sendStartup(id, data); KStartupInfo::sendFinish(id, data); QSignalSpy spy(this, SIGNAL(ready())); spy.wait(5000); QCOMPARE(m_receivedCount, 1); // qDebug() << m_receivedId.id(); // something like "$HOSTNAME;1342544979;490718;8602_TIME0" QCOMPARE(m_receivedData.name(), name); QCOMPARE(m_receivedData.description(), description); QCOMPARE(m_receivedData.applicationId(), appId); QCOMPARE(m_receivedData.icon(), iconPath); QCOMPARE(m_receivedData.bin(), bin); //qDebug() << m_receivedData.bin() << m_receivedData.name() << m_receivedData.description() << m_receivedData.icon() << m_receivedData.pids() << m_receivedData.hostname() << m_receivedData.applicationId(); int waitTime = 0; while (waitTime < 5000 && removedSpy.count() < 1) { QTest::qWait(200); waitTime += 200; } QCOMPARE(removedSpy.count(), 1); } static void doSync() { auto *c = QX11Info::connection(); const auto cookie = xcb_get_input_focus(c); xcb_generic_error_t *error = Q_NULLPTR; QScopedPointer sync(xcb_get_input_focus_reply(c, cookie, &error)); if (error) { free(error); } } void KStartupInfo_UnitTest::dontCrashCleanup_data() { QTest::addColumn("silent"); QTest::addColumn("change"); QTest::addColumn("countRemoveStartup"); QTest::newRow("normal") << false << false << 2; QTest::newRow("silent") << true << false << 0; QTest::newRow("uninited") << false << true << 0; } void KStartupInfo_UnitTest::dontCrashCleanup() { qputenv("KSTARTUPINFO_TIMEOUT", QByteArrayLiteral("1")); KStartupInfoId id; KStartupInfoId id2; id.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_0")); id2.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_1")); KStartupInfoData data; data.setApplicationId(QStringLiteral("/dir with space/kstartupinfo_unittest.desktop")); data.setIcon(QStringLiteral("/dir with space/kstartupinfo_unittest.png")); data.setDescription(QStringLiteral("A description")); data.setName(QStringLiteral("A name")); data.addPid(12345); data.setBin(QStringLiteral("dir with space/kstartupinfo_unittest")); QFETCH(bool, silent); if (silent) { data.setSilent(KStartupInfoData::Yes); } QSignalSpy spy(&m_listener, SIGNAL(gotRemoveStartup(KStartupInfoId,KStartupInfoData))); QFETCH(bool, change); if (change) { KStartupInfo::sendChange(id, data); KStartupInfo::sendChange(id2, data); } else { KStartupInfo::sendStartup(id, data); KStartupInfo::sendStartup(id2, data); } // let's do a roundtrip to the X server doSync(); QFETCH(int, countRemoveStartup); int waitTime = 1900; QTest::qWait(1900); while (waitTime <= 5000) { QTest::qWait(200); waitTime += 200; if (spy.count() == countRemoveStartup) { break; } } QCOMPARE(spy.count(), countRemoveStartup); } void KStartupInfo_UnitTest::checkCleanOnCantDetectTest() { KStartupInfoId id; KStartupInfoId id2; id.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_0")); id2.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_1")); KStartupInfoData data; data.setApplicationId(QStringLiteral("/dir with space/kstartupinfo_unittest.desktop")); data.setIcon(QStringLiteral("/dir with space/kstartupinfo_unittest.png")); data.setDescription(QStringLiteral("A description")); data.setName(QStringLiteral("A name")); data.setBin(QStringLiteral("dir with space/kstartupinfo_unittest")); data.setWMClass(QByteArrayLiteral("0")); xcb_connection_t *c = QX11Info::connection(); xcb_window_t window = xcb_generate_id(c); uint32_t values[] = {XCB_EVENT_MASK_PROPERTY_CHANGE}; xcb_create_window(c, XCB_COPY_FROM_PARENT, window, QX11Info::appRootWindow(), 0, 0, 100, 100, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, XCB_CW_EVENT_MASK, values); KStartupInfo::sendStartup(id, data); KStartupInfo::sendStartup(id2, data); int previousCount = m_receivedCount; doSync(); QTest::qWait(10); xcb_map_window(c, window); xcb_flush(c); QTest::qWait(10); xcb_unmap_window(c, window); xcb_flush(c); QTest::qWait(100); xcb_map_window(c, window); xcb_flush(c); QCOMPARE(m_receivedCount, previousCount + 2); QCOMPARE(m_receivedId, id2); } void KStartupInfo_UnitTest::checkStartupTest_data() { QTest::addColumn("wmClass"); QTest::addColumn("pid"); QTest::newRow("wmClass") << QByteArrayLiteral("kstartupinfotest") << 0; QTest::newRow("pid") << QByteArray() << 12345; } void KStartupInfo_UnitTest::checkStartupTest() { KStartupInfoId id; KStartupInfoId id2; id.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_0")); id2.initId(QByteArrayLiteral("somefancyidwhichisrandom_kstartupinfo_unittest_1")); KStartupInfoData data; data.setApplicationId(QStringLiteral("/dir with space/kstartupinfo_unittest.desktop")); data.setIcon(QStringLiteral("/dir with space/kstartupinfo_unittest.png")); data.setDescription(QStringLiteral("A description")); data.setName(QStringLiteral("A name")); data.setBin(QStringLiteral("dir with space/kstartupinfo_unittest")); QFETCH(int, pid); data.addPid(pid); data.setHostname(QByteArrayLiteral("localhost")); // important for this test: WMClass QFETCH(QByteArray, wmClass); data.setWMClass(wmClass); xcb_connection_t *c = QX11Info::connection(); xcb_window_t window = xcb_generate_id(c); uint32_t values[] = {XCB_EVENT_MASK_PROPERTY_CHANGE}; xcb_create_window(c, XCB_COPY_FROM_PARENT, window, QX11Info::appRootWindow(), 0, 0, 100, 100, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, XCB_CW_EVENT_MASK, values); xcb_change_property(c, XCB_PROP_MODE_REPLACE, window, XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 8, wmClass.length() * 2 + 1, "kstartupinfotest\0kstartupinfotest"); xcb_change_property(c, XCB_PROP_MODE_REPLACE, window, XCB_ATOM_WM_CLIENT_MACHINE, XCB_ATOM_STRING, 8, 9, "localhost"); - NETWinInfo winInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), 0, 0); + NETWinInfo winInfo(QX11Info::connection(), window, QX11Info::appRootWindow(), nullptr, nullptr); winInfo.setPid(pid); KStartupInfo info(KStartupInfo::DisableKWinModule | KStartupInfo::AnnounceSilenceChanges, this); KStartupInfo::sendStartup(id, data); KStartupInfo::sendStartup(id2, data); doSync(); QTest::qWait(100); QCOMPARE(info.checkStartup(window), KStartupInfo::Match); QCOMPARE(info.checkStartup(window), KStartupInfo::Match); } void KStartupInfo_UnitTest::createNewStartupIdTest() { const QByteArray &id = KStartupInfo::createNewStartupId(); QVERIFY(!id.isEmpty()); const int index = id.indexOf(QByteArrayLiteral("TIME")); QVERIFY(index != -1); const QByteArray time = id.mid(index + 4); QVERIFY(time.toULongLong() != 0u); } void KStartupInfo_UnitTest::createNewStartupIdForTimestampTest() { const QByteArray &id = KStartupInfo::createNewStartupIdForTimestamp(5); QVERIFY(!id.isEmpty()); const int index = id.indexOf(QByteArrayLiteral("TIME")); QVERIFY(index != -1); QCOMPARE(id.mid(index + 4).toULongLong(), 5u); } QTEST_MAIN(KStartupInfo_UnitTest) #include "kstartupinfo_unittest.moc" diff --git a/autotests/kwindoweffectstest.cpp b/autotests/kwindoweffectstest.cpp index 921bdb6..fe1adae 100644 --- a/autotests/kwindoweffectstest.cpp +++ b/autotests/kwindoweffectstest.cpp @@ -1,467 +1,467 @@ /* * Copyright 2013 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(KWindowEffects::SlideFromLocation) Q_DECLARE_METATYPE(KWindowEffects::Effect) class KWindowEffectsTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void testSlideWindow_data(); void testSlideWindow(); void testSlideWindowRemove(); void testSlideWindowWidget_data(); void testSlideWindowWidget(); void testSlideWindowWidgetRemove(); void testPresentWindows_data(); void testPresentWindows(); void testPresentWindowsEmptyGroup(); void testPresentWindowsGroup_data(); void testPresentWindowsGroup(); void testHighlightWindows_data(); void testHighlightWindows(); void testHighlightWindowsEmpty(); void testBlur_data(); void testBlur(); void testBlurDisable(); void testMarkAsDashboard(); void testEffectAvailable_data(); void testEffectAvailable(); private: int32_t locationToValue(KWindowEffects::SlideFromLocation location) const; void performSlideWindowTest(xcb_window_t window, int offset, KWindowEffects::SlideFromLocation location) const; void performSlideWindowRemoveTest(xcb_window_t window); void performWindowsOnPropertyTest(xcb_atom_t atom, const QList &windows); void performAtomIsRemoveTest(xcb_window_t window, xcb_atom_t atom); void getHelperAtom(const QByteArray &name, xcb_atom_t *atom) const; xcb_atom_t m_slide; xcb_atom_t m_presentWindows; xcb_atom_t m_presentWindowsGroup; xcb_atom_t m_highlightWindows; xcb_atom_t m_thumbnails; xcb_atom_t m_blur; QScopedPointer m_window; QScopedPointer m_widget; }; void KWindowEffectsTest::initTestCase() { m_window.reset(new QWindow()); QVERIFY(m_window->winId() != XCB_WINDOW_NONE); m_widget.reset(new QWidget()); m_widget->show(); QVERIFY(m_widget->effectiveWinId() != XCB_WINDOW_NONE); getHelperAtom(QByteArrayLiteral("_KDE_SLIDE"), &m_slide); getHelperAtom(QByteArrayLiteral("_KDE_PRESENT_WINDOWS_DESKTOP"), &m_presentWindows); getHelperAtom(QByteArrayLiteral("_KDE_PRESENT_WINDOWS_GROUP"), &m_presentWindowsGroup); getHelperAtom(QByteArrayLiteral("_KDE_WINDOW_HIGHLIGHT"), &m_highlightWindows); getHelperAtom(QByteArrayLiteral("_KDE_WINDOW_PREVIEW"), &m_thumbnails); getHelperAtom(QByteArrayLiteral("_KDE_NET_WM_BLUR_BEHIND_REGION"), &m_blur); } void KWindowEffectsTest::getHelperAtom(const QByteArray &name, xcb_atom_t *atom) const { xcb_connection_t *c = QX11Info::connection(); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, name.length(), name.constData()); - QScopedPointer reply(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer reply(xcb_intern_atom_reply(c, atomCookie, nullptr)); QVERIFY(!reply.isNull()); *atom = reply->atom; } void KWindowEffectsTest::testSlideWindow_data() { QTest::addColumn("offset"); QTest::addColumn("location"); QTest::newRow("Left") << 10 << KWindowEffects::LeftEdge; QTest::newRow("Right") << 20 << KWindowEffects::RightEdge; QTest::newRow("Top") << 0 << KWindowEffects::TopEdge; QTest::newRow("Bottom") << -1 << KWindowEffects::BottomEdge; } void KWindowEffectsTest::testSlideWindow() { QFETCH(int, offset); QFETCH(KWindowEffects::SlideFromLocation, location); KWindowEffects::slideWindow(m_window->winId(), location, offset); performSlideWindowTest(m_window->winId(), offset, location); } void KWindowEffectsTest::testSlideWindowRemove() { xcb_window_t window = m_window->winId(); // first install the atom KWindowEffects::slideWindow(window, KWindowEffects::TopEdge, 0); performSlideWindowTest(window, 0, KWindowEffects::TopEdge); // now delete it KWindowEffects::slideWindow(window, KWindowEffects::NoEdge, 0); performSlideWindowRemoveTest(window); } void KWindowEffectsTest::testSlideWindowWidget_data() { QTest::addColumn("location"); QTest::newRow("Left") << KWindowEffects::LeftEdge; QTest::newRow("Right") << KWindowEffects::RightEdge; QTest::newRow("Top") << KWindowEffects::TopEdge; QTest::newRow("Bottom") << KWindowEffects::BottomEdge; } void KWindowEffectsTest::testSlideWindowWidget() { QFETCH(KWindowEffects::SlideFromLocation, location); KWindowEffects::slideWindow(m_widget.data(), location); performSlideWindowTest(m_widget->effectiveWinId(), -1, location); } void KWindowEffectsTest::testSlideWindowWidgetRemove() { xcb_window_t window = m_widget->effectiveWinId(); // first install the atom KWindowEffects::slideWindow(m_widget.data(), KWindowEffects::TopEdge); performSlideWindowTest(window, -1, KWindowEffects::TopEdge); // now delete it KWindowEffects::slideWindow(m_widget.data(), KWindowEffects::NoEdge); performSlideWindowRemoveTest(window); } void KWindowEffectsTest::performSlideWindowTest(xcb_window_t window, int offset, KWindowEffects::SlideFromLocation location) const { xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, window, m_slide, m_slide, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(2)); QCOMPARE(reply->type, m_slide); int32_t *data = static_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], offset); QCOMPARE(data[1], locationToValue(location)); } void KWindowEffectsTest::performSlideWindowRemoveTest(xcb_window_t window) { performAtomIsRemoveTest(window, m_slide); } void KWindowEffectsTest::performAtomIsRemoveTest(xcb_window_t window, xcb_atom_t atom) { xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, window, atom, atom, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_NONE)); } int32_t KWindowEffectsTest::locationToValue(KWindowEffects::SlideFromLocation location) const { switch (location) { case KWindowEffects::LeftEdge: return 0; case KWindowEffects::TopEdge: return 1; case KWindowEffects::RightEdge: return 2; case KWindowEffects::BottomEdge: return 3; default: return -1; } } void KWindowEffectsTest::testPresentWindows_data() { QTest::addColumn("desktop"); QTest::newRow("all desktops") << -1; QTest::newRow("1") << 1; QTest::newRow("2") << 2; QTest::newRow("3") << 3; QTest::newRow("4") << 4; } void KWindowEffectsTest::testPresentWindows() { QFETCH(int, desktop); KWindowEffects::presentWindows(m_window->winId(), desktop); xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), m_presentWindows, m_presentWindows, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(1)); QCOMPARE(reply->type, m_presentWindows); int32_t *data = static_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], desktop); } void KWindowEffectsTest::testPresentWindowsEmptyGroup() { KWindowEffects::presentWindows(m_window->winId(), QList()); xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), m_presentWindowsGroup, m_presentWindowsGroup, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_NONE)); } void KWindowEffectsTest::testPresentWindowsGroup_data() { QTest::addColumn >("windows"); QTest::newRow("one") << (QList() << m_window->winId()); QTest::newRow("two") << (QList() << m_window->winId() << m_widget->effectiveWinId()); } void KWindowEffectsTest::testPresentWindowsGroup() { QFETCH(QList, windows); KWindowEffects::presentWindows(m_window->winId(), windows); performWindowsOnPropertyTest(m_presentWindowsGroup, windows); } void KWindowEffectsTest::testHighlightWindows_data() { QTest::addColumn >("windows"); QTest::newRow("one") << (QList() << m_window->winId()); QTest::newRow("two") << (QList() << m_window->winId() << m_widget->effectiveWinId()); } void KWindowEffectsTest::testHighlightWindows() { QFETCH(QList, windows); KWindowEffects::highlightWindows(m_window->winId(), windows); performWindowsOnPropertyTest(m_highlightWindows, windows); } void KWindowEffectsTest::testHighlightWindowsEmpty() { // ensure it's empty KWindowEffects::highlightWindows(m_window->winId(), QList()); performAtomIsRemoveTest(m_window->winId(), m_highlightWindows); // install some windows on the atom QList windows; windows.append(m_window->winId()); windows.append(m_widget->effectiveWinId()); KWindowEffects::highlightWindows(m_window->winId(), windows); performWindowsOnPropertyTest(m_highlightWindows, windows); // and remove it again KWindowEffects::highlightWindows(m_window->winId(), QList()); performAtomIsRemoveTest(m_window->winId(), m_highlightWindows); } void KWindowEffectsTest::performWindowsOnPropertyTest(xcb_atom_t atom, const QList< WId > &windows) { xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), atom, atom, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, atom); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(windows.size())); int32_t *data = static_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < windows.size(); ++i) { QCOMPARE(data[i], int32_t(windows.at(i))); } } void KWindowEffectsTest::testBlur_data() { QTest::addColumn("blur"); QRegion region(0, 0, 10, 10); QTest::newRow("one rect") << region; region = region.united(QRect(20, 20, 5, 5)); QTest::newRow("two rects") << region; region = region.united(QRect(100, 100, 20, 20)); QTest::newRow("three rects") << region; QTest::newRow("empty") << QRegion(); } void KWindowEffectsTest::testBlur() { QFETCH(QRegion, blur); KWindowEffects::enableBlurBehind(m_window->winId(), true, blur); xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), m_blur, XCB_ATOM_CARDINAL, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_CARDINAL)); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(blur.rectCount() * 4)); uint32_t *data = static_cast(xcb_get_property_value(reply.data())); QVector rects = blur.rects(); for (int i = 0; i < rects.count(); ++i) { int counter = i * 4; const QRect &rect = rects.at(i); QCOMPARE(data[counter++], uint32_t(rect.x())); QCOMPARE(data[counter++], uint32_t(rect.y())); QCOMPARE(data[counter++], uint32_t(rect.width())); QCOMPARE(data[counter++], uint32_t(rect.height())); } } void KWindowEffectsTest::testBlurDisable() { KWindowEffects::enableBlurBehind(m_window->winId(), false); performAtomIsRemoveTest(m_window->winId(), m_blur); KWindowEffects::enableBlurBehind(m_window->winId(), true); //verify that it got added xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), m_blur, XCB_ATOM_CARDINAL, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_CARDINAL)); // and disable KWindowEffects::enableBlurBehind(m_window->winId(), false); performAtomIsRemoveTest(m_window->winId(), m_blur); } void KWindowEffectsTest::testMarkAsDashboard() { const QByteArray className = QByteArrayLiteral("dashboard"); // should not yet be set xcb_connection_t *c = QX11Info::connection(); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(c, false, m_window->winId(), XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 0, 100); - QScopedPointer reply(xcb_get_property_reply(c, cookie, NULL)); + QScopedPointer reply(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_STRING)); QCOMPARE(reply->format, uint8_t(8)); char *data = static_cast(xcb_get_property_value(reply.data())); QVERIFY(QByteArray(data) != className); // now mark as dashboard KWindowEffects::markAsDashboard(m_window->winId()); cookie = xcb_get_property_unchecked(c, false, m_window->winId(), XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 0, 100); - reply.reset(xcb_get_property_reply(c, cookie, NULL)); + reply.reset(xcb_get_property_reply(c, cookie, nullptr)); QVERIFY(!reply.isNull()); QCOMPARE(reply->type, xcb_atom_t(XCB_ATOM_STRING)); QCOMPARE(reply->format, uint8_t(8)); QCOMPARE(reply->value_len, uint32_t(19)); data = static_cast(xcb_get_property_value(reply.data())); QCOMPARE(QByteArray(data), className); data = data + 10; QCOMPARE(QByteArray(data), className); } void KWindowEffectsTest::testEffectAvailable_data() { QTest::addColumn("effect"); QTest::addColumn("propertyName"); QTest::newRow("slide") << KWindowEffects::Slide << QByteArrayLiteral("_KDE_SLIDE"); QTest::newRow("PresentWindows") << KWindowEffects::PresentWindows << QByteArrayLiteral("_KDE_PRESENT_WINDOWS_DESKTOP"); QTest::newRow("PresentWindowsGroup") << KWindowEffects::PresentWindowsGroup << QByteArrayLiteral("_KDE_PRESENT_WINDOWS_GROUP"); QTest::newRow("HighlightWindows") << KWindowEffects::HighlightWindows << QByteArrayLiteral("_KDE_WINDOW_HIGHLIGHT"); QTest::newRow("BlurBehind") << KWindowEffects::BlurBehind << QByteArrayLiteral("_KDE_NET_WM_BLUR_BEHIND_REGION"); QTest::newRow("Dashboard") << KWindowEffects::Dashboard << QByteArrayLiteral("_WM_EFFECT_KDE_DASHBOARD"); QTest::newRow("BackgroundContrast") << KWindowEffects::BackgroundContrast << QByteArrayLiteral("_KDE_NET_WM_BACKGROUND_CONTRAST_REGION"); } void KWindowEffectsTest::testEffectAvailable() { NETRootInfo rootInfo(QX11Info::connection(), NET::Supported | NET::SupportingWMCheck); if (qstrcmp(rootInfo.wmName(), "KWin") == 0) { QSKIP("KWin running, we don't want to interact with the running system"); } // this test verifies whether an effect is available QFETCH(KWindowEffects::Effect, effect); // without a compositing manager it's not available // try-verify as there still might be the selection claimed from previous data run QTRY_VERIFY(!KWindowSystem::compositingActive()); QVERIFY(!KWindowEffects::isEffectAvailable(effect)); // fake the compositor QSignalSpy compositingChangedSpy(KWindowSystem::self(), &KWindowSystem::compositingChanged); QVERIFY(compositingChangedSpy.isValid()); KSelectionOwner compositorSelection("_NET_WM_CM_S0"); QSignalSpy claimedSpy(&compositorSelection, &KSelectionOwner::claimedOwnership); QVERIFY(claimedSpy.isValid()); compositorSelection.claim(true); QVERIFY(claimedSpy.wait()); QCOMPARE(compositingChangedSpy.count(), 1); QCOMPARE(compositingChangedSpy.first().first().toBool(), true); QVERIFY(KWindowSystem::compositingActive()); // but not yet available QVERIFY(!KWindowEffects::isEffectAvailable(effect)); // set the atom QFETCH(QByteArray, propertyName); xcb_connection_t *c = QX11Info::connection(); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, propertyName.length(), propertyName.constData()); QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, Q_NULLPTR)); QVERIFY(!atom.isNull()); unsigned char dummy = 0; xcb_change_property(c, XCB_PROP_MODE_REPLACE, QX11Info::appRootWindow(), atom->atom, atom->atom, 8, 1, &dummy); xcb_flush(c); // now the effect should be available QVERIFY(KWindowEffects::isEffectAvailable(effect)); // delete the property again xcb_delete_property(c, QX11Info::appRootWindow(), atom->atom); xcb_flush(c); // which means it's no longer available QVERIFY(!KWindowEffects::isEffectAvailable(effect)); // remove compositing selection compositorSelection.release(); QVERIFY(compositingChangedSpy.wait()); QCOMPARE(compositingChangedSpy.count(), 2); QCOMPARE(compositingChangedSpy.last().first().toBool(), false); QVERIFY(!KWindowSystem::compositingActive()); } QTEST_MAIN(KWindowEffectsTest) #include "kwindoweffectstest.moc" diff --git a/autotests/kwindowinfox11test.cpp b/autotests/kwindowinfox11test.cpp index 2020ca8..c9ccf6d 100644 --- a/autotests/kwindowinfox11test.cpp +++ b/autotests/kwindowinfox11test.cpp @@ -1,777 +1,777 @@ /* * Copyright 2014 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "kwindowinfo.h" #include "kwindowsystem.h" #include "netwm.h" #include "nettesthelper.h" #include #include #include #include #include Q_DECLARE_METATYPE(WId) Q_DECLARE_METATYPE(NET::State) Q_DECLARE_METATYPE(NET::States) Q_DECLARE_METATYPE(NET::WindowType) Q_DECLARE_METATYPE(NET::WindowTypeMask) Q_DECLARE_METATYPE(NET::WindowTypes) Q_DECLARE_METATYPE(NET::Properties) Q_DECLARE_METATYPE(NET::Properties2) class KWindowInfoX11Test : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void init(); void cleanup(); void testState_data(); void testState(); void testDemandsAttention(); void testMinimized(); void testMappingState(); void testWindowType_data(); void testWindowType(); void testDesktop(); void testActivities(); void testWindowClass(); void testWindowRole(); void testClientMachine(); void testName(); void testTransientFor(); void testGroupLeader(); void testExtendedStrut(); void testGeometry(); void testDesktopFileName(); void testPid(); // actionSupported is not tested as it's too window manager specific // we could write a test against KWin's behavior, but that would fail on // build.kde.org as we use OpenBox there. private: void showWidget(QWidget *widget); bool waitForWindow(QSignalSpy &spy, WId winId, NET::Properties property, NET::Properties2 properties2 = NET::Properties2()) const; bool verifyMinimized(WId window) const; QScopedPointer window; }; void KWindowInfoX11Test::initTestCase() { QCoreApplication::setAttribute(Qt::AA_ForceRasterWidgets); qRegisterMetaType(); qRegisterMetaType(); } bool KWindowInfoX11Test::waitForWindow(QSignalSpy& spy, WId winId, NET::Properties property, NET::Properties2 property2) const { // we need to wait, window manager has to react and update the property. bool foundOurWindow = false; for (int i = 0; i < 10; ++i) { spy.wait(50); if (spy.isEmpty()) { continue; } for (auto it = spy.constBegin(); it != spy.constEnd(); ++it) { if (it->first().value() != winId) { continue; } if (property != NET::Properties()) { if (it->at(1).value() != property) { continue; } } if (property2 != NET::Properties2()) { if (it->at(2).value() != property2) { continue; } } foundOurWindow = true; break; } if (foundOurWindow) { break; } spy.clear(); } return foundOurWindow; } bool KWindowInfoX11Test::verifyMinimized(WId window) const { KWindowInfo info(window, NET::WMState | NET::XAWMState); return info.isMinimized(); } void KWindowInfoX11Test::init() { // create the window and ensure it has been managed window.reset(new QWidget()); showWidget(window.data()); } void KWindowInfoX11Test::showWidget(QWidget *window) { qRegisterMetaType("WId"); QSignalSpy spy(KWindowSystem::self(), SIGNAL(windowAdded(WId))); window->show(); bool foundOurWindow = false; for (int i = 0; i < 50; ++i) { spy.wait(50); if (spy.isEmpty()) { continue; } for (auto it = spy.constBegin(); it != spy.constEnd(); ++it) { if (it->isEmpty()) { continue; } if (it->first().value() == window->winId()) { foundOurWindow = true; break; } } if (foundOurWindow) { break; } spy.clear(); } } void KWindowInfoX11Test::cleanup() { // we hide the window and wait till it is gone so that we have a clean state in next test if (!window.isNull() && window->isVisible()) { WId id = window->winId(); QSignalSpy spy(KWindowSystem::self(), SIGNAL(windowRemoved(WId))); window->hide(); bool foundOurWindow = false; for (int i = 0; i < 50; ++i) { spy.wait(50); if (spy.isEmpty()) { continue; } for (auto it = spy.constBegin(); it != spy.constEnd(); ++it) { if (it->first().value() == id) { foundOurWindow = true; break; } } if (foundOurWindow) { break; } spy.clear(); } } window.reset(); } void KWindowInfoX11Test::testState_data() { QTest::addColumn("state"); QTest::newRow("max") << NET::States(NET::Max); QTest::newRow("maxHoriz") << NET::States(NET::MaxHoriz); QTest::newRow("shaded") << NET::States(NET::Shaded); QTest::newRow("skipTaskbar") << NET::States(NET::SkipTaskbar); QTest::newRow("skipPager") << NET::States(NET::SkipPager); QTest::newRow("keep above") << NET::States(NET::KeepAbove); QTest::newRow("keep below") << NET::States(NET::KeepBelow); QTest::newRow("fullscreen") << NET::States(NET::FullScreen); // NOTE: modal, sticky and hidden cannot be tested with this variant // demands attention is not tested as that's already part of the first run adjustments } void KWindowInfoX11Test::testState() { QFETCH(NET::States, state); QX11Info::getTimestamp(); KWindowInfo info(window->winId(), NET::WMState); QVERIFY(info.valid()); // all states except demands attention for (int i = 0; i < 12; ++i) { QVERIFY(!info.hasState(NET::States(1 << i))); } QSignalSpy spy(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spy.isValid()); // now we have a clean window and can do fun stuff KWindowSystem::setState(window->winId(), state); QVERIFY(waitForWindow(spy, window->winId(), NET::WMState)); KWindowInfo info3(window->winId(), NET::WMState); QVERIFY(info3.valid()); QCOMPARE(info3.state(), state); QVERIFY(info3.hasState(state)); } // This struct is defined here to avoid a dependency on xcb-icccm struct kde_wm_hints { uint32_t flags; uint32_t input; int32_t initial_state; xcb_pixmap_t icon_pixmap; xcb_window_t icon_window; int32_t icon_x; int32_t icon_y; xcb_pixmap_t icon_mask; xcb_window_t window_group; }; void KWindowInfoX11Test::testDemandsAttention() { QSignalSpy activeWindowSpy(KWindowSystem::self(), SIGNAL(activeWindowChanged(WId))); QVERIFY(activeWindowSpy.isValid()); if (KWindowSystem::activeWindow() != window->winId()) { // we force activate as KWin's focus stealing prevention might kick in KWindowSystem::forceActiveWindow(window->winId()); QVERIFY(activeWindowSpy.wait()); QCOMPARE(activeWindowSpy.first().first().toULongLong(), window->winId()); activeWindowSpy.clear(); } // need a second window for proper interaction QWidget win2; showWidget(&win2); KWindowSystem::forceActiveWindow(win2.winId()); if (activeWindowSpy.isEmpty()) { QVERIFY(activeWindowSpy.wait()); } KWindowInfo info(window->winId(), NET::WMState); QVERIFY(info.valid()); QVERIFY(!info.hasState(NET::DemandsAttention)); QSignalSpy spy(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spy.isValid()); // now we have a clean window and can do fun stuff KWindowSystem::demandAttention(window->winId()); QVERIFY(waitForWindow(spy, window->winId(), NET::WMState)); KWindowInfo info2(window->winId(), NET::WMState); QVERIFY(info2.valid()); QCOMPARE(info2.state(), NET::DemandsAttention); QVERIFY(info2.hasState(NET::DemandsAttention)); // now activate win1, that should remove demands attention spy.clear(); KWindowSystem::forceActiveWindow(window->winId()); QTest::qWait(200); QVERIFY(waitForWindow(spy, window->winId(), NET::WMState)); KWindowInfo info3(window->winId(), NET::WMState); QVERIFY(info3.valid()); QVERIFY(!info3.hasState(NET::DemandsAttention)); // we should be able to demand attention on win2 spy.clear(); KWindowSystem::demandAttention(win2.winId()); xcb_flush(QX11Info::connection()); QVERIFY(waitForWindow(spy, win2.winId(), NET::WMState)); KWindowInfo info4(win2.winId(), NET::WMState); QVERIFY(info4.valid()); QCOMPARE(info4.state(), NET::DemandsAttention); QVERIFY(info4.hasState(NET::DemandsAttention)); // and to remove demand attention on win2 spy.clear(); QTest::qWait(200); KWindowSystem::demandAttention(win2.winId(), false); xcb_flush(QX11Info::connection()); QVERIFY(waitForWindow(spy, win2.winId(), NET::WMState)); KWindowInfo info5(win2.winId(), NET::WMState); QVERIFY(info5.valid()); QVERIFY(!info5.hasState(NET::DemandsAttention)); // WM2Urgency should be mapped to state NET::DemandsAttention kde_wm_hints hints; hints.flags = (1 << 8); hints.icon_mask = XCB_PIXMAP_NONE; hints.icon_pixmap = XCB_PIXMAP_NONE; hints.icon_window = XCB_WINDOW_NONE; hints.input = 0; hints.window_group = XCB_WINDOW_NONE; hints.icon_x = 0; hints.icon_y = 0; hints.initial_state = 0; xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, win2.winId(), XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, &hints); xcb_flush(QX11Info::connection()); // window managers map urgency to demands attention spy.clear(); QVERIFY(waitForWindow(spy, win2.winId(), NET::WMState)); QTest::qWait(100); // a window info with NET::WM2Urgency should show demands attention KWindowInfo urgencyInfo(win2.winId(), NET::WMState); QVERIFY(urgencyInfo.valid()); QVERIFY(urgencyInfo.hasState(NET::DemandsAttention)); // remove urgency again hints.flags = 0; xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, win2.winId(), XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, &hints); xcb_flush(QX11Info::connection()); // TODO: test whether it gets removed again. At least KWin does not remove demands attention // prevent openbox crash (see https://bugzilla.icculus.org/show_bug.cgi?id=6315 ) QTest::qWait(600); } void KWindowInfoX11Test::testMinimized() { // should not be minimized, now QVERIFY(!verifyMinimized(window->winId())); window->showMinimized(); // TODO: improve by using signalspy? QTest::qWait(100); // should be minimized, now QVERIFY(verifyMinimized(window->winId())); // back to normal window->showNormal(); // TODO: improve by using signalspy? QTest::qWait(100); // should no longer be minimized QVERIFY(!verifyMinimized(window->winId())); } void KWindowInfoX11Test::testMappingState() { KWindowInfo info(window->winId(), NET::XAWMState); QCOMPARE(info.mappingState(), NET::Visible); window->showMinimized(); // TODO: improve by using signalspy? QTest::qWait(100); KWindowInfo info2(window->winId(), NET::XAWMState); QCOMPARE(info2.mappingState(), NET::Iconic); window->hide(); // TODO: improve by using signalspy? QTest::qWait(100); KWindowInfo info3(window->winId(), NET::XAWMState); QCOMPARE(info3.mappingState(), NET::Withdrawn); } void KWindowInfoX11Test::testWindowType_data() { QTest::addColumn("mask"); QTest::addColumn("type"); QTest::addColumn("expectedType"); QTest::newRow("desktop") << NET::DesktopMask << NET::Desktop << NET::Desktop; QTest::newRow("dock") << NET::DockMask << NET::Dock << NET::Dock; QTest::newRow("toolbar") << NET::ToolbarMask << NET::Toolbar << NET::Toolbar; QTest::newRow("menu") << NET::MenuMask << NET::Menu << NET::Menu; QTest::newRow("dialog") << NET::DialogMask << NET::Dialog << NET::Dialog; QTest::newRow("override") << NET::OverrideMask << NET::Override << NET::Override; QTest::newRow("override as normal") << NET::NormalMask << NET::Override << NET::Normal; QTest::newRow("topmenu") << NET::TopMenuMask << NET::TopMenu << NET::TopMenu; QTest::newRow("topmenu as dock") << NET::DockMask << NET::TopMenu << NET::Dock; QTest::newRow("utility") << NET::UtilityMask << NET::Utility << NET::Utility; QTest::newRow("utility as dialog") << NET::DialogMask << NET::Utility << NET::Dialog; QTest::newRow("splash") << NET::SplashMask << NET::Splash << NET::Splash; QTest::newRow("splash as dock") << NET::DockMask << NET::Splash << NET::Dock; QTest::newRow("dropdownmenu") << NET::DropdownMenuMask << NET::DropdownMenu << NET::DropdownMenu; QTest::newRow("popupmenu") << NET::PopupMenuMask << NET::PopupMenu << NET::PopupMenu; QTest::newRow("popupmenu as menu") << NET::MenuMask << NET::Menu << NET::Menu; QTest::newRow("tooltip") << NET::TooltipMask << NET::Tooltip << NET::Tooltip; QTest::newRow("notification") << NET::NotificationMask << NET::Notification << NET::Notification; QTest::newRow("ComboBox") << NET::ComboBoxMask << NET::ComboBox << NET::ComboBox; QTest::newRow("DNDIcon") << NET::DNDIconMask << NET::DNDIcon << NET::DNDIcon; QTest::newRow("OnScreenDisplay") << NET::OnScreenDisplayMask << NET::OnScreenDisplay << NET::OnScreenDisplay; // incorrect masks QTest::newRow("desktop-unknown") << NET::NormalMask << NET::Desktop << NET::Unknown; QTest::newRow("dock-unknown") << NET::NormalMask << NET::Dock << NET::Unknown; QTest::newRow("toolbar-unknown") << NET::NormalMask << NET::Toolbar << NET::Unknown; QTest::newRow("menu-unknown") << NET::NormalMask << NET::Menu << NET::Unknown; QTest::newRow("dialog-unknown") << NET::NormalMask << NET::Dialog << NET::Unknown; QTest::newRow("override-unknown") << NET::DialogMask << NET::Override << NET::Unknown; QTest::newRow("topmenu-unknown") << NET::NormalMask << NET::TopMenu << NET::Unknown; QTest::newRow("utility-unknown") << NET::NormalMask << NET::Utility << NET::Unknown; QTest::newRow("splash-unknown") << NET::NormalMask << NET::Splash << NET::Unknown; QTest::newRow("dropdownmenu-unknown") << NET::NormalMask << NET::DropdownMenu << NET::Unknown; QTest::newRow("popupmenu-unknown") << NET::NormalMask << NET::PopupMenu << NET::Unknown; QTest::newRow("tooltip-unknown") << NET::NormalMask << NET::Tooltip << NET::Unknown; QTest::newRow("notification-unknown") << NET::NormalMask << NET::Notification << NET::Unknown; QTest::newRow("ComboBox-unknown") << NET::NormalMask << NET::ComboBox << NET::Unknown; QTest::newRow("DNDIcon-unknown") << NET::NormalMask << NET::DNDIcon << NET::Unknown; QTest::newRow("OnScreenDisplay-unknown") << NET::NormalMask << NET::OnScreenDisplay << NET::Unknown; } void KWindowInfoX11Test::testWindowType() { KWindowInfo info(window->winId(), NET::WMWindowType); QCOMPARE(info.windowType(NET::NormalMask), NET::Normal); QFETCH(NET::WindowTypeMask, mask); QFETCH(NET::WindowType, type); QFETCH(NET::WindowType, expectedType); KWindowSystem::setType(window->winId(), type); // setWindowType just changes an xproperty, so a roundtrip waiting for another property ensures we are updated QX11Info::getTimestamp(); KWindowInfo info2(window->winId(), NET::WMWindowType); QCOMPARE(info2.windowType(mask), expectedType); } void KWindowInfoX11Test::testDesktop() { if (KWindowSystem::numberOfDesktops() < 2) { QSKIP("We need at least two virtual desktops to perform proper virtual desktop testing"); } KWindowInfo info(window->winId(), NET::WMDesktop); QVERIFY(info.isOnCurrentDesktop()); QVERIFY(!info.onAllDesktops()); QCOMPARE(info.desktop(), KWindowSystem::currentDesktop()); for (int i = 1; i < KWindowSystem::numberOfDesktops(); i++) { if (i == KWindowSystem::currentDesktop()) { QVERIFY(info.isOnDesktop(i)); } else { QVERIFY(!info.isOnDesktop(i)); } } // set on all desktop QSignalSpy spy(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spy.isValid()); KWindowSystem::setOnAllDesktops(window->winId(), true); QVERIFY(waitForWindow(spy, window->winId(), NET::WMDesktop)); KWindowInfo info2(window->winId(), NET::WMDesktop); QVERIFY(info2.isOnCurrentDesktop()); QVERIFY(info2.onAllDesktops()); QCOMPARE(info2.desktop(), int(NET::OnAllDesktops)); for (int i = 1; i < KWindowSystem::numberOfDesktops(); i++) { QVERIFY(info2.isOnDesktop(i)); } const int desktop = (KWindowSystem::currentDesktop() % KWindowSystem::numberOfDesktops()) + 1; spy.clear(); KWindowSystem::setOnDesktop(window->winId(), desktop); QX11Info::getTimestamp(); QVERIFY(waitForWindow(spy, window->winId(), NET::WMDesktop)); KWindowInfo info3(window->winId(), NET::WMDesktop); QVERIFY(!info3.isOnCurrentDesktop()); QVERIFY(!info3.onAllDesktops()); QCOMPARE(info3.desktop(), desktop); for (int i = 1; i < KWindowSystem::numberOfDesktops(); i++) { if (i == desktop) { QVERIFY(info3.isOnDesktop(i)); } else { QVERIFY(!info3.isOnDesktop(i)); } } } void KWindowInfoX11Test::testActivities() { NETRootInfo rootInfo(QX11Info::connection(), NET::Supported | NET::SupportingWMCheck); QSignalSpy spyReal(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spyReal.isValid()); - KWindowInfo info(window->winId(), 0, NET::WM2Activities); + KWindowInfo info(window->winId(), nullptr, NET::WM2Activities); QVERIFY(info.valid()); QStringList startingActivities = info.activities(); // The window is either on a specific activity when created, // or on all of them (aka startingActivities is empty or contains // just one element) QVERIFY(startingActivities.size() <= 1); // Window on all activities KWindowSystem::self()->setOnActivities(window->winId(), QStringList()); QVERIFY(waitForWindow(spyReal, window->winId(), NET::Properties(), NET::WM2Activities)); - KWindowInfo info2(window->winId(), 0, NET::WM2Activities); + KWindowInfo info2(window->winId(), nullptr, NET::WM2Activities); QVERIFY(info2.activities().size() == 0); // Window on a specific activity KWindowSystem::self()->setOnActivities(window->winId(), QStringList() << "test-activity"); QVERIFY(waitForWindow(spyReal, window->winId(), NET::Properties(), NET::WM2Activities)); - KWindowInfo info3(window->winId(), 0, NET::WM2Activities); + KWindowInfo info3(window->winId(), nullptr, NET::WM2Activities); QVERIFY(info3.activities().size() == 1); QVERIFY(info3.activities()[0] == "test-activity"); // Window on a two activities KWindowSystem::self()->setOnActivities(window->winId(), QStringList() << "test-activity" << "test-activity2"); QVERIFY(waitForWindow(spyReal, window->winId(), NET::Properties(), NET::WM2Activities)); - KWindowInfo info4(window->winId(), 0, NET::WM2Activities); + KWindowInfo info4(window->winId(), nullptr, NET::WM2Activities); QVERIFY(info4.activities().size() == 2); QVERIFY(info4.activities()[0] == "test-activity"); QVERIFY(info4.activities()[1] == "test-activity2"); // Window on the starting activity KWindowSystem::self()->setOnActivities(window->winId(), startingActivities); QVERIFY(waitForWindow(spyReal, window->winId(), NET::Properties(), NET::WM2Activities)); - KWindowInfo info5(window->winId(), 0, NET::WM2Activities); + KWindowInfo info5(window->winId(), nullptr, NET::WM2Activities); QVERIFY(info5.activities() == startingActivities); } void KWindowInfoX11Test::testWindowClass() { - KWindowInfo info(window->winId(), 0, NET::WM2WindowClass); + KWindowInfo info(window->winId(), nullptr, NET::WM2WindowClass); QCOMPARE(info.windowClassName(), QByteArrayLiteral("kwindowinfox11test")); QCOMPARE(info.windowClassClass(), QByteArrayLiteral("kwindowinfox11test")); // window class needs to be changed using xcb xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, window->winId(), XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 8, 7, "foo\0bar"); xcb_flush(QX11Info::connection()); // it's just a property change so we can easily refresh QX11Info::getTimestamp(); - KWindowInfo info2(window->winId(), 0, NET::WM2WindowClass); + KWindowInfo info2(window->winId(), nullptr, NET::WM2WindowClass); QCOMPARE(info2.windowClassName(), QByteArrayLiteral("foo")); QCOMPARE(info2.windowClassClass(), QByteArrayLiteral("bar")); } void KWindowInfoX11Test::testWindowRole() { - KWindowInfo info(window->winId(), 0, NET::WM2WindowRole); + KWindowInfo info(window->winId(), nullptr, NET::WM2WindowRole); QVERIFY(info.windowRole().isNull()); // window role needs to be changed using xcb KXUtils::Atom atom(QX11Info::connection(), QByteArrayLiteral("WM_WINDOW_ROLE")); xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, window->winId(), atom, XCB_ATOM_STRING, 8, 3, "bar"); xcb_flush(QX11Info::connection()); // it's just a property change so we can easily refresh QX11Info::getTimestamp(); - KWindowInfo info2(window->winId(), 0, NET::WM2WindowRole); + KWindowInfo info2(window->winId(), nullptr, NET::WM2WindowRole); QCOMPARE(info2.windowRole(), QByteArrayLiteral("bar")); } void KWindowInfoX11Test::testClientMachine() { - KWindowInfo info(window->winId(), 0, NET::WM2ClientMachine); + KWindowInfo info(window->winId(), nullptr, NET::WM2ClientMachine); QVERIFY(info.clientMachine().isNull()); // client machine needs to be set through xcb xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, window->winId(), XCB_ATOM_WM_CLIENT_MACHINE, XCB_ATOM_STRING, 8, 9, "localhost"); xcb_flush(QX11Info::connection()); // it's just a property change so we can easily refresh QX11Info::getTimestamp(); - KWindowInfo info2(window->winId(), 0, NET::WM2ClientMachine); + KWindowInfo info2(window->winId(), nullptr, NET::WM2ClientMachine); QCOMPARE(info2.clientMachine(), QByteArrayLiteral("localhost")); } void KWindowInfoX11Test::testName() { KWindowInfo info(window->winId(), NET::WMName | NET::WMVisibleName | NET::WMIconName | NET::WMVisibleIconName | NET::WMState | NET::XAWMState); QCOMPARE(info.name(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info.visibleName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info.visibleNameWithState(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info.iconName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info.visibleIconName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info.visibleIconNameWithState(), QStringLiteral("kwindowinfox11test")); window->showMinimized(); // TODO: improve by using signalspy? QTest::qWait(100); // should be minimized, now QVERIFY(verifyMinimized(window->winId())); // that should have changed the visible name KWindowInfo info2(window->winId(), NET::WMName | NET::WMVisibleName | NET::WMIconName | NET::WMVisibleIconName | NET::WMState | NET::XAWMState); QCOMPARE(info2.name(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info2.visibleName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info2.visibleNameWithState(), QStringLiteral("(kwindowinfox11test)")); QCOMPARE(info2.iconName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info2.visibleIconName(), QStringLiteral("kwindowinfox11test")); QCOMPARE(info2.visibleIconNameWithState(), QStringLiteral("(kwindowinfox11test)")); NETRootInfo rootInfo(QX11Info::connection(), NET::Supported | NET::SupportingWMCheck); if (qstrcmp(rootInfo.wmName(), "Openbox") == 0) { QSKIP("setting name test fails on openbox"); } // create a low level NETWinInfo to manipulate the name - NETWinInfo winInfo(QX11Info::connection(), window->winId(), QX11Info::appRootWindow(), NET::WMName, 0); + NETWinInfo winInfo(QX11Info::connection(), window->winId(), QX11Info::appRootWindow(), NET::WMName, nullptr); winInfo.setName("foobar"); QX11Info::getTimestamp(); KWindowInfo info3(window->winId(), NET::WMName | NET::WMVisibleName | NET::WMIconName | NET::WMVisibleIconName | NET::WMState | NET::XAWMState); QCOMPARE(info3.name(), QStringLiteral("foobar")); QCOMPARE(info3.visibleName(), QStringLiteral("foobar")); QCOMPARE(info3.visibleNameWithState(), QStringLiteral("(foobar)")); QCOMPARE(info3.iconName(), QStringLiteral("foobar")); QCOMPARE(info3.visibleIconName(), QStringLiteral("foobar")); QCOMPARE(info3.visibleIconNameWithState(), QStringLiteral("(foobar)")); } void KWindowInfoX11Test::testTransientFor() { - KWindowInfo info(window->winId(), 0, NET::WM2TransientFor); + KWindowInfo info(window->winId(), nullptr, NET::WM2TransientFor); QCOMPARE(info.transientFor(), WId(0)); // let's create a second window QScopedPointer window2(new QWidget()); window2->show(); QTest::qWaitForWindowExposed(window2.data()); // update the transient for of window1 to window2 const uint32_t id = window2->winId(); xcb_change_property(QX11Info::connection(), XCB_PROP_MODE_REPLACE, window->winId(), XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32, 1, &id); xcb_flush(QX11Info::connection()); - KWindowInfo info2(window->winId(), 0, NET::WM2TransientFor); + KWindowInfo info2(window->winId(), nullptr, NET::WM2TransientFor); QCOMPARE(info2.transientFor(), window2->winId()); } void KWindowInfoX11Test::testGroupLeader() { - KWindowInfo info(window->winId(), 0, NET::WM2GroupLeader); + KWindowInfo info(window->winId(), nullptr, NET::WM2GroupLeader); QCOMPARE(info.groupLeader(), WId(0)); // TODO: here we should try to set a group leader and re-read it // this needs setting and parsing the WMHints } void KWindowInfoX11Test::testExtendedStrut() { - KWindowInfo info(window->winId(), 0, NET::WM2ExtendedStrut); + KWindowInfo info(window->winId(), nullptr, NET::WM2ExtendedStrut); NETExtendedStrut strut = info.extendedStrut(); QCOMPARE(strut.bottom_end, 0); QCOMPARE(strut.bottom_start, 0); QCOMPARE(strut.bottom_width, 0); QCOMPARE(strut.left_end, 0); QCOMPARE(strut.left_start, 0); QCOMPARE(strut.left_width, 0); QCOMPARE(strut.right_end, 0); QCOMPARE(strut.right_start, 0); QCOMPARE(strut.right_width, 0); QCOMPARE(strut.top_end, 0); QCOMPARE(strut.top_start, 0); QCOMPARE(strut.top_width, 0); KWindowSystem::setExtendedStrut(window->winId(), 10, 20, 30, 40, 5, 15, 25, 35, 2, 12, 22, 32); // it's just an xprop, so one roundtrip is good enough QX11Info::getTimestamp(); - KWindowInfo info2(window->winId(), 0, NET::WM2ExtendedStrut); + KWindowInfo info2(window->winId(), nullptr, NET::WM2ExtendedStrut); strut = info2.extendedStrut(); QCOMPARE(strut.bottom_end, 32); QCOMPARE(strut.bottom_start, 22); QCOMPARE(strut.bottom_width, 12); QCOMPARE(strut.left_end, 30); QCOMPARE(strut.left_start, 20); QCOMPARE(strut.left_width, 10); QCOMPARE(strut.right_end, 15); QCOMPARE(strut.right_start, 5); QCOMPARE(strut.right_width, 40); QCOMPARE(strut.top_end, 2); QCOMPARE(strut.top_start, 35); QCOMPARE(strut.top_width, 25); } void KWindowInfoX11Test::testGeometry() { KWindowInfo info(window->winId(), NET::WMGeometry | NET::WMFrameExtents); QCOMPARE(info.geometry().size(), window->geometry().size()); QCOMPARE(info.frameGeometry().size(), window->frameGeometry().size()); QSignalSpy spy(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spy.isValid()); // this is tricky, KWin is smart and doesn't allow all geometries we pass in // setting to center of screen should work, though QRect geo(window->windowHandle()->screen()->geometry().center() - QPoint(window->width()/2-5, window->height()/2-5), window->size() + QSize(10, 10)); window->setGeometry(geo); waitForWindow(spy, window->winId(), NET::WMGeometry); KWindowInfo info2(window->winId(), NET::WMGeometry | NET::WMFrameExtents); QCOMPARE(info2.geometry(), window->geometry()); QCOMPARE(info2.geometry(), geo); QCOMPARE(info2.frameGeometry(), window->frameGeometry()); } void KWindowInfoX11Test::testDesktopFileName() { KWindowInfo info(window->winId(), NET::Properties(), NET::WM2DesktopFileName); QVERIFY(info.valid()); QCOMPARE(info.desktopFileName(), QByteArray()); QSignalSpy spy(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged)); QVERIFY(spy.isValid()); // create a NETWinInfo to set the desktop file name NETWinInfo netInfo(QX11Info::connection(), window->winId(), QX11Info::appRootWindow(), NET::Properties(), NET::Properties2()); netInfo.setDesktopFileName("org.kde.foo"); xcb_flush(QX11Info::connection()); // it's just a property change so we can easily refresh QX11Info::getTimestamp(); QTRY_COMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).value(), window->winId()); QCOMPARE(spy.first().at(2).value(), NET::Properties2(NET::WM2DesktopFileName)); KWindowInfo info2(window->winId(), NET::Properties(), NET::WM2DesktopFileName); QVERIFY(info2.valid()); QCOMPARE(info2.desktopFileName(), QByteArrayLiteral("org.kde.foo")); } void KWindowInfoX11Test::testPid() { KWindowInfo info(window->winId(), NET::WMPid); QVERIFY(info.valid()); QCOMPARE(info.pid(), getpid()); } QTEST_MAIN(KWindowInfoX11Test) #include "kwindowinfox11test.moc" diff --git a/autotests/kwindowsystem_threadtest.cpp b/autotests/kwindowsystem_threadtest.cpp index 729f218..e3a8f32 100644 --- a/autotests/kwindowsystem_threadtest.cpp +++ b/autotests/kwindowsystem_threadtest.cpp @@ -1,114 +1,114 @@ /* * Copyright 2014 Aaron Seigo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "kwindowinfo.h" #include "kwindowsystem.h" #include "netwm.h" #include "nettesthelper.h" #include #include #include #include #include class KWindowSystemThreadTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void testWindowAdded(); void testAccessFromThread(); private: QWidget *m_widget; }; class KWindowSystemCreator : public QRunnable { public: void run() Q_DECL_OVERRIDE { (void)KWindowSystem::self(); } }; class WindowInfoLister : public QThread { public: void run() Q_DECL_OVERRIDE { // simulate some activity in another thread gathering window information const QList windows = KWindowSystem::stackingOrder(); foreach (auto wid, windows) { KWindowInfo info(wid, NET::WMVisibleName); if (info.valid()) { m_names << info.visibleName(); } } } QStringList m_names; }; void KWindowSystemThreadTest::initTestCase() { - m_widget = 0; + m_widget = nullptr; QRunnable *creator = new KWindowSystemCreator; creator->setAutoDelete(true); QThreadPool::globalInstance()->start(creator); QVERIFY(QThreadPool::globalInstance()->waitForDone(5000)); } void KWindowSystemThreadTest::testWindowAdded() { qRegisterMetaType("WId"); QSignalSpy spy(KWindowSystem::self(), SIGNAL(windowAdded(WId))); m_widget = new QWidget; m_widget->show(); QTest::qWaitForWindowExposed(m_widget); QVERIFY(spy.count() > 0); bool hasWId = false; for (auto it = spy.constBegin(); it != spy.constEnd(); ++it) { if ((*it).isEmpty()) { continue; } QCOMPARE((*it).count(), 1); hasWId = (*it).at(0).toULongLong() == m_widget->winId(); if (hasWId) { break; } } QVERIFY(hasWId); QVERIFY(KWindowSystem::hasWId(m_widget->winId())); } void KWindowSystemThreadTest::testAccessFromThread() { WindowInfoLister listerThread; listerThread.start(); QVERIFY(listerThread.wait(5000)); QVERIFY(!listerThread.m_names.isEmpty()); } QTEST_MAIN(KWindowSystemThreadTest) #include diff --git a/autotests/kwindowsystemx11test.cpp b/autotests/kwindowsystemx11test.cpp index 363c805..0a512ca 100644 --- a/autotests/kwindowsystemx11test.cpp +++ b/autotests/kwindowsystemx11test.cpp @@ -1,396 +1,396 @@ /* * Copyright 2013 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "nettesthelper.h" #include "kwindowsystem.h" #include "netwm.h" #include #include #include #include Q_DECLARE_METATYPE(WId) Q_DECLARE_METATYPE(NET::Properties) Q_DECLARE_METATYPE(NET::Properties2) Q_DECLARE_METATYPE(const unsigned long*) class KWindowSystemX11Test : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); // needs to be first test, would fail if run after others (X11) void testActiveWindowChanged(); void testWindowAdded(); void testWindowRemoved(); void testDesktopChanged(); void testNumberOfDesktopsChanged(); void testDesktopNamesChanged(); void testShowingDesktopChanged(); void testSetShowingDesktop(); void testWorkAreaChanged(); void testWindowTitleChanged(); void testMinimizeWindow(); void testPlatformX11(); }; void KWindowSystemX11Test::initTestCase() { QCoreApplication::setAttribute(Qt::AA_ForceRasterWidgets); } void KWindowSystemX11Test::testActiveWindowChanged() { qRegisterMetaType("WId"); QSignalSpy spy(KWindowSystem::self(), SIGNAL(activeWindowChanged(WId))); QScopedPointer widget(new QWidget); widget->show(); QVERIFY(spy.wait()); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toULongLong(), widget->winId()); QCOMPARE(KWindowSystem::activeWindow(), widget->winId()); } void KWindowSystemX11Test::testWindowAdded() { qRegisterMetaType("WId"); QSignalSpy spy(KWindowSystem::self(), SIGNAL(windowAdded(WId))); QSignalSpy stackingOrderSpy(KWindowSystem::self(), SIGNAL(stackingOrderChanged())); QScopedPointer widget(new QWidget); widget->show(); QTest::qWaitForWindowExposed(widget.data()); QVERIFY(spy.count() > 0); bool hasWId = false; for (auto it = spy.constBegin(); it != spy.constEnd(); ++it) { if ((*it).isEmpty()) { continue; } QCOMPARE((*it).count(), 1); hasWId = (*it).at(0).toULongLong() == widget->winId(); if (hasWId) { break; } } QVERIFY(hasWId); QVERIFY(KWindowSystem::hasWId(widget->winId())); QVERIFY(!stackingOrderSpy.isEmpty()); } void KWindowSystemX11Test::testWindowRemoved() { qRegisterMetaType("WId"); QScopedPointer widget(new QWidget); widget->show(); QTest::qWaitForWindowExposed(widget.data()); QVERIFY(KWindowSystem::hasWId(widget->winId())); QSignalSpy spy(KWindowSystem::self(), SIGNAL(windowRemoved(WId))); widget->hide(); spy.wait(1000); QCOMPARE(spy.first().at(0).toULongLong(), widget->winId()); QVERIFY(!KWindowSystem::hasWId(widget->winId())); } void KWindowSystemX11Test::testDesktopChanged() { // This test requires a running NETWM-compliant window manager if (KWindowSystem::numberOfDesktops() == 1) { QSKIP("At least two virtual desktops are required to test desktop changed"); } const int current = KWindowSystem::currentDesktop(); QSignalSpy spy(KWindowSystem::self(), SIGNAL(currentDesktopChanged(int))); int newDesktop = current + 1; if (newDesktop > KWindowSystem::numberOfDesktops()) { newDesktop = 1; } KWindowSystem::setCurrentDesktop(newDesktop); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::currentDesktop(), newDesktop); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toInt(), newDesktop); spy.clear(); // setting to current desktop should not change anything KWindowSystem::setCurrentDesktop(newDesktop); // set back for clean state KWindowSystem::setCurrentDesktop(current); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::currentDesktop(), current); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toInt(), current); } void KWindowSystemX11Test::testNumberOfDesktopsChanged() { // This test requires a running NETWM-compliant window manager const int oldNumber = KWindowSystem::numberOfDesktops(); QSignalSpy spy(KWindowSystem::self(), SIGNAL(numberOfDesktopsChanged(int))); // KWin has arbitrary max number of 20 desktops, so don't fail the test if we use +1 const int newNumber = oldNumber < 20 ? oldNumber + 1 : oldNumber - 1; - NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops, 0); + NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops, nullptr); info.setNumberOfDesktops(newNumber); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::numberOfDesktops(), newNumber); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toInt(), newNumber); spy.clear(); // setting to same number should not change info.setNumberOfDesktops(newNumber); // set back for clean state info.setNumberOfDesktops(oldNumber); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::numberOfDesktops(), oldNumber); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toInt(), oldNumber); } void KWindowSystemX11Test::testDesktopNamesChanged() { // This test requires a running NETWM-compliant window manager const QString origName = KWindowSystem::desktopName(KWindowSystem::currentDesktop()); QSignalSpy spy(KWindowSystem::self(), SIGNAL(desktopNamesChanged())); const QString testName = QStringLiteral("testFooBar"); KWindowSystem::setDesktopName(KWindowSystem::currentDesktop(), testName); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::desktopName(KWindowSystem::currentDesktop()), testName); QCOMPARE(spy.count(), 1); spy.clear(); QX11Info::setAppTime(QX11Info::getTimestamp()); // setting back to clean state KWindowSystem::setDesktopName(KWindowSystem::currentDesktop(), origName); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::desktopName(KWindowSystem::currentDesktop()), origName); QCOMPARE(spy.count(), 1); } void KWindowSystemX11Test::testShowingDesktopChanged() { QX11Info::setAppTime(QX11Info::getTimestamp()); const bool showingDesktop = KWindowSystem::showingDesktop(); QSignalSpy spy(KWindowSystem::self(), SIGNAL(showingDesktopChanged(bool))); - NETRootInfo info(QX11Info::connection(), 0, NET::WM2ShowingDesktop); + NETRootInfo info(QX11Info::connection(), nullptr, NET::WM2ShowingDesktop); info.setShowingDesktop(!showingDesktop); QVERIFY(spy.wait()); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toBool(), !showingDesktop); QCOMPARE(KWindowSystem::showingDesktop(), !showingDesktop); spy.clear(); QX11Info::setAppTime(QX11Info::getTimestamp()); // setting again should not change info.setShowingDesktop(!showingDesktop); // setting back to clean state info.setShowingDesktop(showingDesktop); QVERIFY(spy.wait(100)); QCOMPARE(spy.count(), 1); QCOMPARE(spy.first().at(0).toBool(), showingDesktop); QCOMPARE(KWindowSystem::showingDesktop(), showingDesktop); } void KWindowSystemX11Test::testSetShowingDesktop() { QSignalSpy spy(KWindowSystem::self(), SIGNAL(showingDesktopChanged(bool))); const bool showingDesktop = KWindowSystem::showingDesktop(); // setting the same state shouldn't change it QX11Info::setAppTime(QX11Info::getTimestamp()); KWindowSystem::setShowingDesktop(showingDesktop); QCOMPARE(spy.wait(), false); // spy.wait() waits for 5s QCOMPARE(KWindowSystem::showingDesktop(), showingDesktop); spy.clear(); // set opposite state QX11Info::setAppTime(QX11Info::getTimestamp()); KWindowSystem::setShowingDesktop(!showingDesktop); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::showingDesktop(), !showingDesktop); spy.clear(); // setting back to clean state QX11Info::setAppTime(QX11Info::getTimestamp()); KWindowSystem::setShowingDesktop(showingDesktop); QVERIFY(spy.wait()); QCOMPARE(KWindowSystem::showingDesktop(), showingDesktop); spy.clear(); } void KWindowSystemX11Test::testWorkAreaChanged() { // if there are multiple screens this test can fail as workarea is not multi screen aware QSignalSpy spy(KWindowSystem::self(), SIGNAL(workAreaChanged())); QSignalSpy strutSpy(KWindowSystem::self(), SIGNAL(strutChanged())); QWidget widget; widget.setGeometry(0, 0, 100, 10); widget.show(); KWindowSystem::setExtendedStrut(widget.winId(), 10, 0, 10, 0, 0, 0, 100, 0, 100, 0, 0, 0); QVERIFY(spy.wait()); QVERIFY(!spy.isEmpty()); QVERIFY(!strutSpy.isEmpty()); } void KWindowSystemX11Test::testWindowTitleChanged() { qRegisterMetaType("WId"); qRegisterMetaType("NET::Properties"); qRegisterMetaType("NET::Properties2"); qRegisterMetaType("const ulong*"); QWidget widget; widget.setWindowTitle(QStringLiteral("foo")); widget.show(); QTest::qWaitForWindowExposed(&widget); // wait till the window is mapped, etc. QTest::qWait(200); QSignalSpy propertiesChangedSpy(KWindowSystem::self(), SIGNAL(windowChanged(WId,NET::Properties,NET::Properties2))); QSignalSpy propertyChangedSpy(KWindowSystem::self(), SIGNAL(windowChanged(WId,unsigned int))); QSignalSpy windowChangedSpy(KWindowSystem::self(), SIGNAL(windowChanged(WId))); QVERIFY(propertiesChangedSpy.isValid()); QVERIFY(propertyChangedSpy.isValid()); QVERIFY(windowChangedSpy.isValid()); widget.setWindowTitle(QStringLiteral("bar")); QX11Info::setAppTime(QX11Info::getTimestamp()); int counter = 0; bool gotWMName = false; while (propertiesChangedSpy.wait() && counter < 10) { for (auto it = propertiesChangedSpy.constBegin(); it != propertiesChangedSpy.constEnd(); ++it) { if ((*it).isEmpty()) { continue; } if ((*it).at(0).toULongLong() == widget.winId()) { NET::Properties props = (*it).at(1).value(); if (props.testFlag(NET::WMName)) { gotWMName = true; } } } if (gotWMName) { break; } propertiesChangedSpy.clear(); counter++; } QVERIFY(gotWMName); gotWMName = false; QCOMPARE(propertyChangedSpy.isEmpty(), false); for (auto it = propertyChangedSpy.constBegin(); it != propertyChangedSpy.constEnd(); ++it) { if ((*it).isEmpty()) { continue; } if ((*it).at(0).toULongLong() == widget.winId()) { unsigned int props = (*it).at(1).value(); if (props & NET::WMName) { gotWMName = true; } } if (gotWMName) { break; } } QVERIFY(gotWMName); QCOMPARE(windowChangedSpy.isEmpty(), false); bool gotWindow = false; for (auto it = windowChangedSpy.constBegin(); it != windowChangedSpy.constEnd(); ++it) { if ((*it).isEmpty()) { continue; } if ((*it).at(0).toULongLong() == widget.winId()) { gotWindow = true; } if (gotWindow) { break; } } QVERIFY(gotWindow); // now let's verify the info in KWindowInfo // we wait a little bit more as openbox is updating the visible name QTest::qWait(500); - KWindowInfo info(widget.winId(), NET::WMName | NET::WMVisibleName | NET::WMVisibleIconName | NET::WMIconName, 0); + KWindowInfo info(widget.winId(), NET::WMName | NET::WMVisibleName | NET::WMVisibleIconName | NET::WMIconName, nullptr); QVERIFY(info.valid()); const QString expectedName = QStringLiteral("bar"); QCOMPARE(info.name(), expectedName); QCOMPARE(info.visibleName(), expectedName); QCOMPARE(info.visibleIconName(), expectedName); QCOMPARE(info.iconName(), expectedName); } void KWindowSystemX11Test::testMinimizeWindow() { NETRootInfo rootInfo(QX11Info::connection(), NET::Supported | NET::SupportingWMCheck); if (qstrcmp(rootInfo.wmName(), "Openbox") != 0 && qstrcmp(rootInfo.wmName(), "KWin") != 0) { QSKIP("Test minimize window might not be supported on the used window manager."); } QWidget widget; widget.show(); QTest::qWaitForWindowExposed(&widget); KWindowInfo info(widget.winId(), NET::WMState | NET::XAWMState); QVERIFY(!info.isMinimized()); KWindowSystem::minimizeWindow(widget.winId()); // create a roundtrip, updating minimized state is done by the window manager and wait a short time QX11Info::setAppTime(QX11Info::getTimestamp()); QTest::qWait(200); KWindowInfo info2(widget.winId(), NET::WMState | NET::XAWMState); QVERIFY(info2.isMinimized()); KWindowSystem::unminimizeWindow(widget.winId()); // create a roundtrip, updating minimized state is done by the window manager and wait a short time QX11Info::setAppTime(QX11Info::getTimestamp()); QTest::qWait(200); KWindowInfo info3(widget.winId(), NET::WMState | NET::XAWMState); QVERIFY(!info3.isMinimized()); } void KWindowSystemX11Test::testPlatformX11() { QCOMPARE(KWindowSystem::platform(), KWindowSystem::Platform::X11); QCOMPARE(KWindowSystem::isPlatformX11(), true); QCOMPARE(KWindowSystem::isPlatformWayland(), false); } QTEST_MAIN(KWindowSystemX11Test) #include "kwindowsystemx11test.moc" diff --git a/autotests/netrootinfotestwm.cpp b/autotests/netrootinfotestwm.cpp index f8d672e..f80c04e 100644 --- a/autotests/netrootinfotestwm.cpp +++ b/autotests/netrootinfotestwm.cpp @@ -1,872 +1,872 @@ /* * Copyright 2013 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "nettesthelper.h" #include #include #include // system #include class Property : public QScopedPointer { public: - Property(xcb_get_property_reply_t *p = 0) : QScopedPointer(p) {} + Property(xcb_get_property_reply_t *p = nullptr) : QScopedPointer(p) {} }; Q_DECLARE_METATYPE(NET::Orientation) Q_DECLARE_METATYPE(NET::DesktopLayoutCorner) static const char *s_wmName = "netrootinfotest"; class NetRootInfoTestWM : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void testCtor(); void testSupported(); void testClientList(); void testClientListStacking(); void testNumberOfDesktops(); void testCurrentDesktop(); void testDesktopNames(); void testDesktopLayout_data(); void testDesktopLayout(); void testDesktopGeometry(); void testDesktopViewports(); void testShowingDesktop_data(); void testShowingDesktop(); void testWorkArea(); void testActiveWindow(); void testVirtualRoots(); void testDontCrashMapViewports(); private: void waitForPropertyChange(NETRootInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2 = NET::Property2(0)); xcb_connection_t *connection() { return m_connection; } xcb_connection_t *m_connection; QVector m_connections; QScopedPointer m_xvfb; xcb_window_t m_supportWindow; xcb_window_t m_rootWindow; }; void NetRootInfoTestWM::cleanupTestCase() { while (!m_connections.isEmpty()) { xcb_disconnect(m_connections.takeFirst()); } } void NetRootInfoTestWM::initTestCase() { qsrand(QDateTime::currentMSecsSinceEpoch()); } void NetRootInfoTestWM::init() { // first reset just to be sure m_connection = Q_NULLPTR; m_supportWindow = XCB_WINDOW_NONE; // start Xvfb m_xvfb.reset(new QProcess); // use pipe to pass fd to Xvfb to get back the display id int pipeFds[2]; QVERIFY(pipe(pipeFds) == 0); m_xvfb->start(QStringLiteral("Xvfb"), QStringList{ QStringLiteral("-displayfd"), QString::number(pipeFds[1]) }); QVERIFY(m_xvfb->waitForStarted()); QCOMPARE(m_xvfb->state(), QProcess::Running); // reads from pipe, closes write side close(pipeFds[1]); QFile readPipe; QVERIFY(readPipe.open(pipeFds[0], QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)); QByteArray displayNumber = readPipe.readLine(); readPipe.close(); displayNumber.prepend(QByteArray(":")); displayNumber.remove(displayNumber.size() -1, 1); // create X connection int screen = 0; m_connection = xcb_connect(displayNumber.constData(), &screen); QVERIFY(m_connection); QVERIFY(!xcb_connection_has_error(m_connection)); m_rootWindow = KXUtils::rootWindow(m_connection, screen); uint32_t values[] = {XCB_EVENT_MASK_PROPERTY_CHANGE}; xcb_change_window_attributes(m_connection, m_rootWindow, XCB_CW_EVENT_MASK, values); // create support window values[0] = true; m_supportWindow = xcb_generate_id(m_connection); xcb_create_window(m_connection, XCB_COPY_FROM_PARENT, m_supportWindow, m_rootWindow, 0, 0, 1, 1, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, XCB_CW_OVERRIDE_REDIRECT, values); const uint32_t lowerValues[] = { XCB_STACK_MODE_BELOW }; // we need to do the lower window with a roundtrip, otherwise NETRootInfo is not functioning QScopedPointer error(xcb_request_check(m_connection, xcb_configure_window_checked(m_connection, m_supportWindow, XCB_CONFIG_WINDOW_STACK_MODE, lowerValues))); QVERIFY(error.isNull()); } void NetRootInfoTestWM::cleanup() { // destroy support window xcb_destroy_window(connection(), m_supportWindow); m_supportWindow = XCB_WINDOW_NONE; // close connection // delay till clenupTestCase as otherwise xcb reuses the same memory address m_connections << connection(); // kill Xvfb m_xvfb->terminate(); m_xvfb->waitForFinished(); m_xvfb.reset(); } void NetRootInfoTestWM::waitForPropertyChange(NETRootInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2) { while (true) { KXUtils::ScopedCPointer event(xcb_wait_for_event(connection())); if (event.isNull()) { break; } if ((event->response_type & ~0x80) != XCB_PROPERTY_NOTIFY) { continue; } xcb_property_notify_event_t *pe = reinterpret_cast(event.data()); if (pe->window != m_rootWindow) { continue; } if (pe->atom != atom) { continue; } NET::Properties dirty; NET::Properties2 dirty2; info->event(event.data(), &dirty, &dirty2); if (prop != 0) { QVERIFY(dirty & prop); } if (prop2 != 0) { QVERIFY(dirty2 & prop2); } if (!prop) { QCOMPARE(dirty, NET::Properties()); } if (!prop2) { QCOMPARE(dirty2, NET::Properties2()); } break; } } void NetRootInfoTestWM::testCtor() { QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.xcbConnection(), connection()); QCOMPARE(rootInfo.rootWindow(), m_rootWindow); QCOMPARE(rootInfo.supportWindow(), m_supportWindow); QCOMPARE(rootInfo.wmName(), s_wmName); QCOMPARE(rootInfo.supportedProperties(), NET::WMAllProperties); QCOMPARE(rootInfo.supportedProperties2(), NET::WM2AllProperties); QCOMPARE(rootInfo.supportedActions(), NET::Actions(~0u)); QCOMPARE(rootInfo.supportedStates(), NET::States(~0u)); QCOMPARE(rootInfo.supportedWindowTypes(), NET::AllTypesMask); QCOMPARE(rootInfo.passedProperties(), NET::WMAllProperties); QCOMPARE(rootInfo.passedProperties2(), NET::WM2AllProperties); QCOMPARE(rootInfo.passedActions(), NET::Actions(~0u)); QCOMPARE(rootInfo.passedStates(), NET::States(~0u)); QCOMPARE(rootInfo.passedWindowTypes(), NET::AllTypesMask); } void NetRootInfoTestWM::testSupported() { KXUtils::Atom supported(connection(), QByteArrayLiteral("_NET_SUPPORTED")); KXUtils::Atom wmCheck(connection(), QByteArrayLiteral("_NET_SUPPORTING_WM_CHECK")); KXUtils::Atom wmName(connection(), QByteArrayLiteral("_NET_WM_NAME")); KXUtils::Atom utf8String(connection(), QByteArrayLiteral("UTF8_STRING")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); int count = 0; for (int i = 0; i < 32; ++i) { if (i == 12) { continue; } QVERIFY(rootInfo.isSupported(NET::Property(1 << i))); count++; } for (int i = 0; i < 22; ++i) { QVERIFY(rootInfo.isSupported(NET::Property2(1 << i))); count++; } for (int i = 0; i < 17; ++i) { QVERIFY(rootInfo.isSupported(NET::WindowTypeMask(1 << i))); count++; } for (int i = 0; i < 12; ++i) { QVERIFY(rootInfo.isSupported(NET::State(1 << i))); count++; } for (int i = 0; i < 10; ++i) { QVERIFY(rootInfo.isSupported(NET::Action(1 << i))); count++; } // NET::WMFrameExtents has two properties count += 1; // XAWState, WMGeometry, WM2TransientFor, WM2GroupLeader, WM2WindowClass, WM2WindowRole, WM2ClientMachine count -= 7; // WM2BlockCompositing has two properties count +=1; QVERIFY(supported != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); QVERIFY(wmCheck != XCB_ATOM_NONE); QVERIFY(wmName != XCB_ATOM_NONE); // we should have got some events waitForPropertyChange(&rootInfo, supported, NET::Supported); waitForPropertyChange(&rootInfo, wmCheck, NET::SupportingWMCheck); // get the cookies of the things to check xcb_get_property_cookie_t supportedCookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), supported, XCB_ATOM_ATOM, 0, 101); xcb_get_property_cookie_t wmCheckRootCookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), wmCheck, XCB_ATOM_WINDOW, 0, 1); xcb_get_property_cookie_t wmCheckSupportWinCookie = xcb_get_property_unchecked(connection(), false, m_supportWindow, wmCheck, XCB_ATOM_WINDOW, 0, 1); xcb_get_property_cookie_t wmNameCookie = xcb_get_property_unchecked(connection(), false, m_supportWindow, wmName, utf8String, 0, 16); Property supportedReply(xcb_get_property_reply(connection(), supportedCookie, Q_NULLPTR)); QVERIFY(!supportedReply.isNull()); QCOMPARE(supportedReply->format, uint8_t(32)); QCOMPARE(supportedReply->value_len, uint32_t(count)); // TODO: check that the correct atoms are set? Property wmCheckRootReply(xcb_get_property_reply(connection(), wmCheckRootCookie, Q_NULLPTR)); QVERIFY(!wmCheckRootReply.isNull()); QCOMPARE(wmCheckRootReply->format, uint8_t(32)); QCOMPARE(wmCheckRootReply->value_len, uint32_t(1)); QCOMPARE(reinterpret_cast(xcb_get_property_value(wmCheckRootReply.data()))[0], m_supportWindow); Property wmCheckSupportReply(xcb_get_property_reply(connection(), wmCheckSupportWinCookie, Q_NULLPTR)); QVERIFY(!wmCheckSupportReply.isNull()); QCOMPARE(wmCheckSupportReply->format, uint8_t(32)); QCOMPARE(wmCheckSupportReply->value_len, uint32_t(1)); QCOMPARE(reinterpret_cast(xcb_get_property_value(wmCheckSupportReply.data()))[0], m_supportWindow); Property wmNameReply(xcb_get_property_reply(connection(), wmNameCookie, Q_NULLPTR)); QVERIFY(!wmNameReply.isNull()); QCOMPARE(wmNameReply->format, uint8_t(8)); QCOMPARE(wmNameReply->value_len, uint32_t(15)); QCOMPARE(reinterpret_cast(xcb_get_property_value(wmNameReply.data())), s_wmName); // disable some supported rootInfo.setSupported(NET::WMFrameExtents, false); rootInfo.setSupported(NET::WM2KDETemporaryRules, false); rootInfo.setSupported(NET::ActionChangeDesktop, false); rootInfo.setSupported(NET::FullScreen, false); QVERIFY(rootInfo.isSupported(NET::ToolbarMask)); QVERIFY(rootInfo.isSupported(NET::OnScreenDisplayMask)); QVERIFY(rootInfo.isSupported(NET::DockMask)); rootInfo.setSupported(NET::ToolbarMask, false); rootInfo.setSupported(NET::OnScreenDisplayMask, false); QVERIFY(!rootInfo.isSupported(NET::WMFrameExtents)); QVERIFY(!rootInfo.isSupported(NET::WM2KDETemporaryRules)); QVERIFY(!rootInfo.isSupported(NET::ActionChangeDesktop)); QVERIFY(!rootInfo.isSupported(NET::FullScreen)); QVERIFY(!rootInfo.isSupported(NET::ToolbarMask)); QVERIFY(!rootInfo.isSupported(NET::OnScreenDisplayMask)); QVERIFY(rootInfo.isSupported(NET::DockMask)); // lets get supported again supportedCookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), supported, XCB_ATOM_ATOM, 0, 90); supportedReply.reset(xcb_get_property_reply(connection(), supportedCookie, Q_NULLPTR)); QVERIFY(!supportedReply.isNull()); QCOMPARE(supportedReply->format, uint8_t(32)); QCOMPARE(supportedReply->value_len, uint32_t(count - 7)); for (int i = 0; i < 5; ++i) { // we should have got some events waitForPropertyChange(&rootInfo, supported, NET::Supported); waitForPropertyChange(&rootInfo, wmCheck, NET::SupportingWMCheck); } // turn something off, just to get another event rootInfo.setSupported(NET::WM2BlockCompositing, false); // lets get supported again supportedCookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), supported, XCB_ATOM_ATOM, 0, 90); supportedReply.reset(xcb_get_property_reply(connection(), supportedCookie, Q_NULLPTR)); QVERIFY(!supportedReply.isNull()); QCOMPARE(supportedReply->format, uint8_t(32)); QCOMPARE(supportedReply->value_len, uint32_t(count - 9)); NETRootInfo clientInfo(connection(), NET::Supported | NET::SupportingWMCheck); waitForPropertyChange(&clientInfo, supported, NET::Supported); waitForPropertyChange(&clientInfo, wmCheck, NET::SupportingWMCheck); } void NetRootInfoTestWM::testClientList() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_CLIENT_LIST")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.clientListCount(), 0); QVERIFY(!rootInfo.clientList()); xcb_window_t windows[] = {xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()) }; rootInfo.setClientList(windows, 5); QCOMPARE(rootInfo.clientListCount(), 5); const xcb_window_t *otherWins = rootInfo.clientList(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins[i], windows[i]); } // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_WINDOW, 0, 5); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(5)); const xcb_window_t *propWins = reinterpret_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < 5; ++i) { QCOMPARE(propWins[i], windows[i]); } // wait for our property NETRootInfo clientInfo(connection(), NET::Supported | NET::SupportingWMCheck | NET::ClientList); waitForPropertyChange(&clientInfo, atom, NET::ClientList); QCOMPARE(clientInfo.clientListCount(), 5); const xcb_window_t *otherWins2 = clientInfo.clientList(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins2[i], windows[i]); } } void NetRootInfoTestWM::testClientListStacking() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_CLIENT_LIST_STACKING")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.clientListStackingCount(), 0); QVERIFY(!rootInfo.clientListStacking()); xcb_window_t windows[] = {xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()) }; rootInfo.setClientListStacking(windows, 5); QCOMPARE(rootInfo.clientListStackingCount(), 5); const xcb_window_t *otherWins = rootInfo.clientListStacking(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins[i], windows[i]); } // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_WINDOW, 0, 5); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(5)); const xcb_window_t *propWins = reinterpret_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < 5; ++i) { QCOMPARE(propWins[i], windows[i]); } // wait for our property waitForPropertyChange(&rootInfo, atom, NET::ClientListStacking); QCOMPARE(rootInfo.clientListStackingCount(), 5); const xcb_window_t *otherWins2 = rootInfo.clientListStacking(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins2[i], windows[i]); } } void NetRootInfoTestWM::testVirtualRoots() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_VIRTUAL_ROOTS")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.virtualRootsCount(), 0); QVERIFY(!rootInfo.virtualRoots()); xcb_window_t windows[] = {xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()), xcb_generate_id(connection()) }; rootInfo.setVirtualRoots(windows, 5); QCOMPARE(rootInfo.virtualRootsCount(), 5); const xcb_window_t *otherWins = rootInfo.virtualRoots(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins[i], windows[i]); } // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_WINDOW, 0, 5); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(5)); const xcb_window_t *propWins = reinterpret_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < 5; ++i) { QCOMPARE(propWins[i], windows[i]); } // wait for our property - reported to a Client NETRootInfo NETRootInfo clientInfo(connection(), NET::VirtualRoots); waitForPropertyChange(&clientInfo, atom, NET::VirtualRoots); QCOMPARE(rootInfo.virtualRootsCount(), 5); const xcb_window_t *otherWins2 = rootInfo.virtualRoots(); for (int i = 0; i < 5; ++i) { QCOMPARE(otherWins2[i], windows[i]); } } void NetRootInfoTestWM::testNumberOfDesktops() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_NUMBER_OF_DESKTOPS")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.numberOfDesktops(), 1); rootInfo.setNumberOfDesktops(4); QCOMPARE(rootInfo.numberOfDesktops(), 4); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 1); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(1)); QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], uint32_t(4)); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::NumberOfDesktops); QCOMPARE(rootInfo.numberOfDesktops(), 4); } void NetRootInfoTestWM::testCurrentDesktop() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_CURRENT_DESKTOP")); // TODO: verify that current desktop cannot be higher than number of desktops QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.currentDesktop(), 1); rootInfo.setCurrentDesktop(5); QCOMPARE(rootInfo.currentDesktop(), 5); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 1); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(1)); // note: API starts counting at 1, but property starts counting at 5, because of that subtracting one QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], uint32_t(5 - 1)); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::CurrentDesktop); QCOMPARE(rootInfo.currentDesktop(), 5); } void NetRootInfoTestWM::testDesktopNames() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_DESKTOP_NAMES")); KXUtils::Atom utf8String(connection(), QByteArrayLiteral("UTF8_STRING")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QVERIFY(!rootInfo.desktopName(0)); QVERIFY(!rootInfo.desktopName(1)); QVERIFY(!rootInfo.desktopName(2)); rootInfo.setDesktopName(1, "foo"); rootInfo.setDesktopName(2, "bar"); rootInfo.setNumberOfDesktops(2); QCOMPARE(rootInfo.desktopName(1), "foo"); QCOMPARE(rootInfo.desktopName(2), "bar"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, utf8String, 0, 10000); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(8)); QCOMPARE(reply->value_len, uint32_t(8)); QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo\0bar"); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::DesktopNames); QCOMPARE(rootInfo.desktopName(1), "foo"); QCOMPARE(rootInfo.desktopName(2), "bar"); // there should be two events waitForPropertyChange(&rootInfo, atom, NET::DesktopNames); QCOMPARE(rootInfo.desktopName(1), "foo"); QCOMPARE(rootInfo.desktopName(2), "bar"); } void NetRootInfoTestWM::testActiveWindow() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_ACTIVE_WINDOW")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QVERIFY(rootInfo.activeWindow() == XCB_WINDOW_NONE); // rootinfo doesn't verify whether our window is a window, so we just generate an ID xcb_window_t activeWindow = xcb_generate_id(connection()); rootInfo.setActiveWindow(activeWindow); QCOMPARE(rootInfo.activeWindow(), activeWindow); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_WINDOW, 0, 1); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(1)); QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], activeWindow); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::ActiveWindow); QCOMPARE(rootInfo.activeWindow(), activeWindow); } void NetRootInfoTestWM::testDesktopGeometry() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_DESKTOP_GEOMETRY")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QCOMPARE(rootInfo.desktopGeometry().width, 0); QCOMPARE(rootInfo.desktopGeometry().height, 0); NETSize size; size.width = 1000; size.height = 800; rootInfo.setDesktopGeometry(size); QCOMPARE(rootInfo.desktopGeometry().width, size.width); QCOMPARE(rootInfo.desktopGeometry().height, size.height); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 2); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(2)); uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(size.width)); QCOMPARE(data[1], uint32_t(size.height)); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::DesktopGeometry); QCOMPARE(rootInfo.desktopGeometry().width, size.width); QCOMPARE(rootInfo.desktopGeometry().height, size.height); } void NetRootInfoTestWM::testDesktopLayout_data() { QTest::addColumn("orientation"); QTest::addColumn("columnsRows"); QTest::addColumn("corner"); QTest::newRow("h/1/1/tl") << NET::OrientationHorizontal << QSize(1, 1) << NET::DesktopLayoutCornerTopLeft; QTest::newRow("h/1/0/tr") << NET::OrientationHorizontal << QSize(1, 0) << NET::DesktopLayoutCornerTopRight; QTest::newRow("h/0/1/bl") << NET::OrientationHorizontal << QSize(0, 1) << NET::DesktopLayoutCornerBottomLeft; QTest::newRow("h/1/2/br") << NET::OrientationHorizontal << QSize(1, 2) << NET::DesktopLayoutCornerBottomRight; QTest::newRow("v/3/2/tl") << NET::OrientationVertical << QSize(3, 2) << NET::DesktopLayoutCornerTopLeft; QTest::newRow("v/5/4/tr") << NET::OrientationVertical << QSize(5, 4) << NET::DesktopLayoutCornerTopRight; QTest::newRow("v/2/1/bl") << NET::OrientationVertical << QSize(2, 1) << NET::DesktopLayoutCornerBottomLeft; QTest::newRow("v/3/2/br") << NET::OrientationVertical << QSize(3, 2) << NET::DesktopLayoutCornerBottomRight; } void NetRootInfoTestWM::testDesktopLayout() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_DESKTOP_LAYOUT")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QFETCH(NET::Orientation, orientation); QFETCH(QSize, columnsRows); QFETCH(NET::DesktopLayoutCorner, corner); rootInfo.setDesktopLayout(orientation, columnsRows.width(), columnsRows.height(), corner); QCOMPARE(rootInfo.desktopLayoutOrientation(), orientation); QCOMPARE(rootInfo.desktopLayoutColumnsRows(), columnsRows); QCOMPARE(rootInfo.desktopLayoutCorner(), corner); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 4); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(4)); uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(orientation)); QCOMPARE(data[1], uint32_t(columnsRows.width())); QCOMPARE(data[2], uint32_t(columnsRows.height())); QCOMPARE(data[3], uint32_t(corner)); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::Property(0), NET::WM2DesktopLayout); QCOMPARE(rootInfo.desktopLayoutOrientation(), orientation); QCOMPARE(rootInfo.desktopLayoutColumnsRows(), columnsRows); QCOMPARE(rootInfo.desktopLayoutCorner(), corner); NETRootInfo info2(connection(), NET::WMAllProperties, NET::WM2AllProperties); QCOMPARE(info2.desktopLayoutColumnsRows(), columnsRows); } void NetRootInfoTestWM::testDesktopViewports() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_DESKTOP_VIEWPORT")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); // we need to know the number of desktops, therefore setting it rootInfo.setNumberOfDesktops(4); NETPoint desktopOne; desktopOne.x = 100; desktopOne.y = 50; NETPoint desktopTwo; desktopTwo.x = 200; desktopTwo.y = 100; rootInfo.setDesktopViewport(1, desktopOne); rootInfo.setDesktopViewport(2, desktopTwo); const NETPoint compareZero = rootInfo.desktopViewport(0); QCOMPARE(compareZero.x, 0); QCOMPARE(compareZero.y, 0); const NETPoint compareOne = rootInfo.desktopViewport(1); QCOMPARE(compareOne.x, desktopOne.x); QCOMPARE(compareOne.y, desktopOne.y); const NETPoint compareTwo = rootInfo.desktopViewport(2); QCOMPARE(compareTwo.x, desktopTwo.x); QCOMPARE(compareTwo.y, desktopTwo.y); const NETPoint compareThree = rootInfo.desktopViewport(3); QCOMPARE(compareThree.x, 0); QCOMPARE(compareThree.y, 0); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 8); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(8)); uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(desktopOne.x)); QCOMPARE(data[1], uint32_t(desktopOne.y)); QCOMPARE(data[2], uint32_t(desktopTwo.x)); QCOMPARE(data[3], uint32_t(desktopTwo.y)); QCOMPARE(data[4], uint32_t(0)); QCOMPARE(data[5], uint32_t(0)); QCOMPARE(data[6], uint32_t(0)); QCOMPARE(data[7], uint32_t(0)); // wait for our property - two events waitForPropertyChange(&rootInfo, atom, NET::DesktopViewport); waitForPropertyChange(&rootInfo, atom, NET::DesktopViewport); const NETPoint compareOne2 = rootInfo.desktopViewport(1); QCOMPARE(compareOne2.x, desktopOne.x); QCOMPARE(compareOne2.y, desktopOne.y); const NETPoint compareTwo2 = rootInfo.desktopViewport(2); QCOMPARE(compareTwo2.x, desktopTwo.x); QCOMPARE(compareTwo2.y, desktopTwo.y); const NETPoint compareThree2 = rootInfo.desktopViewport(3); QCOMPARE(compareThree2.x, 0); QCOMPARE(compareThree2.y, 0); } void NetRootInfoTestWM::testShowingDesktop_data() { QTest::addColumn("set"); QTest::addColumn("setValue"); QTest::newRow("true") << true << uint32_t(1); QTest::newRow("false") << false << uint32_t(0); } void NetRootInfoTestWM::testShowingDesktop() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_SHOWING_DESKTOP")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); QFETCH(bool, set); rootInfo.setShowingDesktop(set); QCOMPARE(rootInfo.showingDesktop(), set); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 1); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(1)); QTEST(reinterpret_cast(xcb_get_property_value(reply.data()))[0], "setValue"); // wait for our property waitForPropertyChange(&rootInfo, atom, NET::Property(0), NET::WM2ShowingDesktop); QCOMPARE(rootInfo.showingDesktop(), set); } void NetRootInfoTestWM::testWorkArea() { KXUtils::Atom atom(connection(), QByteArrayLiteral("_NET_WORKAREA")); QVERIFY(connection()); NETRootInfo rootInfo(connection(), m_supportWindow, s_wmName, NET::WMAllProperties, NET::AllTypesMask, NET::States(~0u), NET::WM2AllProperties, NET::Actions(~0u)); // we need to know the number of desktops, therefore setting it rootInfo.setNumberOfDesktops(4); NETRect desktopOne; desktopOne.pos.x = 10; desktopOne.pos.y = 5; desktopOne.size.width = 1000; desktopOne.size.height = 800; NETRect desktopTwo; desktopTwo.pos.x = 20; desktopTwo.pos.y = 10; desktopTwo.size.width = 800; desktopTwo.size.height = 750; rootInfo.setWorkArea(1, desktopOne); rootInfo.setWorkArea(2, desktopTwo); const NETRect compareZero = rootInfo.workArea(0); QCOMPARE(compareZero.pos.x, 0); QCOMPARE(compareZero.pos.y, 0); QCOMPARE(compareZero.size.width, 0); QCOMPARE(compareZero.size.height, 0); const NETRect compareOne = rootInfo.workArea(1); QCOMPARE(compareOne.pos.x, desktopOne.pos.x); QCOMPARE(compareOne.pos.y, desktopOne.pos.y); QCOMPARE(compareOne.size.width, desktopOne.size.width); QCOMPARE(compareOne.size.height, desktopOne.size.height); const NETRect compareTwo = rootInfo.workArea(2); QCOMPARE(compareTwo.pos.x, desktopTwo.pos.x); QCOMPARE(compareTwo.pos.y, desktopTwo.pos.y); QCOMPARE(compareTwo.size.width, desktopTwo.size.width); QCOMPARE(compareTwo.size.height, desktopTwo.size.height); const NETRect compareThree = rootInfo.workArea(3); QCOMPARE(compareThree.pos.x, 0); QCOMPARE(compareThree.pos.y, 0); QCOMPARE(compareThree.size.width, 0); QCOMPARE(compareThree.size.height, 0); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, rootInfo.rootWindow(), atom, XCB_ATOM_CARDINAL, 0, 16); Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); QVERIFY(!reply.isNull()); QCOMPARE(reply->format, uint8_t(32)); QCOMPARE(reply->value_len, uint32_t(16)); uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[ 0], uint32_t(desktopOne.pos.x)); QCOMPARE(data[ 1], uint32_t(desktopOne.pos.y)); QCOMPARE(data[ 2], uint32_t(desktopOne.size.width)); QCOMPARE(data[ 3], uint32_t(desktopOne.size.height)); QCOMPARE(data[ 4], uint32_t(desktopTwo.pos.x)); QCOMPARE(data[ 5], uint32_t(desktopTwo.pos.y)); QCOMPARE(data[ 6], uint32_t(desktopTwo.size.width)); QCOMPARE(data[ 7], uint32_t(desktopTwo.size.height)); QCOMPARE(data[ 8], uint32_t(0)); QCOMPARE(data[ 9], uint32_t(0)); QCOMPARE(data[10], uint32_t(0)); QCOMPARE(data[11], uint32_t(0)); QCOMPARE(data[12], uint32_t(0)); QCOMPARE(data[13], uint32_t(0)); QCOMPARE(data[14], uint32_t(0)); QCOMPARE(data[15], uint32_t(0)); // wait for our property - two events waitForPropertyChange(&rootInfo, atom, NET::WorkArea); waitForPropertyChange(&rootInfo, atom, NET::WorkArea); const NETRect compareOne2 = rootInfo.workArea(1); QCOMPARE(compareOne2.pos.x, desktopOne.pos.x); QCOMPARE(compareOne2.pos.y, desktopOne.pos.y); QCOMPARE(compareOne2.size.width, desktopOne.size.width); QCOMPARE(compareOne2.size.height, desktopOne.size.height); const NETRect compareTwo2 = rootInfo.workArea(2); QCOMPARE(compareTwo2.pos.x, desktopTwo.pos.x); QCOMPARE(compareTwo2.pos.y, desktopTwo.pos.y); QCOMPARE(compareTwo2.size.width, desktopTwo.size.width); QCOMPARE(compareTwo2.size.height, desktopTwo.size.height); const NETRect compareThree2 = rootInfo.workArea(3); QCOMPARE(compareThree2.pos.x, 0); QCOMPARE(compareThree2.pos.y, 0); QCOMPARE(compareThree2.size.width, 0); QCOMPARE(compareThree2.size.height, 0); } void NetRootInfoTestWM::testDontCrashMapViewports() { QProcess p; p.start(QStringLiteral("%1/dontcrashmapviewport").arg(AUTOTEST_BUILD_DIR)); QVERIFY(p.waitForFinished()); QCOMPARE(p.exitStatus(), QProcess::NormalExit); QCOMPARE(p.exitCode(), 0); } QTEST_GUILESS_MAIN(NetRootInfoTestWM) #include "netrootinfotestwm.moc" diff --git a/autotests/netwininfotestclient.cpp b/autotests/netwininfotestclient.cpp index e3451db..9002983 100644 --- a/autotests/netwininfotestclient.cpp +++ b/autotests/netwininfotestclient.cpp @@ -1,1166 +1,1166 @@ /* * Copyright 2013 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "nettesthelper.h" #include #include #include // system #include class Property : public QScopedPointer { public: - Property(xcb_get_property_reply_t *p = 0) : QScopedPointer(p) {} + Property(xcb_get_property_reply_t *p = nullptr) : QScopedPointer(p) {} }; #define INFO NETWinInfo info(m_connection, m_testWindow, m_rootWindow, NET::WMAllProperties, NET::WM2AllProperties, NET::Client); #define ATOM(name) \ KXUtils::Atom atom(connection(), QByteArrayLiteral(#name)); #define UTF8 KXUtils::Atom utf8String(connection(), QByteArrayLiteral("UTF8_STRING")); #define GETPROP(type, length, formatSize) \ xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, m_testWindow, \ atom, type, 0, length); \ Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); \ QVERIFY(!reply.isNull()); \ QCOMPARE(reply->format, uint8_t(formatSize)); \ QCOMPARE(reply->value_len, uint32_t(length)); #define VERIFYDELETED(t) \ xcb_get_property_cookie_t cookieDeleted = xcb_get_property_unchecked(connection(), false, m_testWindow, \ atom, t, 0, 1); \ Property replyDeleted(xcb_get_property_reply(connection(), cookieDeleted, Q_NULLPTR)); \ QVERIFY(!replyDeleted.isNull()); \ QVERIFY(replyDeleted->type == XCB_ATOM_NONE); class NetWinInfoTestClient : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void testBlockCompositing(); void testUserTime(); void testStartupId(); void testDesktopFileName(); void testHandledIcons_data(); void testHandledIcons(); void testPid(); void testName(); void testIconName(); void testStrut(); void testExtendedStrut(); void testIconGeometry(); void testFullscreenMonitors(); void testWindowType_data(); void testWindowType(); void testActivities_data(); void testActivities(); void testWindowRole(); void testWindowClass(); void testClientMachine(); void testGroupLeader(); void testUrgency_data(); void testUrgency(); void testInput_data(); void testInput(); void testInitialMappingState_data(); void testInitialMappingState(); void testIconPixmap_data(); void testIconPixmap(); void testTransientFor(); void testProtocols_data(); void testProtocols(); void testOpaqueRegion_data(); void testOpaqueRegion(); private: void performNameTest(xcb_atom_t atom, const char *(NETWinInfo:: *getter)(void)const, void (NETWinInfo:: *setter)(const char *), NET::Property property); void waitForPropertyChange(NETWinInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2 = NET::Property2(0)); xcb_connection_t *connection() { return m_connection; } xcb_connection_t *m_connection; QVector m_connections; QScopedPointer m_xvfb; xcb_window_t m_rootWindow; xcb_window_t m_testWindow; }; void NetWinInfoTestClient::initTestCase() { qsrand(QDateTime::currentMSecsSinceEpoch()); } void NetWinInfoTestClient::cleanupTestCase() { // close connection while (!m_connections.isEmpty()) { xcb_disconnect(m_connections.takeFirst()); } } void NetWinInfoTestClient::init() { // first reset just to be sure m_connection = Q_NULLPTR; m_rootWindow = XCB_WINDOW_NONE; m_testWindow = XCB_WINDOW_NONE; // start Xvfb m_xvfb.reset(new QProcess); // use pipe to pass fd to Xvfb to get back the display id int pipeFds[2]; QVERIFY(pipe(pipeFds) == 0); m_xvfb->start(QStringLiteral("Xvfb"), QStringList{ QStringLiteral("-displayfd"), QString::number(pipeFds[1]) }); QVERIFY(m_xvfb->waitForStarted()); QCOMPARE(m_xvfb->state(), QProcess::Running); // reads from pipe, closes write side close(pipeFds[1]); QFile readPipe; QVERIFY(readPipe.open(pipeFds[0], QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)); QByteArray displayNumber = readPipe.readLine(); readPipe.close(); displayNumber.prepend(QByteArray(":")); displayNumber.remove(displayNumber.size() -1, 1); // create X connection int screen = 0; m_connection = xcb_connect(displayNumber.constData(), &screen); QVERIFY(m_connection); QVERIFY(!xcb_connection_has_error(m_connection)); m_rootWindow = KXUtils::rootWindow(m_connection, screen); // create test window m_testWindow = xcb_generate_id(m_connection); uint32_t values[] = {XCB_EVENT_MASK_PROPERTY_CHANGE}; xcb_create_window(m_connection, XCB_COPY_FROM_PARENT, m_testWindow, m_rootWindow, 0, 0, 100, 100, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, XCB_CW_EVENT_MASK, values); // and map it xcb_map_window(m_connection, m_testWindow); } void NetWinInfoTestClient::cleanup() { // destroy test window xcb_unmap_window(m_connection, m_testWindow); xcb_destroy_window(m_connection, m_testWindow); m_testWindow = XCB_WINDOW_NONE; // delay till clenupTestCase as otherwise xcb reuses the same memory address m_connections << connection(); // kill Xvfb m_xvfb->terminate(); m_xvfb->waitForFinished(); } void NetWinInfoTestClient::waitForPropertyChange(NETWinInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2) { while (true) { KXUtils::ScopedCPointer event(xcb_wait_for_event(connection())); if (event.isNull()) { break; } if ((event->response_type & ~0x80) != XCB_PROPERTY_NOTIFY) { continue; } xcb_property_notify_event_t *pe = reinterpret_cast(event.data()); if (pe->window != m_testWindow) { continue; } if (pe->atom != atom) { continue; } NET::Properties dirty; NET::Properties2 dirty2; info->event(event.data(), &dirty, &dirty2); if (prop != 0) { QVERIFY(dirty & prop); } if (prop2 != 0) { QVERIFY(dirty2 & prop2); } if (!prop) { QCOMPARE(dirty, NET::Properties()); } if (!prop2) { QCOMPARE(dirty2, NET::Properties2()); } break; } } void NetWinInfoTestClient::testBlockCompositing() { QVERIFY(connection()); ATOM(_KDE_NET_WM_BLOCK_COMPOSITING) INFO QVERIFY(!info.isBlockingCompositing()); info.setBlockingCompositing(true); QVERIFY(info.isBlockingCompositing()); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], uint32_t(1)); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2BlockCompositing); QVERIFY(info.isBlockingCompositing()); // setting false should delete the property again info.setBlockingCompositing(false); QVERIFY(!info.isBlockingCompositing()); VERIFYDELETED(XCB_ATOM_CARDINAL) // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2BlockCompositing); QVERIFY(!info.isBlockingCompositing()); } void NetWinInfoTestClient::testUserTime() { QVERIFY(connection()); ATOM(_NET_WM_USER_TIME) INFO QCOMPARE(info.userTime(), uint32_t(-1)); info.setUserTime(500); QCOMPARE(info.userTime(), uint32_t(500)); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], uint32_t(500)); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2UserTime); QCOMPARE(info.userTime(), uint32_t(500)); } void NetWinInfoTestClient::testStartupId() { QVERIFY(connection()); ATOM(_NET_STARTUP_ID) UTF8 INFO QVERIFY(!info.startupId()); info.setStartupId("foo"); QCOMPARE(info.startupId(), "foo"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); GETPROP(utf8String, 3, 8) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo"); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2StartupId); QCOMPARE(info.startupId(), "foo"); } void NetWinInfoTestClient::testDesktopFileName() { QVERIFY(connection()); ATOM(_KDE_NET_WM_DESKTOP_FILE) UTF8 INFO QVERIFY(!info.desktopFileName()); info.setDesktopFileName("foo"); QCOMPARE(info.desktopFileName(), "foo"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); GETPROP(utf8String, 3, 8) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo"); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2DesktopFileName); QCOMPARE(info.desktopFileName(), "foo"); } void NetWinInfoTestClient::testHandledIcons_data() { QTest::addColumn("handled"); QTest::addColumn("value"); QTest::newRow("enabled") << true << uint32_t(1); QTest::newRow("disabled") << false << uint32_t(0); } void NetWinInfoTestClient::testHandledIcons() { QVERIFY(connection()); ATOM(_NET_WM_HANDLED_ICONS) INFO QVERIFY(!info.handledIcons()); QFETCH(bool, handled); info.setHandledIcons(handled); QCOMPARE(info.handledIcons(), handled); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QTEST(reinterpret_cast(xcb_get_property_value(reply.data()))[0], "value"); // and wait for our event waitForPropertyChange(&info, atom, NET::WMHandledIcons); QCOMPARE(info.handledIcons(), handled); } void NetWinInfoTestClient::testPid() { QVERIFY(connection()); ATOM(_NET_WM_PID) INFO QCOMPARE(info.pid(), 0); info.setPid(m_xvfb->pid()); QCOMPARE(info.pid(), m_xvfb->pid()); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], uint32_t(m_xvfb->pid())); // and wait for our event waitForPropertyChange(&info, atom, NET::WMPid); QCOMPARE(info.pid(), m_xvfb->pid()); } void NetWinInfoTestClient::performNameTest(xcb_atom_t atom, const char *(NETWinInfo:: *getter)(void)const, void (NETWinInfo:: *setter)(const char *), NET::Property property) { UTF8 INFO QVERIFY(!(info.*getter)()); (info.*setter)("foo"); QCOMPARE((info.*getter)(), "foo"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); GETPROP(utf8String, 3, 8) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo"); // and wait for our event waitForPropertyChange(&info, atom, property); QCOMPARE((info.*getter)(), "foo"); // delete the string (info.*setter)(""); QCOMPARE((info.*getter)(), ""); VERIFYDELETED(utf8String) // and wait for our event waitForPropertyChange(&info, atom, property); QVERIFY(!(info.*getter)()); // set it again, to ensure that we don't leak on tear-down (info.*setter)("bar"); QCOMPARE((info.*getter)(), "bar"); xcb_flush(connection()); waitForPropertyChange(&info, atom, property); QCOMPARE((info.*getter)(), "bar"); } void NetWinInfoTestClient::testIconName() { QVERIFY(connection()); ATOM(_NET_WM_ICON_NAME) performNameTest(atom, &NETWinInfo::iconName, &NETWinInfo::setIconName, NET::WMIconName); } void NetWinInfoTestClient::testName() { QVERIFY(connection()); ATOM(_NET_WM_NAME) performNameTest(atom, &NETWinInfo::name, &NETWinInfo::setName, NET::WMName); } void NetWinInfoTestClient::testStrut() { QVERIFY(connection()); ATOM(_NET_WM_STRUT) INFO NETStrut extents = info.strut(); QCOMPARE(extents.bottom, 0); QCOMPARE(extents.left, 0); QCOMPARE(extents.right, 0); QCOMPARE(extents.top, 0); NETStrut newExtents; newExtents.bottom = 10; newExtents.left = 20; newExtents.right = 30; newExtents.top = 40; info.setStrut(newExtents); extents = info.strut(); QCOMPARE(extents.bottom, newExtents.bottom); QCOMPARE(extents.left, newExtents.left); QCOMPARE(extents.right, newExtents.right); QCOMPARE(extents.top, newExtents.top); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 4, 32) uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(newExtents.left)); QCOMPARE(data[1], uint32_t(newExtents.right)); QCOMPARE(data[2], uint32_t(newExtents.top)); QCOMPARE(data[3], uint32_t(newExtents.bottom)); // and wait for our event waitForPropertyChange(&info, atom, NET::WMStrut); extents = info.strut(); QCOMPARE(extents.bottom, newExtents.bottom); QCOMPARE(extents.left, newExtents.left); QCOMPARE(extents.right, newExtents.right); QCOMPARE(extents.top, newExtents.top); } void NetWinInfoTestClient::testExtendedStrut() { QVERIFY(connection()); ATOM(_NET_WM_STRUT_PARTIAL) INFO NETExtendedStrut extents = info.extendedStrut(); QCOMPARE(extents.left_width, 0); QCOMPARE(extents.right_width, 0); QCOMPARE(extents.top_width, 0); QCOMPARE(extents.bottom_width, 0); QCOMPARE(extents.left_start, 0); QCOMPARE(extents.left_end, 0); QCOMPARE(extents.right_start, 0); QCOMPARE(extents.right_end, 0); QCOMPARE(extents.top_start, 0); QCOMPARE(extents.top_end, 0); QCOMPARE(extents.bottom_start, 0); QCOMPARE(extents.bottom_end, 0); NETExtendedStrut newExtents; newExtents.left_width = 10; newExtents.right_width = 20; newExtents.top_width = 30; newExtents.bottom_width = 40; newExtents.left_start = 50; newExtents.left_end = 60; newExtents.right_start = 70; newExtents.right_end = 80; newExtents.top_start = 90; newExtents.top_end = 91; newExtents.bottom_start = 92; newExtents.bottom_end = 93; info.setExtendedStrut(newExtents); extents = info.extendedStrut(); QCOMPARE(extents.left_width, newExtents.left_width); QCOMPARE(extents.right_width, newExtents.right_width); QCOMPARE(extents.top_width, newExtents.top_width); QCOMPARE(extents.bottom_width, newExtents.bottom_width); QCOMPARE(extents.left_start, newExtents.left_start); QCOMPARE(extents.left_end, newExtents.left_end); QCOMPARE(extents.right_start, newExtents.right_start); QCOMPARE(extents.right_end, newExtents.right_end); QCOMPARE(extents.top_start, newExtents.top_start); QCOMPARE(extents.top_end, newExtents.top_end); QCOMPARE(extents.bottom_start, newExtents.bottom_start); QCOMPARE(extents.bottom_end, newExtents.bottom_end); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 12, 32) uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[ 0], uint32_t(newExtents.left_width)); QCOMPARE(data[ 1], uint32_t(newExtents.right_width)); QCOMPARE(data[ 2], uint32_t(newExtents.top_width)); QCOMPARE(data[ 3], uint32_t(newExtents.bottom_width)); QCOMPARE(data[ 4], uint32_t(newExtents.left_start)); QCOMPARE(data[ 5], uint32_t(newExtents.left_end)); QCOMPARE(data[ 6], uint32_t(newExtents.right_start)); QCOMPARE(data[ 7], uint32_t(newExtents.right_end)); QCOMPARE(data[ 8], uint32_t(newExtents.top_start)); QCOMPARE(data[ 9], uint32_t(newExtents.top_end)); QCOMPARE(data[10], uint32_t(newExtents.bottom_start)); QCOMPARE(data[11], uint32_t(newExtents.bottom_end)); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2ExtendedStrut); extents = info.extendedStrut(); QCOMPARE(extents.left_width, newExtents.left_width); QCOMPARE(extents.right_width, newExtents.right_width); QCOMPARE(extents.top_width, newExtents.top_width); QCOMPARE(extents.bottom_width, newExtents.bottom_width); QCOMPARE(extents.left_start, newExtents.left_start); QCOMPARE(extents.left_end, newExtents.left_end); QCOMPARE(extents.right_start, newExtents.right_start); QCOMPARE(extents.right_end, newExtents.right_end); QCOMPARE(extents.top_start, newExtents.top_start); QCOMPARE(extents.top_end, newExtents.top_end); QCOMPARE(extents.bottom_start, newExtents.bottom_start); QCOMPARE(extents.bottom_end, newExtents.bottom_end); } void NetWinInfoTestClient::testIconGeometry() { QVERIFY(connection()); ATOM(_NET_WM_ICON_GEOMETRY) INFO NETRect geo = info.iconGeometry(); QCOMPARE(geo.pos.x, 0); QCOMPARE(geo.pos.y, 0); QCOMPARE(geo.size.width, 0); QCOMPARE(geo.size.height, 0); NETRect newGeo; newGeo.pos.x = 10; newGeo.pos.y = 20; newGeo.size.width = 30; newGeo.size.height = 40; info.setIconGeometry(newGeo); geo = info.iconGeometry(); QCOMPARE(geo.pos.x, newGeo.pos.x); QCOMPARE(geo.pos.y, newGeo.pos.y); QCOMPARE(geo.size.width, newGeo.size.width); QCOMPARE(geo.size.height, newGeo.size.height); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 4, 32) uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(newGeo.pos.x)); QCOMPARE(data[1], uint32_t(newGeo.pos.y)); QCOMPARE(data[2], uint32_t(newGeo.size.width)); QCOMPARE(data[3], uint32_t(newGeo.size.height)); // and wait for our event waitForPropertyChange(&info, atom, NET::WMIconGeometry); geo = info.iconGeometry(); QCOMPARE(geo.pos.x, newGeo.pos.x); QCOMPARE(geo.pos.y, newGeo.pos.y); QCOMPARE(geo.size.width, newGeo.size.width); QCOMPARE(geo.size.height, newGeo.size.height); } void NetWinInfoTestClient::testFullscreenMonitors() { QVERIFY(connection()); ATOM(_NET_WM_FULLSCREEN_MONITORS) INFO NETFullscreenMonitors topology = info.fullscreenMonitors(); QCOMPARE(topology.bottom, 0); QCOMPARE(topology.left, 0); QCOMPARE(topology.right, 0); QCOMPARE(topology.top, -1); NETFullscreenMonitors newTopology; newTopology.bottom = 10; newTopology.left = 20; newTopology.right = 30; newTopology.top = 40; info.setFullscreenMonitors(newTopology); topology = info.fullscreenMonitors(); QCOMPARE(topology.bottom, newTopology.bottom); QCOMPARE(topology.left, newTopology.left); QCOMPARE(topology.right, newTopology.right); QCOMPARE(topology.top, newTopology.top); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 4, 32) uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(newTopology.top)); QCOMPARE(data[1], uint32_t(newTopology.bottom)); QCOMPARE(data[2], uint32_t(newTopology.left)); QCOMPARE(data[3], uint32_t(newTopology.right)); // and wait for our event QEXPECT_FAIL("", "FullscreenMonitors not handled in events", Continue); waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2FullscreenMonitors); topology = info.fullscreenMonitors(); QCOMPARE(topology.bottom, newTopology.bottom); QCOMPARE(topology.left, newTopology.left); QCOMPARE(topology.right, newTopology.right); QCOMPARE(topology.top, newTopology.top); } Q_DECLARE_METATYPE(NET::WindowType) void NetWinInfoTestClient::testWindowType_data() { QTest::addColumn("type"); QTest::addColumn("length"); QTest::addColumn("typeAtom"); QTest::addColumn("secondaryTypeAtom"); QTest::newRow("override") << NET::Override << 2 << QByteArrayLiteral("_KDE_NET_WM_WINDOW_TYPE_OVERRIDE") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NORMAL"); QTest::newRow("TopMenu") << NET::TopMenu << 2 << QByteArrayLiteral("_KDE_NET_WM_WINDOW_TYPE_TOPMENU") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DOCK"); QTest::newRow("Utility") << NET::Utility << 2 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_UTILITY") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DIALOG"); QTest::newRow("Splash") << NET::Splash << 2 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_SPLASH") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DOCK"); // TODO: this should be 2 QTest::newRow("DropdownMenu") << NET::DropdownMenu << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DROPDOWN_MENU") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_MENU"); // TODO: this should be 2 QTest::newRow("PopupMenu") << NET::PopupMenu << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_POPUP_MENU") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_MENU"); // TODO: this should be 2 QTest::newRow("Notification") << NET::Notification << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NOTIFICATION") << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_UTILITY"); QTest::newRow("Dialog") << NET::Dialog << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DIALOG") << QByteArray(); QTest::newRow("Menu") << NET::Menu << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_MENU") << QByteArray(); QTest::newRow("Toolbar") << NET::Toolbar << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_TOOLBAR") << QByteArray(); QTest::newRow("Dock") << NET::Dock << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DOCK") << QByteArray(); QTest::newRow("Desktop") << NET::Desktop << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DESKTOP") << QByteArray(); QTest::newRow("Tooltip") << NET::Tooltip << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_TOOLTIP") << QByteArray(); QTest::newRow("ComboBox") << NET::ComboBox << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_COMBOBOX") << QByteArray(); QTest::newRow("DNDIcon") << NET::DNDIcon << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_DND") << QByteArray(); QTest::newRow("Normal") << NET::Normal << 1 << QByteArrayLiteral("_NET_WM_WINDOW_TYPE_NORMAL") << QByteArray(); QTest::newRow("OnScreenDisplay") << NET::OnScreenDisplay << 1 << QByteArrayLiteral("_KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY") << QByteArray(); } void NetWinInfoTestClient::testWindowType() { QVERIFY(connection()); ATOM(_NET_WM_WINDOW_TYPE) INFO QVERIFY(info.hasWindowType()); QVERIFY(!info.hasNETSupport()); QCOMPARE(info.windowType(NET::AllTypesMask), NET::Unknown); QFETCH(NET::WindowType, type); info.setWindowType(type); // it does not update the internal type! QCOMPARE(info.windowType(NET::AllTypesMask), NET::Unknown); QFETCH(int, length); QFETCH(QByteArray, typeAtom); // compare the X property KXUtils::Atom type1(connection(), typeAtom); QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_ATOM, length, 32) xcb_atom_t *atoms = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(atoms[0], xcb_atom_t(type1)); if (reply->value_len > 1) { QFETCH(QByteArray, secondaryTypeAtom); KXUtils::Atom type2(connection(), secondaryTypeAtom); QVERIFY(type2 != XCB_ATOM_NONE); QCOMPARE(atoms[1], xcb_atom_t(type2)); } waitForPropertyChange(&info, atom, NET::WMWindowType); QCOMPARE(info.windowType(NET::AllTypesMask), type); QVERIFY(info.hasNETSupport()); } void NetWinInfoTestClient::testClientMachine() { QVERIFY(connection()); INFO QVERIFY(!info.clientMachine()); // client machine needs to be changed using xcb xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_CLIENT_MACHINE, XCB_ATOM_STRING, 8, 9, "localhost"); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_CLIENT_MACHINE, NET::Property(0), NET::WM2ClientMachine); QCOMPARE(info.clientMachine(), "localhost"); } void NetWinInfoTestClient::testGroupLeader() { QVERIFY(connection()); INFO QVERIFY(info.groupLeader() == XCB_WINDOW_NONE); // group leader needs to be changed through wm hints uint32_t values[] = { 1 << 6, /* WindowGroupHint*/ 1, /* Input */ 1, /* Normal State */ XCB_NONE, /* icon pixmap */ XCB_NONE, /* icon window */ XCB_NONE, /* icon x */ XCB_NONE, /* icon y */ XCB_NONE, /* icon mask */ m_rootWindow /* group leader */ }; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, values); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_HINTS, NET::Property(0), NET::WM2GroupLeader); QCOMPARE(info.groupLeader(), m_rootWindow); } void NetWinInfoTestClient::testUrgency_data() { QTest::addColumn("flags"); QTest::addColumn("expected"); QTest::newRow("urgency") << quint32(1 << 8) << true; QTest::newRow("none") << quint32(0) << false; QTest::newRow("group_urgency") << quint32((1 << 6) | (1 << 8)) << true; QTest::newRow("input") << quint32(1) << false; } void NetWinInfoTestClient::testUrgency() { QVERIFY(connection()); INFO QVERIFY(!info.urgency()); QFETCH(quint32, flags); // group leader needs to be changed through wm hints uint32_t values[] = { flags, 1, /* Input */ 1, /* Normal State */ XCB_NONE, /* icon pixmap */ XCB_NONE, /* icon window */ XCB_NONE, /* icon x */ XCB_NONE, /* icon y */ XCB_NONE, /* icon mask */ XCB_NONE /* group leader */ }; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, values); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_HINTS, NET::Property(0), NET::WM2Urgency); QTEST(info.urgency(), "expected"); } void NetWinInfoTestClient::testInput_data() { QTest::addColumn("flags"); QTest::addColumn("input"); QTest::addColumn("expected"); QTest::newRow("flag_input") << quint32(1) << quint32(1) << true; QTest::newRow("flag_noinput") << quint32(1) << quint32(0) << false; QTest::newRow("noflag_input") << quint32(0) << quint32(1) << true; QTest::newRow("noflag_noinput") << quint32(0) << quint32(0) << true; QTest::newRow("flag_with_other_input") << quint32(1 | 1 << 8) << quint32(1) << true; QTest::newRow("flag_with_other_noinput") << quint32(1 | 1 << 8) << quint32(0) << false; } void NetWinInfoTestClient::testInput() { QVERIFY(connection()); INFO QVERIFY(info.input()); QFETCH(quint32, flags); QFETCH(quint32, input); // group leader needs to be changed through wm hints uint32_t values[] = { flags, input, /* Input */ 1, /* Normal State */ XCB_NONE, /* icon pixmap */ XCB_NONE, /* icon window */ XCB_NONE, /* icon x */ XCB_NONE, /* icon y */ XCB_NONE, /* icon mask */ XCB_NONE /* group leader */ }; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, values); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_HINTS, NET::Property(0), NET::WM2Urgency); QTEST(info.input(), "expected"); } Q_DECLARE_METATYPE(NET::MappingState) void NetWinInfoTestClient::testInitialMappingState_data() { QTest::addColumn("flags"); QTest::addColumn("state"); QTest::addColumn("expected"); QTest::newRow("flag-iconic") << quint32(2) << quint32(3) << NET::Iconic; QTest::newRow("flag-normal") << quint32(2) << quint32(1) << NET::Visible; QTest::newRow("flag-invalid") << quint32(2) << quint32(8) << NET::Withdrawn; QTest::newRow("noflag-iconic") << quint32(256) << quint32(3) << NET::Withdrawn; QTest::newRow("noflag-normal") << quint32(256) << quint32(1) << NET::Withdrawn; } void NetWinInfoTestClient::testInitialMappingState() { QVERIFY(connection()); INFO QCOMPARE(info.initialMappingState(), NET::Withdrawn); QFETCH(quint32, flags); QFETCH(quint32, state); // group leader needs to be changed through wm hints uint32_t values[] = { flags, 1, /* Input */ state, /* Normal State */ XCB_NONE, /* icon pixmap */ XCB_NONE, /* icon window */ XCB_NONE, /* icon x */ XCB_NONE, /* icon y */ XCB_NONE, /* icon mask */ XCB_NONE /* group leader */ }; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, values); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_HINTS, NET::Property(0), NET::WM2InitialMappingState); QTEST(info.initialMappingState(), "expected"); } void NetWinInfoTestClient::testIconPixmap_data() { QTest::addColumn("flags"); QTest::addColumn("icon"); QTest::addColumn("mask"); QTest::addColumn("expectedPixmap"); QTest::addColumn("expectedMask"); QTest::newRow("invalid-flags") << 1u << 2u << 3u << 0u << 0u; QTest::newRow("pixmap-flags") << 4u << 2u << 3u << 2u << 0u; QTest::newRow("mask-flags") << 32u << 2u << 3u << 0u << 3u; QTest::newRow("pixmap-mask-flags") << 36u << 2u << 3u << 2u << 3u; } void NetWinInfoTestClient::testIconPixmap() { QVERIFY(connection()); INFO QCOMPARE(info.icccmIconPixmap(), 0u); QCOMPARE(info.icccmIconPixmapMask(), 0u); QFETCH(quint32, flags); QFETCH(quint32, icon); QFETCH(quint32, mask); // icon pixmap needs to be changed through wm hints uint32_t values[] = { flags, 1, /* Input */ XCB_NONE, /* Normal State */ icon, /* icon pixmap */ XCB_NONE, /* icon window */ XCB_NONE, /* icon x */ XCB_NONE, /* icon y */ mask, /* icon mask */ XCB_NONE /* group leader */ }; xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 32, 9, values); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_HINTS, NET::Property(0), NET::WM2IconPixmap); QTEST(info.icccmIconPixmap(), "expectedPixmap"); QTEST(info.icccmIconPixmapMask(), "expectedMask"); } void NetWinInfoTestClient::testTransientFor() { QVERIFY(connection()); INFO QVERIFY(info.transientFor() == XCB_WINDOW_NONE); // transient for needs to be changed using xcb xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 32, 1, &m_rootWindow); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_TRANSIENT_FOR, NET::Property(0), NET::WM2TransientFor); QCOMPARE(info.transientFor(), m_rootWindow); } void NetWinInfoTestClient::testWindowClass() { QVERIFY(connection()); INFO QVERIFY(!info.windowClassClass()); QVERIFY(!info.windowClassName()); // window class needs to be changed using xcb xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 8, 7, "foo\0bar"); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, XCB_ATOM_WM_CLASS, NET::Property(0), NET::WM2WindowClass); QCOMPARE(info.windowClassName(), "foo"); QCOMPARE(info.windowClassClass(), "bar"); } void NetWinInfoTestClient::testWindowRole() { QVERIFY(connection()); ATOM(WM_WINDOW_ROLE) INFO QVERIFY(!info.windowRole()); // window role needs to be changed using xcb xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, atom, XCB_ATOM_STRING, 8, 3, "bar"); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2WindowRole); QCOMPARE(info.windowRole(), "bar"); } void NetWinInfoTestClient::testActivities_data() { QTest::addColumn("activities"); QTest::addColumn("expectedActivities"); const QByteArray testActivities = QByteArrayLiteral("foo,bar"); const QByteArray allActivities = QByteArrayLiteral(KDE_ALL_ACTIVITIES_UUID); QTest::newRow("activites") << testActivities << testActivities; QTest::newRow("empty") << QByteArray() << allActivities; QTest::newRow("\\0") << QByteArrayLiteral("\0") << allActivities; } void NetWinInfoTestClient::testActivities() { QVERIFY(connection()); ATOM(_KDE_NET_WM_ACTIVITIES) INFO QVERIFY(!info.activities()); QFETCH(QByteArray, activities); // activities needs to be changed using xcb info.setActivities(activities.isNull() ? Q_NULLPTR : activities.constData()); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2Activities); QTEST(QByteArray(info.activities()), "expectedActivities"); } Q_DECLARE_METATYPE(NET::Protocols) void NetWinInfoTestClient::testProtocols_data() { QTest::addColumn("protocols"); QTest::addColumn("takeFocus"); QTest::addColumn("deleteWindow"); QTest::addColumn("ping"); QTest::addColumn("sync"); QTest::addColumn("context"); const NET::Protocol t = NET::TakeFocusProtocol; const NET::Protocol d = NET::DeleteWindowProtocol; const NET::Protocol p = NET::PingProtocol; const NET::Protocol s = NET::SyncRequestProtocol; const NET::Protocol c = NET::ContextHelpProtocol; QTest::newRow("none") << NET::Protocols(NET::NoProtocol) << false << false << false << false << false; QTest::newRow("t") << NET::Protocols(t) << true << false << false << false << false; QTest::newRow("d") << NET::Protocols(d) << false << true << false << false << false; QTest::newRow("p") << NET::Protocols(p) << false << false << true << false << false; QTest::newRow("s") << NET::Protocols(s) << false << false << false << true << false; QTest::newRow("c") << NET::Protocols(c) << false << false << false << false << true; // all two combinations with t QTest::newRow("t/d") << NET::Protocols(t | d) << true << true << false << false << false; QTest::newRow("t/p") << NET::Protocols(t | p) << true << false << true << false << false; QTest::newRow("t/s") << NET::Protocols(t | s) << true << false << false << true << false; QTest::newRow("t/c") << NET::Protocols(t | c) << true << false << false << false << true; // all two combinations with d QTest::newRow("d/p") << NET::Protocols(d | p) << false << true << true << false << false; QTest::newRow("d/s") << NET::Protocols(d | s) << false << true << false << true << false; QTest::newRow("d/c") << NET::Protocols(d | c) << false << true << false << false << true; // all two combinations with p QTest::newRow("p/s") << NET::Protocols(p | s) << false << false << true << true << false; QTest::newRow("p/c") << NET::Protocols(p | c) << false << false << true << false << true; // and remaining two combination QTest::newRow("s/c") << NET::Protocols(s | c) << false << false << false << true << true; // all three combinations with t QTest::newRow("t/d/p") << NET::Protocols(t | d | p) << true << true << true << false << false; QTest::newRow("t/d/s") << NET::Protocols(t | d | s) << true << true << false << true << false; QTest::newRow("t/d/c") << NET::Protocols(t | d | c) << true << true << false << false << true; QTest::newRow("t/p/s") << NET::Protocols(t | p | s) << true << false << true << true << false; QTest::newRow("t/p/c") << NET::Protocols(t | p | c) << true << false << true << false << true; QTest::newRow("t/s/c") << NET::Protocols(t | s | c) << true << false << false << true << true; // all three combinations with d QTest::newRow("d/p/s") << NET::Protocols(d | p | s) << false << true << true << true << false; QTest::newRow("d/p/c") << NET::Protocols(d | p | c) << false << true << true << false << true; QTest::newRow("d/s/c") << NET::Protocols(d | s | c) << false << true << false << true << true; // and remaining QTest::newRow("p/s/c") << NET::Protocols(p | s | c) << false << false << true << true << true; QTest::newRow("t/d/p/s") << NET::Protocols(t | d | p | s) << true << true << true << true << false; QTest::newRow("t/d/p/c") << NET::Protocols(t | d | p | c) << true << true << true << false << true; QTest::newRow("t/d/s/c") << NET::Protocols(t | d | s | c) << true << true << false << true << true; QTest::newRow("t/p/s/c") << NET::Protocols(t | p | s | c) << true << false << true << true << true; QTest::newRow("d/p/s/c") << NET::Protocols(d | p | s | c) << false << true << true << true << true; QTest::newRow("all") << NET::Protocols(t | d | p | s | c) << true << true << true << true << true; } void NetWinInfoTestClient::testProtocols() { QVERIFY(connection()); ATOM(WM_PROTOCOLS) KXUtils::Atom takeFocus(connection(), QByteArrayLiteral("WM_TAKE_FOCUS")); KXUtils::Atom deleteWindow(connection(), QByteArrayLiteral("WM_DELETE_WINDOW")); KXUtils::Atom ping(connection(), QByteArrayLiteral("_NET_WM_PING")); KXUtils::Atom syncRequest(connection(), QByteArrayLiteral("_NET_WM_SYNC_REQUEST")); KXUtils::Atom contextHelp(connection(), QByteArrayLiteral("_NET_WM_CONTEXT_HELP")); INFO QVERIFY(!info.supportsProtocol(NET::TakeFocusProtocol)); QVERIFY(!info.supportsProtocol(NET::DeleteWindowProtocol)); QVERIFY(!info.supportsProtocol(NET::PingProtocol)); QVERIFY(!info.supportsProtocol(NET::SyncRequestProtocol)); QVERIFY(!info.supportsProtocol(NET::ContextHelpProtocol)); QCOMPARE(info.protocols(), NET::Protocols(NET::NoProtocol)); QVector props; QFETCH(NET::Protocols, protocols); if (protocols.testFlag(NET::TakeFocusProtocol)) { props << takeFocus; } if (protocols.testFlag(NET::DeleteWindowProtocol)) { props << deleteWindow; } if (protocols.testFlag(NET::PingProtocol)) { props << ping; } if (protocols.testFlag(NET::SyncRequestProtocol)) { props << syncRequest; } if (protocols.testFlag(NET::ContextHelpProtocol)) { props << contextHelp; } xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, atom, XCB_ATOM_ATOM, 32, props.size(), props.constData()); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2Protocols); QCOMPARE(info.protocols(), protocols); QTEST(info.supportsProtocol(NET::TakeFocusProtocol), "takeFocus"); QTEST(info.supportsProtocol(NET::DeleteWindowProtocol), "deleteWindow"); QTEST(info.supportsProtocol(NET::PingProtocol), "ping"); QTEST(info.supportsProtocol(NET::SyncRequestProtocol), "sync"); QTEST(info.supportsProtocol(NET::ContextHelpProtocol), "context"); xcb_delete_property(connection(), m_testWindow, atom); xcb_flush(connection()); waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2Protocols); QVERIFY(!info.supportsProtocol(NET::TakeFocusProtocol)); QVERIFY(!info.supportsProtocol(NET::DeleteWindowProtocol)); QVERIFY(!info.supportsProtocol(NET::PingProtocol)); QVERIFY(!info.supportsProtocol(NET::SyncRequestProtocol)); QVERIFY(!info.supportsProtocol(NET::ContextHelpProtocol)); QCOMPARE(info.protocols(), NET::Protocols(NET::NoProtocol)); } void NetWinInfoTestClient::testOpaqueRegion_data() { QTest::addColumn >("geometries"); QTest::newRow("none") << QVector(); QTest::newRow("empty") << QVector({QRect(0, 0, 0, 0)}); QTest::newRow("one rect") << QVector({QRect(10, 20, 30, 40)}); QTest::newRow("two rect") << QVector({QRect(10, 20, 30, 40), QRect(1, 2, 4, 5)}); QTest::newRow("multiple") << QVector({QRect(10, 20, 30, 40), QRect(1, 2, 4, 5), QRect(100, 0, 200, 400), QRect(1, 2, 4, 5)}); } void NetWinInfoTestClient::testOpaqueRegion() { QVERIFY(connection()); ATOM(_NET_WM_OPAQUE_REGION) INFO QCOMPARE(info.opaqueRegion().size(), std::size_t(0)); QFETCH(QVector, geometries); QVector data; for (auto it = geometries.constBegin(); it != geometries.constEnd(); ++it) { const QRect &r = *it; data << r.x(); data << r.y(); data << r.width(); data << r.height(); } xcb_change_property(connection(), XCB_PROP_MODE_REPLACE, m_testWindow, atom, XCB_ATOM_CARDINAL, 32, data.size(), data.constData()); xcb_flush(connection()); // only updated after event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2OpaqueRegion); const auto opaqueRegion = info.opaqueRegion(); QCOMPARE(opaqueRegion.size(), std::size_t(geometries.size())); for (std::size_t i = 0; i < opaqueRegion.size(); ++i) { auto r1 = opaqueRegion.at(i); auto r2 = geometries.at(i); QCOMPARE(r1.pos.x, r2.x()); QCOMPARE(r1.pos.y, r2.y()); QCOMPARE(r1.size.width, r2.width()); QCOMPARE(r1.size.height, r2.height()); } xcb_delete_property(connection(), m_testWindow, atom); xcb_flush(connection()); waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2OpaqueRegion); QCOMPARE(info.opaqueRegion().size(), std::size_t(0)); } QTEST_GUILESS_MAIN(NetWinInfoTestClient) #include "netwininfotestclient.moc" diff --git a/autotests/netwininfotestwm.cpp b/autotests/netwininfotestwm.cpp index 561cd27..cecc142 100644 --- a/autotests/netwininfotestwm.cpp +++ b/autotests/netwininfotestwm.cpp @@ -1,569 +1,569 @@ /* * Copyright 2013 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "nettesthelper.h" #include #include #include // system #include Q_DECLARE_METATYPE(NET::State) Q_DECLARE_METATYPE(NET::States) Q_DECLARE_METATYPE(NET::Actions) class Property : public QScopedPointer { public: - Property(xcb_get_property_reply_t *p = 0) : QScopedPointer(p) {} + Property(xcb_get_property_reply_t *p = nullptr) : QScopedPointer(p) {} }; #define INFO NETWinInfo info(m_connection, m_testWindow, m_rootWindow, NET::WMAllProperties, NET::WM2AllProperties, NET::WindowManager); #define ATOM(name) \ KXUtils::Atom atom(connection(), QByteArrayLiteral(#name)); #define UTF8 KXUtils::Atom utf8String(connection(), QByteArrayLiteral("UTF8_STRING")); #define GETPROP(type, length, formatSize) \ xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(connection(), false, m_testWindow, \ atom, type, 0, length); \ Property reply(xcb_get_property_reply(connection(), cookie, Q_NULLPTR)); \ QVERIFY(!reply.isNull()); \ QCOMPARE(reply->format, uint8_t(formatSize)); \ QCOMPARE(reply->value_len, uint32_t(length)); #define VERIFYDELETED(t) \ xcb_get_property_cookie_t cookieDeleted = xcb_get_property_unchecked(connection(), false, m_testWindow, \ atom, t, 0, 1); \ Property replyDeleted(xcb_get_property_reply(connection(), cookieDeleted, Q_NULLPTR)); \ QVERIFY(!replyDeleted.isNull()); \ QVERIFY(replyDeleted->type == XCB_ATOM_NONE); class NetWinInfoTestWM : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); void testState_data(); void testState(); void testVisibleName(); void testVisibleIconName(); void testDesktop_data(); void testDesktop(); void testOpacity_data(); void testOpacity(); void testAllowedActions_data(); void testAllowedActions(); void testFrameExtents(); void testFrameExtentsKDE(); void testFrameOverlap(); private: bool hasAtomFlag(const xcb_atom_t *atoms, int atomsLenght, const QByteArray &actionName); void testStrut(xcb_atom_t atom, NETStrut(NETWinInfo:: *getter)(void)const, void (NETWinInfo:: *setter)(NETStrut), NET::Property property, NET::Property2 property2 = NET::Property2(0)); void waitForPropertyChange(NETWinInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2 = NET::Property2(0)); xcb_connection_t *connection() { return m_connection; } xcb_connection_t *m_connection; QVector m_connections; QScopedPointer m_xvfb; xcb_window_t m_rootWindow; xcb_window_t m_testWindow; }; void NetWinInfoTestWM::initTestCase() { qsrand(QDateTime::currentMSecsSinceEpoch()); } void NetWinInfoTestWM::cleanupTestCase() { // close connection while (!m_connections.isEmpty()) { xcb_disconnect(m_connections.takeFirst()); } } void NetWinInfoTestWM::init() { // first reset just to be sure m_connection = Q_NULLPTR; m_rootWindow = XCB_WINDOW_NONE; m_testWindow = XCB_WINDOW_NONE; // start Xvfb m_xvfb.reset(new QProcess); // use pipe to pass fd to Xvfb to get back the display id int pipeFds[2]; QVERIFY(pipe(pipeFds) == 0); m_xvfb->start(QStringLiteral("Xvfb"), QStringList{ QStringLiteral("-displayfd"), QString::number(pipeFds[1]) }); QVERIFY(m_xvfb->waitForStarted()); QCOMPARE(m_xvfb->state(), QProcess::Running); // reads from pipe, closes write side close(pipeFds[1]); QFile readPipe; QVERIFY(readPipe.open(pipeFds[0], QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)); QByteArray displayNumber = readPipe.readLine(); readPipe.close(); displayNumber.prepend(QByteArray(":")); displayNumber.remove(displayNumber.size() -1, 1); // create X connection int screen = 0; m_connection = xcb_connect(displayNumber.constData(), &screen); QVERIFY(m_connection); QVERIFY(!xcb_connection_has_error(m_connection)); m_rootWindow = KXUtils::rootWindow(m_connection, screen); // create test window m_testWindow = xcb_generate_id(m_connection); uint32_t values[] = {XCB_EVENT_MASK_PROPERTY_CHANGE}; xcb_create_window(m_connection, XCB_COPY_FROM_PARENT, m_testWindow, m_rootWindow, 0, 0, 100, 100, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, XCB_CW_EVENT_MASK, values); // and map it xcb_map_window(m_connection, m_testWindow); } void NetWinInfoTestWM::cleanup() { // destroy test window xcb_unmap_window(m_connection, m_testWindow); xcb_destroy_window(m_connection, m_testWindow); m_testWindow = XCB_WINDOW_NONE; // delay till clenupTestCase as otherwise xcb reuses the same memory address m_connections << connection(); // kill Xvfb m_xvfb->terminate(); m_xvfb->waitForFinished(); } void NetWinInfoTestWM::waitForPropertyChange(NETWinInfo *info, xcb_atom_t atom, NET::Property prop, NET::Property2 prop2) { while (true) { KXUtils::ScopedCPointer event(xcb_wait_for_event(connection())); if (event.isNull()) { break; } if ((event->response_type & ~0x80) != XCB_PROPERTY_NOTIFY) { continue; } xcb_property_notify_event_t *pe = reinterpret_cast(event.data()); if (pe->window != m_testWindow) { continue; } if (pe->atom != atom) { continue; } NET::Properties dirty; NET::Properties2 dirty2; info->event(event.data(), &dirty, &dirty2); if (prop != 0) { QVERIFY(dirty & prop); } if (prop2 != 0) { QVERIFY(dirty2 & prop2); } if (!prop) { QCOMPARE(dirty, NET::Properties()); } if (!prop2) { QCOMPARE(dirty2, NET::Properties2()); } break; } } bool NetWinInfoTestWM::hasAtomFlag(const xcb_atom_t *atoms, int atomsLength, const QByteArray &actionName) { KXUtils::Atom atom(connection(), actionName); if (atom == XCB_ATOM_NONE) { qDebug() << "get atom failed"; return false; } for (int i = 0; i < atomsLength; ++i) { if (atoms[i] == atom) { return true; } } return false; } void NetWinInfoTestWM::testAllowedActions_data() { QTest::addColumn("actions"); QTest::addColumn >("names"); const QByteArray move = QByteArrayLiteral("_NET_WM_ACTION_MOVE"); const QByteArray resize = QByteArrayLiteral("_NET_WM_ACTION_RESIZE"); const QByteArray minimize = QByteArrayLiteral("_NET_WM_ACTION_MINIMIZE"); const QByteArray shade = QByteArrayLiteral("_NET_WM_ACTION_SHADE"); const QByteArray stick = QByteArrayLiteral("_NET_WM_ACTION_STICK"); const QByteArray maxVert = QByteArrayLiteral("_NET_WM_ACTION_MAXIMIZE_VERT"); const QByteArray maxHoriz = QByteArrayLiteral("_NET_WM_ACTION_MAXIMIZE_HORZ"); const QByteArray fullscreen = QByteArrayLiteral("_NET_WM_ACTION_FULLSCREEN"); const QByteArray desktop = QByteArrayLiteral("_NET_WM_ACTION_CHANGE_DESKTOP"); const QByteArray close = QByteArrayLiteral("_NET_WM_ACTION_CLOSE"); QTest::newRow("move") << NET::Actions(NET::ActionMove) << (QVector() << move); QTest::newRow("resize") << NET::Actions(NET::ActionResize) << (QVector() << resize); QTest::newRow("minimize") << NET::Actions(NET::ActionMinimize) << (QVector() << minimize); QTest::newRow("shade") << NET::Actions(NET::ActionShade) << (QVector() << shade); QTest::newRow("stick") << NET::Actions(NET::ActionStick) << (QVector() << stick); QTest::newRow("maxVert") << NET::Actions(NET::ActionMaxVert) << (QVector() << maxVert); QTest::newRow("maxHoriz") << NET::Actions(NET::ActionMaxHoriz) << (QVector() << maxHoriz); QTest::newRow("fullscreen") << NET::Actions(NET::ActionFullScreen) << (QVector() << fullscreen); QTest::newRow("desktop") << NET::Actions(NET::ActionChangeDesktop) << (QVector() << desktop); QTest::newRow("close") << NET::Actions(NET::ActionClose) << (QVector() << close); QTest::newRow("none") << NET::Actions() << QVector(); QTest::newRow("all") << NET::Actions(NET::ActionMove | NET::ActionResize | NET::ActionMinimize | NET::ActionShade | NET::ActionStick | NET::ActionMaxVert | NET::ActionMaxHoriz | NET::ActionFullScreen | NET::ActionChangeDesktop | NET::ActionClose) << (QVector() << move << resize << minimize << shade << stick << maxVert << maxHoriz << fullscreen << desktop << close); } void NetWinInfoTestWM::testAllowedActions() { QVERIFY(connection()); ATOM(_NET_WM_ALLOWED_ACTIONS) INFO - QCOMPARE(info.allowedActions(), NET::Actions(0)); + QCOMPARE(info.allowedActions(), NET::Actions(nullptr)); QFETCH(NET::Actions, actions); info.setAllowedActions(actions); QCOMPARE(info.allowedActions(), actions); // compare with the X property QFETCH(QVector, names); QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_ATOM, names.size(), 32) xcb_atom_t *atoms = reinterpret_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < names.size(); ++i) { QVERIFY(hasAtomFlag(atoms, names.size(), names.at(i))); } // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2AllowedActions); QCOMPARE(info.allowedActions(), actions); } void NetWinInfoTestWM::testDesktop_data() { QTest::addColumn("desktop"); QTest::addColumn("propertyDesktop"); QTest::newRow("1") << 1 << uint32_t(0); QTest::newRow("4") << 4 << uint32_t(3); QTest::newRow("on all") << int(NET::OnAllDesktops) << uint32_t(~0); } void NetWinInfoTestWM::testDesktop() { QVERIFY(connection()); ATOM(_NET_WM_DESKTOP) INFO QCOMPARE(info.desktop(), 0); QFETCH(int, desktop); info.setDesktop(desktop); QCOMPARE(info.desktop(), desktop); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QTEST(reinterpret_cast(xcb_get_property_value(reply.data()))[0], "propertyDesktop"); // and wait for our event waitForPropertyChange(&info, atom, NET::WMDesktop); QCOMPARE(info.desktop(), desktop); // delete it info.setDesktop(0); QCOMPARE(info.desktop(), 0); VERIFYDELETED(XCB_ATOM_CARDINAL) // and wait for our event waitForPropertyChange(&info, atom, NET::WMDesktop); QCOMPARE(info.desktop(), 0); } void NetWinInfoTestWM::testStrut(xcb_atom_t atom, NETStrut(NETWinInfo:: *getter)(void)const, void (NETWinInfo:: *setter)(NETStrut), NET::Property property, NET::Property2 property2) { INFO NETStrut extents = (info.*getter)(); QCOMPARE(extents.bottom, 0); QCOMPARE(extents.left, 0); QCOMPARE(extents.right, 0); QCOMPARE(extents.top, 0); NETStrut newExtents; newExtents.bottom = 10; newExtents.left = 20; newExtents.right = 30; newExtents.top = 40; (info.*setter)(newExtents); extents = (info.*getter)(); QCOMPARE(extents.bottom, newExtents.bottom); QCOMPARE(extents.left, newExtents.left); QCOMPARE(extents.right, newExtents.right); QCOMPARE(extents.top, newExtents.top); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 4, 32) uint32_t *data = reinterpret_cast(xcb_get_property_value(reply.data())); QCOMPARE(data[0], uint32_t(newExtents.left)); QCOMPARE(data[1], uint32_t(newExtents.right)); QCOMPARE(data[2], uint32_t(newExtents.top)); QCOMPARE(data[3], uint32_t(newExtents.bottom)); // and wait for our event waitForPropertyChange(&info, atom, property, property2); extents = (info.*getter)(); QCOMPARE(extents.bottom, newExtents.bottom); QCOMPARE(extents.left, newExtents.left); QCOMPARE(extents.right, newExtents.right); QCOMPARE(extents.top, newExtents.top); } void NetWinInfoTestWM::testFrameExtents() { QVERIFY(connection()); ATOM(_NET_FRAME_EXTENTS) testStrut(atom, &NETWinInfo::frameExtents, &NETWinInfo::setFrameExtents, NET::WMFrameExtents); } void NetWinInfoTestWM::testFrameExtentsKDE() { // same as testFrameExtents just with a different atom name QVERIFY(connection()); ATOM(_KDE_NET_WM_FRAME_STRUT) testStrut(atom, &NETWinInfo::frameExtents, &NETWinInfo::setFrameExtents, NET::WMFrameExtents); } void NetWinInfoTestWM::testFrameOverlap() { QVERIFY(connection()); ATOM(_NET_WM_FRAME_OVERLAP) testStrut(atom, &NETWinInfo::frameOverlap, &NETWinInfo::setFrameOverlap, NET::Property(0), NET::WM2FrameOverlap); } void NetWinInfoTestWM::testOpacity_data() { QTest::addColumn("opacity"); QTest::newRow("0 %") << uint32_t(0); QTest::newRow("50 %") << uint32_t(0x0000ffff); QTest::newRow("100 %") << uint32_t(0xffffffff); } void NetWinInfoTestWM::testOpacity() { QVERIFY(connection()); ATOM(_NET_WM_WINDOW_OPACITY) INFO QCOMPARE(info.opacity(), static_cast(0xffffffffU)); QFETCH(uint32_t, opacity); info.setOpacity(opacity); QCOMPARE(info.opacity(), static_cast(opacity)); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_CARDINAL, 1, 32) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data()))[0], opacity); // and wait for our event waitForPropertyChange(&info, atom, NET::Property(0), NET::WM2Opacity); QCOMPARE(info.opacity(), static_cast(opacity)); } void NetWinInfoTestWM::testState_data() { QTest::addColumn("states"); QTest::addColumn >("names"); const QByteArray modal = QByteArrayLiteral("_NET_WM_STATE_MODAL"); const QByteArray sticky = QByteArrayLiteral("_NET_WM_STATE_STICKY"); const QByteArray maxVert = QByteArrayLiteral("_NET_WM_STATE_MAXIMIZED_VERT"); const QByteArray maxHoriz = QByteArrayLiteral("_NET_WM_STATE_MAXIMIZED_HORZ"); const QByteArray shaded = QByteArrayLiteral("_NET_WM_STATE_SHADED"); const QByteArray skipTaskbar = QByteArrayLiteral("_NET_WM_STATE_SKIP_TASKBAR"); const QByteArray keepAbove = QByteArrayLiteral("_NET_WM_STATE_ABOVE"); const QByteArray staysOnTop = QByteArrayLiteral("_NET_WM_STATE_STAYS_ON_TOP"); const QByteArray skipPager = QByteArrayLiteral("_NET_WM_STATE_SKIP_PAGER"); const QByteArray hidden = QByteArrayLiteral("_NET_WM_STATE_HIDDEN"); const QByteArray fullScreen = QByteArrayLiteral("_NET_WM_STATE_FULLSCREEN"); const QByteArray keepBelow = QByteArrayLiteral("_NET_WM_STATE_BELOW"); const QByteArray demandsAttention = QByteArrayLiteral("_NET_WM_STATE_DEMANDS_ATTENTION"); QTest::newRow("modal") << NET::States(NET::Modal) << (QVector() << modal); QTest::newRow("sticky") << NET::States(NET::Sticky) << (QVector() << sticky); QTest::newRow("maxVert") << NET::States(NET::MaxVert) << (QVector() << maxVert); QTest::newRow("maxHoriz") << NET::States(NET::MaxHoriz) << (QVector() << maxHoriz); QTest::newRow("shaded") << NET::States(NET::Shaded) << (QVector() << shaded); QTest::newRow("skipTaskbar") << NET::States(NET::SkipTaskbar) << (QVector() << skipTaskbar); QTest::newRow("keepAbove") << NET::States(NET::KeepAbove) << (QVector() << keepAbove << staysOnTop); QTest::newRow("staysOnTop") << NET::States(NET::StaysOnTop) << (QVector() << keepAbove << staysOnTop); QTest::newRow("skipPager") << NET::States(NET::SkipPager) << (QVector() << skipPager); QTest::newRow("hidden") << NET::States(NET::Hidden) << (QVector() << hidden); QTest::newRow("fullScreen") << NET::States(NET::FullScreen) << (QVector() << fullScreen); QTest::newRow("keepBelow") << NET::States(NET::KeepBelow) << (QVector() << keepBelow); QTest::newRow("demandsAttention") << NET::States(NET::DemandsAttention) << (QVector() << demandsAttention); // TODO: it's possible to be keep above and below at the same time?!? QTest::newRow("all") << NET::States(NET::Modal | NET::Sticky | NET::Max | NET::Shaded | NET::SkipTaskbar | NET::SkipPager | NET::KeepAbove | NET::KeepBelow | NET::Hidden | NET::FullScreen | NET::DemandsAttention) << (QVector() << modal << sticky << maxVert << maxHoriz << shaded << skipTaskbar << keepAbove << skipPager << hidden << fullScreen << keepBelow << demandsAttention << staysOnTop); } void NetWinInfoTestWM::testState() { QVERIFY(connection()); ATOM(_NET_WM_STATE) INFO - QCOMPARE(info.state(), NET::States(0)); + QCOMPARE(info.state(), NET::States(nullptr)); QFETCH(NET::States, states); - info.setState(states, 0); + info.setState(states, nullptr); QCOMPARE(info.state(), states); // compare with the X property QFETCH(QVector, names); QVERIFY(atom != XCB_ATOM_NONE); GETPROP(XCB_ATOM_ATOM, names.size(), 32) xcb_atom_t *atoms = reinterpret_cast(xcb_get_property_value(reply.data())); for (int i = 0; i < names.size(); ++i) { QVERIFY(hasAtomFlag(atoms, names.size(), names.at(i))); } // and wait for our event waitForPropertyChange(&info, atom, NET::WMState); QCOMPARE(info.state(), states); } void NetWinInfoTestWM::testVisibleIconName() { QVERIFY(connection()); ATOM(_NET_WM_VISIBLE_ICON_NAME) UTF8 INFO QVERIFY(!info.visibleIconName()); info.setVisibleIconName("foo"); QCOMPARE(info.visibleIconName(), "foo"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); GETPROP(utf8String, 3, 8) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo"); // and wait for our event waitForPropertyChange(&info, atom, NET::WMVisibleIconName); QCOMPARE(info.visibleIconName(), "foo"); // delete the string info.setVisibleIconName(""); QCOMPARE(info.visibleIconName(), ""); VERIFYDELETED(utf8String) // and wait for our event waitForPropertyChange(&info, atom, NET::WMVisibleIconName); QVERIFY(!info.visibleIconName()); // set again, to ensure we don't leak on tear down info.setVisibleIconName("bar"); xcb_flush(connection()); waitForPropertyChange(&info, atom, NET::WMVisibleIconName); QCOMPARE(info.visibleIconName(), "bar"); } void NetWinInfoTestWM::testVisibleName() { QVERIFY(connection()); ATOM(_NET_WM_VISIBLE_NAME) UTF8 INFO QVERIFY(!info.visibleName()); info.setVisibleName("foo"); QCOMPARE(info.visibleName(), "foo"); // compare with the X property QVERIFY(atom != XCB_ATOM_NONE); QVERIFY(utf8String != XCB_ATOM_NONE); GETPROP(utf8String, 3, 8) QCOMPARE(reinterpret_cast(xcb_get_property_value(reply.data())), "foo"); // and wait for our event waitForPropertyChange(&info, atom, NET::WMVisibleName); QCOMPARE(info.visibleName(), "foo"); // delete the string info.setVisibleName(""); QCOMPARE(info.visibleName(), ""); VERIFYDELETED(utf8String) // and wait for our event waitForPropertyChange(&info, atom, NET::WMVisibleName); QVERIFY(!info.visibleName()); // set again, to ensure we don't leak on tear down info.setVisibleName("bar"); xcb_flush(connection()); waitForPropertyChange(&info, atom, NET::WMVisibleName); QCOMPARE(info.visibleName(), "bar"); } QTEST_GUILESS_MAIN(NetWinInfoTestWM) #include "netwininfotestwm.moc" diff --git a/src/kkeyserver.cpp b/src/kkeyserver.cpp index 811fb4e..823c7a9 100644 --- a/src/kkeyserver.cpp +++ b/src/kkeyserver.cpp @@ -1,293 +1,293 @@ /* Copyright (C) 2001 Ellis Whitehead Win32 port: Copyright (C) 2004 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kkeyserver.h" #include namespace KKeyServer { //--------------------------------------------------------------------- // Array Structures //--------------------------------------------------------------------- struct ModInfo { int modQt; const char *psName; QString *sLabel; // this struct is used in static objects, so must use a pointer here. }; //--------------------------------------------------------------------- // Arrays //--------------------------------------------------------------------- // Key names with this context are extracted elsewhere, // no need for I18N_NOOP2's here. #define KEYCTXT "keyboard-key-name" static ModInfo g_rgModInfo[4] = { - { Qt::SHIFT, "Shift", 0 }, - { Qt::CTRL, "Ctrl", 0 }, - { Qt::ALT, "Alt", 0 }, - { Qt::META, "Meta", 0 } + { Qt::SHIFT, "Shift", nullptr }, + { Qt::CTRL, "Ctrl", nullptr }, + { Qt::ALT, "Alt", nullptr }, + { Qt::META, "Meta", nullptr } }; //--------------------------------------------------------------------- // Initialization //--------------------------------------------------------------------- static bool g_bInitializedKKeyLabels; static bool g_bMacLabels; static void intializeKKeyLabels() { g_rgModInfo[0].sLabel = new QString(QApplication::translate("KKeyServer", (g_rgModInfo[0].psName), KEYCTXT)); g_rgModInfo[1].sLabel = new QString(QApplication::translate("KKeyServer", (g_rgModInfo[1].psName), KEYCTXT)); g_rgModInfo[2].sLabel = new QString(QApplication::translate("KKeyServer", (g_rgModInfo[2].psName), KEYCTXT)); g_rgModInfo[3].sLabel = new QString(QApplication::translate("KKeyServer", (g_rgModInfo[3].psName), KEYCTXT)); g_bMacLabels = (*g_rgModInfo[2].sLabel == QLatin1String("Command")); g_bInitializedKKeyLabels = true; } //--------------------------------------------------------------------- // Public functions //--------------------------------------------------------------------- static QString modToString(uint mod, bool bUserSpace) { if (bUserSpace && !g_bInitializedKKeyLabels) { intializeKKeyLabels(); } QString s; for (int i = 3; i >= 0; i--) { if (mod & g_rgModInfo[i].modQt) { if (!s.isEmpty()) { s += QLatin1Char('+'); } s += (bUserSpace) ? *g_rgModInfo[i].sLabel : QLatin1String(g_rgModInfo[i].psName); } } return s; } QString modToStringUser(uint mod) { return modToString(mod, true); } uint stringUserToMod(const QString &mod) { for (int i = 3; i >= 0; i--) { if (mod.toLower() == g_rgModInfo[i].sLabel->toLower()) { return g_rgModInfo[i].modQt; } } return 0; } bool isShiftAsModifierAllowed(int keyQt) { // remove any modifiers keyQt &= ~Qt::KeyboardModifierMask; // Shift only works as a modifier with certain keys. It's not possible // to enter the SHIFT+5 key sequence for me because this is handled as // '%' by qt on my keyboard. // The working keys are all hardcoded here :-( if (keyQt >= Qt::Key_F1 && keyQt <= Qt::Key_F35) { return true; } if (QChar(keyQt).isLetter()) { return true; } switch (keyQt) { case Qt::Key_Return: case Qt::Key_Space: case Qt::Key_Backspace: case Qt::Key_Tab: case Qt::Key_Backtab: case Qt::Key_Escape: case Qt::Key_Print: case Qt::Key_ScrollLock: case Qt::Key_Pause: case Qt::Key_PageUp: case Qt::Key_PageDown: case Qt::Key_Insert: case Qt::Key_Delete: case Qt::Key_Home: case Qt::Key_End: case Qt::Key_Up: case Qt::Key_Down: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Enter: case Qt::Key_SysReq: case Qt::Key_CapsLock: case Qt::Key_NumLock: case Qt::Key_Help: case Qt::Key_Back: case Qt::Key_Forward: case Qt::Key_Stop: case Qt::Key_Refresh: case Qt::Key_Favorites: case Qt::Key_LaunchMedia: case Qt::Key_OpenUrl: case Qt::Key_HomePage: case Qt::Key_Search: case Qt::Key_VolumeDown: case Qt::Key_VolumeMute: case Qt::Key_VolumeUp: case Qt::Key_BassBoost: case Qt::Key_BassUp: case Qt::Key_BassDown: case Qt::Key_TrebleUp: case Qt::Key_TrebleDown: case Qt::Key_MediaPlay: case Qt::Key_MediaStop: case Qt::Key_MediaPrevious: case Qt::Key_MediaNext: case Qt::Key_MediaRecord: case Qt::Key_MediaPause: case Qt::Key_MediaTogglePlayPause: case Qt::Key_LaunchMail: case Qt::Key_Calculator: case Qt::Key_Memo: case Qt::Key_ToDoList: case Qt::Key_Calendar: case Qt::Key_PowerDown: case Qt::Key_ContrastAdjust: case Qt::Key_Standby: case Qt::Key_MonBrightnessUp: case Qt::Key_MonBrightnessDown: case Qt::Key_KeyboardLightOnOff: case Qt::Key_KeyboardBrightnessUp: case Qt::Key_KeyboardBrightnessDown: case Qt::Key_PowerOff: case Qt::Key_WakeUp: case Qt::Key_Eject: case Qt::Key_ScreenSaver: case Qt::Key_WWW: case Qt::Key_Sleep: case Qt::Key_LightBulb: case Qt::Key_Shop: case Qt::Key_History: case Qt::Key_AddFavorite: case Qt::Key_HotLinks: case Qt::Key_BrightnessAdjust: case Qt::Key_Finance: case Qt::Key_Community: case Qt::Key_AudioRewind: case Qt::Key_BackForward: case Qt::Key_ApplicationLeft: case Qt::Key_ApplicationRight: case Qt::Key_Book: case Qt::Key_CD: case Qt::Key_Clear: case Qt::Key_ClearGrab: case Qt::Key_Close: case Qt::Key_Copy: case Qt::Key_Cut: case Qt::Key_Display: case Qt::Key_DOS: case Qt::Key_Documents: case Qt::Key_Excel: case Qt::Key_Explorer: case Qt::Key_Game: case Qt::Key_Go: case Qt::Key_iTouch: case Qt::Key_LogOff: case Qt::Key_Market: case Qt::Key_Meeting: case Qt::Key_MenuKB: case Qt::Key_MenuPB: case Qt::Key_MySites: case Qt::Key_News: case Qt::Key_OfficeHome: case Qt::Key_Option: case Qt::Key_Paste: case Qt::Key_Phone: case Qt::Key_Reply: case Qt::Key_Reload: case Qt::Key_RotateWindows: case Qt::Key_RotationPB: case Qt::Key_RotationKB: case Qt::Key_Save: case Qt::Key_Send: case Qt::Key_Spell: case Qt::Key_SplitScreen: case Qt::Key_Support: case Qt::Key_TaskPane: case Qt::Key_Terminal: case Qt::Key_Tools: case Qt::Key_Travel: case Qt::Key_Video: case Qt::Key_Word: case Qt::Key_Xfer: case Qt::Key_ZoomIn: case Qt::Key_ZoomOut: case Qt::Key_Away: case Qt::Key_Messenger: case Qt::Key_WebCam: case Qt::Key_MailForward: case Qt::Key_Pictures: case Qt::Key_Music: case Qt::Key_Battery: case Qt::Key_Bluetooth: case Qt::Key_WLAN: case Qt::Key_UWB: case Qt::Key_AudioForward: case Qt::Key_AudioRepeat: case Qt::Key_AudioRandomPlay: case Qt::Key_Subtitle: case Qt::Key_AudioCycleTrack: case Qt::Key_Time: case Qt::Key_Select: case Qt::Key_View: case Qt::Key_TopMenu: case Qt::Key_Suspend: case Qt::Key_Hibernate: case Qt::Key_Launch0: case Qt::Key_Launch1: case Qt::Key_Launch2: case Qt::Key_Launch3: case Qt::Key_Launch4: case Qt::Key_Launch5: case Qt::Key_Launch6: case Qt::Key_Launch7: case Qt::Key_Launch8: case Qt::Key_Launch9: case Qt::Key_LaunchA: case Qt::Key_LaunchB: case Qt::Key_LaunchC: case Qt::Key_LaunchD: case Qt::Key_LaunchE: case Qt::Key_LaunchF: return true; default: return false; } } } diff --git a/src/kstartupinfo.cpp b/src/kstartupinfo.cpp index 1be0595..1453c26 100644 --- a/src/kstartupinfo.cpp +++ b/src/kstartupinfo.cpp @@ -1,1666 +1,1666 @@ /**************************************************************************** Copyright (C) 2001-2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ // qDebug() can't be turned off in kdeinit #if 0 #define KSTARTUPINFO_ALL_DEBUG #ifdef __GNUC__ #warning Extra KStartupInfo debug messages enabled. #endif #endif #ifdef QT_NO_CAST_FROM_ASCII #undef QT_NO_CAST_FROM_ASCII #endif #include "kstartupinfo.h" #include "netwm_def.h" #include "debug_p.h" #include #include #include // KWINDOWSYSTEM_HAVE_X11 // need to resolve INT32(qglobal.h)<>INT32(Xlibint.h) conflict #ifndef QT_CLEAN_NAMESPACE #define QT_CLEAN_NAMESPACE #endif #ifndef Q_OS_WIN #include #include #else #include #include #endif #include #include #include #if KWINDOWSYSTEM_HAVE_X11 #include #include #endif #include #include #include #include #if KWINDOWSYSTEM_HAVE_X11 #include #include #include #include #endif static const char NET_STARTUP_MSG[] = "_NET_STARTUP_INFO"; static const char NET_STARTUP_WINDOW[] = "_NET_STARTUP_ID"; // DESKTOP_STARTUP_ID is used also in kinit/wrapper.c , // kdesu in both kdelibs and kdebase and who knows where else static const char NET_STARTUP_ENV[] = "DESKTOP_STARTUP_ID"; static QByteArray s_startup_id; static long get_num(const QString &item_P); static QString get_str(const QString &item_P); static QByteArray get_cstr(const QString &item_P); static QStringList get_fields(const QString &txt_P); static QString escape_str(const QString &str_P); class KStartupInfo::Data : public KStartupInfoData { public: Data() : age(0) {} // just because it's in a QMap Data(const QString &txt_P) : KStartupInfoData(txt_P), age(0) {} unsigned int age; }; struct KStartupInfoId::Private { Private() : id("") {} QString to_text() const; QByteArray id; // id }; struct KStartupInfoData::Private { Private() : desktop(0), wmclass(""), hostname(""), silent(KStartupInfoData::Unknown), screen(-1), xinerama(-1), launched_by(0) {} QString to_text() const; void remove_pid(pid_t pid); QString bin; QString name; QString description; QString icon; int desktop; QList< pid_t > pids; QByteArray wmclass; QByteArray hostname; KStartupInfoData::TriState silent; int screen; int xinerama; WId launched_by; QString application_id; }; class KStartupInfo::Private { public: // private slots void startups_cleanup(); void startups_cleanup_no_age(); void got_message(const QString &msg); void window_added(WId w); void slot_window_added(WId w); void init(int flags); void got_startup_info(const QString &msg_P, bool update_only_P); void got_remove_startup_info(const QString &msg_P); void new_startup_info_internal(const KStartupInfoId &id_P, Data &data_P, bool update_only_P); void removeAllStartupInfoInternal(const KStartupInfoId &id_P); /** * Emits the gotRemoveStartup signal and erases the @p it from the startups map. * @returns Iterator to next item in the startups map. **/ QMap< KStartupInfoId, Data >::iterator removeStartupInfoInternal(QMap< KStartupInfoId, Data >::iterator it); void remove_startup_pids(const KStartupInfoId &id, const KStartupInfoData &data); void remove_startup_pids(const KStartupInfoData &data); startup_t check_startup_internal(WId w, KStartupInfoId *id, KStartupInfoData *data); bool find_id(const QByteArray &id_P, KStartupInfoId *id_O, KStartupInfoData *data_O); bool find_pid(pid_t pid_P, const QByteArray &hostname, KStartupInfoId *id_O, KStartupInfoData *data_O); bool find_wclass(const QByteArray &res_name_P, const QByteArray &res_class_P, KStartupInfoId *id_O, KStartupInfoData *data_O); void startups_cleanup_internal(bool age_P); void clean_all_noncompliant(); static QString check_required_startup_fields(const QString &msg, const KStartupInfoData &data, int screen); KStartupInfo *q; unsigned int timeout; QMap< KStartupInfoId, KStartupInfo::Data > startups; // contains silenced ASN's only if !AnnounceSilencedChanges QMap< KStartupInfoId, KStartupInfo::Data > silent_startups; // contains ASN's that had change: but no new: yet QMap< KStartupInfoId, KStartupInfo::Data > uninited_startups; #if KWINDOWSYSTEM_HAVE_X11 KXMessages msgs; #endif QTimer *cleanup; int flags; Private(int flags_P, KStartupInfo *q) : q(q), timeout(60), #if KWINDOWSYSTEM_HAVE_X11 msgs(NET_STARTUP_MSG), #endif cleanup(Q_NULLPTR), flags(flags_P) { } void createConnections() { #if KWINDOWSYSTEM_HAVE_X11 // d == NULL means "disabled" if (!QX11Info::isPlatformX11() || !QX11Info::display()) { return; } if (!(flags & DisableKWinModule)) { QObject::connect(KWindowSystem::self(), SIGNAL(windowAdded(WId)), q, SLOT(slot_window_added(WId))); #ifdef __GNUC__ #warning "systemTrayWindowAdded signal was remove from KWindowSystem class" #endif //QObject::connect( KWindowSystem::self(), SIGNAL(systemTrayWindowAdded(WId)), q, SLOT(slot_window_added(WId))); } QObject::connect(&msgs, SIGNAL(gotMessage(QString)), q, SLOT(got_message(QString))); cleanup = new QTimer(q); QObject::connect(cleanup, SIGNAL(timeout()), q, SLOT(startups_cleanup())); #endif } }; KStartupInfo::KStartupInfo(int flags_P, QObject *parent_P) : QObject(parent_P), d(new Private(flags_P, this)) { d->createConnections(); } #ifndef KWINDOWSYSTEM_NO_DEPRECATED KStartupInfo::KStartupInfo(bool clean_on_cantdetect_P, QObject *parent_P) : QObject(parent_P), d(new Private(clean_on_cantdetect_P ? CleanOnCantDetect : 0, this)) { d->createConnections(); } #endif KStartupInfo::~KStartupInfo() { delete d; } void KStartupInfo::Private::got_message(const QString &msg_P) { #if KWINDOWSYSTEM_HAVE_X11 // TODO do something with SCREEN= ? //qCDebug(LOG_KWINDOWSYSTEM) << "got:" << msg_P; QString msg = msg_P.trimmed(); if (msg.startsWith(QLatin1String("new:"))) { // must match length below got_startup_info(msg.mid(4), false); } else if (msg.startsWith(QLatin1String("change:"))) { // must match length below got_startup_info(msg.mid(7), true); } else if (msg.startsWith(QLatin1String("remove:"))) { // must match length below got_remove_startup_info(msg.mid(7)); } #else Q_UNUSED(msg_P) #endif } // if the application stops responding for a while, KWindowSystem may get // the information about the already mapped window before KXMessages // actually gets the info about the started application (depends // on their order in the native x11 event filter) // simply delay info from KWindowSystem a bit // SELI??? namespace { class DelayedWindowEvent : public QEvent { public: DelayedWindowEvent(WId w_P) : QEvent(uniqueType()), w(w_P) {} #if KWINDOWSYSTEM_HAVE_X11 Window w; #else WId w; #endif static Type uniqueType() { return Type(QEvent::User + 15); } }; } void KStartupInfo::Private::slot_window_added(WId w_P) { qApp->postEvent(q, new DelayedWindowEvent(w_P)); } void KStartupInfo::customEvent(QEvent *e_P) { #if KWINDOWSYSTEM_HAVE_X11 if (e_P->type() == DelayedWindowEvent::uniqueType()) { d->window_added(static_cast< DelayedWindowEvent * >(e_P)->w); } else #endif QObject::customEvent(e_P); } void KStartupInfo::Private::window_added(WId w_P) { KStartupInfoId id; KStartupInfoData data; startup_t ret = check_startup_internal(w_P, &id, &data); switch (ret) { case Match: //qCDebug(LOG_KWINDOWSYSTEM) << "new window match"; break; case NoMatch: break; // nothing case CantDetect: if (flags & CleanOnCantDetect) { clean_all_noncompliant(); } break; } } void KStartupInfo::Private::got_startup_info(const QString &msg_P, bool update_P) { KStartupInfoId id(msg_P); if (id.isNull()) { return; } KStartupInfo::Data data(msg_P); new_startup_info_internal(id, data, update_P); } void KStartupInfo::Private::new_startup_info_internal(const KStartupInfoId &id_P, KStartupInfo::Data &data_P, bool update_P) { if (id_P.isNull()) { return; } if (startups.contains(id_P)) { // already reported, update startups[ id_P ].update(data_P); startups[ id_P ].age = 0; // CHECKME //qCDebug(LOG_KWINDOWSYSTEM) << "updating"; if (startups[ id_P ].silent() == KStartupInfo::Data::Yes && !(flags & AnnounceSilenceChanges)) { silent_startups[ id_P ] = startups[ id_P ]; startups.remove(id_P); emit q->gotRemoveStartup(id_P, silent_startups[ id_P ]); return; } emit q->gotStartupChange(id_P, startups[ id_P ]); return; } if (silent_startups.contains(id_P)) { // already reported, update silent_startups[ id_P ].update(data_P); silent_startups[ id_P ].age = 0; // CHECKME //qCDebug(LOG_KWINDOWSYSTEM) << "updating silenced"; if (silent_startups[ id_P ].silent() != Data::Yes) { startups[ id_P ] = silent_startups[ id_P ]; silent_startups.remove(id_P); q->emit gotNewStartup(id_P, startups[ id_P ]); return; } emit q->gotStartupChange(id_P, silent_startups[ id_P ]); return; } if (uninited_startups.contains(id_P)) { uninited_startups[ id_P ].update(data_P); //qCDebug(LOG_KWINDOWSYSTEM) << "updating uninited"; if (!update_P) { // uninited finally got new: startups[ id_P ] = uninited_startups[ id_P ]; uninited_startups.remove(id_P); emit q->gotNewStartup(id_P, startups[ id_P ]); return; } // no change announce, it's still uninited return; } if (update_P) { // change: without any new: first //qCDebug(LOG_KWINDOWSYSTEM) << "adding uninited"; uninited_startups.insert(id_P, data_P); } else if (data_P.silent() != Data::Yes || flags & AnnounceSilenceChanges) { //qCDebug(LOG_KWINDOWSYSTEM) << "adding"; startups.insert(id_P, data_P); emit q->gotNewStartup(id_P, data_P); } else { // new silenced, and silent shouldn't be announced //qCDebug(LOG_KWINDOWSYSTEM) << "adding silent"; silent_startups.insert(id_P, data_P); } cleanup->start(1000); // 1 sec } void KStartupInfo::Private::got_remove_startup_info(const QString &msg_P) { KStartupInfoId id(msg_P); KStartupInfoData data(msg_P); if (data.pids().count() > 0) { if (!id.isNull()) { remove_startup_pids(id, data); } else { remove_startup_pids(data); } return; } removeAllStartupInfoInternal(id); } void KStartupInfo::Private::removeAllStartupInfoInternal(const KStartupInfoId &id_P) { auto it = startups.find(id_P); if (it != startups.end()) { //qCDebug(LOG_KWINDOWSYSTEM) << "removing"; emit q->gotRemoveStartup(it.key(), it.value()); startups.erase(it); return; } it = silent_startups.find(id_P); if (it != silent_startups.end()) { silent_startups.erase(it); return; } it = uninited_startups.find(id_P); if (it != uninited_startups.end()) { uninited_startups.erase(it); } } QMap< KStartupInfoId, KStartupInfo::Data >::iterator KStartupInfo::Private::removeStartupInfoInternal(QMap< KStartupInfoId, Data >::iterator it) { emit q->gotRemoveStartup(it.key(), it.value()); return startups.erase(it); } void KStartupInfo::Private::remove_startup_pids(const KStartupInfoData &data_P) { // first find the matching info for (QMap< KStartupInfoId, KStartupInfo::Data >::Iterator it = startups.begin(); it != startups.end(); ++it) { if ((*it).hostname() != data_P.hostname()) { continue; } if (!(*it).is_pid(data_P.pids().first())) { continue; // not the matching info } remove_startup_pids(it.key(), data_P); break; } } void KStartupInfo::Private::remove_startup_pids(const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (data_P.pids().count() == 0) { qFatal("data_P.pids().count() == 0"); } - Data *data = NULL; + Data *data = nullptr; if (startups.contains(id_P)) { data = &startups[ id_P ]; } else if (silent_startups.contains(id_P)) { data = &silent_startups[ id_P ]; } else if (uninited_startups.contains(id_P)) { data = &uninited_startups[ id_P ]; } else { return; } for (QList< pid_t >::ConstIterator it2 = data_P.pids().constBegin(); it2 != data_P.pids().constEnd(); ++it2) { data->d->remove_pid(*it2); // remove all pids from the info } if (data->pids().count() == 0) { // all pids removed -> remove info removeAllStartupInfoInternal(id_P); } } bool KStartupInfo::sendStartup(const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 return sendStartupXcb(QX11Info::connection(), QX11Info::appScreen(), id_P, data_P); #else Q_UNUSED(data_P) #endif return true; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED bool KStartupInfo::sendStartupX(Display *disp_P, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("new: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); msg = Private::check_required_startup_fields(msg, data_P, DefaultScreen(disp_P)); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(disp_P, NET_STARTUP_MSG, msg); #else Q_UNUSED(disp_P) Q_UNUSED(data_P) return true; #endif } #endif bool KStartupInfo::sendStartupXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("new: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); msg = Private::check_required_startup_fields(msg, data_P, screen); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(conn, NET_STARTUP_MSG, msg, screen); #else Q_UNUSED(conn) Q_UNUSED(screen) Q_UNUSED(data_P) return true; #endif } QString KStartupInfo::Private::check_required_startup_fields(const QString &msg, const KStartupInfoData &data_P, int screen) { QString ret = msg; if (data_P.name().isEmpty()) { // qWarning() << "NAME not specified in initial startup message"; QString name = data_P.bin(); if (name.isEmpty()) { name = "UNKNOWN"; } ret += QString(" NAME=\"%1\"").arg(escape_str(name)); } if (data_P.screen() == -1) { // add automatically if needed ret += QString(" SCREEN=%1").arg(screen); } return ret; } bool KStartupInfo::sendChange(const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 return sendChangeXcb(QX11Info::connection(), QX11Info::appScreen(), id_P, data_P); #else Q_UNUSED(data_P) #endif return true; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED bool KStartupInfo::sendChangeX(Display *disp_P, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("change: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(disp_P, NET_STARTUP_MSG, msg); #else Q_UNUSED(disp_P) Q_UNUSED(data_P) return true; #endif } #endif bool KStartupInfo::sendChangeXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("change: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(conn, NET_STARTUP_MSG, msg, screen); #else Q_UNUSED(conn) Q_UNUSED(screen) Q_UNUSED(data_P) return true; #endif } bool KStartupInfo::sendFinish(const KStartupInfoId &id_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 return sendFinishXcb(QX11Info::connection(), QX11Info::appScreen(), id_P); #endif return true; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED bool KStartupInfo::sendFinishX(Display *disp_P, const KStartupInfoId &id_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("remove: %1").arg(id_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(disp_P, NET_STARTUP_MSG, msg); #else Q_UNUSED(disp_P) return true; #endif } #endif bool KStartupInfo::sendFinishXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id_P) { if (id_P.isNull()) { return false; } #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("remove: %1").arg(id_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(conn, NET_STARTUP_MSG, msg, screen); #else Q_UNUSED(conn) Q_UNUSED(screen) return true; #endif } bool KStartupInfo::sendFinish(const KStartupInfoId &id_P, const KStartupInfoData &data_P) { // if( id_P.isNull()) // id may be null, the pids and hostname matter then // return false; #if KWINDOWSYSTEM_HAVE_X11 return sendFinishXcb(QX11Info::connection(), QX11Info::appScreen(), id_P, data_P); #else Q_UNUSED(id_P) Q_UNUSED(data_P) #endif return true; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED bool KStartupInfo::sendFinishX(Display *disp_P, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { // if( id_P.isNull()) // id may be null, the pids and hostname matter then // return false; #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("remove: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(disp_P, NET_STARTUP_MSG, msg); #else Q_UNUSED(disp_P) Q_UNUSED(id_P) Q_UNUSED(data_P) return true; #endif } #endif bool KStartupInfo::sendFinishXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id_P, const KStartupInfoData &data_P) { // if( id_P.isNull()) // id may be null, the pids and hostname matter then // return false; #if KWINDOWSYSTEM_HAVE_X11 QString msg = QString::fromLatin1("remove: %1 %2") .arg(id_P.d->to_text()).arg(data_P.d->to_text()); #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "sending " << msg; #endif return KXMessages::broadcastMessageX(conn, NET_STARTUP_MSG, msg, screen); #else Q_UNUSED(conn) Q_UNUSED(screen) Q_UNUSED(id_P) Q_UNUSED(data_P) return true; #endif } void KStartupInfo::appStarted() { appStarted(startupId()); setStartupId("0"); // reset the id, no longer valid (must use clearStartupId() to avoid infinite loop) } void KStartupInfo::appStarted(const QByteArray &startup_id) { KStartupInfoId id; id.initId(startup_id); if (id.isNull()) { return; } #if KWINDOWSYSTEM_HAVE_X11 if (QX11Info::isPlatformX11() && !qgetenv("DISPLAY").isEmpty()) { // don't rely on QX11Info::display() - Display *disp = XOpenDisplay(NULL); - if (disp != NULL) { + Display *disp = XOpenDisplay(nullptr); + if (disp != nullptr) { KStartupInfo::sendFinishX(disp, id); XCloseDisplay(disp); } } #endif } void KStartupInfo::silenceStartup(bool silence) { KStartupInfoId id; id.initId(startupId()); if (id.isNull()) { return; } KStartupInfoData data; data.setSilent(silence ? KStartupInfoData::Yes : KStartupInfoData::No); sendChange(id, data); } QByteArray KStartupInfo::startupId() { if (s_startup_id.isEmpty()) { KStartupInfoId id = currentStartupIdEnv(); resetStartupEnv(); s_startup_id = id.id(); } return s_startup_id; } void KStartupInfo::setStartupId(const QByteArray &startup_id) { if (startup_id == startupId()) { return; } if (startup_id.isEmpty()) { s_startup_id = "0"; } else { s_startup_id = startup_id; #if KWINDOWSYSTEM_HAVE_X11 if (QX11Info::isPlatformX11()) { KStartupInfoId id; id.initId(startup_id); long timestamp = id.timestamp(); if (timestamp != 0) { if (QX11Info::appUserTime() == 0 || NET::timestampCompare(timestamp, QX11Info::appUserTime()) > 0) { // time > appUserTime QX11Info::setAppUserTime(timestamp); } if (QX11Info::appTime() == 0 || NET::timestampCompare(timestamp, QX11Info::appTime()) > 0) { // time > appTime QX11Info::setAppTime(timestamp); } } } #endif } } void KStartupInfo::setNewStartupId(QWidget *window, const QByteArray &startup_id) { bool activate = true; setStartupId(startup_id); #if KWINDOWSYSTEM_HAVE_X11 - if (window != NULL && QX11Info::isPlatformX11()) { + if (window != nullptr && QX11Info::isPlatformX11()) { if (!startup_id.isEmpty() && startup_id != "0") { NETRootInfo i(QX11Info::connection(), NET::Supported); if (i.isSupported(NET::WM2StartupId)) { KStartupInfo::setWindowStartupId(window->winId(), startup_id); activate = false; // WM will take care of it } } if (activate) { KWindowSystem::setOnDesktop(window->winId(), KWindowSystem::currentDesktop()); // This is not very nice, but there's no way how to get any // usable timestamp without ASN, so force activating the window. // And even with ASN, it's not possible to get the timestamp here, // so if the WM doesn't have support for ASN, it can't be used either. KWindowSystem::forceActiveWindow(window->winId()); } } #else Q_UNUSED(activate) Q_UNUSED(window) #endif } KStartupInfo::startup_t KStartupInfo::checkStartup(WId w_P, KStartupInfoId &id_O, KStartupInfoData &data_O) { return d->check_startup_internal(w_P, &id_O, &data_O); } KStartupInfo::startup_t KStartupInfo::checkStartup(WId w_P, KStartupInfoId &id_O) { - return d->check_startup_internal(w_P, &id_O, NULL); + return d->check_startup_internal(w_P, &id_O, nullptr); } KStartupInfo::startup_t KStartupInfo::checkStartup(WId w_P, KStartupInfoData &data_O) { - return d->check_startup_internal(w_P, NULL, &data_O); + return d->check_startup_internal(w_P, nullptr, &data_O); } KStartupInfo::startup_t KStartupInfo::checkStartup(WId w_P) { - return d->check_startup_internal(w_P, NULL, NULL); + return d->check_startup_internal(w_P, nullptr, nullptr); } KStartupInfo::startup_t KStartupInfo::Private::check_startup_internal(WId w_P, KStartupInfoId *id_O, KStartupInfoData *data_O) { if (startups.count() == 0) { return NoMatch; // no startups } // Strategy: // // Is this a compliant app ? // - Yes - test for match // - No - Is this a NET_WM compliant app ? // - Yes - test for pid match // - No - test for WM_CLASS match qCDebug(LOG_KWINDOWSYSTEM) << "check_startup"; QByteArray id = windowStartupId(w_P); if (!id.isNull()) { if (id.isEmpty() || id == "0") { // means ignore this window qCDebug(LOG_KWINDOWSYSTEM) << "ignore"; return NoMatch; } return find_id(id, id_O, data_O) ? Match : NoMatch; } #if KWINDOWSYSTEM_HAVE_X11 if (!QX11Info::isPlatformX11()) { qCDebug(LOG_KWINDOWSYSTEM) << "check_startup:cantdetect"; return CantDetect; } NETWinInfo info(QX11Info::connection(), w_P, QX11Info::appRootWindow(), NET::WMWindowType | NET::WMPid | NET::WMState, NET::WM2WindowClass | NET::WM2ClientMachine | NET::WM2TransientFor); pid_t pid = info.pid(); if (pid > 0) { QByteArray hostname = info.clientMachine(); if (!hostname.isEmpty() && find_pid(pid, hostname, id_O, data_O)) { return Match; } // try XClass matching , this PID stuff sucks :( } if (find_wclass(info.windowClassName(), info.windowClassClass(), id_O, data_O)) { return Match; } // ignore NET::Tool and other special window types, if they can't be matched NET::WindowType type = info.windowType(NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask); if (type != NET::Normal && type != NET::Override && type != NET::Unknown && type != NET::Dialog && type != NET::Utility) // && type != NET::Dock ) why did I put this here? { return NoMatch; } // lets see if this is a transient xcb_window_t transient_for = info.transientFor(); if (transient_for != QX11Info::appRootWindow() && transient_for != XCB_WINDOW_NONE) { return NoMatch; } #endif qCDebug(LOG_KWINDOWSYSTEM) << "check_startup:cantdetect"; return CantDetect; } bool KStartupInfo::Private::find_id(const QByteArray &id_P, KStartupInfoId *id_O, KStartupInfoData *data_O) { //qCDebug(LOG_KWINDOWSYSTEM) << "find_id:" << id_P; KStartupInfoId id; id.initId(id_P); if (startups.contains(id)) { - if (id_O != NULL) { + if (id_O != nullptr) { *id_O = id; } - if (data_O != NULL) { + if (data_O != nullptr) { *data_O = startups[ id ]; } //qCDebug(LOG_KWINDOWSYSTEM) << "check_startup_id:match"; return true; } return false; } bool KStartupInfo::Private::find_pid(pid_t pid_P, const QByteArray &hostname_P, KStartupInfoId *id_O, KStartupInfoData *data_O) { //qCDebug(LOG_KWINDOWSYSTEM) << "find_pid:" << pid_P; for (QMap< KStartupInfoId, KStartupInfo::Data >::Iterator it = startups.begin(); it != startups.end(); ++it) { if ((*it).is_pid(pid_P) && (*it).hostname() == hostname_P) { // Found it ! - if (id_O != NULL) { + if (id_O != nullptr) { *id_O = it.key(); } - if (data_O != NULL) { + if (data_O != nullptr) { *data_O = *it; } // non-compliant, remove on first match removeStartupInfoInternal(it); //qCDebug(LOG_KWINDOWSYSTEM) << "check_startup_pid:match"; return true; } } return false; } bool KStartupInfo::Private::find_wclass(const QByteArray &_res_name, const QByteArray &_res_class, KStartupInfoId *id_O, KStartupInfoData *data_O) { QByteArray res_name = _res_name.toLower(); QByteArray res_class = _res_class.toLower(); //qCDebug(LOG_KWINDOWSYSTEM) << "find_wclass:" << res_name << ":" << res_class; for (QMap< KStartupInfoId, Data >::Iterator it = startups.begin(); it != startups.end(); ++it) { const QByteArray wmclass = (*it).findWMClass(); if (wmclass.toLower() == res_name || wmclass.toLower() == res_class) { // Found it ! - if (id_O != NULL) { + if (id_O != nullptr) { *id_O = it.key(); } - if (data_O != NULL) { + if (data_O != nullptr) { *data_O = *it; } // non-compliant, remove on first match removeStartupInfoInternal(it); //qCDebug(LOG_KWINDOWSYSTEM) << "check_startup_wclass:match"; return true; } } return false; } QByteArray KStartupInfo::windowStartupId(WId w_P) { #if KWINDOWSYSTEM_HAVE_X11 if (!QX11Info::isPlatformX11()) { return QByteArray(); } - NETWinInfo info(QX11Info::connection(), w_P, QX11Info::appRootWindow(), 0, NET::WM2StartupId | NET::WM2GroupLeader); + NETWinInfo info(QX11Info::connection(), w_P, QX11Info::appRootWindow(), nullptr, NET::WM2StartupId | NET::WM2GroupLeader); QByteArray ret = info.startupId(); if (ret.isEmpty() && info.groupLeader() != XCB_WINDOW_NONE) { // retry with window group leader, as the spec says - NETWinInfo groupLeaderInfo(QX11Info::connection(), info.groupLeader(), QX11Info::appRootWindow(), 0, NET::WM2StartupId); + NETWinInfo groupLeaderInfo(QX11Info::connection(), info.groupLeader(), QX11Info::appRootWindow(), nullptr, NET::WM2StartupId); ret = groupLeaderInfo.startupId(); } return ret; #else Q_UNUSED(w_P) return QByteArray(); #endif } void KStartupInfo::setWindowStartupId(WId w_P, const QByteArray &id_P) { #if KWINDOWSYSTEM_HAVE_X11 if (!QX11Info::isPlatformX11()) { return; } if (id_P.isNull()) { return; } - NETWinInfo info(QX11Info::connection(), w_P, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), w_P, QX11Info::appRootWindow(), nullptr, nullptr); info.setStartupId(id_P.constData()); #else Q_UNUSED(w_P) Q_UNUSED(id_P) #endif } void KStartupInfo::setTimeout(unsigned int secs_P) { d->timeout = secs_P; // schedule removing entries that are older than the new timeout QTimer::singleShot(0, this, SLOT(startups_cleanup_no_age())); } void KStartupInfo::Private::startups_cleanup_no_age() { startups_cleanup_internal(false); } void KStartupInfo::Private::startups_cleanup() { if (startups.count() == 0 && silent_startups.count() == 0 && uninited_startups.count() == 0) { cleanup->stop(); return; } startups_cleanup_internal(true); } void KStartupInfo::Private::startups_cleanup_internal(bool age_P) { auto checkCleanup = [this, age_P](QMap &s, bool doEmit) { auto it = s.begin(); while (it != s.end()) { if (age_P) { (*it).age++; } unsigned int tout = timeout; if ((*it).silent() == KStartupInfo::Data::Yes) { // give kdesu time to get a password tout *= 20; } const QByteArray timeoutEnvVariable = qgetenv("KSTARTUPINFO_TIMEOUT"); if (!timeoutEnvVariable.isNull()) { tout = timeoutEnvVariable.toUInt(); } if ((*it).age >= tout) { if (doEmit) { emit q->gotRemoveStartup(it.key(), it.value()); } it = s.erase(it); } else { ++it; } } }; checkCleanup(startups, true); checkCleanup(silent_startups, false); checkCleanup(uninited_startups, false); } void KStartupInfo::Private::clean_all_noncompliant() { for (QMap< KStartupInfoId, KStartupInfo::Data >::Iterator it = startups.begin(); it != startups.end(); ) { if ((*it).WMClass() != "0") { ++it; continue; } it = removeStartupInfoInternal(it); } } QByteArray KStartupInfo::createNewStartupId() { quint32 timestamp = 0; #if KWINDOWSYSTEM_HAVE_X11 if (QX11Info::isPlatformX11()) { timestamp = QX11Info::getTimestamp(); } #endif return KStartupInfo::createNewStartupIdForTimestamp(timestamp); } QByteArray KStartupInfo::createNewStartupIdForTimestamp(quint32 timestamp) { // Assign a unique id, use hostname+time+pid, that should be 200% unique. // Also append the user timestamp (for focus stealing prevention). struct timeval tm; #ifdef Q_OS_WIN //on windows only msecs accuracy instead of usecs like with gettimeofday //XXX: use Win API to get better accuracy qint64 msecsSinceEpoch = QDateTime::currentMSecsSinceEpoch(); tm.tv_sec = msecsSinceEpoch / 1000; tm.tv_usec = (msecsSinceEpoch % 1000) * 1000; #else - gettimeofday(&tm, NULL); + gettimeofday(&tm, nullptr); #endif char hostname[ 256 ]; hostname[ 0 ] = '\0'; if (!gethostname(hostname, 255)) { hostname[sizeof(hostname) - 1] = '\0'; } QByteArray id = QString::fromLatin1("%1;%2;%3;%4_TIME%5").arg(hostname).arg(tm.tv_sec) .arg(tm.tv_usec).arg(getpid()).arg(timestamp).toUtf8(); //qCDebug(LOG_KWINDOWSYSTEM) << "creating: " << id << ":" << (qApp ? qAppName() : QString("unnamed app") /* e.g. kdeinit */); return id; } const QByteArray &KStartupInfoId::id() const { return d->id; } QString KStartupInfoId::Private::to_text() const { return QString::fromLatin1(" ID=\"%1\" ").arg(escape_str(id)); } KStartupInfoId::KStartupInfoId(const QString &txt_P) : d(new Private) { const QStringList items = get_fields(txt_P); const QString id_str = QLatin1String("ID="); for (QStringList::ConstIterator it = items.begin(); it != items.end(); ++it) { if ((*it).startsWith(id_str)) { d->id = get_cstr(*it); } } } void KStartupInfoId::initId(const QByteArray &id_P) { if (!id_P.isEmpty()) { d->id = id_P; #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "using: " << d->id; #endif return; } const QByteArray startup_env = qgetenv(NET_STARTUP_ENV); if (!startup_env.isEmpty()) { // already has id d->id = startup_env; #ifdef KSTARTUPINFO_ALL_DEBUG qCDebug(LOG_KWINDOWSYSTEM) << "reusing: " << d->id; #endif return; } d->id = KStartupInfo::createNewStartupId(); } bool KStartupInfoId::setupStartupEnv() const { if (isNull()) { qunsetenv(NET_STARTUP_ENV); return false; } return ! qputenv(NET_STARTUP_ENV, id()) == 0; } KStartupInfoId KStartupInfo::currentStartupIdEnv() { const QByteArray startup_env = qgetenv(NET_STARTUP_ENV); KStartupInfoId id; if (!startup_env.isEmpty()) { id.d->id = startup_env; } else { id.d->id = "0"; } return id; } void KStartupInfo::resetStartupEnv() { qunsetenv(NET_STARTUP_ENV); } KStartupInfoId::KStartupInfoId() : d(new Private) { } KStartupInfoId::~KStartupInfoId() { delete d; } KStartupInfoId::KStartupInfoId(const KStartupInfoId &id_P) : d(new Private(*id_P.d)) { } KStartupInfoId &KStartupInfoId::operator=(const KStartupInfoId &id_P) { if (&id_P == this) { return *this; } *d = *id_P.d; return *this; } bool KStartupInfoId::operator==(const KStartupInfoId &id_P) const { return id() == id_P.id(); } bool KStartupInfoId::operator!=(const KStartupInfoId &id_P) const { return !(*this == id_P); } // needed for QMap bool KStartupInfoId::operator<(const KStartupInfoId &id_P) const { return id() < id_P.id(); } bool KStartupInfoId::isNull() const { return d->id.isEmpty() || d->id == "0"; } unsigned long KStartupInfoId::timestamp() const { if (isNull()) { return 0; } // As per the spec, the ID must contain the _TIME followed by the timestamp int pos = d->id.lastIndexOf("_TIME"); if (pos >= 0) { bool ok; unsigned long time = QString(d->id.mid(pos + 5)).toULong(&ok); if (!ok && d->id[ pos + 5 ] == '-') { // try if it's as a negative signed number perhaps time = QString(d->id.mid(pos + 5)).toLong(&ok); } if (ok) { return time; } } return 0; } QString KStartupInfoData::Private::to_text() const { QString ret; if (!bin.isEmpty()) { ret += QString::fromLatin1(" BIN=\"%1\"").arg(escape_str(bin)); } if (!name.isEmpty()) { ret += QString::fromLatin1(" NAME=\"%1\"").arg(escape_str(name)); } if (!description.isEmpty()) { ret += QString::fromLatin1(" DESCRIPTION=\"%1\"").arg(escape_str(description)); } if (!icon.isEmpty()) { ret += QString::fromLatin1(" ICON=\"%1\"").arg(icon); } if (desktop != 0) ret += QString::fromLatin1(" DESKTOP=%1") .arg(desktop == NET::OnAllDesktops ? NET::OnAllDesktops : desktop - 1); // spec counts from 0 if (!wmclass.isEmpty()) { ret += QString::fromLatin1(" WMCLASS=\"%1\"").arg(QString(wmclass)); } if (!hostname.isEmpty()) { ret += QString::fromLatin1(" HOSTNAME=%1").arg(QString(hostname)); } for (QList< pid_t >::ConstIterator it = pids.begin(); it != pids.end(); ++it) { ret += QString::fromLatin1(" PID=%1").arg(*it); } if (silent != KStartupInfoData::Unknown) { ret += QString::fromLatin1(" SILENT=%1").arg(silent == KStartupInfoData::Yes ? 1 : 0); } if (screen != -1) { ret += QString::fromLatin1(" SCREEN=%1").arg(screen); } if (xinerama != -1) { ret += QString::fromLatin1(" XINERAMA=%1").arg(xinerama); } if (launched_by != 0) { ret += QString::fromLatin1(" LAUNCHED_BY=%1").arg((qptrdiff)launched_by); } if (!application_id.isEmpty()) { ret += QString::fromLatin1(" APPLICATION_ID=\"%1\"").arg(application_id); } return ret; } KStartupInfoData::KStartupInfoData(const QString &txt_P) : d(new Private) { const QStringList items = get_fields(txt_P); const QString bin_str = QString::fromLatin1("BIN="); const QString name_str = QString::fromLatin1("NAME="); const QString description_str = QString::fromLatin1("DESCRIPTION="); const QString icon_str = QString::fromLatin1("ICON="); const QString desktop_str = QString::fromLatin1("DESKTOP="); const QString wmclass_str = QString::fromLatin1("WMCLASS="); const QString hostname_str = QString::fromLatin1("HOSTNAME="); // added to version 1 (2014) const QString pid_str = QString::fromLatin1("PID="); // added to version 1 (2014) const QString silent_str = QString::fromLatin1("SILENT="); const QString timestamp_str = QString::fromLatin1("TIMESTAMP="); const QString screen_str = QString::fromLatin1("SCREEN="); const QString xinerama_str = QString::fromLatin1("XINERAMA="); const QString launched_by_str = QString::fromLatin1("LAUNCHED_BY="); const QString application_id_str = QString::fromLatin1("APPLICATION_ID="); for (QStringList::ConstIterator it = items.begin(); it != items.end(); ++it) { if ((*it).startsWith(bin_str)) { d->bin = get_str(*it); } else if ((*it).startsWith(name_str)) { d->name = get_str(*it); } else if ((*it).startsWith(description_str)) { d->description = get_str(*it); } else if ((*it).startsWith(icon_str)) { d->icon = get_str(*it); } else if ((*it).startsWith(desktop_str)) { d->desktop = get_num(*it); if (d->desktop != NET::OnAllDesktops) ++d->desktop; // spec counts from 0 } else if ((*it).startsWith(wmclass_str)) { d->wmclass = get_cstr(*it); } else if ((*it).startsWith(hostname_str)) { d->hostname = get_cstr(*it); } else if ((*it).startsWith(pid_str)) { addPid(get_num(*it)); } else if ((*it).startsWith(silent_str)) { d->silent = get_num(*it) != 0 ? Yes : No; } else if ((*it).startsWith(screen_str)) { d->screen = get_num(*it); } else if ((*it).startsWith(xinerama_str)) { d->xinerama = get_num(*it); } else if ((*it).startsWith(launched_by_str)) { d->launched_by = (WId) get_num(*it); } else if ((*it).startsWith(application_id_str)) { d->application_id = get_str(*it); } } } KStartupInfoData::KStartupInfoData(const KStartupInfoData &data) : d(new Private(*data.d)) { } KStartupInfoData &KStartupInfoData::operator=(const KStartupInfoData &data) { if (&data == this) { return *this; } *d = *data.d; return *this; } void KStartupInfoData::update(const KStartupInfoData &data_P) { if (!data_P.bin().isEmpty()) { d->bin = data_P.bin(); } if (!data_P.name().isEmpty() && name().isEmpty()) { // don't overwrite d->name = data_P.name(); } if (!data_P.description().isEmpty() && description().isEmpty()) { // don't overwrite d->description = data_P.description(); } if (!data_P.icon().isEmpty() && icon().isEmpty()) { // don't overwrite d->icon = data_P.icon(); } if (data_P.desktop() != 0 && desktop() == 0) { // don't overwrite d->desktop = data_P.desktop(); } if (!data_P.d->wmclass.isEmpty()) { d->wmclass = data_P.d->wmclass; } if (!data_P.d->hostname.isEmpty()) { d->hostname = data_P.d->hostname; } for (QList< pid_t >::ConstIterator it = data_P.d->pids.constBegin(); it != data_P.d->pids.constEnd(); ++it) { addPid(*it); } if (data_P.silent() != Unknown) { d->silent = data_P.silent(); } if (data_P.screen() != -1) { d->screen = data_P.screen(); } if (data_P.xinerama() != -1 && xinerama() != -1) { // don't overwrite d->xinerama = data_P.xinerama(); } if (data_P.launchedBy() != 0 && launchedBy() != 0) { // don't overwrite d->launched_by = data_P.launchedBy(); } if (!data_P.applicationId().isEmpty() && applicationId().isEmpty()) { // don't overwrite d->application_id = data_P.applicationId(); } } KStartupInfoData::KStartupInfoData() : d(new Private) { } KStartupInfoData::~KStartupInfoData() { delete d; } void KStartupInfoData::setBin(const QString &bin_P) { d->bin = bin_P; } const QString &KStartupInfoData::bin() const { return d->bin; } void KStartupInfoData::setName(const QString &name_P) { d->name = name_P; } const QString &KStartupInfoData::name() const { return d->name; } const QString &KStartupInfoData::findName() const { if (!name().isEmpty()) { return name(); } return bin(); } void KStartupInfoData::setDescription(const QString &desc_P) { d->description = desc_P; } const QString &KStartupInfoData::description() const { return d->description; } const QString &KStartupInfoData::findDescription() const { if (!description().isEmpty()) { return description(); } return name(); } void KStartupInfoData::setIcon(const QString &icon_P) { d->icon = icon_P; } const QString &KStartupInfoData::findIcon() const { if (!icon().isEmpty()) { return icon(); } return bin(); } const QString &KStartupInfoData::icon() const { return d->icon; } void KStartupInfoData::setDesktop(int desktop_P) { d->desktop = desktop_P; } int KStartupInfoData::desktop() const { return d->desktop; } void KStartupInfoData::setWMClass(const QByteArray &wmclass_P) { d->wmclass = wmclass_P; } const QByteArray KStartupInfoData::findWMClass() const { if (!WMClass().isEmpty() && WMClass() != "0") { return WMClass(); } return bin().toUtf8(); } QByteArray KStartupInfoData::WMClass() const { return d->wmclass; } void KStartupInfoData::setHostname(const QByteArray &hostname_P) { if (!hostname_P.isNull()) { d->hostname = hostname_P; } else { char tmp[ 256 ]; tmp[ 0 ] = '\0'; if (!gethostname(tmp, 255)) { tmp[sizeof(tmp) - 1] = '\0'; } d->hostname = tmp; } } QByteArray KStartupInfoData::hostname() const { return d->hostname; } void KStartupInfoData::addPid(pid_t pid_P) { if (!d->pids.contains(pid_P)) { d->pids.append(pid_P); } } void KStartupInfoData::Private::remove_pid(pid_t pid_P) { pids.removeAll(pid_P); } QList< pid_t > KStartupInfoData::pids() const { return d->pids; } bool KStartupInfoData::is_pid(pid_t pid_P) const { return d->pids.contains(pid_P); } void KStartupInfoData::setSilent(TriState state_P) { d->silent = state_P; } KStartupInfoData::TriState KStartupInfoData::silent() const { return d->silent; } void KStartupInfoData::setScreen(int _screen) { d->screen = _screen; } int KStartupInfoData::screen() const { return d->screen; } void KStartupInfoData::setXinerama(int xinerama) { d->xinerama = xinerama; } int KStartupInfoData::xinerama() const { return d->xinerama; } void KStartupInfoData::setLaunchedBy(WId window) { d->launched_by = window; } WId KStartupInfoData::launchedBy() const { return d->launched_by; } void KStartupInfoData::setApplicationId(const QString &desktop) { if (desktop.startsWith('/')) { d->application_id = desktop; return; } // the spec requires this is always a full path, in order for everyone to be able to find it QString desk = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, desktop); if (desk.isEmpty()) { desk = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kservices5/" + desktop); } if (desk.isEmpty()) { return; } d->application_id = desk; } QString KStartupInfoData::applicationId() const { return d->application_id; } static long get_num(const QString &item_P) { unsigned int pos = item_P.indexOf(QLatin1Char('=')); return item_P.mid(pos + 1).toLong(); } static QString get_str(const QString &item_P) { int pos = item_P.indexOf(QLatin1Char('=')); if (item_P.length() > pos + 2 && item_P.at(pos + 1) == QLatin1Char('\"')) { int pos2 = item_P.left(pos + 2).indexOf(QLatin1Char('\"')); if (pos2 < 0) { return QString(); // 01234 } return item_P.mid(pos + 2, pos2 - 2 - pos); // A="C" } return item_P.mid(pos + 1); } static QByteArray get_cstr(const QString &item_P) { return get_str(item_P).toUtf8(); } static QStringList get_fields(const QString &txt_P) { QString txt = txt_P.simplified(); QStringList ret; QString item = ""; bool in = false; bool escape = false; for (int pos = 0; pos < txt.length(); ++pos) { if (escape) { item += txt[ pos ]; escape = false; } else if (txt[ pos ] == '\\') { escape = true; } else if (txt[ pos ] == '\"') { in = !in; } else if (txt[ pos ] == ' ' && !in) { ret.append(item); item = ""; } else { item += txt[ pos ]; } } ret.append(item); return ret; } static QString escape_str(const QString &str_P) { QString ret = ""; for (int pos = 0; pos < str_P.length(); ++pos) { if (str_P[ pos ] == '\\' || str_P[ pos ] == '"') { ret += '\\'; } ret += str_P[ pos ]; } return ret; } #include "moc_kstartupinfo.cpp" diff --git a/src/kstartupinfo.h b/src/kstartupinfo.h index f6cf3de..80e4c82 100644 --- a/src/kstartupinfo.h +++ b/src/kstartupinfo.h @@ -1,746 +1,746 @@ /**************************************************************************** Copyright (C) 2001-2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef KSTARTUPINFO_H #define KSTARTUPINFO_H #include #include #include #include #include #include typedef struct _XDisplay Display; struct xcb_connection_t; #ifdef Q_CC_MSVC typedef int pid_t; #endif class KStartupInfoId; class KStartupInfoData; /** * Class for manipulating the application startup notification. * * This class can be used to send information about started application, * change the information and receive this information. For detailed * description, see kdelibs/kdecore/README.kstartupinfo. * * You usually don't need to use this class for sending the notification * information, as KDE libraries should do this when an application is * started (e.g. KRun class). * * For receiving the startup notification info, create an instance and connect * to its slots. It will automatically detect started applications and when * they are ready. * * @see KStartupInfoId * @see KStartupInfoData * * @author Lubos Lunak */ class KWINDOWSYSTEM_EXPORT KStartupInfo : public QObject { Q_OBJECT public: /** * Manual notification that the application has started. * If you do not map a (toplevel) window, then startup * notification will not disappear for the application * until a timeout. You can use this as an alternative * method in this case. */ static void appStarted(); /** * Sends explicit notification that the startup notification * with id startup_id should end. */ static void appStarted(const QByteArray &startup_id); /** * Returns the app startup notification identifier for this running * application. * @return the startup notification identifier */ static QByteArray startupId(); /** * Sets a new value for the application startup notification window property for newly * created toplevel windows. * @param startup_id the startup notification identifier * @see KStartupInfo::setNewStartupId */ static void setStartupId(const QByteArray &startup_id); /** * Use this function if the application got a request with startup * notification from outside (for example, when KUniqueApplication::newInstance() * is called, or e.g. when khelpcenter opens new URL in its window). * The window can be either an already existing and visible window, * or a new one, before being shown. Note that this function is usually * needed only when a window is reused. */ static void setNewStartupId(QWidget *window, const QByteArray &startup_id); /** * If your application shows temporarily some window during its startup, * for example a dialog, and only after closing it shows the main window, * startup notification would normally be shown while the dialog is visible. * To temporarily suspend and resume the notification, use this function. * Note that this is cumulative, i.e. after suspending twice, you have to * resume twice. */ static void silenceStartup(bool silence); /** * Creates and returns new startup id. The id includes properly setup * user timestamp. * * On the X11 platform the current timestamp will be fetched from the * X-Server. If the caller has an adaquat timestamp (e.g. from a QMouseEvent) * it should prefer using createNewStartupIdForTimestamp to not trigger a * roundtrip to the X-Server * * @see createNewStartupIdForTimestamp */ static QByteArray createNewStartupId(); /** * Creates and returns new startup id with @p timestamp as user timestamp part. * * @param timestamp The timestamp for the startup id. * @see createNewStartupId * @since 5.5 **/ static QByteArray createNewStartupIdForTimestamp(quint32 timestamp); /** * */ enum { CleanOnCantDetect = 1 << 0, DisableKWinModule = 1 << 1, AnnounceSilenceChanges = 1 << 2 }; /** * Creates an instance that will receive the startup notifications. * The various flags passed may be * @li CleanOnCantDetect - when a new unknown window appears, all startup * notifications for applications that are not compliant with * the startup protocol are removed * @li DisableKWinModule - KWinModule, which is normally used to detect * new windows, is disabled. With this flag, checkStartup() must be * called in order to check newly mapped windows. * @li AnnounceSilenceChanges - normally, startup notifications are * "removed" when they're silenced, and "recreated" when they're resumed. * With this flag, the change is normally announced with gotStartupChange(). * * @param flags OR-ed combination of flags * @param parent the parent of this QObject (can be 0 for no parent) * */ - explicit KStartupInfo(int flags, QObject *parent = 0); + explicit KStartupInfo(int flags, QObject *parent = nullptr); /** * Creates an instance that will receive the startup notifications. * * @param clean_on_cantdetect if true, and a new unknown window appears, * removes all notification for applications that are not compliant * with the app startup protocol * @param parent the parent of this QObject (can be 0 for no parent) * * @obsolete * @deprecated since 5.0 */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED - KWINDOWSYSTEM_DEPRECATED explicit KStartupInfo(bool clean_on_cantdetect, QObject *parent = 0); + KWINDOWSYSTEM_DEPRECATED explicit KStartupInfo(bool clean_on_cantdetect, QObject *parent = nullptr); #endif virtual ~KStartupInfo(); /** * Sends given notification data about started application * with the given startup identification. If no notification for this identification * exists yet, it is created, otherwise it's updated. Note that the name field * in data is required. * * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @see KStartupInfoId * @see KStartupInfoData */ static bool sendStartup(const KStartupInfoId &id, const KStartupInfoData &data); /** * Like sendStartup , uses dpy instead of qt_x11display() for sending the info. * @param dpy the display of the application. Note that the name field * in data is required. * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @deprecated since 5.18 use sendStartupXcb */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED static bool sendStartupX(Display *dpy, const KStartupInfoId &id, const KStartupInfoData &data); #endif /** * Like sendStartup , uses @p conn instead of QX11Info::connection() for sending the info. * @param conn the xcb connection of the application. Note that the name field * in data is required. * @param screen The x11 screen the connection belongs to * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @since 5.18 */ static bool sendStartupXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id, const KStartupInfoData &data); /** * Sends given notification data about started application * with the given startup identification. This is used for updating the notification * info, if no notification for this identification exists, it's ignored. * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @see KStartupInfoId * @see KStartupInfoData */ static bool sendChange(const KStartupInfoId &id, const KStartupInfoData &data); /** * Like sendChange , uses dpy instead of qt_x11display() for sending the info. * @param dpy the display of the application. * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @deprecated since 5.18 use sendChangeXcb */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED static bool sendChangeX(Display *dpy, const KStartupInfoId &id, const KStartupInfoData &data); #endif /** * Like sendChange , uses @p conn instead of QX11Info::connection() for sending the info. * @param conn the xcb connection of the application. * @param screen The x11 screen the connection belongs to * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @since 5.18 */ static bool sendChangeXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id, const KStartupInfoData &data); /** * Ends startup notification with the given identification. * @param id the id of the application * @return true if successful, false otherwise */ static bool sendFinish(const KStartupInfoId &id); /** * Like sendFinish , uses dpy instead of qt_x11display() for sending the info. * @param dpy the display of the application. * @param id the id of the application * @return true if successful, false otherwise * @deprecated since 5.18 use sendFinishXcb */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED static bool sendFinishX(Display *dpy, const KStartupInfoId &id); #endif /** * Like sendFinish , uses @p conn instead of QX11Info::connection() for sending the info. * @param conn the xcb connection of the application. * @param screen The x11 screen the connection belongs to * @param id the id of the application * @return true if successful, false otherwise * @since 5.18 */ static bool sendFinishXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id); /** * Ends startup notification with the given identification and the given data ( e.g. * PIDs of processes for this startup notification that exited ). * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise */ static bool sendFinish(const KStartupInfoId &id, const KStartupInfoData &data); /** * Like sendFinish , uses dpy instead of qt_x11display() for sending the info. * @param dpy the display of the application. * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @deprecated since 5.18 use sendFinishXcb */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED static bool sendFinishX(Display *dpy, const KStartupInfoId &id, const KStartupInfoData &data); #endif /** * Like sendFinish , uses @p conn instead of QX11Info::connection() for sending the info. * @param conn the xcb connection of the application. * @param screen The x11 screen the connection belongs to * @param id the id of the application * @param data the application's data * @return true if successful, false otherwise * @since 5.18 */ static bool sendFinishXcb(xcb_connection_t *conn, int screen, const KStartupInfoId &id, const KStartupInfoData &data); /** * Returns the current startup notification identification for the current * startup notification environment variable. Note that KApplication constructor * unsets the variable and you have to use KApplication::startupId . * @return the current startup notification identification */ static KStartupInfoId currentStartupIdEnv(); /** * Unsets the startup notification environment variable. */ static void resetStartupEnv(); /** * @li NoMatch - the window doesn't match any existing startup notification * @li Match - the window matches an existing startup notification * @li CantDetect - unable to detect if the window matches any existing * startup notification */ enum startup_t { NoMatch, Match, CantDetect }; /** * Checks if the given windows matches any existing startup notification. * @param w the window id to check * @return the result of the operation */ startup_t checkStartup(WId w); /** * Checks if the given windows matches any existing startup notification, and * if yes, returns the identification in id. * @param w the window id to check * @param id if found, the id of the startup notification will be written here * @return the result of the operation */ startup_t checkStartup(WId w, KStartupInfoId &id); /** * Checks if the given windows matches any existing startup notification, and * if yes, returns the notification data in data. * @param w the window id to check * @param data if found, the data of the startup notification will be written here * @return the result of the operation */ startup_t checkStartup(WId w, KStartupInfoData &data); /** * Checks if the given windows matches any existing startup notification, and * if yes, returns the identification in id and notification data in data. * @param w the window id to check * @param id if found, the id of the startup notification will be written here * @param data if found, the data of the startup notification will be written here * @return the result of the operation */ startup_t checkStartup(WId w, KStartupInfoId &id, KStartupInfoData &data); /** * Sets the timeout for notifications, after this timeout a notification is removed. * @param secs the new timeout in seconds */ void setTimeout(unsigned int secs); /** * Sets the startup notification window property on the given window. * @param window the id of the window * @param id the startup notification id */ static void setWindowStartupId(WId window, const QByteArray &id); /** * Returns startup notification identification of the given window. * @param w the id of the window * @return the startup notification id. Can be null if not found. */ static QByteArray windowStartupId(WId w); /** * @internal */ class Data; /** * @internal */ class Private; Q_SIGNALS: /** * Emitted when a new startup notification is created (i.e. a new application is * being started). * @param id the notification identification * @param data the notification data */ void gotNewStartup(const KStartupInfoId &id, const KStartupInfoData &data); /** * Emitted when a startup notification changes. * @param id the notification identification * @param data the notification data */ void gotStartupChange(const KStartupInfoId &id, const KStartupInfoData &data); /** * Emitted when a startup notification is removed (either because it was detected * that the application is ready or because of a timeout). * @param id the notification identification * @param data the notification data */ void gotRemoveStartup(const KStartupInfoId &id, const KStartupInfoData &data); protected: /** * */ void customEvent(QEvent *e_P) Q_DECL_OVERRIDE; private: Q_PRIVATE_SLOT(d, void startups_cleanup()) Q_PRIVATE_SLOT(d, void startups_cleanup_no_age()) Q_PRIVATE_SLOT(d, void got_message(const QString &msg)) Q_PRIVATE_SLOT(d, void window_added(WId w)) Q_PRIVATE_SLOT(d, void slot_window_added(WId w)) Private *const d; Q_DISABLE_COPY(KStartupInfo) }; /** * Class representing an identification of application startup notification. * * Every existing notification about a starting application has its own unique * identification, that's used to identify and manipulate the notification. * * @see KStartupInfo * @see KStartupInfoData * * @author Lubos Lunak */ class KWINDOWSYSTEM_EXPORT KStartupInfoId { public: /** * Overloaded operator. * @return true if the notification identifications are the same */ bool operator==(const KStartupInfoId &id) const; /** * Overloaded operator. * @return true if the notification identifications are different */ bool operator!=(const KStartupInfoId &id) const; /** * Checks whether the identifier is valid. * @return true if this object doesn't represent a valid notification identification */ bool isNull() const; #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED bool none() const { return isNull(); } #endif /** * Initializes this object with the given identification ( which may be also "0" * for no notification ), or if "" is given, tries to read it from the startup * notification environment variable, and if it's not set, creates a new one. * @param id the new identification, "0" for no notification or "" to read * the environment variable */ void initId(const QByteArray &id = ""); /** * Returns the notification identifier as string. * @return the identification string for the notification */ const QByteArray &id() const; /** * Return the user timestamp for the startup notification, or 0 if no timestamp * is set. */ unsigned long timestamp() const; /** * Sets the startup notification environment variable to this identification. * @return true if successful, false otherwise */ bool setupStartupEnv() const; /** * Creates an empty identification */ KStartupInfoId(); /** * Copy constructor. */ KStartupInfoId(const KStartupInfoId &data); ~KStartupInfoId(); KStartupInfoId &operator=(const KStartupInfoId &data); bool operator<(const KStartupInfoId &id) const; private: explicit KStartupInfoId(const QString &txt); friend class KStartupInfo; friend class KStartupInfo::Private; struct Private; Private *const d; }; /** * Class representing data about an application startup notification. * * Such data include the icon of the starting application, the desktop on which * the application should start, the binary name of the application, etc. * * @see KStartupInfo * @see KStartupInfoId * * @author Lubos Lunak */ class KWINDOWSYSTEM_EXPORT KStartupInfoData { public: /** * Sets the binary name of the application ( e.g. 'kcontrol' ). * @param bin the new binary name of the application */ void setBin(const QString &bin); /** * Returns the binary name of the starting application * @return the new binary name of the application */ const QString &bin() const; /** * Sets the name for the notification (e.g. 'Control Center') */ void setName(const QString &name); /** * Returns the name of the startup notification. If it's not available, * it tries to use other information (binary name). * @return the name of the startup notification */ const QString &findName() const; /** * Returns the name of the startup notification, or empty if not available. * @return the name of the startup notification, or an empty string * if not set. */ const QString &name() const; /** * Sets the description for the notification (e.g. 'Launching Control Center'). * I.e. name() describes what is being started, while description() is * the actual action performed by the starting. */ void setDescription(const QString &descr); /** * Returns the description of the startup notification. If it's not available, * it returns name(). * @return the description of the startup notification */ const QString &findDescription() const; /** * Returns the name of the startup notification, or empty if not available. * @return the name of the startup notificaiton, or an empty string * if not set. */ const QString &description() const; /** * Sets the icon for the startup notification ( e.g. 'kcontrol' ) * @param icon the name of the icon */ void setIcon(const QString &icon); /** * Returns the icon of the startup notification, and if it's not available, * tries to get it from the binary name. * @return the name of the startup notification's icon, or the name of * the binary if not set */ const QString &findIcon() const; /** * Returns the icon of the startup notification, or empty if not available. * @return the name of the icon, or an empty string if not set. */ const QString &icon() const; /** * Sets the desktop for the startup notification ( i.e. the desktop on which * the starting application should appear ). * @param desktop the desktop for the startup notification */ void setDesktop(int desktop); /** * Returns the desktop for the startup notification. * @return the desktop for the startup notification */ int desktop() const; /** * Sets a WM_CLASS value for the startup notification, it may be used for increasing * the chance that the windows created by the starting application will be * detected correctly. * @param wmclass the WM_CLASS value for the startup notification */ void setWMClass(const QByteArray &wmclass); /** * Returns the WM_CLASS value for the startup notification, or binary name if not * available. * @return the WM_CLASS value for the startup notification, or the binary name * if not set */ const QByteArray findWMClass() const; /** * Returns the WM_CLASS value for the startup notification, or empty if not available. * @return the WM_CLASS value for the startup notification, or empty * if not set */ QByteArray WMClass() const; /** * Adds a PID to the list of processes that belong to the startup notification. It * may be used to increase the chance that the windows created by the starting * application will be detected correctly, and also for detecting if the application * has quit without creating any window. * @param pid the PID to add */ void addPid(pid_t pid); /** * Returns all PIDs for the startup notification. * @return the list of all PIDs */ QList< pid_t > pids() const; /** * Checks whether the given @p pid is in the list of PIDs for starup * notification. * @return true if the given @p pid is in the list of PIDs for the startup notification */ bool is_pid(pid_t pid) const; /** * Sets the hostname on which the application is starting. It's necessary to set * it if PIDs are set. * @param hostname the application's hostname. If it's a null string, the current hostname is used */ void setHostname(const QByteArray &hostname = QByteArray()); /** * Returns the hostname for the startup notification. * @return the hostname */ QByteArray hostname() const; /** * */ enum TriState { Yes, No, Unknown }; /** * Sets whether the visual feedback for this startup notification * should be silenced (temporarily suspended). */ void setSilent(TriState state); /** * Return the silence status for the startup notification. * @return KStartupInfoData::Yes if visual feedback is silenced */ TriState silent() const; /** * The X11 screen on which the startup notification is happening, -1 if unknown. */ int screen() const; /** * Sets the X11 screen on which the startup notification should happen. * This is usually not necessary to set, as it's set by default to QX11Info::screen(). */ void setScreen(int screen); /** * The Xinerama screen for the startup notification, -1 if unknown. */ int xinerama() const; /** * Sets the Xinerama screen for the startup notification ( i.e. the screeen on which * the starting application should appear ). * @param xinerama the Xinerama screen for the startup notification */ void setXinerama(int xinerama); /** * The toplevel window of the application that caused this startup notification, * 0 if unknown. */ WId launchedBy() const; /** * Sets the toplevel window of the application that caused this startup notification. * @param window window ID of the toplevel window that is responsible for this startup */ void setLaunchedBy(WId window); /** * The .desktop file used to initiate this startup notification, or empty. This information * should be used only to identify the application, not to read any additional information. * @since 4.5 **/ QString applicationId() const; /** * Sets the .desktop file that was used to initiate the startup notification. * @since 4.5 */ void setApplicationId(const QString &desktop); /** * Updates the notification data from the given data. Some data, such as the desktop * or the name, won't be rewritten if already set. * @param data the data to update */ void update(const KStartupInfoData &data); /** * Constructor. Initializes all the data to their default empty values. */ KStartupInfoData(); /** * Copy constructor. */ KStartupInfoData(const KStartupInfoData &data); ~KStartupInfoData(); KStartupInfoData &operator=(const KStartupInfoData &data); private: explicit KStartupInfoData(const QString &txt); friend class KStartupInfo; friend class KStartupInfo::Data; friend class KStartupInfo::Private; struct Private; Private *const d; }; #endif diff --git a/src/kwindowinfo.cpp b/src/kwindowinfo.cpp index 3ec001e..6ec16b3 100644 --- a/src/kwindowinfo.cpp +++ b/src/kwindowinfo.cpp @@ -1,418 +1,418 @@ /* * Copyright 2014 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "kwindowinfo.h" #include "kwindowinfo_p.h" #include "kwindowsystem.h" #include "pluginwrapper_p.h" #include #include "kwindowinfo_dummy_p.h" #include #include // private KWindowInfoPrivate *KWindowInfoPrivate::create(WId window, NET::Properties properties, NET::Properties2 properties2) { return KWindowSystemPluginWrapper::self().createWindowInfo(window, properties, properties2); } KWindowInfoPrivateDesktopFileNameExtension::KWindowInfoPrivateDesktopFileNameExtension() = default; KWindowInfoPrivateDesktopFileNameExtension::~KWindowInfoPrivateDesktopFileNameExtension() = default; KWindowInfoPrivatePidExtension::KWindowInfoPrivatePidExtension() = default; KWindowInfoPrivatePidExtension::~KWindowInfoPrivatePidExtension() = default; class KWindowInfoPrivate::Private { public: Private(WId window, NET::Properties properties, NET::Properties2 properties2); WId window; NET::Properties properties; NET::Properties2 properties2; KWindowInfoPrivateDesktopFileNameExtension *desktopFileNameExtension; KWindowInfoPrivatePidExtension *pidExtension; }; KWindowInfoPrivate::Private::Private(WId window, NET::Properties properties, NET::Properties2 properties2) : window(window) , properties(properties) , properties2(properties2) , desktopFileNameExtension(Q_NULLPTR) , pidExtension(Q_NULLPTR) { } KWindowInfoPrivate::KWindowInfoPrivate(WId window, NET::Properties properties, NET::Properties2 properties2) : d(new Private(window, properties, properties2)) { } KWindowInfoPrivate::~KWindowInfoPrivate() { } WId KWindowInfoPrivate::win() const { return d->window; } KWindowInfoPrivateDesktopFileNameExtension *KWindowInfoPrivate::desktopFileNameExtension() const { return d->desktopFileNameExtension; } void KWindowInfoPrivate::installDesktopFileNameExtension(KWindowInfoPrivateDesktopFileNameExtension *extension) { d->desktopFileNameExtension = extension; } KWindowInfoPrivatePidExtension *KWindowInfoPrivate::pidExtension() const { return d->pidExtension; } void KWindowInfoPrivate::installPidExtension(KWindowInfoPrivatePidExtension *extension) { d->pidExtension = extension; } KWindowInfoPrivateDummy::KWindowInfoPrivateDummy(WId window, NET::Properties properties, NET::Properties2 properties2) : KWindowInfoPrivate(window, properties, properties2) { } KWindowInfoPrivateDummy::~KWindowInfoPrivateDummy() { } bool KWindowInfoPrivateDummy::valid(bool withdrawn_is_valid) const { Q_UNUSED(withdrawn_is_valid) return false; } NET::States KWindowInfoPrivateDummy::state() const { - return 0; + return nullptr; } bool KWindowInfoPrivateDummy::isMinimized() const { return false; } NET::MappingState KWindowInfoPrivateDummy::mappingState() const { return NET::Visible; } NETExtendedStrut KWindowInfoPrivateDummy::extendedStrut() const { return NETExtendedStrut(); } NET::WindowType KWindowInfoPrivateDummy::windowType(NET::WindowTypes supported_types) const { Q_UNUSED(supported_types) return NET::Unknown; } QString KWindowInfoPrivateDummy::visibleName() const { return QString(); } QString KWindowInfoPrivateDummy::visibleNameWithState() const { return QString(); } QString KWindowInfoPrivateDummy::name() const { return QString(); } QString KWindowInfoPrivateDummy::visibleIconName() const { return QString(); } QString KWindowInfoPrivateDummy::visibleIconNameWithState() const { return QString(); } QString KWindowInfoPrivateDummy::iconName() const { return QString(); } bool KWindowInfoPrivateDummy::onAllDesktops() const { return false; } bool KWindowInfoPrivateDummy::isOnDesktop(int desktop) const { Q_UNUSED(desktop) return false; } int KWindowInfoPrivateDummy::desktop() const { return 0; } QStringList KWindowInfoPrivateDummy::activities() const { return QStringList(); } QRect KWindowInfoPrivateDummy::geometry() const { return QRect(); } QRect KWindowInfoPrivateDummy::frameGeometry() const { return QRect(); } WId KWindowInfoPrivateDummy::transientFor() const { return 0; } WId KWindowInfoPrivateDummy::groupLeader() const { return 0; } QByteArray KWindowInfoPrivateDummy::windowClassClass() const { return QByteArray(); } QByteArray KWindowInfoPrivateDummy::windowClassName() const { return QByteArray(); } QByteArray KWindowInfoPrivateDummy::windowRole() const { return QByteArray(); } QByteArray KWindowInfoPrivateDummy::clientMachine() const { return QByteArray(); } bool KWindowInfoPrivateDummy::actionSupported(NET::Action action) const { Q_UNUSED(action) return false; } // public KWindowInfo::KWindowInfo(WId window, NET::Properties properties, NET::Properties2 properties2) : d(KWindowInfoPrivate::create(window, properties, properties2)) { } KWindowInfo::KWindowInfo(const KWindowInfo &other) : d(other.d) { } KWindowInfo::~KWindowInfo() { } KWindowInfo &KWindowInfo::operator=(const KWindowInfo &other) { if (d != other.d) { d = other.d; } return *this; } #define DELEGATE(name, args) \ return d->name( args ); bool KWindowInfo::valid(bool withdrawn_is_valid) const { DELEGATE(valid, withdrawn_is_valid) } WId KWindowInfo::win() const { return d->win(); } NET::States KWindowInfo::state() const { DELEGATE(state, ) } bool KWindowInfo::hasState(NET::States s) const { return (state() & s) == s; } bool KWindowInfo::isMinimized() const { DELEGATE(isMinimized, ) } NET::MappingState KWindowInfo::mappingState() const { DELEGATE(mappingState, ) } NETExtendedStrut KWindowInfo::extendedStrut() const { DELEGATE(extendedStrut, ) } NET::WindowType KWindowInfo::windowType(NET::WindowTypes supported_types) const { DELEGATE(windowType, supported_types) } QString KWindowInfo::visibleName() const { DELEGATE(visibleName, ) } QString KWindowInfo::visibleNameWithState() const { DELEGATE(visibleNameWithState, ) } QString KWindowInfo::name() const { DELEGATE(name, ) } QString KWindowInfo::visibleIconName() const { DELEGATE(visibleIconName, ) } QString KWindowInfo::visibleIconNameWithState() const { DELEGATE(visibleIconNameWithState, ) } QString KWindowInfo::iconName() const { DELEGATE(iconName, ) } bool KWindowInfo::isOnCurrentDesktop() const { return isOnDesktop(KWindowSystem::currentDesktop()); } bool KWindowInfo::isOnDesktop(int desktop) const { DELEGATE(isOnDesktop, desktop) } bool KWindowInfo::onAllDesktops() const { DELEGATE(onAllDesktops, ) } int KWindowInfo::desktop() const { DELEGATE(desktop, ) } QStringList KWindowInfo::activities() const { DELEGATE(activities, ) } QRect KWindowInfo::geometry() const { DELEGATE(geometry, ) } QRect KWindowInfo::frameGeometry() const { DELEGATE(frameGeometry, ) } WId KWindowInfo::transientFor() const { DELEGATE(transientFor, ) } WId KWindowInfo::groupLeader() const { DELEGATE(groupLeader, ) } QByteArray KWindowInfo::windowClassClass() const { DELEGATE(windowClassClass, ) } QByteArray KWindowInfo::windowClassName() const { DELEGATE(windowClassName, ) } QByteArray KWindowInfo::windowRole() const { DELEGATE(windowRole, ) } QByteArray KWindowInfo::clientMachine() const { DELEGATE(clientMachine, ) } bool KWindowInfo::actionSupported(NET::Action action) const { DELEGATE(actionSupported, action) } QByteArray KWindowInfo::desktopFileName() const { if (auto extension = d->desktopFileNameExtension()) { return extension->desktopFileName(); } return QByteArray(); } int KWindowInfo::pid() const { if (auto extension = d->pidExtension()) { return extension->pid(); } return 0; } #undef DELEGATE diff --git a/src/kwindowinfo.h b/src/kwindowinfo.h index e43d72d..4469edc 100644 --- a/src/kwindowinfo.h +++ b/src/kwindowinfo.h @@ -1,599 +1,599 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Matthias Ettrich (ettrich@kde.org) Copyright (C) 2007 Lubos Lunak (l.lunak@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /* * kwindowinfo.h. Part of the KDE project. */ #ifndef KWINDOWINFO_H #define KWINDOWINFO_H #include #include //For WId #include #include #include class KWindowInfoPrivate; /** * This class provides information about a given window in the platform specific * windowing system. It provides the information for the current state when a * KWindowInfo instance gets created. The instance does not get updated when the * window changes. To get update about window changes connect to the * @link KWindowSystem::windowChanged windowChanged@endlink signal of KWindowSystem * and create a new KWindowInfo instance to reflect the current state. * * KWindowInfo does not encapsulate all information about the window. One needs to * request which information is required by passing the appropriate NET::Property and * NET::Property2 flags to the constructor. Please refer to the documentation of the * methods to see which flags are required. This is done to limit the interaction with * the underlying windowing system as fetching the information can cause several context * switches and roundtrips to a server instance (e.g. when using the X11 platform). * * Please note that KWindowInfo is an abstraction of the underlying windowing system * inspired by the X11 platform. Thus not all concepts apply to all platforms and some * methods might return a default value for some platforms. * * Example usage of this class illustrated by monitoring a QWidget for change of the * demands attention window state: * * @code * QWidget *widget = new QWidget(Q_NULLPTR); * widget->show(); // ensures native window gets created * connect(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged), * [window](WId winId, unsigned int properties) { * if (widget->winId() != winId) { * return; // not our window * } * if (properties & NET::WMState) { * // let's check whether our window is demanding attention * KWindowInfo info(widget->winId(), NET::WMState); * qDebug() << "Has demands attention: " << info.hasState(NET::DemandsAttention); * } * }); * @endcode */ class KWINDOWSYSTEM_EXPORT KWindowInfo { public: /** * Reads all the info about the given window. * * Only the information requested through the @p properties and @p properties2 * parameters are fetched. Refer to the methods you are interested in to see * which flags to pass. * * @param window The platform specific window identifier * @param properties Bitmask of NET::Property * @param properties2 Bitmask of NET::Property2 */ - KWindowInfo(WId window, NET::Properties properties, NET::Properties2 properties2 = 0); + KWindowInfo(WId window, NET::Properties properties, NET::Properties2 properties2 = nullptr); ~KWindowInfo(); /** * Returns false if this window info is not valid. * * In case the window does not exist @c false is returned. Also if there is no * appropriate implementation for KWindowInfo on the current windowing * system platform this method returns @c false. In that case all methods return a * default value and thus it is recommended to check whether valid returns @c true. * * @param withdrawn_is_valid if true, windows in the withdrawn state * (i.e. not managed) are also considered. This is usually not the case. */ bool valid(bool withdrawn_is_valid = false) const; /** * Returns the window identifier. */ WId win() const; /** * Returns the window's state flags. * * Requires NET::WMState passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMState); * if (info.valid()) * info.state(); * @endcode * * @see NET::State */ NET::States state() const; /** * Returns true if the window has the given state flag set. * * Requires NET::WMState passed as properties parameter to the constructor. * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMState); * if (info.valid()) * info.hasState(NET::DemandsAttention); * @endcode * * @see NET::State */ bool hasState(NET::States s) const; /** * Returns true if the window is minimized. * * Note that it is true only if the window is truly minimized, * not shaded or on another virtual desktops, * which makes it different from mappingState() == NET::Iconic * or QWidget::isMinimized(). * Requires NET::WMState and NET::XAWMState passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMState | NET::XAWMState); * if (info.valid()) * info.isMinimized(); * @endcode */ bool isMinimized() const; /** * Returns the mapping state of the window. * * Note that it's very likely that you don't want to use this function, * and use isOnDesktop(), isMinimized() etc. instead. * Requires NET::XAWMState passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::XAWMState); * if (info.valid()) * info.mappingState(); * @endcode * * @see NET::MappingState * @see isOnDesktop() * @see isMinimzed() */ NET::MappingState mappingState() const; /** * Returns the window extended (partial) strut. * * Requires NET::WM2ExtendedStrut passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2ExtendedStrut); * if (info.valid()) * info.extendedStrut(); * @endcode */ NETExtendedStrut extendedStrut() const; /** * Returns the window type of this window. * * The argument should be all window types your application supports. * Requires NET::WMWindowType passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMWindowType); * if (info.valid()) * info.windowType(NET::NormalMask | NET::DialogMask); * @endcode * * @see NET::WindowType * @see NET::WindowTypeMask */ NET::WindowType windowType(NET::WindowTypes supported_types) const; /** * Returns the visible name of the window. * * The visible name differs from the name by including possible <2> appended * when there are two or more windows with the same name. * Requires NET::WMVisibleName passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMVisibleName); * if (info.valid()) * info.visibleName(); * @endcode * * @see name() */ QString visibleName() const; /** * Returns a visible name with state. * * This is a simple convenience function that returns the * visible name but with parentheses around minimized windows. * Requires NET::WMVisibleName, NET::WMState and NET::XAWMState passed * as properties parameter to the constructor. * @return the window name with state * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMVisibleName | NET::WMState | NET::XAWMState); * if (info.valid()) * info.visibleNameWithState(); * @endcode * * @see visibleName() */ QString visibleNameWithState() const; /** * Returns the name of the window, as specified by the application. * * The difference to visibleName() is that this is the name provided by * the application without any modifications by the window manager. * You should often use visibleName() instead. * Requires NET::WMName passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMName); * if (info.valid()) * info.name(); * @endcode * * @see visibleName() */ QString name() const; /** * Returns the visible name of the window that should be shown in a taskbar. * * Note that this has nothing to do with normal icons but with an "iconic" * representation of the window. * Requires NET::WMVisibleIconName passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMVisibleIconName); * if (info.valid()) * info.visibleIconName(); * @endcode */ QString visibleIconName() const; /** * Returns a visible icon name with state. * * This is a simple convenience function that returns the * visible iconic name but with parentheses around minimized windows. * Note that this has nothing to do with normal icons. * Requires NET::WMVisibleIconName, NET::WMState and NET::XAWMState passed * as properties parameter to the constructor. * @return the window iconic name with state * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMVisibleIconName | NET::WMState | NET::XAWMState); * if (info.valid()) * info.visibleIconNameWithState(); * @endcode * * @see visibleIconName() */ QString visibleIconNameWithState() const; /** * Returns the name of the window that should be shown in taskbar. * * Note that this has nothing to do with normal icons but with an "iconic" * representation of the window. * Requires NET::WMIconName passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMIconName); * if (info.valid()) * info.iconName(); * @endcode */ QString iconName() const; /** * Returns true if the window is on the currently active virtual desktop. * * Requires NET::WMDesktop passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMDesktop); * if (info.valid()) * info.isOnCurrentDesktop(); * @endcode */ bool isOnCurrentDesktop() const; /** * Returns true if the window is on the given virtual desktop. * * Requires NET::WMDesktop passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMDesktop); * if (info.valid()) * info.isOnDesktop(KWindowSystem::currentDesktop()); * @endcode */ bool isOnDesktop(int desktop) const; /** * Returns true if the window is on all desktops. * * A window is on all desktops if desktop() returns NET::OnAllDesktops. * Requires NET::WMDesktop passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMDesktop); * if (info.valid()) * info.onAllDesktops(); * @endcode * * @see desktop() */ bool onAllDesktops() const; /** * Returns the virtual desktop this window is on. * * If the window is on all desktops NET::OnAllDesktops is returned. * You should prefer using isOnDesktop(). * Requires NET::WMDesktop passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMDesktop); * if (info.valid()) * info.desktop(); * @endcode * * @see isOnDesktop() */ int desktop() const; /** * Returns the list of activity UUIDs this window belongs to. * * The Plasma workspace allows the user to separate her work into * different activities, by assigning windows, documents etc. to * the specific ones. An activity is an abstract concept whose meaning * can differ from one user to another. Typical examples of activities * are "developing a KDE project", "studying the 19th century art", * "composing music", "lazing on a Sunday afternoon" etc. * * If the list is empty, or contains a null UUID, the window is on * all activities. * * Requires NET::WM2Activities passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2Activities); * if (info.valid()) * info.desktop(); * @endcode * * @note Activities are only supported on Plasma Workspace on X11 * * @since 5.0 */ QStringList activities() const; /** * Returns the position and size of the window contents. * * Requires NET::WMGeometry passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMGeometry); * if (info.valid()) * info.geometry(); * @endcode */ QRect geometry() const; /** * Returns the frame geometry of the window, i.e. including the window decoration. * * Requires NET::WMFrameExtents passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMFrameExtents); * if (info.valid()) * info.frameGeometry(); * @endcode */ QRect frameGeometry() const; /** * Returns the window identifier of the main window this window belongs to. * * On platform X11 this is the value of the WM_TRANSIENT_FOR property. * * Requires NET::WM2TransientFor passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2TransientFor); * if (info.valid()) * info.transientFor(); * @endcode */ WId transientFor() const; /** * Returns the leader window for the group the window is in, if any. * * Requires NET::WM2GroupLeader passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2GroupLeader); * if (info.valid()) * info.groupLeader(); * @endcode */ WId groupLeader() const; /** * Returns the class component of the window class for the window. * * On platform X11 this is part of the WM_CLASS property. * Requires NET::WM2WindowClass passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2WindowClass); * if (info.valid()) * info.windowClassClass(); * @endcode */ QByteArray windowClassClass() const; /** * Returns the name component of the window class for the window. * * On platform X11 this is part of the WM_CLASS property. * Requires NET::WM2WindowClass passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2WindowClass); * if (info.valid()) * info.windowClassName(); * @endcode */ QByteArray windowClassName() const; /** * Returns the window role for the window. * * On platform X11 this is the value of the WM_WINDOW_ROLE property. * Requires NET::WM2WindowRole passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2WindowRole); * if (info.valid()) * info.windowRole(); * @endcode */ QByteArray windowRole() const; /** * Returns the client machine for the window. * * On platform X11 this is the value of the WM_CLIENT_MACHINE property. * Requires NET::WM2ClientMachine passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2ClientMachine); * if (info.valid()) * info.clientMachine(); * @endcode */ QByteArray clientMachine() const; /** * Returns true if the given action is currently supported for the window. * * On platform X11 the supported actions are set by the window manager and * can differ depending on the window manager. * Requires NET::WM2AllowedActions passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2AllowedActions); * if (info.valid()) * info.actionSupported(NET::ActionClose); * @endcode */ bool actionSupported(NET::Action action) const; /** * Returns the desktop file name of the window's application if present. * * This is either the base name without full path and without file extension of the * desktop file for the window's application (e.g. "org.kde.foo"). * * If the application's desktop file name is not at a standard location it should be * the full path to the desktop file name (e.g. "/opt/kde/share/org.kde.foo.desktop"). * * Requires NET::WM2DesktopFileName passed as properties2 parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), 0, NET::WM2DesktopFileName); * if (info.valid()) * info.desktopFileName(); * @endcode * * @since 5.29 **/ QByteArray desktopFileName() const; /** * Returns the process ID of the window's application if present. * * Requires NET::WMPid passed as properties parameter to the constructor. * * @code * QWidget *window = new QWidget(Q_NULLPTR); * window->show(); * KWindowInfo info(window->winId(), NET::WMPid); * if (info.valid()) * info.desktopFileName(); * @endcode * * @since 5.29 */ int pid() const; /** * Copy constructor. */ KWindowInfo(const KWindowInfo &); /** * Assignment operator. */ KWindowInfo &operator=(const KWindowInfo &); private: QExplicitlySharedDataPointer d; }; #endif // multiple inclusion guard diff --git a/src/kwindowsystem.h b/src/kwindowsystem.h index a282ecd..27e9e09 100644 --- a/src/kwindowsystem.h +++ b/src/kwindowsystem.h @@ -1,759 +1,759 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Matthias Ettrich (ettrich@kde.org) Copyright (C) 2007 Lubos Lunak (l.lunak@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /* * kwindowsystem.h. Part of the KDE project. */ #ifndef KWINDOWSYSTEM_H #define KWINDOWSYSTEM_H #include #include #include //For WId #include #include class KWindowSystemPrivate; class NETWinInfo; /** * * Convenience access to certain properties and features of the * window manager. * * The class KWindowSystem provides information about the state of the * window manager and allows asking the window manager to change them * using a more high-level interface than the NETWinInfo/NETRootInfo * lowlevel classes. * * Because of limitiations of the way Qt is implemented on Mac OSX, the WId's * returned by methods in this class are not compatible with those expected * by other Qt methods. So while it should be fine to pass WId's retrieved by * for example calling the winId method on a QWidget to methods in this class * the reverse is not true. You should never pass a WId obtained from this class * to a Qt method accepting a WId parameter. * * @short Class for interaction with the window manager. * @author Matthias Ettrich (ettrich@kde.org) */ class KWINDOWSYSTEM_EXPORT KWindowSystem : public QObject, public NET { Q_OBJECT public: /** * Access to the singleton instance. Useful mainly for connecting to signals. */ static KWindowSystem *self(); /** * Returns the list of all toplevel windows currently managed by the * window manager in the order of creation. Please do not rely on * indexes of this list: Whenever you enter Qt's event loop in your * application, it may happen that entries are removed or added. * Your module should perhaps work on a copy of this list and verify a * window with hasWId() before any operations. * * Iteration over this list can be done easily with * \code * QList windows = KWindowSystem::windows(); * for (auto it = windows.cbegin(), end = windows.cend(); it != end; ++it) { * ... do something here, (*it) is the current WId. * } * \endcode * @return the list of all toplevel windows */ static QList windows(); /** * Test to see if @p id still managed at present. * @param id the window id to test * @return true if the window id is still managed **/ static bool hasWId(WId id); #ifndef KWINDOWSYSTEM_NO_DEPRECATED /** * Returns information about window @p win. It is recommended to check * whether the returned info is valid by calling the valid() method. * @param win the id of the window * @param properties all properties that should be retrieved (see NET::Property * enum for details). Unlisted properties cause related information to be invalid * in the returned data, but make this function faster when not all data is needed. * @param properties2 additional properties (see NET::Property2 enum) * @return the window information * @deprecated use KWindowInfo directly */ - KWINDOWSYSTEM_DEPRECATED static KWindowInfo windowInfo(WId win, NET::Properties properties, NET::Properties2 properties2 = 0); + KWINDOWSYSTEM_DEPRECATED static KWindowInfo windowInfo(WId win, NET::Properties properties, NET::Properties2 properties2 = nullptr); #endif /** * Returns the list of all toplevel windows currently managed by the * window manager in the current stacking order (from lower to * higher). May be useful for pagers. * @return the list of all toplevel windows in stacking order */ static QList stackingOrder(); /** * Returns the currently active window, or 0 if no window is active. * @return the window id of the active window, or 0 if no window is * active **/ static WId activeWindow(); /** * Requests that window @p win is activated. * * There are two ways how to activate a window, by calling * activateWindow() and forceActiveWindow(). Generally, * applications shouldn't make attempts to explicitly activate * their windows, and instead let the user to activate them. * In the special cases where this may be needed, applications * should use activateWindow(). Window manager may consider whether * this request wouldn't result in focus stealing, which * would be obtrusive, and may refuse the request. * * The usage of forceActiveWindow() is meant only for pagers * and similar tools, which represent direct user actions * related to window manipulation. * Except for rare cases, this request will be always honored, * and normal applications are forbidden to use it. * * In case of problems, consult the KWin README in the kdebase * package (kdebase/kwin/README), or ask on the kwin@kde.org * mailing list. * * @param win the id of the window to make active * @param time X server timestamp of the user activity that * caused this request */ static void activateWindow(WId win, long time = 0); /** * Sets window @p win to be the active window. Note that this * should be called only in special cases, applications * shouldn't force themselves or other windows to be the active * window. Generally, this call should used only by pagers * and similar tools. See the explanation in description * of activateWindow(). * * @param win the id of the window to make active * @param time X server timestamp of the user activity that * caused this request */ static void forceActiveWindow(WId win, long time = 0); /** * When application finishes some operation and wants to notify * the user about it, it can call demandAttention(). Instead * of activating the window, which could be obtrusive, the window * will be marked specially as demanding user's attention. * See also explanation in description of activateWindow(). * * Note that it's usually better to use KNotifyClient. */ static void demandAttention(WId win, bool set = true); /** * Returns true if a compositing manager is running (i.e. ARGB windows * are supported, effects will be provided, etc.). */ static bool compositingActive(); /** * Returns the current virtual desktop. * @return the current virtual desktop **/ static int currentDesktop(); /** * Returns the number of virtual desktops. * @return the number of virtual desktops **/ static int numberOfDesktops(); /** * Convenience function to set the current desktop to @p desktop. * See NETRootInfo. * @param desktop the number of the new desktop */ static void setCurrentDesktop(int desktop); /** * Sets window @p win to be present on all virtual desktops if @p * is true. Otherwise the window lives only on one single desktop. * * @param win the id of the window * @param b true to show the window on all desktops, false * otherwise */ static void setOnAllDesktops(WId win, bool b); /** * Moves window @p win to desktop @p desktop. * * @param win the id of the window * @param desktop the number of the new desktop */ static void setOnDesktop(WId win, int desktop); /** * Moves window @p win to activities @p activities. * * @param win the id of the window * @param activities the list of activity UUIDs * * @since 5.1 * @see KWindowInfo::activities */ static void setOnActivities(WId win, const QStringList &activities); /** * Sets the parent window of @p subwindow to be @p mainwindow. * This overrides the parent set the usual way as the QWidget parent, * but only for the window manager - e.g. stacking order and window grouping * will be affected, but features like automatic deletion of children * when the parent is deleted are unaffected and normally use * the QWidget parent. * * This function should be used before a dialog is shown for a window * that belongs to another application. */ static void setMainWindow(QWidget *subwindow, WId mainwindow); #ifndef KWINDOWSYSTEM_NO_DEPRECATED /** * Returns the WM_TRANSIENT_FOR property for the given window, i.e. the mainwindow * for this window. * * @param window the id of the window * @deprecated Use KWindowInfo::transientFor */ KWINDOWSYSTEM_DEPRECATED static WId transientFor(WId window); /** * Returns the leader window for the group the given window is in, if any. * @param window the id of the window * @deprecated Use KWindowInfo::groupLeader */ KWINDOWSYSTEM_DEPRECATED static WId groupLeader(WId window); #endif /** * Returns an icon for window @p win. * * If @p width and @p height are specified, the best icon for the requested * size is returned. * * If @p scale is true, the icon is smooth-scaled to have exactly * the requested size. * * @param win the id of the window * @param width the desired width, or -1 * @param height the desired height, or -1 * @param scale if true the icon will be scaled to the desired size. Otherwise the * icon will not be modified. * @return the icon of the window */ static QPixmap icon(WId win, int width = -1, int height = -1, bool scale = false); /** * Masks specifying from which sources to read an icon. They are tried from the best * until an icon is found. * @li NETWM from property from the window manager specification * @li WMHints from WMHints property * @li ClassHint load icon after getting name from the classhint * @li XApp load the standard X icon (last fallback) */ enum IconSource { NETWM = 1, //!< read from property from the window manager specification WMHints = 2, //!< read from WMHints property ClassHint = 4, //!< load icon after getting name from the classhint XApp = 8 //! &excludes, int desktop = -1); /** * Returns the name of the specified desktop. * @param desktop the number of the desktop * @return the name of the desktop **/ static QString desktopName(int desktop); /** * Sets the name of the specified desktop. * @param desktop the number of the desktop * @param name the new name for the desktop **/ static void setDesktopName(int desktop, const QString &name); /** * Returns the state of showing the desktop. */ static bool showingDesktop(); /** * Sets the state of the "showing desktop" mode of the window manager. If on, * windows are hidden and desktop background is shown and focused. * * @param showing if true, the window manager is put in "showing desktop" mode. * If false, the window manager is put out of that mode. * * @since 5.7.0 */ static void setShowingDesktop(bool showing); /** * Sets user timestamp @p time on window @p win. The timestamp * is expressed as XServer time. If a window * is shown with user timestamp older than the time of the last * user action, it won't be activated after being shown. * The most common case is the special value 0 which means * not to activate the window after being shown. */ static void setUserTime(WId win, long time); /** * Sets the strut of window @p win to @p to @p left width * ranging from @p left_start to @p left_end on the left edge, * and simiarly for the other edges. For not reserving a strut, pass 0 as the width. * E.g. to reserve 10x10 square in the topleft corner, use e.g. * setExtendedStrut( w, 10, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0 ). * * @param win the id of the window * @param left_width width of the strut at the left edge * @param left_start starting y coordinate of the strut at the left edge * @param left_end ending y coordinate of the strut at the left edge * @param right_width width of the strut at the right edge * @param right_start starting y coordinate of the strut at the right edge * @param right_end ending y coordinate of the strut at the right edge * @param top_width width of the strut at the top edge * @param top_start starting x coordinate of the strut at the top edge * @param top_end ending x coordinate of the strut at the top edge * @param bottom_width width of the strut at the bottom edge * @param bottom_start starting x coordinate of the strut at the bottom edge * @param bottom_end ending x coordinate of the strut at the bottom edge */ static void setExtendedStrut(WId win, int left_width, int left_start, int left_end, int right_width, int right_start, int right_end, int top_width, int top_start, int top_end, int bottom_width, int bottom_start, int bottom_end); /** * Convenience function for setExtendedStrut() that automatically makes struts * as wide/high as the screen width/height. * Sets the strut of window @p win to @p left, @p right, @p top, @p bottom. * * @param win the id of the window * @param left the left strut * @param right the right strut * @param top the top strut * @param bottom the bottom strut */ static void setStrut(WId win, int left, int right, int top, int bottom); /** * Returns true if the WM announces which actions it allows for windows. */ static bool allowedActionsSupported(); /** * Function that reads and returns the contents of the given text * property (WM_NAME, WM_ICON_NAME,...). */ static QString readNameProperty(WId window, unsigned long atom); /** * Allows a window from another process to raise and activate itself. * Depending on the window manager, the grant may only be temporary, * or for a single activation, and it may require the current process * to be the "foreground" one" (ie. the process with the input focus). * * You should call this function before executing actions that may trigger * the showing of a window or dialog in another process, e.g. a dbus signal * or function call, or any other inter-process notification mechanism. * * This is mostly used on Windows, where windows are not allowed to be raised * and activated if their process is not the foreground one, but it may also * apply to other window managers. * * @param pid if specified, the grant only applies to windows belonging to the * specific process. By default, a value of -1 means all processes. */ static void allowExternalProcessWindowActivation(int pid = -1); /** * Sets whether the client wishes to block compositing (for better performance) * @since 4.7 */ static void setBlockingCompositing(WId window, bool active); /** * @internal * Returns true if viewports are mapped to virtual desktops. */ static bool mapViewport(); /** * @internal * Returns mapped virtual desktop for the given position in the viewport. */ static int viewportToDesktop(const QPoint &pos); /** * @internal * Returns mapped virtual desktop for the given window geometry. */ static int viewportWindowToDesktop(const QRect &r); /** * @internal * Returns topleft corner of the viewport area for the given mapped virtual desktop. */ static QPoint desktopToViewport(int desktop, bool absolute); /** * @internal * @since 4.0.1 * Checks the relative difference used to move a window will still be inside * valid desktop area. */ static QPoint constrainViewportRelativePosition(const QPoint &pos); /** * Enum describing the windowing system platform used by the QGuiApplication. * @see platform * @since 5.25 **/ enum class Platform { /** * A platform unknown to the application is used **/ Unknown, /** * The xcb/X11 windowing system platorm. **/ X11, /** * The Wayland windowing system platform. **/ Wayland }; /** * Returns the Platform used by the QGuiApplication. * This method allows to check for the used windowing system in a cheap and reliable way. * The Platform gets resolved the first time the method is invoked and cached for further * usages. * @returns The Platform used by the QGuiApplication. * @since 5.25 **/ static Platform platform(); /** * Convenience method to check whether the Platform is X11. * @see platform * @see isPlatformWayland * @since 5.25 **/ static bool isPlatformX11(); /** * Convenience method to check whether the Platform is Wayland. * @see platform * @see isPlatformX11 * @since 5.25 **/ static bool isPlatformWayland(); Q_SIGNALS: /** * Switched to another virtual desktop. * @param desktop the number of the new desktop */ void currentDesktopChanged(int desktop); /** * A window has been added. * @param id the id of the window */ void windowAdded(WId id); /** * A window has been removed. * @param id the id of the window that has been removed */ void windowRemoved(WId id); /** * Hint that \ is active (= has focus) now. * @param id the id of the window that is active */ void activeWindowChanged(WId id); /** * Desktops have been renamed. */ void desktopNamesChanged(); /** * The number of desktops changed. * @param num the new number of desktops */ void numberOfDesktopsChanged(int num); /** * The workarea has changed. */ void workAreaChanged(); /** * Something changed with the struts, may or may not have changed * the work area. Usually just using the workAreaChanged() signal * is sufficient. */ void strutChanged(); /** * Emitted when the stacking order of the window changed. The new order * can be obtained with stackingOrder(). */ void stackingOrderChanged(); /** * The window changed. * * Carries the NET::Properties and NET::Properties2 that were changed. * * @param id the id of the window * @param properties the properties that were modified * @param properties2 the properties2 that were modified * * @since 5.0 **/ void windowChanged(WId id, NET::Properties properties, NET::Properties2 properties2); /** * The window changed. * * The properties parameter contains the NET properties that * were modified (see netwm_def.h). First element are NET::Property * values, second element are NET::Property2 values (i.e. the format * is the same like for the NETWinInfo class constructor). * @param id the id of the window * @param properties the properties that were modified * * @deprecated since 5.0 use windowChanged(WId, NET::Properties, NET::Properties2) */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED QT_MOC_COMPAT void windowChanged(WId id, const unsigned long *properties); #endif /** * @deprecated * The window changed. * * The unsigned int parameter contains the NET properties that * were modified (see netwm_def.h). * @param id the id of the window * @param properties the properties that were modified */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED QT_MOC_COMPAT void windowChanged(WId id, unsigned int properties); #endif /** * The window changed somehow. * @param id the id of the window */ void windowChanged(WId id); /** * The state of showing the desktop has changed. */ void showingDesktopChanged(bool showing); /** * Compositing was enabled or disabled. * * Note that this signal may be emitted before any compositing plugins * have been initialized in the window manager. * * If you need to check if a specific compositing plugin such as the * blur effect is enabled, you should track that separately rather * than test for it in a slot connected to this signal. * * @since 4.7.1 */ void compositingChanged(bool enabled); protected: void connectNotify(const QMetaMethod &signal) Q_DECL_OVERRIDE; private: friend class KWindowSystemStaticContainer; KWindowSystem() {} static KWindowSystemPrivate *d_func(); }; #endif diff --git a/src/kwindowsystemplugininterface_p.h b/src/kwindowsystemplugininterface_p.h index 4291604..5f8103d 100644 --- a/src/kwindowsystemplugininterface_p.h +++ b/src/kwindowsystemplugininterface_p.h @@ -1,46 +1,46 @@ /* * Copyright 2015 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #ifndef KWINDOWSYSTEMPLUGININTERFACE_P_H #define KWINDOWSYSTEMPLUGININTERFACE_P_H #include #include "netwm_def.h" #include #include //For WId class KWindowEffectsPrivate; class KWindowInfoPrivate; class KWindowSystemPrivate; class KWINDOWSYSTEM_EXPORT KWindowSystemPluginInterface : public QObject { Q_OBJECT public: - explicit KWindowSystemPluginInterface(QObject *parent = 0); + explicit KWindowSystemPluginInterface(QObject *parent = nullptr); virtual ~KWindowSystemPluginInterface(); virtual KWindowEffectsPrivate *createEffects(); virtual KWindowSystemPrivate *createWindowSystem(); virtual KWindowInfoPrivate *createWindowInfo(WId window, NET::Properties properties, NET::Properties2 properties2); }; Q_DECLARE_INTERFACE(KWindowSystemPluginInterface, "org.kde.kwindowsystem.KWindowSystemPluginInterface") #endif diff --git a/src/netwm_def.h b/src/netwm_def.h index e191602..484361c 100644 --- a/src/netwm_def.h +++ b/src/netwm_def.h @@ -1,804 +1,804 @@ /* Copyright (c) 2000 Troll Tech AS Copyright (c) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef netwm_def_h #define netwm_def_h #include #include /** Simple point class for NET classes. This class is a convenience class defining a point x, y. The existence of this class is to keep the implementation from being dependent on a separate framework/library. NETPoint is only used by the NET API. Usually QPoint is the appropriate class for representing a point. @author Bradley T. Hughes **/ struct NETPoint { /** Constructor to initialize this point to 0,0. **/ NETPoint() : x(0), y(0) { } /* Public data member. **/ int x, ///< x coordinate. y; ///< y coordinate }; /** Simple size class for NET classes. This class is a convenience class defining a size width by height. The existence of this class is to keep the implementation from being dependent on a separate framework/library. NETSize is only used by the NET API. Usually QSize is the appropriate class for representing a size. @author Bradley T. Hughes **/ struct NETSize { /** Constructor to initialize this size to 0x0 **/ NETSize() : width(0), height(0) { } /* Public data member. **/ int width, ///< Width. height; ///< Height. }; /** Simple rectangle class for NET classes. This class is a convenience class defining a rectangle as a point x,y with a size width by height. The existence of this class is to keep the implementation from being dependent on a separate framework/library; NETRect is only used by the NET API. Usually QRect is the appropriate class for representing a rectangle. **/ struct NETRect { /** Position of the rectangle. @see NETPoint **/ NETPoint pos; /** Size of the rectangle. @see NETSize **/ NETSize size; }; /** Simple icon class for NET classes. This class is a convenience class defining an icon of size width by height. The existence of this class is to keep the implementation from being dependent on a separate framework/library. NETIcon is only used by the NET API. Usually QIcon is the appropriate class for representing an icon. **/ struct NETIcon { /** Constructor to initialize this icon to 0x0 with data=0 **/ - NETIcon() : data(0) { } + NETIcon() : data(nullptr) { } /** Size of the icon. @see NETSize **/ NETSize size; /** Image data for the icon. This is an array of 32bit packed CARDINAL ARGB with high byte being A, low byte being B. First two bytes are width, height. Data is in rows, left to right and top to bottom. **/ unsigned char *data; }; /** Partial strut class for NET classes. This class is a convenience class defining a strut with left, right, top and bottom border values, and ranges for them. The existence of this class is to keep the implementation from being dependent on a separate framework/library. See the _NET_WM_STRUT_PARTIAL property in the NETWM spec. **/ struct NETExtendedStrut { /** Constructor to initialize this struct to 0,0,0,0 **/ NETExtendedStrut() : left_width(0), left_start(0), left_end(0), right_width(0), right_start(0), right_end(0), top_width(0), top_start(0), top_end(0), bottom_width(0), bottom_start(0), bottom_end(0) {} /** Left border of the strut, width and range. **/ int left_width, left_start, left_end; /** Right border of the strut, width and range. **/ int right_width, right_start, right_end; /** Top border of the strut, width and range. **/ int top_width, top_start, top_end; /** Bottom border of the strut, width and range. **/ int bottom_width, bottom_start, bottom_end; }; /** @deprecated use NETExtendedStrut Simple strut class for NET classes. This class is a convenience class defining a strut with left, right, top and bottom border values. The existence of this class is to keep the implementation from being dependent on a separate framework/library. See the _NET_WM_STRUT property in the NETWM spec. **/ struct NETStrut { /** Constructor to initialize this struct to 0,0,0,0 **/ NETStrut() : left(0), right(0), top(0), bottom(0) { } /** Left border of the strut. **/ int left; /** Right border of the strut. **/ int right; /** Top border of the strut. **/ int top; /** Bottom border of the strut. **/ int bottom; }; /** Simple multiple monitor topology class for NET classes. This class is a convenience class, defining a multiple monitor topology for fullscreen applications that wish to be present on more than one monitor/head. As per the _NET_WM_FULLSCREEN_MONITORS hint in the EWMH spec, this topology consists of 4 monitor indices such that the bounding rectangle is defined by the top edge of the top monitor, the bottom edge of the bottom monitor, the left edge of the left monitor, and the right edge of the right monitor. See the _NET_WM_FULLSCREEN_MONITORS hint in the EWMH spec. **/ struct NETFullscreenMonitors { /** Constructor to initialize this struct to -1,0,0,0 (an initialized, albeit invalid, topology). **/ NETFullscreenMonitors() : top(-1), bottom(0), left(0), right(0) { } /** Monitor index whose top border defines the top edge of the topology. **/ int top; /** Monitor index whose bottom border defines the bottom edge of the topology. **/ int bottom; /** Monitor index whose left border defines the left edge of the topology. **/ int left; /** Monitor index whose right border defines the right edge of the topology. **/ int right; /** Convenience check to make sure that we are not holding the initial (invalid) values. Note that we don't want to call this isValid() because we're not actually validating the monitor topology here, but merely that our initial values were overwritten at some point by real (non-negative) monitor indices. **/ bool isSet() const { return (top != -1); } }; /** Base namespace class. The NET API is an implementation of the NET Window Manager Specification. This class is the base class for the NETRootInfo and NETWinInfo classes, which are used to retrieve and modify the properties of windows. To keep the namespace relatively clean, all enums are defined here. @see http://www.freedesktop.org/standards/wm-spec/ **/ class KWINDOWSYSTEM_EXPORT NET { public: /** Application role. This is used internally to determine how several action should be performed (if at all). **/ enum Role { /** indicates that the application is a client application. **/ Client, /** indicates that the application is a window manager application. **/ WindowManager }; /** Window type. **/ enum WindowType { /** indicates that the window did not define a window type. **/ Unknown = -1, /** indicates that this is a normal, top-level window **/ Normal = 0, /** indicates a desktop feature. This can include a single window containing desktop icons with the same dimensions as the screen, allowing the desktop environment to have full control of the desktop, without the need for proxying root window clicks. **/ Desktop = 1, /** indicates a dock or panel feature **/ Dock = 2, /** indicates a toolbar window **/ Toolbar = 3, /** indicates a pinnable (torn-off) menu window **/ Menu = 4, /** indicates that this is a dialog window **/ Dialog = 5, /** @deprecated has unclear meaning and is KDE-only **/ Override = 6, // NON STANDARD /** indicates a toplevel menu (AKA macmenu). This is a KDE extension to the _NET_WM_WINDOW_TYPE mechanism. **/ TopMenu = 7, // NON STANDARD /** indicates a utility window **/ Utility = 8, /** indicates that this window is a splash screen window. **/ Splash = 9, /** indicates a dropdown menu (from a menubar typically) **/ DropdownMenu = 10, /** indicates a popup menu (a context menu typically) **/ PopupMenu = 11, /** indicates a tooltip window **/ Tooltip = 12, /** indicates a notification window **/ Notification = 13, /** indicates that the window is a list for a combobox **/ ComboBox = 14, /** indicates a window that represents the dragged object during DND operation **/ DNDIcon = 15, /** indicates an On Screen Display window (such as volume feedback) @since 5.6 **/ OnScreenDisplay = 16 // NON STANDARD }; /** Values for WindowType when they should be OR'ed together, e.g. for the properties argument of the NETRootInfo constructor. **/ enum WindowTypeMask { NormalMask = 1u << 0, ///< @see Normal DesktopMask = 1u << 1, ///< @see Desktop DockMask = 1u << 2, ///< @see Dock ToolbarMask = 1u << 3, ///< @see Toolbar MenuMask = 1u << 4, ///< @see Menu DialogMask = 1u << 5, ///< @see Dialog OverrideMask = 1u << 6, ///< @see Override TopMenuMask = 1u << 7, ///< @see TopMenu UtilityMask = 1u << 8, ///< @see Utility SplashMask = 1u << 9, ///< @see Splash DropdownMenuMask = 1u << 10, ///< @see DropdownMenu PopupMenuMask = 1u << 11, ///< @see PopupMenu TooltipMask = 1u << 12, ///< @see Tooltip NotificationMask = 1u << 13, ///< @see Notification ComboBoxMask = 1u << 14, ///< @see ComboBox DNDIconMask = 1u << 15, ///< @see DNDIcon OnScreenDisplayMask = 1u << 16, ///< NON STANDARD @see OnScreenDisplay @since 5.6 AllTypesMask = 0U - 1 ///< All window types. }; Q_DECLARE_FLAGS(WindowTypes, WindowTypeMask) /** * Returns true if the given window type matches the mask given * using WindowTypeMask flags. */ static bool typeMatchesMask(WindowType type, WindowTypes mask); /** Window state. To set the state of a window, you'll typically do something like: \code KWindowSystem::setState( winId(), NET::SkipTaskbar | NET::SkipPager ); \endcode for example to not show the window on the taskbar and desktop pager. winId() is a function of QWidget() Note that KeepAbove (StaysOnTop) and KeepBelow are meant as user preference and applications should avoid setting these states themselves. **/ enum State { /** indicates that this is a modal dialog box. The WM_TRANSIENT_FOR hint MUST be set to indicate which window the dialog is a modal for, or set to the root window if the dialog is a modal for its window group. **/ Modal = 1u << 0, /** indicates that the Window Manager SHOULD keep the window's position fixed on the screen, even when the virtual desktop scrolls. Note that this is different from being kept on all desktops. **/ Sticky = 1u << 1, /** indicates that the window is vertically maximized. **/ MaxVert = 1u << 2, /** indicates that the window is horizontally maximized. **/ MaxHoriz = 1u << 3, /** convenience value. Equal to MaxVert | MaxHoriz. **/ Max = MaxVert | MaxHoriz, /** indicates that the window is shaded (rolled-up). **/ Shaded = 1u << 4, /** indicates that a window should not be included on a taskbar. **/ SkipTaskbar = 1u << 5, /** indicates that a window should on top of most windows (but below fullscreen windows). **/ KeepAbove = 1u << 6, /** @deprecated This is an obsolete name for KeepAbove. **/ StaysOnTop = KeepAbove, // NOT STANDARD /** indicates that a window should not be included on a pager. **/ SkipPager = 1u << 7, /** indicates that a window should not be visible on the screen (e.g. when minimised). Only the window manager is allowed to change it. **/ Hidden = 1u << 8, /** indicates that a window should fill the entire screen and have no window decorations. **/ FullScreen = 1u << 9, /** indicates that a window should be below most windows (but above any desktop windows). **/ KeepBelow = 1u << 10, /** there was an attempt to activate this window, but the window manager prevented this. E.g. taskbar should mark such window specially to bring user's attention to this window. Only the window manager is allowed to change it. **/ DemandsAttention = 1u << 11 }; Q_DECLARE_FLAGS(States, State) /** Direction for WMMoveResize. When a client wants the Window Manager to start a WMMoveResize, it should specify one of: @li TopLeft @li Top @li TopRight @li Right @li BottomRight @li Bottom @li BottomLeft @li Left @li Move (for movement only) @li KeyboardSize (resizing via keyboard) @li KeyboardMove (movement via keyboard) **/ enum Direction { TopLeft = 0, Top = 1, TopRight = 2, Right = 3, BottomRight = 4, Bottom = 5, BottomLeft = 6, Left = 7, Move = 8, // movement only KeyboardSize = 9, // size via keyboard KeyboardMove = 10, // move via keyboard MoveResizeCancel = 11 // to ask the WM to stop moving a window }; /** Client window mapping state. The class automatically watches the mapping state of the client windows, and uses the mapping state to determine how to set/change different properties. Note that this is very lowlevel and you most probably don't want to use this state. **/ enum MappingState { /** indicates the client window is visible to the user. **/ Visible = 1, //NormalState, /** indicates that neither the client window nor its icon is visible. **/ Withdrawn = 0, //WithdrawnState, /** indicates that the client window is not visible, but its icon is. This can be when the window is minimized or when it's on a different virtual desktop. See also NET::Hidden. **/ Iconic = 3 // IconicState }; /** Actions that can be done with a window (_NET_WM_ALLOWED_ACTIONS). **/ enum Action { ActionMove = 1u << 0, ActionResize = 1u << 1, ActionMinimize = 1u << 2, ActionShade = 1u << 3, ActionStick = 1u << 4, ActionMaxVert = 1u << 5, ActionMaxHoriz = 1u << 6, ActionMax = ActionMaxVert | ActionMaxHoriz, ActionFullScreen = 1u << 7, ActionChangeDesktop = 1u << 8, ActionClose = 1u << 9 }; Q_DECLARE_FLAGS(Actions, Action) /** Supported properties. Clients and Window Managers must define which properties/protocols it wants to support. Root/Desktop window properties and protocols: @li Supported @li ClientList @li ClientListStacking @li NumberOfDesktops @li DesktopGeometry @li DesktopViewport @li CurrentDesktop @li DesktopNames @li ActiveWindow @li WorkArea @li SupportingWMCheck @li VirtualRoots @li CloseWindow @li WMMoveResize Client window properties and protocols: @li WMName @li WMVisibleName @li WMDesktop @li WMWindowType @li WMState @li WMStrut (obsoleted by WM2ExtendedStrut) @li WMGeometry @li WMFrameExtents @li WMIconGeometry @li WMIcon @li WMIconName @li WMVisibleIconName @li WMHandledIcons @li WMPid @li WMPing ICCCM properties (provided for convenience): @li XAWMState **/ enum Property { // root Supported = 1u << 0, ClientList = 1u << 1, ClientListStacking = 1u << 2, NumberOfDesktops = 1u << 3, DesktopGeometry = 1u << 4, DesktopViewport = 1u << 5, CurrentDesktop = 1u << 6, DesktopNames = 1u << 7, ActiveWindow = 1u << 8, WorkArea = 1u << 9, SupportingWMCheck = 1u << 10, VirtualRoots = 1u << 11, // CloseWindow = 1u << 13, WMMoveResize = 1u << 14, // window WMName = 1u << 15, WMVisibleName = 1u << 16, WMDesktop = 1u << 17, WMWindowType = 1u << 18, WMState = 1u << 19, WMStrut = 1u << 20, WMIconGeometry = 1u << 21, WMIcon = 1u << 22, WMPid = 1u << 23, WMHandledIcons = 1u << 24, WMPing = 1u << 25, XAWMState = 1u << 27, WMFrameExtents = 1u << 28, // Need to be reordered WMIconName = 1u << 29, WMVisibleIconName = 1u << 30, WMGeometry = 1u << 31, WMAllProperties = ~0u }; Q_DECLARE_FLAGS(Properties, Property) /** Supported properties. This enum is an extension to NET::Property, because them enum is limited only to 32 bits. Client window properties and protocols: @li WM2UserTime @li WM2StartupId @li WM2TransientFor mainwindow for the window (WM_TRANSIENT_FOR) @li WM2GroupLeader group leader (window_group in WM_HINTS) @li WM2AllowedActions @li WM2RestackWindow @li WM2MoveResizeWindow @li WM2ExtendedStrut @li WM2TemporaryRules internal, for kstart @li WM2WindowClass WM_CLASS @li WM2WindowRole WM_WINDOW_ROLE @li WM2ClientMachine WM_CLIENT_MACHINE @li WM2ShowingDesktop @li WM2Opacity _NET_WM_WINDOW_OPACITY @li WM2DesktopLayout _NET_DESKTOP_LAYOUT @li WM2FullPlacement _NET_WM_FULL_PLACEMENT @li WM2FullscreenMonitors _NET_WM_FULLSCREEN_MONITORS @li WM2Urgency urgency hint in WM_HINTS (see ICCCM 4.1.2.4) @li WM2Input input hint (input in WM_HINTS, see ICCCM 4.1.2.4) @li WM2Protocols see NET::Protocol @li WM2InitialMappingState initial state hint of WM_HINTS (see ICCCM 4.1.2.4) @li WM2IconPixmap icon pixmap and mask in WM_HINTS (see ICCCM 4.1.2.4) @li WM2OpaqueRegion @li WM2DesktopFileName the base name of the desktop file name or the full path to the desktop file **/ enum Property2 { WM2UserTime = 1u << 0, WM2StartupId = 1u << 1, WM2TransientFor = 1u << 2, WM2GroupLeader = 1u << 3, WM2AllowedActions = 1u << 4, WM2RestackWindow = 1u << 5, WM2MoveResizeWindow = 1u << 6, WM2ExtendedStrut = 1u << 7, WM2KDETemporaryRules = 1u << 8, // NOT STANDARD WM2WindowClass = 1u << 9, WM2WindowRole = 1u << 10, WM2ClientMachine = 1u << 11, WM2ShowingDesktop = 1u << 12, WM2Opacity = 1u << 13, WM2DesktopLayout = 1u << 14, WM2FullPlacement = 1u << 15, WM2FullscreenMonitors = 1u << 16, WM2FrameOverlap = 1u << 17, // NOT STANDARD WM2Activities = 1u << 18, // NOT STANDARD @since 4.6 WM2BlockCompositing = 1u << 19, // NOT STANDARD @since 4.7, STANDARD @since 5.17 WM2KDEShadow = 1u << 20, // NOT Standard @since 4.7 WM2Urgency = 1u << 21, // @since 5.3 WM2Input = 1u << 22, // @since 5.3 WM2Protocols = 1u << 23, // @since 5.3 WM2InitialMappingState = 1u << 24, // @since 5.5 WM2IconPixmap = 1u << 25, // @since 5.7 WM2OpaqueRegion = 1u << 25, // @since 5.7 WM2DesktopFileName = 1u << 26, // NOT STANDARD @since 5.28 WM2AllProperties = ~0u }; Q_DECLARE_FLAGS(Properties2, Property2) /** Sentinel value to indicate that the client wishes to be visible on all desktops. **/ enum { OnAllDesktops = -1 }; /** Source of the request. **/ // must match the values for data.l[0] field in _NET_ACTIVE_WINDOW message enum RequestSource { /** @internal indicates that the source of the request is unknown **/ FromUnknown = 0, // internal /** indicates that the request comes from a normal application **/ FromApplication = 1, /** indicated that the request comes from pager or similar tool **/ FromTool = 2 }; /** Orientation. **/ enum Orientation { OrientationHorizontal = 0, OrientationVertical = 1 }; /** Starting corner for desktop layout. **/ enum DesktopLayoutCorner { DesktopLayoutCornerTopLeft = 0, DesktopLayoutCornerTopRight = 1, DesktopLayoutCornerBottomLeft = 2, DesktopLayoutCornerBottomRight = 3 }; /** * Protocols supported by the client. * See ICCCM 4.1.2.7. * * @since 5.3 **/ enum Protocol { NoProtocol = 0, TakeFocusProtocol = 1 << 0, ///< WM_TAKE_FOCUS DeleteWindowProtocol = 1 << 1, ///< WM_DELETE_WINDOW PingProtocol = 1 << 2, ///< _NET_WM_PING from EWMH SyncRequestProtocol = 1 << 3, ///< _NET_WM_SYNC_REQUEST from EWMH ContextHelpProtocol = 1 << 4 ///< _NET_WM_CONTEXT_HELP, NON STANDARD! }; Q_DECLARE_FLAGS(Protocols, Protocol) /** Compares two X timestamps, taking into account wrapping and 64bit architectures. Return value is like with strcmp(), 0 for equal, -1 for time1 < time2, 1 for time1 > time2. */ static int timestampCompare(unsigned long time1, unsigned long time2); /** Returns a difference of two X timestamps, time2 - time1, where time2 must be later than time1, as returned by timestampCompare(). */ static int timestampDiff(unsigned long time1, unsigned long time2); }; Q_DECLARE_OPERATORS_FOR_FLAGS(NET::Properties) Q_DECLARE_OPERATORS_FOR_FLAGS(NET::Properties2) Q_DECLARE_OPERATORS_FOR_FLAGS(NET::WindowTypes) Q_DECLARE_OPERATORS_FOR_FLAGS(NET::States) Q_DECLARE_OPERATORS_FOR_FLAGS(NET::Actions) Q_DECLARE_OPERATORS_FOR_FLAGS(NET::Protocols) #endif // netwm_def_h diff --git a/src/platforms/wayland/plugin.h b/src/platforms/wayland/plugin.h index 6f90e08..11ff43c 100644 --- a/src/platforms/wayland/plugin.h +++ b/src/platforms/wayland/plugin.h @@ -1,38 +1,38 @@ /* * Copyright 2015 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #ifndef KWINDOWSYSTEM_WAYLAND_PLUGIN_H #define KWINDOWSYSTEM_WAYLAND_PLUGIN_H #include "kwindowsystemplugininterface_p.h" class WaylandPlugin : public KWindowSystemPluginInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.kwindowsystem.KWindowSystemPluginInterface" FILE "wayland.json") Q_INTERFACES(KWindowSystemPluginInterface) public: - explicit WaylandPlugin(QObject *parent = 0); + explicit WaylandPlugin(QObject *parent = nullptr); virtual ~WaylandPlugin(); KWindowSystemPrivate *createWindowSystem() Q_DECL_OVERRIDE; }; #endif diff --git a/src/platforms/xcb/kkeyserver.cpp b/src/platforms/xcb/kkeyserver.cpp index b627422..4d9558e 100644 --- a/src/platforms/xcb/kkeyserver.cpp +++ b/src/platforms/xcb/kkeyserver.cpp @@ -1,944 +1,944 @@ /* Copyright (C) 2001 Ellis Whitehead Win32 port: Copyright (C) 2004 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kkeyserver_x11.h" #include "../../debug_p.h" #include #include # define XK_MISCELLANY # define XK_XKB_KEYS # include # include # include # include #include # define X11_ONLY(arg) arg, //allows to omit an argument // #define KKEYSERVER_DEBUG 1 namespace KKeyServer { //--------------------------------------------------------------------- // Data Structures //--------------------------------------------------------------------- struct Mod { int m_mod; }; //--------------------------------------------------------------------- // Array Structures //--------------------------------------------------------------------- struct X11ModInfo { int modQt; int modX; }; struct SymVariation { uint sym, symVariation; bool bActive; }; struct SymName { uint sym; const char *psName; }; struct TransKey { int keySymQt; uint keySymX; }; //--------------------------------------------------------------------- // Arrays //--------------------------------------------------------------------- static X11ModInfo g_rgX11ModInfo[4] = { { Qt::SHIFT, X11_ONLY(ShiftMask) }, { Qt::CTRL, X11_ONLY(ControlMask) }, { Qt::ALT, X11_ONLY(Mod1Mask) }, { Qt::META, X11_ONLY(Mod4Mask) } }; // These are the X equivalents to the Qt keycodes 0x1000 - 0x1026 static const TransKey g_rgQtToSymX[] = { { Qt::Key_Escape, XK_Escape }, { Qt::Key_Tab, XK_Tab }, { Qt::Key_Backtab, XK_ISO_Left_Tab }, { Qt::Key_Backspace, XK_BackSpace }, { Qt::Key_Return, XK_Return }, { Qt::Key_Enter, XK_KP_Enter }, { Qt::Key_Insert, XK_Insert }, { Qt::Key_Delete, XK_Delete }, { Qt::Key_Pause, XK_Pause }, #ifdef sun { Qt::Key_Print, XK_F22 }, #else { Qt::Key_Print, XK_Print }, #endif { Qt::Key_SysReq, XK_Sys_Req }, { Qt::Key_Home, XK_Home }, { Qt::Key_End, XK_End }, { Qt::Key_Left, XK_Left }, { Qt::Key_Up, XK_Up }, { Qt::Key_Right, XK_Right }, { Qt::Key_Down, XK_Down }, { Qt::Key_PageUp, XK_Prior }, { Qt::Key_PageDown, XK_Next }, //{ Qt::Key_Shift, 0 }, //{ Qt::Key_Control, 0 }, //{ Qt::Key_Meta, 0 }, //{ Qt::Key_Alt, 0 }, { Qt::Key_CapsLock, XK_Caps_Lock }, { Qt::Key_NumLock, XK_Num_Lock }, { Qt::Key_ScrollLock, XK_Scroll_Lock }, { Qt::Key_F1, XK_F1 }, { Qt::Key_F2, XK_F2 }, { Qt::Key_F3, XK_F3 }, { Qt::Key_F4, XK_F4 }, { Qt::Key_F5, XK_F5 }, { Qt::Key_F6, XK_F6 }, { Qt::Key_F7, XK_F7 }, { Qt::Key_F8, XK_F8 }, { Qt::Key_F9, XK_F9 }, { Qt::Key_F10, XK_F10 }, { Qt::Key_F11, XK_F11 }, { Qt::Key_F12, XK_F12 }, { Qt::Key_F13, XK_F13 }, { Qt::Key_F14, XK_F14 }, { Qt::Key_F15, XK_F15 }, { Qt::Key_F16, XK_F16 }, { Qt::Key_F17, XK_F17 }, { Qt::Key_F18, XK_F18 }, { Qt::Key_F19, XK_F19 }, { Qt::Key_F20, XK_F20 }, { Qt::Key_F21, XK_F21 }, { Qt::Key_F22, XK_F22 }, { Qt::Key_F23, XK_F23 }, { Qt::Key_F24, XK_F24 }, { Qt::Key_F25, XK_F25 }, { Qt::Key_F26, XK_F26 }, { Qt::Key_F27, XK_F27 }, { Qt::Key_F28, XK_F28 }, { Qt::Key_F29, XK_F29 }, { Qt::Key_F30, XK_F30 }, { Qt::Key_F31, XK_F31 }, { Qt::Key_F32, XK_F32 }, { Qt::Key_F33, XK_F33 }, { Qt::Key_F34, XK_F34 }, { Qt::Key_F35, XK_F35 }, { Qt::Key_Super_L, XK_Super_L }, { Qt::Key_Super_R, XK_Super_R }, { Qt::Key_Menu, XK_Menu }, { Qt::Key_Hyper_L, XK_Hyper_L }, { Qt::Key_Hyper_R, XK_Hyper_R }, { Qt::Key_Help, XK_Help }, //{ Qt::Key_Direction_L, XK_Direction_L }, These keys don't exist in X11 //{ Qt::Key_Direction_R, XK_Direction_R }, { '/', XK_KP_Divide }, { '*', XK_KP_Multiply }, { '-', XK_KP_Subtract }, { '+', XK_KP_Add }, { Qt::Key_Return, XK_KP_Enter } // the next lines are taken on 10/2009 from X.org (X11/XF86keysym.h), defining some special // multimedia keys. They are included here as not every system has them. #define XF86XK_MonBrightnessUp 0x1008FF02 #define XF86XK_MonBrightnessDown 0x1008FF03 #define XF86XK_KbdLightOnOff 0x1008FF04 #define XF86XK_KbdBrightnessUp 0x1008FF05 #define XF86XK_KbdBrightnessDown 0x1008FF06 #define XF86XK_Standby 0x1008FF10 #define XF86XK_AudioLowerVolume 0x1008FF11 #define XF86XK_AudioMute 0x1008FF12 #define XF86XK_AudioRaiseVolume 0x1008FF13 #define XF86XK_AudioPlay 0x1008FF14 #define XF86XK_AudioStop 0x1008FF15 #define XF86XK_AudioPrev 0x1008FF16 #define XF86XK_AudioNext 0x1008FF17 #define XF86XK_HomePage 0x1008FF18 #define XF86XK_Mail 0x1008FF19 #define XF86XK_Start 0x1008FF1A #define XF86XK_Search 0x1008FF1B #define XF86XK_AudioRecord 0x1008FF1C #define XF86XK_Calculator 0x1008FF1D #define XF86XK_Memo 0x1008FF1E #define XF86XK_ToDoList 0x1008FF1F #define XF86XK_Calendar 0x1008FF20 #define XF86XK_PowerDown 0x1008FF21 #define XF86XK_ContrastAdjust 0x1008FF22 #define XF86XK_Back 0x1008FF26 #define XF86XK_Forward 0x1008FF27 #define XF86XK_Stop 0x1008FF28 #define XF86XK_Refresh 0x1008FF29 #define XF86XK_PowerOff 0x1008FF2A #define XF86XK_WakeUp 0x1008FF2B #define XF86XK_Eject 0x1008FF2C #define XF86XK_ScreenSaver 0x1008FF2D #define XF86XK_WWW 0x1008FF2E #define XF86XK_Sleep 0x1008FF2F #define XF86XK_Favorites 0x1008FF30 #define XF86XK_AudioPause 0x1008FF31 #define XF86XK_AudioMedia 0x1008FF32 #define XF86XK_MyComputer 0x1008FF33 #define XF86XK_LightBulb 0x1008FF35 #define XF86XK_Shop 0x1008FF36 #define XF86XK_History 0x1008FF37 #define XF86XK_OpenURL 0x1008FF38 #define XF86XK_AddFavorite 0x1008FF39 #define XF86XK_HotLinks 0x1008FF3A #define XF86XK_BrightnessAdjust 0x1008FF3B #define XF86XK_Finance 0x1008FF3C #define XF86XK_Community 0x1008FF3D #define XF86XK_AudioRewind 0x1008FF3E #define XF86XK_BackForward 0x1008FF3F #define XF86XK_Launch0 0x1008FF40 #define XF86XK_Launch1 0x1008FF41 #define XF86XK_Launch2 0x1008FF42 #define XF86XK_Launch3 0x1008FF43 #define XF86XK_Launch4 0x1008FF44 #define XF86XK_Launch5 0x1008FF45 #define XF86XK_Launch6 0x1008FF46 #define XF86XK_Launch7 0x1008FF47 #define XF86XK_Launch8 0x1008FF48 #define XF86XK_Launch9 0x1008FF49 #define XF86XK_LaunchA 0x1008FF4A #define XF86XK_LaunchB 0x1008FF4B #define XF86XK_LaunchC 0x1008FF4C #define XF86XK_LaunchD 0x1008FF4D #define XF86XK_LaunchE 0x1008FF4E #define XF86XK_LaunchF 0x1008FF4F #define XF86XK_ApplicationLeft 0x1008FF50 #define XF86XK_ApplicationRight 0x1008FF51 #define XF86XK_Book 0x1008FF52 #define XF86XK_CD 0x1008FF53 #define XF86XK_Calculater 0x1008FF54 #define XF86XK_Clear 0x1008FF55 #define XF86XK_ClearGrab 0x1008FE21 #define XF86XK_Close 0x1008FF56 #define XF86XK_Copy 0x1008FF57 #define XF86XK_Cut 0x1008FF58 #define XF86XK_Display 0x1008FF59 #define XF86XK_DOS 0x1008FF5A #define XF86XK_Documents 0x1008FF5B #define XF86XK_Excel 0x1008FF5C #define XF86XK_Explorer 0x1008FF5D #define XF86XK_Game 0x1008FF5E #define XF86XK_Go 0x1008FF5F #define XF86XK_iTouch 0x1008FF60 #define XF86XK_LogOff 0x1008FF61 #define XF86XK_Market 0x1008FF62 #define XF86XK_Meeting 0x1008FF63 #define XF86XK_MenuKB 0x1008FF65 #define XF86XK_MenuPB 0x1008FF66 #define XF86XK_MySites 0x1008FF67 #define XF86XK_News 0x1008FF69 #define XF86XK_OfficeHome 0x1008FF6A #define XF86XK_Option 0x1008FF6C #define XF86XK_Paste 0x1008FF6D #define XF86XK_Phone 0x1008FF6E #define XF86XK_Reply 0x1008FF72 #define XF86XK_Reload 0x1008FF73 #define XF86XK_RotateWindows 0x1008FF74 #define XF86XK_RotationPB 0x1008FF75 #define XF86XK_RotationKB 0x1008FF76 #define XF86XK_Save 0x1008FF77 #define XF86XK_Send 0x1008FF7B #define XF86XK_Spell 0x1008FF7C #define XF86XK_SplitScreen 0x1008FF7D #define XF86XK_Support 0x1008FF7E #define XF86XK_TaskPane 0x1008FF7F #define XF86XK_Terminal 0x1008FF80 #define XF86XK_Tools 0x1008FF81 #define XF86XK_Travel 0x1008FF82 #define XF86XK_Video 0x1008FF87 #define XF86XK_Word 0x1008FF89 #define XF86XK_Xfer 0x1008FF8A #define XF86XK_ZoomIn 0x1008FF8B #define XF86XK_ZoomOut 0x1008FF8C #define XF86XK_Away 0x1008FF8D #define XF86XK_Messenger 0x1008FF8E #define XF86XK_WebCam 0x1008FF8F #define XF86XK_MailForward 0x1008FF90 #define XF86XK_Pictures 0x1008FF91 #define XF86XK_Music 0x1008FF92 #define XF86XK_Battery 0x1008FF93 #define XF86XK_Bluetooth 0x1008FF94 #define XF86XK_WLAN 0x1008FF95 #define XF86XK_UWB 0x1008FF96 #define XF86XK_AudioForward 0x1008FF97 #define XF86XK_AudioRepeat 0x1008FF98 #define XF86XK_AudioRandomPlay 0x1008FF99 #define XF86XK_Subtitle 0x1008FF9A #define XF86XK_AudioCycleTrack 0x1008FF9B #define XF86XK_Time 0x1008FF9F #define XF86XK_Select 0x1008FFA0 #define XF86XK_View 0x1008FFA1 #define XF86XK_TopMenu 0x1008FFA2 #define XF86XK_Suspend 0x1008FFA7 #define XF86XK_Hibernate 0x1008FFA8 #define XF86XK_TouchpadToggle 0x1008FFA9 #define XF86XK_TouchpadOn 0x1008FFB0 #define XF86XK_TouchpadOff 0x1008FFB1 #define XF86XK_AudioMicMute 0x1008FFB2 // end of XF86keysyms.h , // All of the stuff below really has to match qxcbkeyboard.cpp in Qt! { Qt::Key_Back, XF86XK_Back }, { Qt::Key_Forward, XF86XK_Forward }, { Qt::Key_Stop, XF86XK_Stop }, { Qt::Key_Refresh, XF86XK_Refresh }, { Qt::Key_Favorites, XF86XK_Favorites }, { Qt::Key_LaunchMedia, XF86XK_AudioMedia }, { Qt::Key_OpenUrl, XF86XK_OpenURL }, { Qt::Key_HomePage, XF86XK_HomePage }, { Qt::Key_Search, XF86XK_Search }, { Qt::Key_VolumeDown, XF86XK_AudioLowerVolume }, { Qt::Key_VolumeMute, XF86XK_AudioMute }, { Qt::Key_VolumeUp, XF86XK_AudioRaiseVolume }, { Qt::Key_MediaPlay, XF86XK_AudioPlay }, { Qt::Key_MediaStop, XF86XK_AudioStop }, { Qt::Key_MediaPrevious, XF86XK_AudioPrev }, { Qt::Key_MediaNext, XF86XK_AudioNext }, { Qt::Key_MediaRecord, XF86XK_AudioRecord }, { Qt::Key_LaunchMail, XF86XK_Mail }, { Qt::Key_Launch0, XF86XK_MyComputer }, { Qt::Key_Launch1, XF86XK_Calculator }, { Qt::Key_Memo, XF86XK_Memo }, { Qt::Key_ToDoList, XF86XK_ToDoList }, { Qt::Key_Calendar, XF86XK_Calendar }, { Qt::Key_PowerDown, XF86XK_PowerDown }, { Qt::Key_ContrastAdjust, XF86XK_ContrastAdjust }, { Qt::Key_Standby, XF86XK_Standby }, { Qt::Key_MonBrightnessUp, XF86XK_MonBrightnessUp }, { Qt::Key_MonBrightnessDown, XF86XK_MonBrightnessDown }, { Qt::Key_KeyboardLightOnOff, XF86XK_KbdLightOnOff }, { Qt::Key_KeyboardBrightnessUp, XF86XK_KbdBrightnessUp }, { Qt::Key_KeyboardBrightnessDown, XF86XK_KbdBrightnessDown }, { Qt::Key_PowerOff, XF86XK_PowerOff }, { Qt::Key_WakeUp, XF86XK_WakeUp }, { Qt::Key_Eject, XF86XK_Eject }, { Qt::Key_ScreenSaver, XF86XK_ScreenSaver }, { Qt::Key_WWW, XF86XK_WWW }, { Qt::Key_Sleep, XF86XK_Sleep }, { Qt::Key_LightBulb, XF86XK_LightBulb }, { Qt::Key_Shop, XF86XK_Shop }, { Qt::Key_History, XF86XK_History }, { Qt::Key_AddFavorite, XF86XK_AddFavorite }, { Qt::Key_HotLinks, XF86XK_HotLinks }, { Qt::Key_BrightnessAdjust, XF86XK_BrightnessAdjust }, { Qt::Key_Finance, XF86XK_Finance }, { Qt::Key_Community, XF86XK_Community }, { Qt::Key_AudioRewind, XF86XK_AudioRewind }, { Qt::Key_BackForward, XF86XK_BackForward }, { Qt::Key_ApplicationLeft, XF86XK_ApplicationLeft }, { Qt::Key_ApplicationRight, XF86XK_ApplicationRight }, { Qt::Key_Book, XF86XK_Book }, { Qt::Key_CD, XF86XK_CD }, { Qt::Key_Calculator, XF86XK_Calculater }, { Qt::Key_Clear, XF86XK_Clear }, { Qt::Key_ClearGrab, XF86XK_ClearGrab }, { Qt::Key_Close, XF86XK_Close }, { Qt::Key_Copy, XF86XK_Copy }, { Qt::Key_Cut, XF86XK_Cut }, { Qt::Key_Display, XF86XK_Display }, { Qt::Key_DOS, XF86XK_DOS }, { Qt::Key_Documents, XF86XK_Documents }, { Qt::Key_Excel, XF86XK_Excel }, { Qt::Key_Explorer, XF86XK_Explorer }, { Qt::Key_Game, XF86XK_Game }, { Qt::Key_Go, XF86XK_Go }, { Qt::Key_iTouch, XF86XK_iTouch }, { Qt::Key_LogOff, XF86XK_LogOff }, { Qt::Key_Market, XF86XK_Market }, { Qt::Key_Meeting, XF86XK_Meeting }, { Qt::Key_MenuKB, XF86XK_MenuKB }, { Qt::Key_MenuPB, XF86XK_MenuPB }, { Qt::Key_MySites, XF86XK_MySites }, { Qt::Key_News, XF86XK_News }, { Qt::Key_OfficeHome, XF86XK_OfficeHome }, { Qt::Key_Option, XF86XK_Option }, { Qt::Key_Paste, XF86XK_Paste }, { Qt::Key_Phone, XF86XK_Phone }, { Qt::Key_Reply, XF86XK_Reply }, { Qt::Key_Reload, XF86XK_Reload }, { Qt::Key_RotateWindows, XF86XK_RotateWindows }, { Qt::Key_RotationPB, XF86XK_RotationPB }, { Qt::Key_RotationKB, XF86XK_RotationKB }, { Qt::Key_Save, XF86XK_Save }, { Qt::Key_Send, XF86XK_Send }, { Qt::Key_Spell, XF86XK_Spell }, { Qt::Key_SplitScreen, XF86XK_SplitScreen }, { Qt::Key_Support, XF86XK_Support }, { Qt::Key_TaskPane, XF86XK_TaskPane }, { Qt::Key_Terminal, XF86XK_Terminal }, { Qt::Key_Tools, XF86XK_Tools }, { Qt::Key_Travel, XF86XK_Travel }, { Qt::Key_Video, XF86XK_Video }, { Qt::Key_Word, XF86XK_Word }, { Qt::Key_Xfer, XF86XK_Xfer }, { Qt::Key_ZoomIn, XF86XK_ZoomIn }, { Qt::Key_ZoomOut, XF86XK_ZoomOut }, { Qt::Key_Away, XF86XK_Away }, { Qt::Key_Messenger, XF86XK_Messenger }, { Qt::Key_WebCam, XF86XK_WebCam }, { Qt::Key_MailForward, XF86XK_MailForward }, { Qt::Key_Pictures, XF86XK_Pictures }, { Qt::Key_Music, XF86XK_Music }, { Qt::Key_Battery, XF86XK_Battery }, { Qt::Key_Bluetooth, XF86XK_Bluetooth }, { Qt::Key_WLAN, XF86XK_WLAN }, { Qt::Key_UWB, XF86XK_UWB }, { Qt::Key_AudioForward, XF86XK_AudioForward }, { Qt::Key_AudioRepeat, XF86XK_AudioRepeat }, { Qt::Key_AudioRandomPlay, XF86XK_AudioRandomPlay }, { Qt::Key_Subtitle, XF86XK_Subtitle }, { Qt::Key_AudioCycleTrack, XF86XK_AudioCycleTrack }, { Qt::Key_Time, XF86XK_Time }, { Qt::Key_Select, XF86XK_Select }, { Qt::Key_View, XF86XK_View }, { Qt::Key_TopMenu, XF86XK_TopMenu }, { Qt::Key_Bluetooth, XF86XK_Bluetooth }, { Qt::Key_Suspend, XF86XK_Suspend }, { Qt::Key_Hibernate, XF86XK_Hibernate }, { Qt::Key_TouchpadToggle, XF86XK_TouchpadToggle }, { Qt::Key_TouchpadOn, XF86XK_TouchpadOn }, { Qt::Key_TouchpadOff, XF86XK_TouchpadOff }, { Qt::Key_MicMute, XF86XK_AudioMicMute }, { Qt::Key_Launch2, XF86XK_Launch0 }, { Qt::Key_Launch3, XF86XK_Launch1 }, { Qt::Key_Launch4, XF86XK_Launch2 }, { Qt::Key_Launch5, XF86XK_Launch3 }, { Qt::Key_Launch6, XF86XK_Launch4 }, { Qt::Key_Launch7, XF86XK_Launch5 }, { Qt::Key_Launch8, XF86XK_Launch6 }, { Qt::Key_Launch9, XF86XK_Launch7 }, { Qt::Key_LaunchA, XF86XK_Launch8 }, { Qt::Key_LaunchB, XF86XK_Launch9 }, { Qt::Key_LaunchC, XF86XK_LaunchA }, { Qt::Key_LaunchD, XF86XK_LaunchB }, { Qt::Key_LaunchE, XF86XK_LaunchC }, { Qt::Key_LaunchF, XF86XK_LaunchD }, }; //--------------------------------------------------------------------- // Debugging //--------------------------------------------------------------------- #ifndef NDEBUG inline void checkDisplay() { // Some non-GUI apps might try to use us. if (!QX11Info::display()) { qCCritical(LOG_KKEYSERVER_X11) << "QX11Info::display() returns 0. I'm probably going to crash now." << endl; qCCritical(LOG_KKEYSERVER_X11) << "If this is a KApplication initialized without GUI stuff, change it to be " "initialized with GUI stuff." << endl; } } #else // NDEBUG # define checkDisplay() #endif //--------------------------------------------------------------------- // Initialization //--------------------------------------------------------------------- static bool g_bInitializedMods; static uint g_modXNumLock, g_modXScrollLock, g_modXModeSwitch, g_alt_mask, g_meta_mask, g_super_mask, g_hyper_mask; bool initializeMods() { // Reinitialize the masks g_modXNumLock = 0; g_modXScrollLock = 0; g_modXModeSwitch = 0; g_alt_mask = 0; g_meta_mask = 0; g_super_mask = 0; g_hyper_mask = 0; if (!QX11Info::isPlatformX11()) { qCWarning(LOG_KKEYSERVER_X11) << "X11 implementation of KKeyServer accessed from non-X11 platform! This is an application bug."; g_bInitializedMods = true; return false; } checkDisplay(); XModifierKeymap *xmk = XGetModifierMapping(QX11Info::display()); int min_keycode, max_keycode; int keysyms_per_keycode = 0; XDisplayKeycodes(QX11Info::display(), &min_keycode, &max_keycode); XFree(XGetKeyboardMapping(QX11Info::display(), min_keycode, 1, &keysyms_per_keycode)); for (int i = Mod1MapIndex; i < 8; i++) { uint mask = (1 << i); uint keySymX = NoSymbol; // This used to be only XKeycodeToKeysym( ... , 0 ), but that fails with XFree4.3.99 // and X.org R6.7 , where for some reason only ( ... , 1 ) works. I have absolutely no // idea what the problem is, but searching all possibilities until something valid is // found fixes the problem. for (int j = 0; j < xmk->max_keypermod; ++j) { for (int k = 0; k < keysyms_per_keycode; ++k) { keySymX = XKeycodeToKeysym(QX11Info::display(), xmk->modifiermap[xmk->max_keypermod * i + j], k); switch (keySymX) { case XK_Alt_L: case XK_Alt_R: g_alt_mask |= mask; break; case XK_Super_L: case XK_Super_R: g_super_mask |= mask; break; case XK_Hyper_L: case XK_Hyper_R: g_hyper_mask |= mask; break; case XK_Meta_L: case XK_Meta_R: g_meta_mask |= mask; break; case XK_Num_Lock: g_modXNumLock |= mask; break; case XK_Scroll_Lock: g_modXScrollLock |= mask; break; case XK_Mode_switch: g_modXModeSwitch |= mask; break; } } } } #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Alt:" << g_alt_mask; qCDebug(LOG_KKEYSERVER_X11) << "Meta:" << g_meta_mask; qCDebug(LOG_KKEYSERVER_X11) << "Super:" << g_super_mask; qCDebug(LOG_KKEYSERVER_X11) << "Hyper:" << g_hyper_mask; qCDebug(LOG_KKEYSERVER_X11) << "NumLock:" << g_modXNumLock; qCDebug(LOG_KKEYSERVER_X11) << "ScrollLock:" << g_modXScrollLock; qCDebug(LOG_KKEYSERVER_X11) << "ModeSwitch:" << g_modXModeSwitch; #endif // Check if hyper overlaps with super or meta or alt if (g_hyper_mask & (g_super_mask | g_meta_mask | g_alt_mask)) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Hyper conflicts with super, meta or alt."; #endif // Remove the conflicting masks g_hyper_mask &= ~(g_super_mask | g_meta_mask | g_alt_mask); } // Check if super overlaps with meta or alt if (g_super_mask & (g_meta_mask | g_alt_mask)) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Super conflicts with meta or alt."; #endif // Remove the conflicting masks g_super_mask &= ~(g_meta_mask | g_alt_mask); } // Check if meta overlaps with alt if (g_meta_mask | g_alt_mask) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Meta conflicts with alt."; #endif // Remove the conflicting masks g_meta_mask &= ~(g_alt_mask); } if (!g_meta_mask) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Meta is not set or conflicted with alt."; #endif if (g_super_mask) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Using super for meta"; #endif // Use Super g_meta_mask = g_super_mask; } else if (g_hyper_mask) { #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Using hyper for meta"; #endif // User Hyper g_meta_mask = g_hyper_mask; } else { // ???? Nothing left g_meta_mask = 0; } } #ifdef KKEYSERVER_DEBUG qCDebug(LOG_KKEYSERVER_X11) << "Alt:" << g_alt_mask; qCDebug(LOG_KKEYSERVER_X11) << "Meta:" << g_meta_mask; qCDebug(LOG_KKEYSERVER_X11) << "Super:" << g_super_mask; qCDebug(LOG_KKEYSERVER_X11) << "Hyper:" << g_hyper_mask; qCDebug(LOG_KKEYSERVER_X11) << "NumLock:" << g_modXNumLock; qCDebug(LOG_KKEYSERVER_X11) << "ScrollLock:" << g_modXScrollLock; qCDebug(LOG_KKEYSERVER_X11) << "ModeSwitch:" << g_modXModeSwitch; #endif if (!g_meta_mask) { qCWarning(LOG_KKEYSERVER_X11) << "Your keyboard setup doesn't provide a key to use for meta. See 'xmodmap -pm' or 'xkbcomp $DISPLAY'"; } g_rgX11ModInfo[2].modX = g_alt_mask; g_rgX11ModInfo[3].modX = g_meta_mask; XFreeModifiermap(xmk); g_bInitializedMods = true; return true; } //--------------------------------------------------------------------- // Public functions //--------------------------------------------------------------------- uint modXShift() { return ShiftMask; } uint modXCtrl() { return ControlMask; } uint modXAlt() { if (!g_bInitializedMods) { initializeMods(); } return g_alt_mask; } uint modXMeta() { if (!g_bInitializedMods) { initializeMods(); } return g_meta_mask; } uint modXNumLock() { if (!g_bInitializedMods) { initializeMods(); } return g_modXNumLock; } uint modXLock() { return LockMask; } uint modXScrollLock() { if (!g_bInitializedMods) { initializeMods(); } return g_modXScrollLock; } uint modXModeSwitch() { if (!g_bInitializedMods) { initializeMods(); } return g_modXModeSwitch; } bool keyboardHasMetaKey() { return modXMeta() != 0; } uint getModsRequired(uint sym) { if (!QX11Info::isPlatformX11()) { qCWarning(LOG_KKEYSERVER_X11) << "X11 implementation of KKeyServer accessed from non-X11 platform! This is an application bug."; return 0; } uint mod = 0; // FIXME: This might not be true on all keyboard layouts! if (sym == XK_Sys_Req) { return Qt::ALT; } if (sym == XK_Break) { return Qt::CTRL; } if (sym < 0x3000) { QChar c(sym); if (c.isLetter() && c.toLower() != c.toUpper() && sym == c.toUpper().unicode()) { return Qt::SHIFT; } } uchar code = XKeysymToKeycode(QX11Info::display(), sym); if (code) { // need to check index 0 before the others, so that a null-mod // can take precedence over the others, in case the modified // key produces the same symbol. if (sym == XKeycodeToKeysym(QX11Info::display(), code, 0)) ; else if (sym == XKeycodeToKeysym(QX11Info::display(), code, 1)) { mod = Qt::SHIFT; } else if (sym == XKeycodeToKeysym(QX11Info::display(), code, 2)) { mod = MODE_SWITCH; } else if (sym == XKeycodeToKeysym(QX11Info::display(), code, 3)) { mod = Qt::SHIFT | MODE_SWITCH; } } return mod; } bool keyQtToCodeX(int keyQt, int *keyCode) { if (!QX11Info::isPlatformX11()) { qCWarning(LOG_KKEYSERVER_X11) << "X11 implementation of KKeyServer accessed from non-X11 platform! This is an application bug."; return false; } int sym; uint mod; keyQtToSymX(keyQt, &sym); keyQtToModX(keyQt, &mod); // Get any extra mods required by the sym. // E.g., XK_Plus requires SHIFT on the en layout. uint modExtra = getModsRequired(sym); // Get the X modifier equivalent. if (!sym || !keyQtToModX((keyQt & Qt::KeyboardModifierMask) | modExtra, &mod)) { *keyCode = 0; return false; } *keyCode = XKeysymToKeycode(QX11Info::display(), sym); return true; } bool keyQtToSymX(int keyQt, int *keySym) { int symQt = keyQt & ~Qt::KeyboardModifierMask; if (symQt < 0x1000) { *keySym = QChar(symQt).toUpper().unicode(); return true; } for (uint i = 0; i < sizeof(g_rgQtToSymX) / sizeof(TransKey); i++) { if (g_rgQtToSymX[i].keySymQt == symQt) { *keySym = g_rgQtToSymX[i].keySymX; return true; } } *keySym = 0; if (symQt != Qt::Key_Shift && symQt != Qt::Key_Control && symQt != Qt::Key_Alt && symQt != Qt::Key_Meta && symQt != Qt::Key_Direction_L && symQt != Qt::Key_Direction_R) { // qCDebug(LOG_KKEYSERVER_X11) << "Sym::initQt( " << QString::number(keyQt,16) << " ): failed to convert key."; } return false; } bool symXToKeyQt(uint keySym, int *keyQt) { *keyQt = Qt::Key_unknown; if (keySym < 0x1000) { if (keySym >= 'a' && keySym <= 'z') { *keyQt = QChar(keySym).toUpper().unicode(); } else { *keyQt = keySym; } } else if (keySym < 0x3000) { *keyQt = keySym; } else { for (uint i = 0; i < sizeof(g_rgQtToSymX) / sizeof(TransKey); i++) if (g_rgQtToSymX[i].keySymX == keySym) { *keyQt = g_rgQtToSymX[i].keySymQt; break; } } return (*keyQt != Qt::Key_unknown); } /* are these things actually used anywhere? there's no way they can do anything on non-X11 */ bool keyQtToModX(int modQt, uint *modX) { if (!g_bInitializedMods) { initializeMods(); } *modX = 0; for (int i = 0; i < 4; i++) { if (modQt & g_rgX11ModInfo[i].modQt) { if (g_rgX11ModInfo[i].modX) { *modX |= g_rgX11ModInfo[i].modX; } else { // The qt modifier has no x equivalent. Return false return false; } } } return true; } bool modXToQt(uint modX, int *modQt) { if (!g_bInitializedMods) { initializeMods(); } *modQt = 0; for (int i = 0; i < 4; i++) { if (modX & g_rgX11ModInfo[i].modX) { *modQt |= g_rgX11ModInfo[i].modQt; continue; } } return true; } bool codeXToSym(uchar codeX, uint modX, uint *sym) { if (!QX11Info::isPlatformX11()) { qCWarning(LOG_KKEYSERVER_X11) << "X11 implementation of KKeyServer accessed from non-X11 platform! This is an application bug."; return false; } KeySym keySym; XKeyPressedEvent event; checkDisplay(); event.type = KeyPress; event.display = QX11Info::display(); event.state = modX; event.keycode = codeX; - XLookupString(&event, 0, 0, &keySym, 0); + XLookupString(&event, nullptr, 0, &keySym, nullptr); *sym = (uint) keySym; return true; } uint accelModMaskX() { return modXShift() | modXCtrl() | modXAlt() | modXMeta(); } bool xEventToQt(XEvent *e, int *keyQt) { Q_ASSERT(e->type == KeyPress || e->type == KeyRelease); uchar keyCodeX = e->xkey.keycode; uint keyModX = e->xkey.state & (accelModMaskX() | MODE_SWITCH); KeySym keySym; char buffer[16]; - XLookupString((XKeyEvent *) e, buffer, 15, &keySym, 0); + XLookupString((XKeyEvent *) e, buffer, 15, &keySym, nullptr); uint keySymX = (uint)keySym; // If numlock is active and a keypad key is pressed, XOR the SHIFT state. // e.g., KP_4 => Shift+KP_Left, and Shift+KP_4 => KP_Left. if (e->xkey.state & modXNumLock()) { uint sym = XKeycodeToKeysym(QX11Info::display(), keyCodeX, 0); // TODO: what's the xor operator in c++? // If this is a keypad key, if (sym >= XK_KP_Space && sym <= XK_KP_9) { switch (sym) { // Leave the following keys unaltered // FIXME: The proper solution is to see which keysyms don't change when shifted. case XK_KP_Multiply: case XK_KP_Add: case XK_KP_Subtract: case XK_KP_Divide: break; default: if (keyModX & modXShift()) { keyModX &= ~modXShift(); } else { keyModX |= modXShift(); } } } } int keyCodeQt; int keyModQt; symXToKeyQt(keySymX, &keyCodeQt); modXToQt(keyModX, &keyModQt); *keyQt = keyCodeQt | keyModQt; return true; } bool xcbKeyPressEventToQt(xcb_generic_event_t *e, int *keyQt) { if ((e->response_type & ~0x80) != XCB_KEY_PRESS && (e->response_type & ~0x80) != XCB_KEY_RELEASE) { return false; } return xcbKeyPressEventToQt(reinterpret_cast(e), keyQt); } bool xcbKeyPressEventToQt(xcb_key_press_event_t *e, int *keyQt) { xcb_keycode_t keyCodeX = e->detail; uint keyModX = e->state & (accelModMaskX() | MODE_SWITCH); xcb_key_symbols_t *symbols = xcb_key_symbols_alloc(QX11Info::connection()); xcb_keysym_t keySymX = xcb_key_symbols_get_keysym(symbols, keyCodeX, 0); // If numlock is active and a keypad key is pressed, XOR the SHIFT state. // e.g., KP_4 => Shift+KP_Left, and Shift+KP_4 => KP_Left. if (e->state & modXNumLock()) { // If this is a keypad key, if (keySymX >= XK_KP_Space && keySymX <= XK_KP_9) { switch (keySymX) { // Leave the following keys unaltered // FIXME: The proper solution is to see which keysyms don't change when shifted. case XK_KP_Multiply: case XK_KP_Add: case XK_KP_Subtract: case XK_KP_Divide: break; default: if (keyModX & modXShift()) { keyModX &= ~modXShift(); } else { keyModX |= modXShift(); } } } } int keyCodeQt; int keyModQt; symXToKeyQt(keySymX, &keyCodeQt); modXToQt(keyModX, &keyModQt); *keyQt = keyCodeQt | keyModQt; xcb_key_symbols_free(symbols); return true; } } // end of namespace KKeyServer block diff --git a/src/platforms/xcb/kselectionowner.cpp b/src/platforms/xcb/kselectionowner.cpp index 6abc89b..21a9d5d 100644 --- a/src/platforms/xcb/kselectionowner.cpp +++ b/src/platforms/xcb/kselectionowner.cpp @@ -1,608 +1,608 @@ /**************************************************************************** Copyright (C) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "kselectionowner.h" #include #include #include #include #include #include #include #include static xcb_window_t get_selection_owner(xcb_connection_t *c, xcb_atom_t selection) { xcb_window_t owner = XCB_NONE; - xcb_get_selection_owner_reply_t *reply = xcb_get_selection_owner_reply(c, xcb_get_selection_owner(c, selection), 0); + xcb_get_selection_owner_reply_t *reply = xcb_get_selection_owner_reply(c, xcb_get_selection_owner(c, selection), nullptr); if (reply) { owner = reply->owner; free(reply); } return owner; } static xcb_atom_t intern_atom(xcb_connection_t *c, const char *name) { xcb_atom_t atom = XCB_NONE; - xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, xcb_intern_atom(c, false, strlen(name), name), 0); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, xcb_intern_atom(c, false, strlen(name), name), nullptr); if (reply) { atom = reply->atom; free(reply); } return atom; } class KSelectionOwner::Private : public QAbstractNativeEventFilter { public: enum State { Idle, WaitingForTimestamp, WaitingForPreviousOwner }; Private(KSelectionOwner *owner_P, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root) : state(Idle), selection(selection_P), connection(c), root(root), window(XCB_NONE), prev_owner(XCB_NONE), timestamp(XCB_CURRENT_TIME), extra1(0), extra2(0), force_kill(false), owner(owner_P) { QCoreApplication::instance()->installNativeEventFilter(this); } void claimSucceeded(); void gotTimestamp(); void timeout(); State state; const xcb_atom_t selection; xcb_connection_t *connection; xcb_window_t root; xcb_window_t window; xcb_window_t prev_owner; xcb_timestamp_t timestamp; uint32_t extra1, extra2; QBasicTimer timer; bool force_kill; static xcb_atom_t manager_atom; static xcb_atom_t xa_multiple; static xcb_atom_t xa_targets; static xcb_atom_t xa_timestamp; static Private *create(KSelectionOwner *owner, xcb_atom_t selection_P, int screen_P); static Private *create(KSelectionOwner *owner, const char *selection_P, int screen_P); static Private *create(KSelectionOwner *owner, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root); static Private *create(KSelectionOwner *owner, const char *selection_P, xcb_connection_t *c, xcb_window_t root); protected: bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE { Q_UNUSED(result); if (eventType != "xcb_generic_event_t") { return false; } return owner->filterEvent(message); } private: KSelectionOwner *owner; }; KSelectionOwner::Private* KSelectionOwner::Private::create(KSelectionOwner *owner, xcb_atom_t selection_P, int screen_P) { if (QGuiApplication::platformName() == QStringLiteral("xcb")) { return create(owner, selection_P, QX11Info::connection(), QX11Info::appRootWindow(screen_P)); } qWarning() << "Trying to use KSelectionOwner on a non-X11 platform! This is an application bug."; return Q_NULLPTR; } KSelectionOwner::Private *KSelectionOwner::Private::create(KSelectionOwner *owner, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root) { return new Private(owner, selection_P, c, root); } KSelectionOwner::Private *KSelectionOwner::Private::create(KSelectionOwner *owner, const char *selection_P, int screen_P) { if (QGuiApplication::platformName() == QStringLiteral("xcb")) { return create(owner, selection_P, QX11Info::connection(), QX11Info::appRootWindow(screen_P)); } qWarning() << "Trying to use KSelectionOwner on a non-X11 platform! This is an application bug."; return Q_NULLPTR; } KSelectionOwner::Private *KSelectionOwner::Private::create(KSelectionOwner *owner, const char *selection_P, xcb_connection_t *c, xcb_window_t root) { return new Private(owner, intern_atom(c, selection_P), c, root); } KSelectionOwner::KSelectionOwner(xcb_atom_t selection_P, int screen_P, QObject *parent_P) : QObject(parent_P), d(Private::create(this, selection_P, screen_P)) { } KSelectionOwner::KSelectionOwner(const char *selection_P, int screen_P, QObject *parent_P) : QObject(parent_P), d(Private::create(this, selection_P, screen_P)) { } KSelectionOwner::KSelectionOwner(xcb_atom_t selection, xcb_connection_t *c, xcb_window_t root, QObject *parent) : QObject(parent) , d(Private::create(this, selection, c, root)) { } KSelectionOwner::KSelectionOwner(const char *selection, xcb_connection_t *c, xcb_window_t root, QObject *parent) : QObject(parent) , d(Private::create(this, selection, c, root)) { } KSelectionOwner::~KSelectionOwner() { if (d) { release(); if (d->window != XCB_WINDOW_NONE) { xcb_destroy_window(d->connection, d->window); // also makes the selection not owned } delete d; } } void KSelectionOwner::Private::claimSucceeded() { state = Idle; xcb_client_message_event_t ev; ev.response_type = XCB_CLIENT_MESSAGE; ev.format = 32; ev.window = root; ev.type = Private::manager_atom; ev.data.data32[0] = timestamp; ev.data.data32[1] = selection; ev.data.data32[2] = window; ev.data.data32[3] = extra1; ev.data.data32[4] = extra2; xcb_send_event(connection, false, root, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (const char *) &ev); // qDebug() << "Claimed selection"; emit owner->claimedOwnership(); } void KSelectionOwner::Private::gotTimestamp() { Q_ASSERT(state == WaitingForTimestamp); state = Idle; xcb_connection_t *c = connection; // Set the selection owner and immediately verify that the claim was successful xcb_set_selection_owner(c, window, selection, timestamp); xcb_window_t new_owner = get_selection_owner(c, selection); if (new_owner != window) { // qDebug() << "Failed to claim selection : " << new_owner; xcb_destroy_window(c, window); timestamp = XCB_CURRENT_TIME; window = XCB_NONE; emit owner->failedToClaimOwnership(); return; } if (prev_owner != XCB_NONE && force_kill) { // qDebug() << "Waiting for previous owner to disown"; timer.start(1000, owner); state = WaitingForPreviousOwner; // Note: We've already selected for structure notify events // on the previous owner window } else { // If there was no previous owner, we're done claimSucceeded(); } } void KSelectionOwner::Private::timeout() { Q_ASSERT(state == WaitingForPreviousOwner); state = Idle; if (force_kill) { // qDebug() << "Killing previous owner"; xcb_connection_t *c = connection; // Ignore any errors from the kill request xcb_generic_error_t *err = xcb_request_check(c, xcb_kill_client_checked(c, prev_owner)); free(err); claimSucceeded(); } else { emit owner->failedToClaimOwnership(); } } void KSelectionOwner::claim(bool force_P, bool force_kill_P) { if (!d) { return; } Q_ASSERT(d->state == Private::Idle); if (Private::manager_atom == XCB_NONE) { getAtoms(); } if (d->timestamp != XCB_CURRENT_TIME) { release(); } xcb_connection_t *c = d->connection; d->prev_owner = get_selection_owner(c, d->selection); if (d->prev_owner != XCB_NONE) { if (!force_P) { // qDebug() << "Selection already owned, failing"; emit failedToClaimOwnership(); return; } // Select structure notify events so get an event when the previous owner // destroys the window uint32_t mask = XCB_EVENT_MASK_STRUCTURE_NOTIFY; xcb_change_window_attributes(c, d->prev_owner, XCB_CW_EVENT_MASK, &mask); } uint32_t values[] = { true, XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_STRUCTURE_NOTIFY }; d->window = xcb_generate_id(c); xcb_create_window(c, XCB_COPY_FROM_PARENT, d->window, d->root, 0, 0, 1, 1, 0, XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK, values); // Trigger a property change event so we get a timestamp xcb_atom_t tmp = XCB_ATOM_ATOM; xcb_change_property(c, XCB_PROP_MODE_REPLACE, d->window, XCB_ATOM_ATOM, XCB_ATOM_ATOM, 32, 1, (const void *) &tmp); // Now we have to return to the event loop and wait for the property change event d->force_kill = force_kill_P; d->state = Private::WaitingForTimestamp; } // destroy resource first void KSelectionOwner::release() { if (!d) { return; } if (d->timestamp == XCB_CURRENT_TIME) { return; } xcb_destroy_window(d->connection, d->window); // also makes the selection not owned d->window = XCB_NONE; // qDebug() << "Releasing selection"; d->timestamp = XCB_CURRENT_TIME; } xcb_window_t KSelectionOwner::ownerWindow() const { if (!d) { return XCB_WINDOW_NONE; } if (d->timestamp == XCB_CURRENT_TIME) { return XCB_NONE; } return d->window; } void KSelectionOwner::setData(uint32_t extra1_P, uint32_t extra2_P) { if (!d) { return; } d->extra1 = extra1_P; d->extra2 = extra2_P; } bool KSelectionOwner::filterEvent(void *ev_P) { if (!d) { return false; } xcb_generic_event_t *event = reinterpret_cast(ev_P); const uint response_type = event->response_type & ~0x80; #if 0 // There's no generic way to get the window for an event in xcb, it depends on the type of event // This handleMessage virtual doesn't seem used anyway. if (d->timestamp != CurrentTime && ev_P->xany.window == d->window) { if (handleMessage(ev_P)) { return true; } } #endif switch (response_type) { case XCB_SELECTION_CLEAR: { xcb_selection_clear_event_t *ev = reinterpret_cast(event); if (d->timestamp == XCB_CURRENT_TIME || ev->selection != d->selection) { return false; } d->timestamp = XCB_CURRENT_TIME; // qDebug() << "Lost selection"; xcb_window_t window = d->window; emit lostOwnership(); // Unset the event mask before we destroy the window so we don't get a destroy event uint32_t event_mask = XCB_NONE; xcb_change_window_attributes(d->connection, window, XCB_CW_EVENT_MASK, &event_mask); xcb_destroy_window(d->connection, window); return true; } case XCB_DESTROY_NOTIFY: { xcb_destroy_notify_event_t *ev = reinterpret_cast(event); if (ev->window == d->prev_owner) { if (d->state == Private::WaitingForPreviousOwner) { d->timer.stop(); d->claimSucceeded(); return true; } // It is possible for the previous owner to be destroyed // while we're waiting for the timestamp d->prev_owner = XCB_NONE; } if (d->timestamp == XCB_CURRENT_TIME || ev->window != d->window) { return false; } d->timestamp = XCB_CURRENT_TIME; // qDebug() << "Lost selection (destroyed)"; emit lostOwnership(); return true; } case XCB_SELECTION_NOTIFY: { xcb_selection_notify_event_t *ev = reinterpret_cast(event); if (d->timestamp == XCB_CURRENT_TIME || ev->selection != d->selection) { return false; } // ignore? return false; } case XCB_SELECTION_REQUEST: filter_selection_request(event); return false; case XCB_PROPERTY_NOTIFY: { xcb_property_notify_event_t *ev = reinterpret_cast(event); if (ev->window == d->window && d->state == Private::WaitingForTimestamp) { d->timestamp = ev->time; d->gotTimestamp(); return true; } return false; } default: return false; } } void KSelectionOwner::timerEvent(QTimerEvent *event) { if (!d) { QObject::timerEvent(event); return; } if (event->timerId() == d->timer.timerId()) { d->timer.stop(); d->timeout(); return; } QObject::timerEvent(event); } #if 0 bool KSelectionOwner::handleMessage(XEvent *) { return false; } #endif void KSelectionOwner::filter_selection_request(void *event) { if (!d) { return; } xcb_selection_request_event_t *ev = reinterpret_cast(event); if (d->timestamp == XCB_CURRENT_TIME || ev->selection != d->selection) { return; } if (ev->time != XCB_CURRENT_TIME && ev->time - d->timestamp > 1U << 31) { return; // too old or too new request } // qDebug() << "Got selection request"; xcb_connection_t *c = d->connection; bool handled = false; if (ev->target == Private::xa_multiple) { if (ev->property != XCB_NONE) { const int MAX_ATOMS = 100; xcb_get_property_cookie_t cookie = xcb_get_property(c, false, ev->requestor, ev->property, XCB_GET_PROPERTY_TYPE_ANY, 0, MAX_ATOMS); - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (reply && reply->format == 32 && reply->value_len % 2 == 0) { xcb_atom_t *atoms = reinterpret_cast(xcb_get_property_value(reply)); bool handled_array[MAX_ATOMS]; for (uint i = 0; i < reply->value_len / 2; i++) { handled_array[i] = handle_selection(atoms[i * 2], atoms[i * 2 + 1], ev->requestor); } bool all_handled = true; for (uint i = 0; i < reply->value_len / 2; i++) { if (!handled_array[i]) { all_handled = false; atoms[i * 2 + 1] = XCB_NONE; } } if (!all_handled) { xcb_change_property(c, ev->requestor, ev->property, XCB_ATOM_ATOM, 32, XCB_PROP_MODE_REPLACE, reply->value_len, reinterpret_cast(atoms)); } handled = true; } if (reply) { free(reply); } } } else { if (ev->property == XCB_NONE) { // obsolete client ev->property = ev->target; } handled = handle_selection(ev->target, ev->property, ev->requestor); } xcb_selection_notify_event_t xev; xev.response_type = XCB_SELECTION_NOTIFY; xev.selection = ev->selection; xev.requestor = ev->requestor; xev.target = ev->target; xev.property = handled ? ev->property : XCB_NONE; xcb_send_event(c, false, ev->requestor, 0, (const char *) &xev); } bool KSelectionOwner::handle_selection(xcb_atom_t target_P, xcb_atom_t property_P, xcb_window_t requestor_P) { if (!d) { return false; } if (target_P == Private::xa_timestamp) { // qDebug() << "Handling timestamp request"; xcb_change_property(d->connection, requestor_P, property_P, XCB_ATOM_INTEGER, 32, XCB_PROP_MODE_REPLACE, 1, reinterpret_cast(&d->timestamp)); } else if (target_P == Private::xa_targets) { replyTargets(property_P, requestor_P); } else if (genericReply(target_P, property_P, requestor_P)) { // handled } else { return false; // unknown } return true; } void KSelectionOwner::replyTargets(xcb_atom_t property_P, xcb_window_t requestor_P) { if (!d) { return; } xcb_atom_t atoms[3] = { Private::xa_multiple, Private::xa_timestamp, Private::xa_targets }; xcb_change_property(d->connection, requestor_P, property_P, XCB_ATOM_ATOM, 32, XCB_PROP_MODE_REPLACE, sizeof(atoms) / sizeof(atoms[0]), reinterpret_cast(atoms)); // qDebug() << "Handling targets request"; } bool KSelectionOwner::genericReply(xcb_atom_t, xcb_atom_t, xcb_window_t) { return false; } void KSelectionOwner::getAtoms() { if (!d) { return; } if (Private::manager_atom != XCB_NONE) { return; } xcb_connection_t *c = d->connection; struct { const char *name; xcb_atom_t *atom; } atoms[] = { { "MANAGER", &Private::manager_atom }, { "MULTIPLE", &Private::xa_multiple }, { "TARGETS", &Private::xa_targets }, { "TIMESTAMP", &Private::xa_timestamp } }; const int count = sizeof(atoms) / sizeof(atoms[0]); xcb_intern_atom_cookie_t cookies[count]; for (int i = 0; i < count; i++) { cookies[i] = xcb_intern_atom(c, false, strlen(atoms[i].name), atoms[i].name); } for (int i = 0; i < count; i++) { - if (xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, cookies[i], 0)) { + if (xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, cookies[i], nullptr)) { *atoms[i].atom = reply->atom; free(reply); } } } xcb_atom_t KSelectionOwner::Private::manager_atom = XCB_NONE; xcb_atom_t KSelectionOwner::Private::xa_multiple = XCB_NONE; xcb_atom_t KSelectionOwner::Private::xa_targets = XCB_NONE; xcb_atom_t KSelectionOwner::Private::xa_timestamp = XCB_NONE; diff --git a/src/platforms/xcb/kselectionowner.h b/src/platforms/xcb/kselectionowner.h index 307b0d3..0fb8caf 100644 --- a/src/platforms/xcb/kselectionowner.h +++ b/src/platforms/xcb/kselectionowner.h @@ -1,207 +1,207 @@ /**************************************************************************** Copyright (C) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef KSELECTIONOWNER_H #define KSELECTIONOWNER_H #include #include #include #include /** This class implements claiming and owning manager selections, as described in the ICCCM, section 2.8. The selection atom is passed to the constructor, claim() attemps to claim ownership of the selection, release() gives up the selection ownership. Signal lostOwnership() is emitted when the selection is claimed by another owner. @short ICCCM manager selection owner This class is only useful on the xcb platform. On other platforms the code is only functional if the constructor overloads taking an xcb_connection_t are used. In case you inherit from this class ensure that you don't use xcb and/or XLib without verifying the platform. */ class KWINDOWSYSTEM_EXPORT KSelectionOwner : public QObject { Q_OBJECT public: /** * This constructor initializes the object, but doesn't perform any * operation on the selection. * * @param selection atom representing the manager selection * @param screen X screen, or -1 for default * @param parent parent object, or NULL if there is none */ - explicit KSelectionOwner(xcb_atom_t selection, int screen = -1, QObject *parent = NULL); + explicit KSelectionOwner(xcb_atom_t selection, int screen = -1, QObject *parent = nullptr); /** * @overload * This constructor accepts the selection name and creates the appropriate atom * for it automatically. * * @param selection name of the manager selection * @param screen X screen, or -1 for default * @param parent parent object, or NULL if there is none */ - explicit KSelectionOwner(const char *selection, int screen = -1, QObject *parent = NULL); + explicit KSelectionOwner(const char *selection, int screen = -1, QObject *parent = nullptr); /** * @overload * This constructor accepts the xcb_connection_t and root window and doesn't depend on * running on the xcb platform. Otherwise this constructor behaves like the similar one * without the xcb_connection_t. * * @param selection atom representing the manager selection * @param c the xcb connection this KSelectionWatcher should use * @param root the root window this KSelectionWatcher should use * @param parent parent object, or NULL if there is none * @since 5.8 **/ explicit KSelectionOwner(xcb_atom_t selection, xcb_connection_t *c, xcb_window_t root, QObject *parent = Q_NULLPTR); /** * @overload * This constructor accepts the xcb_connection_t and root window and doesn't depend on * running on the xcb platform. Otherwise this constructor behaves like the similar one * without the xcb_connection_t. * * @param selection name of the manager selection * @param c the xcb connection this KSelectionWatcher should use * @param root the root window this KSelectionWatcher should use * @param parent parent object, or NULL if there is none * @since 5.8 **/ explicit KSelectionOwner(const char *selection, xcb_connection_t *c, xcb_window_t root, QObject *parent = Q_NULLPTR); /** * Destructor. Calls release(). */ virtual ~KSelectionOwner(); /** * Try to claim ownership of the manager selection using the current X timestamp. * * This function returns immediately, but it may take up to one second for the claim * to succeed or fail, at which point either the claimedOwnership() or * failedToClaimOwnership() signal is emitted. The claim will not be completed until * the caller has returned to the event loop. * * If @p force is false, and the selection is already owned, the selection is not claimed, * and failedToClaimOwnership() is emitted. If @p force is true and the selection is * owned by another client, the client will be given one second to relinquish ownership * of the selection. If @p force_kill is true, and the previous owner fails to disown * the selection in time, it will be forcibly killed. */ void claim(bool force, bool force_kill = true); /** * If the selection is owned, the ownership is given up. */ void release(); /** * If the selection is owned, returns the window used internally * for owning the selection. */ xcb_window_t ownerWindow() const; // None if not owning the selection /** * @internal */ bool filterEvent(void *ev_P); // internal /** * @internal */ void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE; Q_SIGNALS: /** * This signal is emitted if the selection was owned and the ownership * has been lost due to another client claiming it, this signal is emitted. * IMPORTANT: It's not safe to delete the instance in a slot connected * to this signal. */ void lostOwnership(); /** * This signal is emitted when claim() was succesful in claiming * ownership of the selection. */ void claimedOwnership(); /** * This signal is emitted when claim() failed to claim ownership * of the selection. */ void failedToClaimOwnership(); protected: /** * Called for every X event received on the window used for owning * the selection. If true is returned, the event is filtered out. */ //virtual bool handleMessage( XEvent* ev ); // removed for KF5, please shout if you need this /** * Called when a SelectionRequest event is received. A reply should * be sent using the selection handling mechanism described in the ICCCM * section 2. * * @param target requested target type * @param property property to use for the reply data * @param requestor requestor window */ virtual bool genericReply(xcb_atom_t target, xcb_atom_t property, xcb_window_t requestor); /** * Called to announce the supported targets, as described in the ICCCM * section 2.6. The default implementation announces the required targets * MULTIPLE, TIMESTAMP and TARGETS. */ virtual void replyTargets(xcb_atom_t property, xcb_window_t requestor); /** * Called to create atoms needed for claiming the selection and * communication using the selection handling mechanism. The default * implementation must be called if reimplemented. This method * may be called repeatedly. */ virtual void getAtoms(); /** * Sets extra data to be sent in the message sent to root window * after successfully claiming a selection. These extra data * are in data.l[3] and data.l[4] fields of the XClientMessage. */ void setData(uint32_t extra1, uint32_t extra2); private: void filter_selection_request(void *ev_P); bool handle_selection(xcb_atom_t target_P, xcb_atom_t property_P, xcb_window_t requestor_P); class Private; Private *const d; }; #endif diff --git a/src/platforms/xcb/kselectionwatcher.cpp b/src/platforms/xcb/kselectionwatcher.cpp index 26406af..38e9f18 100644 --- a/src/platforms/xcb/kselectionwatcher.cpp +++ b/src/platforms/xcb/kselectionwatcher.cpp @@ -1,264 +1,264 @@ /**************************************************************************** Copyright (C) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "kselectionwatcher.h" #include #include #include #include #include static xcb_window_t get_selection_owner(xcb_connection_t *c, xcb_atom_t selection) { xcb_window_t owner = XCB_NONE; - xcb_get_selection_owner_reply_t *reply = xcb_get_selection_owner_reply(c, xcb_get_selection_owner(c, selection), 0); + xcb_get_selection_owner_reply_t *reply = xcb_get_selection_owner_reply(c, xcb_get_selection_owner(c, selection), nullptr); if (reply) { owner = reply->owner; free(reply); } return owner; } static xcb_atom_t intern_atom(xcb_connection_t *c, const char *name) { xcb_atom_t atom = XCB_NONE; - xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, xcb_intern_atom(c, false, strlen(name), name), 0); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(c, xcb_intern_atom(c, false, strlen(name), name), nullptr); if (reply) { atom = reply->atom; free(reply); } return atom; } //******************************************* // KSelectionWatcher //******************************************* class KSelectionWatcher::Private : public QAbstractNativeEventFilter { public: Private(KSelectionWatcher *watcher_P, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root) : connection(c), root(root), selection(selection_P), selection_owner(XCB_NONE), watcher(watcher_P) { QCoreApplication::instance()->installNativeEventFilter(this); } xcb_connection_t *connection; xcb_window_t root; const xcb_atom_t selection; xcb_window_t selection_owner; static xcb_atom_t manager_atom; static Private *create(KSelectionWatcher *watcher, xcb_atom_t selection_P, int screen_P); static Private *create(KSelectionWatcher *watcher, const char *selection_P, int screen_P); static Private *create(KSelectionWatcher *watcher, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root); static Private *create(KSelectionWatcher *watcher, const char *selection_P, xcb_connection_t *c, xcb_window_t root); protected: bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE { Q_UNUSED(result); if (eventType != "xcb_generic_event_t") { return false; } watcher->filterEvent(message); return false; } private: KSelectionWatcher *watcher; }; KSelectionWatcher::Private *KSelectionWatcher::Private::create(KSelectionWatcher *watcher, xcb_atom_t selection_P, int screen_P) { if (QGuiApplication::platformName() == QStringLiteral("xcb")) { return create(watcher, selection_P, QX11Info::connection(), QX11Info::appRootWindow(screen_P)); } return Q_NULLPTR; } KSelectionWatcher::Private *KSelectionWatcher::Private::create(KSelectionWatcher *watcher, xcb_atom_t selection_P, xcb_connection_t *c, xcb_window_t root) { return new Private(watcher, selection_P, c, root); } KSelectionWatcher::Private *KSelectionWatcher::Private::create(KSelectionWatcher *watcher, const char *selection_P, int screen_P) { if (QGuiApplication::platformName() == QStringLiteral("xcb")) { return create(watcher, selection_P, QX11Info::connection(), QX11Info::appRootWindow(screen_P)); } return Q_NULLPTR; } KSelectionWatcher::Private *KSelectionWatcher::Private::create(KSelectionWatcher *watcher, const char *selection_P, xcb_connection_t *c, xcb_window_t root) { return new Private(watcher, intern_atom(c, selection_P), c, root); } KSelectionWatcher::KSelectionWatcher(xcb_atom_t selection_P, int screen_P, QObject *parent_P) : QObject(parent_P), d(Private::create(this, selection_P, screen_P)) { init(); } KSelectionWatcher::KSelectionWatcher(const char *selection_P, int screen_P, QObject *parent_P) : QObject(parent_P), d(Private::create(this, selection_P, screen_P)) { init(); } KSelectionWatcher::KSelectionWatcher(xcb_atom_t selection, xcb_connection_t *c, xcb_window_t root, QObject *parent) : QObject(parent) , d(Private::create(this, selection, c, root)) { init(); } KSelectionWatcher::KSelectionWatcher(const char *selection, xcb_connection_t *c, xcb_window_t root, QObject *parent) : QObject(parent) , d(Private::create(this, selection, c, root)) { init(); } KSelectionWatcher::~KSelectionWatcher() { delete d; } void KSelectionWatcher::init() { if (!d) { return; } if (Private::manager_atom == XCB_NONE) { xcb_connection_t *c = d->connection; xcb_intern_atom_cookie_t atom_cookie = xcb_intern_atom(c, false, strlen("MANAGER"), "MANAGER"); xcb_get_window_attributes_cookie_t attr_cookie = xcb_get_window_attributes(c, d->root); - xcb_intern_atom_reply_t *atom_reply = xcb_intern_atom_reply(c, atom_cookie, 0); + xcb_intern_atom_reply_t *atom_reply = xcb_intern_atom_reply(c, atom_cookie, nullptr); Private::manager_atom = atom_reply->atom; free(atom_reply); - xcb_get_window_attributes_reply_t *attr = xcb_get_window_attributes_reply(c, attr_cookie, 0); + xcb_get_window_attributes_reply_t *attr = xcb_get_window_attributes_reply(c, attr_cookie, nullptr); uint32_t event_mask = attr->your_event_mask; free(attr); if (!(event_mask & XCB_EVENT_MASK_STRUCTURE_NOTIFY)) { // We need XCB_EVENT_MASK_STRUCTURE_NORITY on the root window event_mask |= XCB_EVENT_MASK_STRUCTURE_NOTIFY; xcb_change_window_attributes(c, d->root, XCB_CW_EVENT_MASK, &event_mask); } } owner(); // trigger reading of current selection status } xcb_window_t KSelectionWatcher::owner() { if (!d) { return XCB_WINDOW_NONE; } xcb_connection_t *c = d->connection; xcb_window_t current_owner = get_selection_owner(c, d->selection); if (current_owner == XCB_NONE) { return XCB_NONE; } if (current_owner == d->selection_owner) { return d->selection_owner; } // We have a new selection owner - select for structure notify events uint32_t mask = XCB_EVENT_MASK_STRUCTURE_NOTIFY; xcb_void_cookie_t cookie = xcb_change_window_attributes_checked(c, current_owner, XCB_CW_EVENT_MASK, &mask); // Verify that the owner didn't change again while selecting for events xcb_window_t new_owner = get_selection_owner(c, d->selection); xcb_generic_error_t *err = xcb_request_check(c, cookie); if (!err && current_owner == new_owner) { d->selection_owner = current_owner; emit newOwner(d->selection_owner); } else { // ### This doesn't look right - the selection could have an owner d->selection_owner = XCB_NONE; } if (err) { free(err); } return d->selection_owner; } void KSelectionWatcher::filterEvent(void *ev_P) { if (!d) { return; } xcb_generic_event_t *event = reinterpret_cast(ev_P); const uint response_type = event->response_type & ~0x80; if (response_type == XCB_CLIENT_MESSAGE) { xcb_client_message_event_t *cm_event = reinterpret_cast(event); if (cm_event->type != Private::manager_atom || cm_event->data.data32[ 1 ] != d->selection) { return; } // owner() checks whether the owner changed and emits newOwner() owner(); return; } if (response_type == XCB_DESTROY_NOTIFY) { xcb_destroy_notify_event_t *ev = reinterpret_cast(event); if (d->selection_owner == XCB_NONE || ev->window != d->selection_owner) { return; } d->selection_owner = XCB_NONE; // in case the exactly same ID gets reused as the owner if (owner() == XCB_NONE) { emit lostOwner(); // it must be safe to delete 'this' in a slot } return; } } xcb_atom_t KSelectionWatcher::Private::manager_atom = XCB_NONE; diff --git a/src/platforms/xcb/kselectionwatcher.h b/src/platforms/xcb/kselectionwatcher.h index 1c52ced..0ec411f 100644 --- a/src/platforms/xcb/kselectionwatcher.h +++ b/src/platforms/xcb/kselectionwatcher.h @@ -1,128 +1,128 @@ /**************************************************************************** Copyright (C) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef KSELECTIONWATCHER_H #define KSELECTIONWATCHER_H #include #include #include #include /** This class implements watching manager selections, as described in the ICCCM section 2.8. It emits signal newOwner() when a new owner claim the selection, and emits lostOwner() when the selection ownership is given up. To find out current owner of the selection, owner() can be used. @short ICCCM manager selection watching This class is only useful on the xcb platform. On other platforms the code is only functional if the constructor overloads taking an xcb_connection_t are used. In case you inherit from this class ensure that you don't use xcb and/or XLib without verifying the platform. */ class KWINDOWSYSTEM_EXPORT KSelectionWatcher : public QObject { Q_OBJECT public: /** * This constructor initializes the object, but doesn't perform any * operation on the selection. * * @param selection atom representing the manager selection * @param screen X screen, or -1 for default * @param parent parent object, or NULL if there is none */ - explicit KSelectionWatcher(xcb_atom_t selection, int screen = -1, QObject *parent = NULL); + explicit KSelectionWatcher(xcb_atom_t selection, int screen = -1, QObject *parent = nullptr); /** * @overload * This constructor accepts the selection name and creates the appropriate atom * for it automatically. * * @param selection name of the manager selection * @param screen X screen, or -1 for default * @param parent parent object, or NULL if there is none */ - explicit KSelectionWatcher(const char *selection, int screen = -1, QObject *parent = NULL); + explicit KSelectionWatcher(const char *selection, int screen = -1, QObject *parent = nullptr); /** * @overload * This constructor accepts the xcb_connection_t and root window and doesn't depend on * running on the xcb platform. Otherwise this constructor behaves like the similar one * without the xcb_connection_t. * * @param selection atom representing the manager selection * @param c the xcb connection this KSelectionWatcher should use * @param root the root window this KSelectionWatcher should use * @since 5.8 **/ explicit KSelectionWatcher(xcb_atom_t selection, xcb_connection_t *c, xcb_window_t root, QObject *parent = Q_NULLPTR); /** * @overload * This constructor accepts the xcb_connection_t and root window and doesn't depend on * running on the xcb platform. Otherwise this constructor behaves like the similar one * without the xcb_connection_t. * * @param selection name of the manager selection * @param c the xcb connection this KSelectionWatcher should use * @param root the root window this KSelectionWatcher should use * @since 5.8 **/ explicit KSelectionWatcher(const char *selection, xcb_connection_t *c, xcb_window_t root, QObject *parent = Q_NULLPTR); virtual ~KSelectionWatcher(); /** * Return the current owner of the manager selection, if any. Note that if the event * informing about the owner change is still in the input queue, newOwner() might * have been emitted yet. */ xcb_window_t owner(); /** * @internal */ void filterEvent(void *ev_P); // internal Q_SIGNALS: /** * This signal is emitted when the selection is successfully claimed by a new * owner. * @param owner the new owner of the selection */ void newOwner(xcb_window_t owner); /** * This signal is emitted when the selection is given up, i.e. there's no * owner. Note that the selection may be immediatelly claimed again, * so the newOwner() signal may be emitted right after this one. * It's safe to delete the instance in a slot connected to this signal. */ void lostOwner(); private: void init(); class Private; Private *const d; }; Q_DECLARE_METATYPE(xcb_window_t) #endif diff --git a/src/platforms/xcb/kwindoweffects.cpp b/src/platforms/xcb/kwindoweffects.cpp index 77bd7e5..528838e 100644 --- a/src/platforms/xcb/kwindoweffects.cpp +++ b/src/platforms/xcb/kwindoweffects.cpp @@ -1,345 +1,345 @@ /* * Copyright 2009 Marco Martin * Copyright 2014 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "kwindoweffects_x11.h" #include #include "kwindowsystem.h" #include #include #include #include static const char DASHBOARD_WIN_CLASS[] = "dashboard\0dashboard"; using namespace KWindowEffects; KWindowEffectsPrivateX11::KWindowEffectsPrivateX11() { } KWindowEffectsPrivateX11::~KWindowEffectsPrivateX11() { } bool KWindowEffectsPrivateX11::isEffectAvailable(Effect effect) { if (!KWindowSystem::self()->compositingActive()) { return false; } QByteArray effectName; switch (effect) { case Slide: effectName = QByteArrayLiteral("_KDE_SLIDE"); break; case PresentWindows: effectName = QByteArrayLiteral("_KDE_PRESENT_WINDOWS_DESKTOP"); break; case PresentWindowsGroup: effectName = QByteArrayLiteral("_KDE_PRESENT_WINDOWS_GROUP"); break; case HighlightWindows: effectName = QByteArrayLiteral("_KDE_WINDOW_HIGHLIGHT"); break; case BlurBehind: effectName = QByteArrayLiteral("_KDE_NET_WM_BLUR_BEHIND_REGION"); break; case Dashboard: // TODO: Better namespacing for atoms effectName = QByteArrayLiteral("_WM_EFFECT_KDE_DASHBOARD"); break; case BackgroundContrast: effectName = QByteArrayLiteral("_KDE_NET_WM_BACKGROUND_CONTRAST_REGION"); break; default: return false; } // hackish way to find out if KWin has the effect enabled, // TODO provide proper support xcb_connection_t *c = QX11Info::connection(); xcb_list_properties_cookie_t propsCookie = xcb_list_properties_unchecked(c, QX11Info::appRootWindow()); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer props(xcb_list_properties_reply(c, propsCookie, NULL)); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer props(xcb_list_properties_reply(c, propsCookie, nullptr)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom || !props) { return false; } xcb_atom_t *atoms = xcb_list_properties_atoms(props.data()); for (int i = 0; i < props->atoms_len; ++i) { if (atoms[i] == atom->atom) { return true; } } return false; } void KWindowEffectsPrivateX11::slideWindow(WId id, SlideFromLocation location, int offset) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } const QByteArray effectName = QByteArrayLiteral("_KDE_SLIDE"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); const int size = 2; int32_t data[size]; data[0] = offset; switch (location) { case LeftEdge: data[1] = 0; break; case TopEdge: data[1] = 1; break; case RightEdge: data[1] = 2; break; case BottomEdge: data[1] = 3; default: break; } - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } if (location == NoEdge) { xcb_delete_property(c, id, atom->atom); } else { xcb_change_property(c, XCB_PROP_MODE_REPLACE, id, atom->atom, atom->atom, 32, size, data); } } void KWindowEffectsPrivateX11::slideWindow(QWidget *widget, SlideFromLocation location) { slideWindow(widget->effectiveWinId(), location, -1); } QList KWindowEffectsPrivateX11::windowSizes(const QList &ids) { QList windowSizes; Q_FOREACH (WId id, ids) { if (id > 0) { KWindowInfo info(id, NET::WMGeometry | NET::WMFrameExtents); windowSizes.append(info.frameGeometry().size()); } else { windowSizes.append(QSize()); } } return windowSizes; } void KWindowEffectsPrivateX11::presentWindows(WId controller, const QList &ids) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } const int numWindows = ids.count(); QVarLengthArray data(numWindows); int actualCount = 0; for (int i = 0; i < numWindows; ++i) { data[i] = ids.at(i); ++actualCount; } if (actualCount != numWindows) { data.resize(actualCount); } if (data.isEmpty()) { return; } const QByteArray effectName = QByteArrayLiteral("_KDE_PRESENT_WINDOWS_GROUP"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } xcb_change_property(c, XCB_PROP_MODE_REPLACE, controller, atom->atom, atom->atom, 32, data.size(), data.constData()); } void KWindowEffectsPrivateX11::presentWindows(WId controller, int desktop) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } const QByteArray effectName = QByteArrayLiteral("_KDE_PRESENT_WINDOWS_DESKTOP"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } int32_t data = desktop; xcb_change_property(c, XCB_PROP_MODE_REPLACE, controller, atom->atom, atom->atom, 32, 1, &data); } void KWindowEffectsPrivateX11::highlightWindows(WId controller, const QList &ids) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } const QByteArray effectName = QByteArrayLiteral("_KDE_WINDOW_HIGHLIGHT"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } const int numWindows = ids.count(); if (numWindows == 0) { xcb_delete_property(c, controller, atom->atom); return; } QVarLengthArray data(numWindows); int actualCount = 0; for (int i = 0; i < numWindows; ++i) { data[i] = ids.at(i); ++actualCount; } if (actualCount != numWindows) { data.resize(actualCount); } if (data.isEmpty()) { return; } xcb_change_property(c, XCB_PROP_MODE_REPLACE, controller, atom->atom, atom->atom, 32, data.size(), data.constData()); } void KWindowEffectsPrivateX11::enableBlurBehind(WId window, bool enable, const QRegion ®ion) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } const QByteArray effectName = QByteArrayLiteral("_KDE_NET_WM_BLUR_BEHIND_REGION"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } if (enable) { QVector rects = region.rects(); QVector data; Q_FOREACH (const QRect &r, rects) { data << r.x() << r.y() << r.width() << r.height(); } xcb_change_property(c, XCB_PROP_MODE_REPLACE, window, atom->atom, XCB_ATOM_CARDINAL, 32, data.size(), data.constData()); } else { xcb_delete_property(c, window, atom->atom); } } void KWindowEffectsPrivateX11::enableBackgroundContrast(WId window, bool enable, qreal contrast, qreal intensity, qreal saturation, const QRegion ®ion) { xcb_connection_t *c = QX11Info::connection(); const QByteArray effectName = QByteArrayLiteral("_KDE_NET_WM_BACKGROUND_CONTRAST_REGION"); xcb_intern_atom_cookie_t atomCookie = xcb_intern_atom_unchecked(c, false, effectName.length(), effectName.constData()); - QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, NULL)); + QScopedPointer atom(xcb_intern_atom_reply(c, atomCookie, nullptr)); if (!atom) { return; } if (enable) { QVector rects = region.rects(); QVector data; Q_FOREACH (const QRect &r, rects) { data << r.x() << r.y() << r.width() << r.height(); } QMatrix4x4 satMatrix; //saturation QMatrix4x4 intMatrix; //intensity QMatrix4x4 contMatrix; //contrast //Saturation matrix if (!qFuzzyCompare(saturation, 1.0)) { const qreal rval = (1.0 - saturation) * .2126; const qreal gval = (1.0 - saturation) * .7152; const qreal bval = (1.0 - saturation) * .0722; satMatrix = QMatrix4x4(rval + saturation, rval, rval, 0.0, gval, gval + saturation, gval, 0.0, bval, bval, bval + saturation, 0.0, 0, 0, 0, 1.0); } //IntensityMatrix if (!qFuzzyCompare(intensity, 1.0)) { intMatrix.scale(intensity, intensity, intensity); } //Contrast Matrix if (!qFuzzyCompare(contrast, 1.0)) { const float transl = (1.0 - contrast) / 2.0; contMatrix = QMatrix4x4(contrast, 0, 0, 0.0, 0, contrast, 0, 0.0, 0, 0, contrast, 0.0, transl, transl, transl, 1.0); } QMatrix4x4 colorMatrix = contMatrix * satMatrix * intMatrix; colorMatrix = colorMatrix; colorMatrix = colorMatrix.transposed(); uint32_t *rawData = reinterpret_cast(colorMatrix.data()); for (int i = 0; i < 16; ++i) { data << rawData[i]; } xcb_change_property(c, XCB_PROP_MODE_REPLACE, window, atom->atom, atom->atom, 32, data.size(), data.constData()); } else { xcb_delete_property(c, window, atom->atom); } } void KWindowEffectsPrivateX11::markAsDashboard(WId window) { xcb_connection_t *c = QX11Info::connection(); if (!c) { return; } xcb_change_property(c, XCB_PROP_MODE_REPLACE, window, XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 8, 19, DASHBOARD_WIN_CLASS); } diff --git a/src/platforms/xcb/kwindowinfo.cpp b/src/platforms/xcb/kwindowinfo.cpp index 9e6fb1f..8338ad2 100644 --- a/src/platforms/xcb/kwindowinfo.cpp +++ b/src/platforms/xcb/kwindowinfo.cpp @@ -1,440 +1,440 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Matthias Ettrich (ettrich@kde.org) Copyright (C) 2007 Lubos Lunak (l.lunak@kde.org) Copyright 2014 Martin Gräßlin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kwindowinfo_p_x11.h" #include "kwindowsystem.h" #include #include #include #include #include // KWindowSystem::info() should be updated too if something has to be changed here KWindowInfoPrivateX11::KWindowInfoPrivateX11(WId _win, NET::Properties properties, NET::Properties2 properties2) : KWindowInfoPrivate(_win, properties, properties2) , KWindowInfoPrivateDesktopFileNameExtension() , KWindowInfoPrivatePidExtension() { installDesktopFileNameExtension(this); installPidExtension(this); KXErrorHandler handler; if (properties & NET::WMVisibleIconName) { properties |= NET::WMIconName | NET::WMVisibleName; // force, in case it will be used as a fallback } if (properties & NET::WMVisibleName) { properties |= NET::WMName; // force, in case it will be used as a fallback } if (properties2 & NET::WM2ExtendedStrut) { properties |= NET::WMStrut; // will be used as fallback } if (properties & NET::WMWindowType) { properties2 |= NET::WM2TransientFor; // will be used when type is not set } if ((properties & NET::WMDesktop) && KWindowSystem::mapViewport()) { properties |= NET::WMGeometry; // for viewports, the desktop (workspace) is determined from the geometry } properties |= NET::XAWMState; // force to get error detection for valid() m_info.reset(new NETWinInfo(QX11Info::connection(), _win, QX11Info::appRootWindow(), properties, properties2)); if (properties & NET::WMName) { if (m_info->name() && m_info->name()[ 0 ] != '\0') { m_name = QString::fromUtf8(m_info->name()); } else { m_name = KWindowSystem::readNameProperty(_win, XA_WM_NAME); } } if (properties & NET::WMIconName) { if (m_info->iconName() && m_info->iconName()[ 0 ] != '\0') { m_iconic_name = QString::fromUtf8(m_info->iconName()); } else { m_iconic_name = KWindowSystem::readNameProperty(_win, XA_WM_ICON_NAME); } } if (properties & (NET::WMGeometry | NET::WMFrameExtents)) { NETRect frame, geom; m_info->kdeGeometry(frame, geom); m_geometry.setRect(geom.pos.x, geom.pos.y, geom.size.width, geom.size.height); m_frame_geometry.setRect(frame.pos.x, frame.pos.y, frame.size.width, frame.size.height); } m_valid = !handler.error(false); // no sync - NETWinInfo did roundtrips } KWindowInfoPrivateX11::~KWindowInfoPrivateX11() { } bool KWindowInfoPrivateX11::valid(bool withdrawn_is_valid) const { if (!m_valid) { return false; } if (!withdrawn_is_valid && mappingState() == NET::Withdrawn) { return false; } return true; } NET::States KWindowInfoPrivateX11::state() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMState)) { qWarning() << "Pass NET::WMState to KWindowInfo"; } #endif return m_info->state(); } NET::MappingState KWindowInfoPrivateX11::mappingState() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::XAWMState)) { qWarning() << "Pass NET::XAWMState to KWindowInfo"; } #endif return m_info->mappingState(); } NETExtendedStrut KWindowInfoPrivateX11::extendedStrut() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2ExtendedStrut)) { qWarning() << "Pass NET::WM2ExtendedStrut to KWindowInfo"; } #endif NETExtendedStrut ext = m_info->extendedStrut(); NETStrut str = m_info->strut(); if (ext.left_width == 0 && ext.right_width == 0 && ext.top_width == 0 && ext.bottom_width == 0 && (str.left != 0 || str.right != 0 || str.top != 0 || str.bottom != 0)) { // build extended from simple if (str.left != 0) { ext.left_width = str.left; ext.left_start = 0; ext.left_end = XDisplayHeight(QX11Info::display(), DefaultScreen(QX11Info::display())); } if (str.right != 0) { ext.right_width = str.right; ext.right_start = 0; ext.right_end = XDisplayHeight(QX11Info::display(), DefaultScreen(QX11Info::display())); } if (str.top != 0) { ext.top_width = str.top; ext.top_start = 0; ext.top_end = XDisplayWidth(QX11Info::display(), DefaultScreen(QX11Info::display())); } if (str.bottom != 0) { ext.bottom_width = str.bottom; ext.bottom_start = 0; ext.bottom_end = XDisplayWidth(QX11Info::display(), DefaultScreen(QX11Info::display())); } } return ext; } NET::WindowType KWindowInfoPrivateX11::windowType(NET::WindowTypes supported_types) const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMWindowType)) { qWarning() << "Pass NET::WMWindowType to KWindowInfo"; } #endif if (!m_info->hasWindowType()) { // fallback, per spec recommendation if (transientFor() != XCB_WINDOW_NONE) { // dialog if (supported_types & NET::DialogMask) { return NET::Dialog; } } else { if (supported_types & NET::NormalMask) { return NET::Normal; } } } return m_info->windowType(supported_types); } QString KWindowInfoPrivateX11::visibleNameWithState() const { QString s = visibleName(); if (isMinimized()) { s.prepend(QLatin1Char('(')); s.append(QLatin1Char(')')); } return s; } QString KWindowInfoPrivateX11::visibleName() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMVisibleName)) { qWarning() << "Pass NET::WMVisibleName to KWindowInfo"; } #endif return m_info->visibleName() && m_info->visibleName()[ 0 ] != '\0' ? QString::fromUtf8(m_info->visibleName()) : name(); } QString KWindowInfoPrivateX11::name() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMName)) { qWarning() << "Pass NET::WMName to KWindowInfo"; } #endif return m_name; } QString KWindowInfoPrivateX11::visibleIconNameWithState() const { QString s = visibleIconName(); if (isMinimized()) { s.prepend(QLatin1Char('(')); s.append(QLatin1Char(')')); } return s; } QString KWindowInfoPrivateX11::visibleIconName() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMVisibleIconName)) { qWarning() << "Pass NET::WMVisibleIconName to KWindowInfo"; } #endif if (m_info->visibleIconName() && m_info->visibleIconName()[ 0 ] != '\0') { return QString::fromUtf8(m_info->visibleIconName()); } if (m_info->iconName() && m_info->iconName()[ 0 ] != '\0') { return QString::fromUtf8(m_info->iconName()); } if (!m_iconic_name.isEmpty()) { return m_iconic_name; } return visibleName(); } QString KWindowInfoPrivateX11::iconName() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMIconName)) { qWarning() << "Pass NET::WMIconName to KWindowInfo"; } #endif if (m_info->iconName() && m_info->iconName()[ 0 ] != '\0') { return QString::fromUtf8(m_info->iconName()); } if (!m_iconic_name.isEmpty()) { return m_iconic_name; } return name(); } bool KWindowInfoPrivateX11::isOnDesktop(int _desktop) const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMDesktop)) { qWarning() << "Pass NET::WMDesktop to KWindowInfo"; } #endif if (KWindowSystem::mapViewport()) { if (onAllDesktops()) { return true; } return KWindowSystem::viewportWindowToDesktop(m_geometry) == _desktop; } return m_info->desktop() == _desktop || m_info->desktop() == NET::OnAllDesktops; } bool KWindowInfoPrivateX11::onAllDesktops() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMDesktop)) { qWarning() << "Pass NET::WMDesktop to KWindowInfo"; } #endif if (KWindowSystem::mapViewport()) { if (m_info->passedProperties() & NET::WMState) { return m_info->state() & NET::Sticky; } - NETWinInfo info(QX11Info::connection(), win(), QX11Info::appRootWindow(), NET::WMState, 0); + NETWinInfo info(QX11Info::connection(), win(), QX11Info::appRootWindow(), NET::WMState, nullptr); return info.state() & NET::Sticky; } return m_info->desktop() == NET::OnAllDesktops; } int KWindowInfoPrivateX11::desktop() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMDesktop)) { qWarning() << "Pass NET::WMDesktop to KWindowInfo"; } #endif if (KWindowSystem::mapViewport()) { if (onAllDesktops()) { return NET::OnAllDesktops; } return KWindowSystem::viewportWindowToDesktop(m_geometry); } return m_info->desktop(); } QStringList KWindowInfoPrivateX11::activities() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2Activities)) { qWarning() << "Pass NET::WM2Activities to KWindowInfo"; } #endif const QStringList result = QString::fromLatin1(m_info->activities()).split( QLatin1Char(','), QString::SkipEmptyParts); return result.contains(QStringLiteral(KDE_ALL_ACTIVITIES_UUID)) ? QStringList() : result; } QRect KWindowInfoPrivateX11::geometry() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMGeometry)) { qWarning() << "Pass NET::WMGeometry to KWindowInfo"; } #endif return m_geometry; } QRect KWindowInfoPrivateX11::frameGeometry() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMFrameExtents)) { qWarning() << "Pass NET::WMFrameExtents to KWindowInfo"; } #endif return m_frame_geometry; } WId KWindowInfoPrivateX11::transientFor() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2TransientFor)) { qWarning() << "Pass NET::WM2TransientFor to KWindowInfo"; } #endif return m_info->transientFor(); } WId KWindowInfoPrivateX11::groupLeader() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2GroupLeader)) { qWarning() << "Pass NET::WM2GroupLeader to KWindowInfo"; } #endif return m_info->groupLeader(); } QByteArray KWindowInfoPrivateX11::windowClassClass() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2WindowClass)) { qWarning() << "Pass NET::WM2WindowClass to KWindowInfo"; } #endif return m_info->windowClassClass(); } QByteArray KWindowInfoPrivateX11::windowClassName() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2WindowClass)) { qWarning() << "Pass NET::WM2WindowClass to KWindowInfo"; } #endif return m_info->windowClassName(); } QByteArray KWindowInfoPrivateX11::windowRole() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2WindowRole)) { qWarning() << "Pass NET::WM2WindowRole to KWindowInfo"; } #endif return m_info->windowRole(); } QByteArray KWindowInfoPrivateX11::clientMachine() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2ClientMachine)) { qWarning() << "Pass NET::WM2ClientMachine to KWindowInfo"; } #endif return m_info->clientMachine(); } bool KWindowInfoPrivateX11::actionSupported(NET::Action action) const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2AllowedActions)) { qWarning() << "Pass NET::WM2AllowedActions to KWindowInfo"; } #endif if (KWindowSystem::allowedActionsSupported()) { return m_info->allowedActions() & action; } else { return true; // no idea if it's supported or not -> pretend it is } } // see NETWM spec section 7.6 bool KWindowInfoPrivateX11::isMinimized() const { if (mappingState() != NET::Iconic) { return false; } // NETWM 1.2 compliant WM - uses NET::Hidden for minimized windows if ((state() & NET::Hidden) != 0 && (state() & NET::Shaded) == 0) { // shaded may have NET::Hidden too return true; } // older WMs use WithdrawnState for other virtual desktops // and IconicState only for minimized return KWindowSystem::icccmCompliantMappingState() ? false : true; } QByteArray KWindowInfoPrivateX11::desktopFileName() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties2() & NET::WM2DesktopFileName)) { qWarning() << "Pass NET::WM2DesktopFileName to KWindowInfo"; } #endif return QByteArray(m_info->desktopFileName()); } int KWindowInfoPrivateX11::pid() const { #if !defined(KDE_NO_WARNING_OUTPUT) if (!(m_info->passedProperties() & NET::WMPid)) { qWarning() << "Pass NET::WMPid to KWindowInfo"; } #endif return m_info->pid(); } diff --git a/src/platforms/xcb/kwindowsystem.cpp b/src/platforms/xcb/kwindowsystem.cpp index 091c71a..c627680 100644 --- a/src/platforms/xcb/kwindowsystem.cpp +++ b/src/platforms/xcb/kwindowsystem.cpp @@ -1,1216 +1,1216 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Matthias Ettrich (ettrich@kde.org) Copyright (C) 2007 Lubos Lunak (l.lunak@kde.org) Copyright 2014 Martin Gräßlin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include "kwindowsystem.h" #include "kwindowsystem_p_x11.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if KWINDOWSYSTEM_HAVE_XFIXES #include #endif static Atom net_wm_cm; static void create_atoms(); static inline const QRect &displayGeometry() { static QRect displayGeometry; static bool isDirty = true; if (isDirty) { static QList connections; auto dirtify = [&] { isDirty = true; foreach (const QMetaObject::Connection &con, connections) QObject::disconnect(con); connections.clear(); }; QObject::connect(qApp, &QGuiApplication::screenAdded, dirtify); QObject::connect(qApp, &QGuiApplication::screenRemoved, dirtify); const QList screenList = QGuiApplication::screens(); QRegion region; for (int i = 0; i < screenList.count(); ++i) { const QScreen *screen = screenList.at(i); connections << QObject::connect(screen, &QScreen::geometryChanged, dirtify); region += screen->geometry(); } displayGeometry = region.boundingRect(); isDirty = false; } return displayGeometry; } static inline int displayWidth() { return displayGeometry().width(); } static inline int displayHeight() { return displayGeometry().height(); } static const NET::Properties windowsProperties = NET::ClientList | NET::ClientListStacking | NET::Supported | NET::NumberOfDesktops | NET::DesktopGeometry | NET::DesktopViewport | NET::CurrentDesktop | NET::DesktopNames | NET::ActiveWindow | NET::WorkArea; static const NET::Properties2 windowsProperties2 = NET::WM2ShowingDesktop; // ClientList and ClientListStacking is not per-window information, but a desktop information, // so track it even with only INFO_BASIC static const NET::Properties desktopProperties = NET::ClientList | NET::ClientListStacking | NET::Supported | NET::NumberOfDesktops | NET::DesktopGeometry | NET::DesktopViewport | NET::CurrentDesktop | NET::DesktopNames | NET::ActiveWindow | NET::WorkArea; static const NET::Properties2 desktopProperties2 = NET::WM2ShowingDesktop; MainThreadInstantiator::MainThreadInstantiator(KWindowSystemPrivateX11::FilterInfo _what) : QObject(), m_what(_what) { } NETEventFilter *MainThreadInstantiator::createNETEventFilter() { return new NETEventFilter(m_what); } NETEventFilter::NETEventFilter(KWindowSystemPrivateX11::FilterInfo _what) : NETRootInfo(QX11Info::connection(), _what >= KWindowSystemPrivateX11::INFO_WINDOWS ? windowsProperties : desktopProperties, _what >= KWindowSystemPrivateX11::INFO_WINDOWS ? windowsProperties2 : desktopProperties2, -1, false), QAbstractNativeEventFilter(), strutSignalConnected(false), compositingEnabled(false), haveXfixes(false), what(_what), winId(XCB_WINDOW_NONE), m_appRootWindow(QX11Info::appRootWindow()) { QCoreApplication::instance()->installNativeEventFilter(this); #if KWINDOWSYSTEM_HAVE_XFIXES int errorBase; if ((haveXfixes = XFixesQueryExtension(QX11Info::display(), &xfixesEventBase, &errorBase))) { create_atoms(); winId = xcb_generate_id(QX11Info::connection()); uint32_t values[] = { true, XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_STRUCTURE_NOTIFY }; xcb_create_window(QX11Info::connection(), XCB_COPY_FROM_PARENT, winId, m_appRootWindow, 0, 0, 1, 1, 0, XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK, values); XFixesSelectSelectionInput(QX11Info::display(), winId, net_wm_cm, XFixesSetSelectionOwnerNotifyMask | XFixesSelectionWindowDestroyNotifyMask | XFixesSelectionClientCloseNotifyMask); compositingEnabled = XGetSelectionOwner(QX11Info::display(), net_wm_cm) != None; } #endif } NETEventFilter::~NETEventFilter() { if (QX11Info::connection() && winId != XCB_WINDOW_NONE) { xcb_destroy_window(QX11Info::connection(), winId); winId = XCB_WINDOW_NONE; } } // not virtual, but it's called directly only from init() void NETEventFilter::activate() { NETRootInfo::activate(); updateStackingOrder(); } bool NETEventFilter::nativeEventFilter(const QByteArray &eventType, void *message, long int *result) { Q_UNUSED(result) if (eventType != "xcb_generic_event_t") { // only interested in XCB events of course return false; } return nativeEventFilter(reinterpret_cast(message)); } bool NETEventFilter::nativeEventFilter(xcb_generic_event_t *ev) { KWindowSystem *s_q = KWindowSystem::self(); const uint8_t eventType = ev->response_type & ~0x80; if (eventType == xfixesEventBase + XCB_XFIXES_SELECTION_NOTIFY) { xcb_xfixes_selection_notify_event_t *event = reinterpret_cast(ev); if (event->window == winId) { bool haveOwner = event->owner != XCB_WINDOW_NONE; if (compositingEnabled != haveOwner) { compositingEnabled = haveOwner; emit s_q->compositingChanged(compositingEnabled); } return true; } // Qt compresses XFixesSelectionNotifyEvents without caring about the actual window // gui/kernel/qapplication_x11.cpp // until that can be assumed fixed, we also react on events on the root (caused by Qts own compositing tracker) if (event->window == m_appRootWindow) { if (event->selection == net_wm_cm) { bool haveOwner = event->owner != XCB_WINDOW_NONE; if (compositingEnabled != haveOwner) { compositingEnabled = haveOwner; emit s_q->compositingChanged(compositingEnabled); } // NOTICE this is not our event, we just randomly captured it from Qt -> pass on return false; } } return false; } xcb_window_t eventWindow = XCB_WINDOW_NONE; switch (eventType) { case XCB_CLIENT_MESSAGE: eventWindow = reinterpret_cast(ev)->window; break; case XCB_PROPERTY_NOTIFY: eventWindow = reinterpret_cast(ev)->window; break; case XCB_CONFIGURE_NOTIFY: eventWindow = reinterpret_cast(ev)->window; break; } if (eventWindow == m_appRootWindow) { int old_current_desktop = currentDesktop(); xcb_window_t old_active_window = activeWindow(); int old_number_of_desktops = numberOfDesktops(); bool old_showing_desktop = showingDesktop(); unsigned long m[ 5 ]; NETRootInfo::event(ev, m, 5); if ((m[ PROTOCOLS ] & CurrentDesktop) && currentDesktop() != old_current_desktop) { emit s_q->currentDesktopChanged(currentDesktop()); } if ((m[ PROTOCOLS ] & DesktopViewport) && mapViewport() && currentDesktop() != old_current_desktop) { emit s_q->currentDesktopChanged(currentDesktop()); } if ((m[ PROTOCOLS ] & ActiveWindow) && activeWindow() != old_active_window) { emit s_q->activeWindowChanged(activeWindow()); } if (m[ PROTOCOLS ] & DesktopNames) { emit s_q->desktopNamesChanged(); } if ((m[ PROTOCOLS ] & NumberOfDesktops) && numberOfDesktops() != old_number_of_desktops) { emit s_q->numberOfDesktopsChanged(numberOfDesktops()); } if ((m[ PROTOCOLS ] & DesktopGeometry) && mapViewport() && numberOfDesktops() != old_number_of_desktops) { emit s_q->numberOfDesktopsChanged(numberOfDesktops()); } if (m[ PROTOCOLS ] & WorkArea) { emit s_q->workAreaChanged(); } if (m[ PROTOCOLS ] & ClientListStacking) { updateStackingOrder(); emit s_q->stackingOrderChanged(); } if ((m[ PROTOCOLS2 ] & WM2ShowingDesktop) && showingDesktop() != old_showing_desktop) { emit s_q->showingDesktopChanged(showingDesktop()); } } else if (windows.contains(eventWindow)) { - NETWinInfo ni(QX11Info::connection(), eventWindow, m_appRootWindow, 0, 0); + NETWinInfo ni(QX11Info::connection(), eventWindow, m_appRootWindow, nullptr, nullptr); NET::Properties dirtyProperties; NET::Properties2 dirtyProperties2; ni.event(ev, &dirtyProperties, &dirtyProperties2); if (eventType == XCB_PROPERTY_NOTIFY) { xcb_property_notify_event_t *event = reinterpret_cast(ev); if (event->atom == XCB_ATOM_WM_HINTS) { dirtyProperties |= NET::WMIcon; // support for old icons } else if (event->atom == XCB_ATOM_WM_NAME) { dirtyProperties |= NET::WMName; // support for old name } else if (event->atom == XCB_ATOM_WM_ICON_NAME) { dirtyProperties |= NET::WMIconName; // support for old iconic name } } if (mapViewport() && (dirtyProperties & (NET::WMState | NET::WMGeometry))) { /* geometry change -> possible viewport change * state change -> possible NET::Sticky change */ dirtyProperties |= NET::WMDesktop; } if ((dirtyProperties & NET::WMStrut) != 0) { removeStrutWindow(eventWindow); if (!possibleStrutWindows.contains(eventWindow)) { possibleStrutWindows.append(eventWindow); } } if (dirtyProperties || dirtyProperties2) { emit s_q->windowChanged(eventWindow); emit s_q->windowChanged(eventWindow, dirtyProperties, dirtyProperties2); #ifndef KWINDOWSYSTEM_NO_DEPRECATED unsigned long dirty[ 2 ] = {dirtyProperties, dirtyProperties2}; emit s_q->windowChanged(eventWindow, dirty); emit s_q->windowChanged(eventWindow, dirtyProperties); #endif if ((dirtyProperties & NET::WMStrut) != 0) { emit s_q->strutChanged(); } } } return false; } bool NETEventFilter::removeStrutWindow(WId w) { for (QList< StrutData >::Iterator it = strutWindows.begin(); it != strutWindows.end(); ++it) if ((*it).window == w) { strutWindows.erase(it); return true; } return false; } void NETEventFilter::updateStackingOrder() { stackingOrder.clear(); for (int i = 0; i < clientListStackingCount(); i++) { stackingOrder.append(clientListStacking()[i]); } } void NETEventFilter::addClient(xcb_window_t w) { KWindowSystem *s_q = KWindowSystem::self(); if ((what >= KWindowSystemPrivateX11::INFO_WINDOWS)) { xcb_connection_t *c = QX11Info::connection(); QScopedPointer attr(xcb_get_window_attributes_reply(c, xcb_get_window_attributes_unchecked(c, w), Q_NULLPTR)); uint32_t events = XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; if (!attr.isNull()) { events = events | attr->your_event_mask; } xcb_change_window_attributes(c, w, XCB_CW_EVENT_MASK, &events); } bool emit_strutChanged = false; if (strutSignalConnected) { - NETWinInfo info(QX11Info::connection(), w, QX11Info::appRootWindow(), NET::WMStrut | NET::WMDesktop, 0); + NETWinInfo info(QX11Info::connection(), w, QX11Info::appRootWindow(), NET::WMStrut | NET::WMDesktop, nullptr); NETStrut strut = info.strut(); if (strut.left || strut.top || strut.right || strut.bottom) { strutWindows.append(StrutData(w, strut, info.desktop())); emit_strutChanged = true; } } else { possibleStrutWindows.append(w); } windows.append(w); emit s_q->windowAdded(w); if (emit_strutChanged) { emit s_q->strutChanged(); } } void NETEventFilter::removeClient(xcb_window_t w) { KWindowSystem *s_q = KWindowSystem::self(); bool emit_strutChanged = removeStrutWindow(w); if (strutSignalConnected && possibleStrutWindows.contains(w)) { - NETWinInfo info(QX11Info::connection(), w, QX11Info::appRootWindow(), NET::WMStrut, 0); + NETWinInfo info(QX11Info::connection(), w, QX11Info::appRootWindow(), NET::WMStrut, nullptr); NETStrut strut = info.strut(); if (strut.left || strut.top || strut.right || strut.bottom) { emit_strutChanged = true; } } possibleStrutWindows.removeAll(w); windows.removeAll(w); emit s_q->windowRemoved(w); if (emit_strutChanged) { emit s_q->strutChanged(); } } bool NETEventFilter::mapViewport() { // compiz claims support even though it doesn't use virtual desktops :( // if( isSupported( NET::DesktopViewport ) && !isSupported( NET::NumberOfDesktops )) // this test is duplicated in KWindowSystem::mapViewport() if (isSupported(NET::DesktopViewport) && numberOfDesktops(true) <= 1 && (desktopGeometry().width > displayWidth() || desktopGeometry().height > displayHeight())) { return true; } return false; } static bool atoms_created = false; static Atom _wm_protocols; static Atom _wm_change_state; static Atom kwm_utf8_string; static void create_atoms() { if (!atoms_created) { const int max = 20; Atom *atoms[max]; const char *names[max]; Atom atoms_return[max]; int n = 0; atoms[n] = &_wm_protocols; names[n++] = "WM_PROTOCOLS"; atoms[n] = &_wm_change_state; names[n++] = "WM_CHANGE_STATE"; atoms[n] = &kwm_utf8_string; names[n++] = "UTF8_STRING"; char net_wm_cm_name[ 100 ]; sprintf(net_wm_cm_name, "_NET_WM_CM_S%d", QX11Info::appScreen()); atoms[n] = &net_wm_cm; names[n++] = net_wm_cm_name; // we need a const_cast for the shitty X API XInternAtoms(QX11Info::display(), const_cast(names), n, false, atoms_return); for (int i = 0; i < n; i++) { *atoms[i] = atoms_return[i]; } atoms_created = True; } } // optimalization - create KWindowSystemPrivate only when needed and only for what is needed void KWindowSystemPrivateX11::connectNotify(const QMetaMethod &signal) { FilterInfo what = INFO_BASIC; if (signal == QMetaMethod::fromSignal(&KWindowSystem::workAreaChanged)) { what = INFO_WINDOWS; } else if (signal == QMetaMethod::fromSignal(&KWindowSystem::strutChanged)) { what = INFO_WINDOWS; } else if (signal == QMetaMethod::fromSignal(static_cast(&KWindowSystem::windowChanged))) { what = INFO_WINDOWS; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED else if (signal == QMetaMethod::fromSignal(static_cast(&KWindowSystem::windowChanged))) { what = INFO_WINDOWS; } else if (signal == QMetaMethod::fromSignal(static_cast(&KWindowSystem::windowChanged))) { what = INFO_WINDOWS; } #endif else if (signal == QMetaMethod::fromSignal(static_cast(&KWindowSystem::windowChanged))) { what = INFO_WINDOWS; } init(what); NETEventFilter *const s_d = s_d_func(); if (!s_d->strutSignalConnected && signal == QMetaMethod::fromSignal(&KWindowSystem::strutChanged)) { s_d->strutSignalConnected = true; } } // WARNING // you have to call s_d_func() again after calling this function if you want a valid pointer! void KWindowSystemPrivateX11::init(FilterInfo what) { NETEventFilter *const s_d = s_d_func(); if (what >= INFO_WINDOWS) { what = INFO_WINDOWS; } else { what = INFO_BASIC; } if (!s_d || s_d->what < what) { const bool wasCompositing = s_d ? s_d->compositingEnabled : false; MainThreadInstantiator instantiator(what); NETEventFilter *filter; if (instantiator.thread() == QCoreApplication::instance()->thread()) { filter = instantiator.createNETEventFilter(); } else { // the instantiator is not in the main app thread, which implies // we are being called in a thread that is not the main app thread // so we move the instantiator to the main app thread and invoke // the method with a blocking call instantiator.moveToThread(QCoreApplication::instance()->thread()); QMetaObject::invokeMethod(&instantiator, "createNETEventFilter", Qt::BlockingQueuedConnection, Q_RETURN_ARG(NETEventFilter *, filter)); } d.reset(filter); d->activate(); if (wasCompositing != s_d_func()->compositingEnabled) { emit KWindowSystem::self()->compositingChanged(s_d_func()->compositingEnabled); } } } QList KWindowSystemPrivateX11::windows() { init(INFO_BASIC); return s_d_func()->windows; } QList KWindowSystemPrivateX11::stackingOrder() { init(INFO_BASIC); return s_d_func()->stackingOrder; } int KWindowSystemPrivateX11::currentDesktop() { if (!QX11Info::connection()) { return 1; } if (mapViewport()) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); NETPoint p = s_d->desktopViewport(s_d->currentDesktop(true)); return viewportToDesktop(QPoint(p.x, p.y)); } NETEventFilter *const s_d = s_d_func(); if (s_d) { return s_d->currentDesktop(true); } NETRootInfo info(QX11Info::connection(), NET::CurrentDesktop); return info.currentDesktop(true); } int KWindowSystemPrivateX11::numberOfDesktops() { if (!QX11Info::connection()) { return 1; } if (mapViewport()) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); NETSize s = s_d->desktopGeometry(); return s.width / displayWidth() * s.height / displayHeight(); } NETEventFilter *const s_d = s_d_func(); if (s_d) { return s_d->numberOfDesktops(true); } NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops); return info.numberOfDesktops(true); } void KWindowSystemPrivateX11::setCurrentDesktop(int desktop) { if (mapViewport()) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); - NETRootInfo info(QX11Info::connection(), 0); + NETRootInfo info(QX11Info::connection(), nullptr); QPoint pos = desktopToViewport(desktop, true); NETPoint p; p.x = pos.x(); p.y = pos.y(); info.setDesktopViewport(s_d->currentDesktop(true), p); return; } - NETRootInfo info(QX11Info::connection(), 0); + NETRootInfo info(QX11Info::connection(), nullptr); info.setCurrentDesktop(desktop, true); } void KWindowSystemPrivateX11::setOnAllDesktops(WId win, bool b) { if (mapViewport()) { if (b) { setState(win, NET::Sticky); } else { clearState(win, NET::Sticky); } return; } - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMDesktop, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMDesktop, nullptr); if (b) { info.setDesktop(NETWinInfo::OnAllDesktops, true); } else if (info.desktop(true) == NETWinInfo::OnAllDesktops) { NETRootInfo rinfo(QX11Info::connection(), NET::CurrentDesktop); info.setDesktop(rinfo.currentDesktop(true), true); } } void KWindowSystemPrivateX11::setOnDesktop(WId win, int desktop) { if (mapViewport()) { if (desktop == NET::OnAllDesktops) { return setOnAllDesktops(win, true); } else { clearState(win, NET::Sticky); } init(INFO_BASIC); QPoint p = desktopToViewport(desktop, false); Window dummy; int x, y; unsigned int w, h, b, dp; XGetGeometry(QX11Info::display(), win, &dummy, &x, &y, &w, &h, &b, &dp); // get global position XTranslateCoordinates(QX11Info::display(), win, QX11Info::appRootWindow(), 0, 0, &x, &y, &dummy); x += w / 2; // center y += h / 2; // transform to coordinates on the current "desktop" x = x % displayWidth(); y = y % displayHeight(); if (x < 0) { x = x + displayWidth(); } if (y < 0) { y = y + displayHeight(); } x += p.x(); // move to given "desktop" y += p.y(); x -= w / 2; // from center back to topleft y -= h / 2; p = constrainViewportRelativePosition(QPoint(x, y)); int flags = (NET::FromTool << 12) | (0x03 << 8) | 10; // from tool(?), x/y, static gravity NETEventFilter *const s_d = s_d_func(); s_d->moveResizeWindowRequest(win, flags, p.x(), p.y(), w, h); return; } - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMDesktop, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMDesktop, nullptr); info.setDesktop(desktop, true); } void KWindowSystemPrivateX11::setOnActivities(WId win, const QStringList &activities) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), 0, NET::WM2Activities); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), nullptr, NET::WM2Activities); info.setActivities(activities.join(QLatin1Char(',')).toLatin1().constData()); } WId KWindowSystemPrivateX11::activeWindow() { NETEventFilter *const s_d = s_d_func(); if (s_d) { return s_d->activeWindow(); } NETRootInfo info(QX11Info::connection(), NET::ActiveWindow); return info.activeWindow(); } void KWindowSystemPrivateX11::activateWindow(WId win, long time) { - NETRootInfo info(QX11Info::connection(), 0); + NETRootInfo info(QX11Info::connection(), nullptr); if (time == 0) { time = QX11Info::appUserTime(); } info.setActiveWindow(win, NET::FromApplication, time, QGuiApplication::focusWindow() ? QGuiApplication::focusWindow()->winId() : 0); } void KWindowSystemPrivateX11::forceActiveWindow(WId win, long time) { - NETRootInfo info(QX11Info::connection(), 0); + NETRootInfo info(QX11Info::connection(), nullptr); if (time == 0) { time = QX11Info::appTime(); } info.setActiveWindow(win, NET::FromTool, time, 0); } void KWindowSystemPrivateX11::demandAttention(WId win, bool set) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, 0); - info.setState(set ? NET::DemandsAttention : NET::States(0), NET::DemandsAttention); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, nullptr); + info.setState(set ? NET::DemandsAttention : NET::States(nullptr), NET::DemandsAttention); } #ifndef KWINDOWSYSTEM_NO_DEPRECATED WId KWindowSystemPrivateX11::transientFor(WId win) { - KWindowInfo info(win, 0, NET::WM2TransientFor); + KWindowInfo info(win, nullptr, NET::WM2TransientFor); return info.transientFor(); } #endif #ifndef KWINDOWSYSTEM_NO_DEPRECATED WId KWindowSystemPrivateX11::groupLeader(WId win) { - KWindowInfo info(win, 0, NET::WM2GroupLeader); + KWindowInfo info(win, nullptr, NET::WM2GroupLeader); return info.groupLeader(); } #endif QPixmap KWindowSystemPrivateX11::icon(WId win, int width, int height, bool scale, int flags) { NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMIcon, NET::WM2WindowClass | NET::WM2IconPixmap); return iconFromNetWinInfo(width, height, scale, flags, &info); } QPixmap KWindowSystemPrivateX11::iconFromNetWinInfo(int width, int height, bool scale, int flags, NETWinInfo *info) { QPixmap result; if (!info) { return result; } if (flags & KWindowSystem::NETWM) { NETIcon ni = info->icon(width, height); if (ni.data && ni.size.width > 0 && ni.size.height > 0) { QImage img((uchar *) ni.data, (int) ni.size.width, (int) ni.size.height, QImage::Format_ARGB32); if (scale && width > 0 && height > 0 && img.size() != QSize(width, height) && !img.isNull()) { img = img.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } if (!img.isNull()) { result = QPixmap::fromImage(img); } return result; } } if (flags & KWindowSystem::WMHints) { xcb_pixmap_t p = info->icccmIconPixmap(); xcb_pixmap_t p_mask = info->icccmIconPixmapMask(); if (p != XCB_PIXMAP_NONE) { QPixmap pm = KXUtils::createPixmapFromHandle(info->xcbConnection(), p, p_mask); if (scale && width > 0 && height > 0 && !pm.isNull() && (pm.width() != width || pm.height() != height)) { result = QPixmap::fromImage(pm.toImage().scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } else { result = pm; } } } // Since width can be any arbitrary size, but the icons cannot, // take the nearest value for best results (ignoring 22 pixel // icons as they don't exist for apps): int iconWidth; if (width < 24) { iconWidth = 16; } else if (width < 40) { iconWidth = 32; } else if (width < 56) { iconWidth = 48; } else if (width < 96) { iconWidth = 64; } else if (width < 192) { iconWidth = 128; } else { iconWidth = 256; } if (flags & KWindowSystem::ClassHint) { // Try to load the icon from the classhint if the app didn't specify // its own: if (result.isNull()) { const QIcon icon = QIcon::fromTheme(QString::fromUtf8(info->windowClassClass()).toLower()); const QPixmap pm = icon.isNull() ? QPixmap() : icon.pixmap(iconWidth, iconWidth); if (scale && !pm.isNull()) { result = QPixmap::fromImage(pm.toImage().scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } else { result = pm; } } } if (flags & KWindowSystem::XApp) { // If the icon is still a null pixmap, load the icon for X applications // as a last resort: if (result.isNull()) { const QIcon icon = QIcon::fromTheme(QLatin1String("xorg")); const QPixmap pm = icon.isNull() ? QPixmap() : icon.pixmap(iconWidth, iconWidth); if (scale && !pm.isNull()) { result = QPixmap::fromImage(pm.toImage().scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } else { result = pm; } } } return result; } void KWindowSystemPrivateX11::setIcons(WId win, const QPixmap &icon, const QPixmap &miniIcon) { if (icon.isNull()) { return; } - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), nullptr, nullptr); QImage img = icon.toImage().convertToFormat(QImage::Format_ARGB32); NETIcon ni; ni.size.width = img.size().width(); ni.size.height = img.size().height(); ni.data = (unsigned char *) img.bits(); info.setIcon(ni, true); if (miniIcon.isNull()) { return; } img = miniIcon.toImage().convertToFormat(QImage::Format_ARGB32); if (img.isNull()) { return; } ni.size.width = img.size().width(); ni.size.height = img.size().height(); ni.data = (unsigned char *) img.bits(); info.setIcon(ni, false); } void KWindowSystemPrivateX11::setType(WId win, NET::WindowType windowType) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), nullptr, nullptr); info.setWindowType(windowType); } void KWindowSystemPrivateX11::setState(WId win, NET::States state) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, nullptr); info.setState(state, state); } void KWindowSystemPrivateX11::clearState(WId win, NET::States state) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, 0); - info.setState(0, state); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), NET::WMState, nullptr); + info.setState(nullptr, state); } // enum values for ICCCM 4.1.2.4 and 4.1.4, defined to not depend on xcb-icccm enum { _ICCCM_WM_STATE_WITHDRAWN = 0, _ICCCM_WM_STATE_NORMAL = 1, _ICCCM_WM_STATE_ICONIC = 3 }; void KWindowSystemPrivateX11::minimizeWindow(WId win) { create_atoms(); // as described in ICCCM 4.1.4 xcb_client_message_event_t ev; memset(&ev, 0, sizeof(ev)); ev.response_type = XCB_CLIENT_MESSAGE; ev.window = win; ev.type = _wm_change_state; ev.format = 32; ev.data.data32[0] = _ICCCM_WM_STATE_ICONIC; ev.data.data32[1] = 0; ev.data.data32[2] = 0; ev.data.data32[3] = 0; ev.data.data32[4] = 0; xcb_send_event(QX11Info::connection(), false, QX11Info::appRootWindow(), XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, reinterpret_cast(&ev)); } void KWindowSystemPrivateX11::unminimizeWindow(WId win) { xcb_map_window(QX11Info::connection(), win); } void KWindowSystemPrivateX11::raiseWindow(WId win) { NETRootInfo info(QX11Info::connection(), NET::Supported); if (info.isSupported(NET::WM2RestackWindow)) { info.restackRequest(win, NET::FromTool, XCB_WINDOW_NONE, XCB_STACK_MODE_ABOVE, QX11Info::appUserTime()); } else { const uint32_t values[] = { XCB_STACK_MODE_ABOVE }; xcb_configure_window(QX11Info::connection(), win, XCB_CONFIG_WINDOW_STACK_MODE, values); } } void KWindowSystemPrivateX11::lowerWindow(WId win) { NETRootInfo info(QX11Info::connection(), NET::Supported); if (info.isSupported(NET::WM2RestackWindow)) { info.restackRequest(win, NET::FromTool, XCB_WINDOW_NONE, XCB_STACK_MODE_BELOW, QX11Info::appUserTime()); } else { const uint32_t values[] = { XCB_STACK_MODE_BELOW }; xcb_configure_window(QX11Info::connection(), win, XCB_CONFIG_WINDOW_STACK_MODE, values); } } bool KWindowSystemPrivateX11::compositingActive() { init(INFO_BASIC); if (s_d_func()->haveXfixes) { return s_d_func()->compositingEnabled; } else { create_atoms(); return XGetSelectionOwner(QX11Info::display(), net_wm_cm); } } QRect KWindowSystemPrivateX11::workArea(int desktop) { init(INFO_BASIC); int desk = (desktop > 0 && desktop <= (int) s_d_func()->numberOfDesktops()) ? desktop : currentDesktop(); if (desk <= 0) { return displayGeometry(); } NETRect r = s_d_func()->workArea(desk); if (r.size.width <= 0 || r.size.height <= 0) { // not set return displayGeometry(); } return QRect(r.pos.x, r.pos.y, r.size.width, r.size.height); } QRect KWindowSystemPrivateX11::workArea(const QList &exclude, int desktop) { init(INFO_WINDOWS); // invalidates s_d_func's return value NETEventFilter *const s_d = s_d_func(); QRect all = displayGeometry(); QRect a = all; if (desktop == -1) { desktop = s_d->currentDesktop(); } QList::ConstIterator it1; for (it1 = s_d->windows.constBegin(); it1 != s_d->windows.constEnd(); ++it1) { if (exclude.contains(*it1)) { continue; } // Kicker (very) extensively calls this function, causing hundreds of roundtrips just // to repeatedly find out struts of all windows. Therefore strut values for strut // windows are cached here. NETStrut strut; auto it2 = s_d->strutWindows.begin(); for (; it2 != s_d->strutWindows.end(); ++it2) if ((*it2).window == *it1) { break; } if (it2 != s_d->strutWindows.end()) { if (!((*it2).desktop == desktop || (*it2).desktop == NETWinInfo::OnAllDesktops)) { continue; } strut = (*it2).strut; } else if (s_d->possibleStrutWindows.contains(*it1)) { - NETWinInfo info(QX11Info::connection(), (*it1), QX11Info::appRootWindow(), NET::WMStrut | NET::WMDesktop, 0); + NETWinInfo info(QX11Info::connection(), (*it1), QX11Info::appRootWindow(), NET::WMStrut | NET::WMDesktop, nullptr); strut = info.strut(); s_d->possibleStrutWindows.removeAll(*it1); s_d->strutWindows.append(NETEventFilter::StrutData(*it1, info.strut(), info.desktop())); if (!(info.desktop() == desktop || info.desktop() == NETWinInfo::OnAllDesktops)) { continue; } } else { continue; // not a strut window } QRect r = all; if (strut.left > 0) { r.setLeft(r.left() + (int) strut.left); } if (strut.top > 0) { r.setTop(r.top() + (int) strut.top); } if (strut.right > 0) { r.setRight(r.right() - (int) strut.right); } if (strut.bottom > 0) { r.setBottom(r.bottom() - (int) strut.bottom); } a = a.intersected(r); } return a; } QString KWindowSystemPrivateX11::desktopName(int desktop) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); bool isDesktopSane = (desktop > 0 && desktop <= (int) s_d->numberOfDesktops()); const char *name = s_d->desktopName(isDesktopSane ? desktop : currentDesktop()); if (name && name[0]) { return QString::fromUtf8(name); } return KWindowSystem::tr("Desktop %1").arg(desktop); } void KWindowSystemPrivateX11::setDesktopName(int desktop, const QString &name) { NETEventFilter *const s_d = s_d_func(); if (desktop <= 0 || desktop > (int) numberOfDesktops()) { desktop = currentDesktop(); } if (s_d) { s_d->setDesktopName(desktop, name.toUtf8().constData()); return; } - NETRootInfo info(QX11Info::connection(), 0); + NETRootInfo info(QX11Info::connection(), nullptr); info.setDesktopName(desktop, name.toUtf8().constData()); } bool KWindowSystemPrivateX11::showingDesktop() { init(INFO_BASIC); return s_d_func()->showingDesktop(); } void KWindowSystemPrivateX11::setShowingDesktop(bool showing) { - NETRootInfo info(QX11Info::connection(), 0, NET::WM2ShowingDesktop); + NETRootInfo info(QX11Info::connection(), nullptr, NET::WM2ShowingDesktop); info.setShowingDesktop(showing); } void KWindowSystemPrivateX11::setUserTime(WId win, long time) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), nullptr, nullptr); info.setUserTime(time); } void KWindowSystemPrivateX11::setExtendedStrut(WId win, int left_width, int left_start, int left_end, int right_width, int right_start, int right_end, int top_width, int top_start, int top_end, int bottom_width, int bottom_start, int bottom_end) { - NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), win, QX11Info::appRootWindow(), nullptr, nullptr); NETExtendedStrut strut; strut.left_width = left_width; strut.right_width = right_width; strut.top_width = top_width; strut.bottom_width = bottom_width; strut.left_start = left_start; strut.left_end = left_end; strut.right_start = right_start; strut.right_end = right_end; strut.top_start = top_start; strut.top_end = top_end; strut.bottom_start = bottom_start; strut.bottom_end = bottom_end; info.setExtendedStrut(strut); NETStrut oldstrut; oldstrut.left = left_width; oldstrut.right = right_width; oldstrut.top = top_width; oldstrut.bottom = bottom_width; info.setStrut(oldstrut); } void KWindowSystemPrivateX11::setStrut(WId win, int left, int right, int top, int bottom) { int w = displayWidth(); int h = displayHeight(); setExtendedStrut(win, left, 0, left != 0 ? w : 0, right, 0, right != 0 ? w : 0, top, 0, top != 0 ? h : 0, bottom, 0, bottom != 0 ? h : 0); } bool KWindowSystemPrivateX11::icccmCompliantMappingState() { static enum { noidea, yes, no } wm_is_1_2_compliant = noidea; if (wm_is_1_2_compliant == noidea) { NETRootInfo info(QX11Info::connection(), NET::Supported); wm_is_1_2_compliant = info.isSupported(NET::Hidden) ? yes : no; } return wm_is_1_2_compliant == yes; } bool KWindowSystemPrivateX11::allowedActionsSupported() { static enum { noidea, yes, no } wm_supports_allowed_actions = noidea; if (wm_supports_allowed_actions == noidea) { NETRootInfo info(QX11Info::connection(), NET::Supported); wm_supports_allowed_actions = info.isSupported(NET::WM2AllowedActions) ? yes : no; } return wm_supports_allowed_actions == yes; } QString KWindowSystemPrivateX11::readNameProperty(WId win, unsigned long atom) { XTextProperty tp; - char **text = NULL; + char **text = nullptr; int count; QString result; - if (XGetTextProperty(QX11Info::display(), win, &tp, atom) != 0 && tp.value != NULL) { + if (XGetTextProperty(QX11Info::display(), win, &tp, atom) != 0 && tp.value != nullptr) { create_atoms(); if (tp.encoding == kwm_utf8_string) { result = QString::fromUtf8((const char *) tp.value); } else if (XmbTextPropertyToTextList(QX11Info::display(), &tp, &text, &count) == Success && - text != NULL && count > 0) { + text != nullptr && count > 0) { result = QString::fromLocal8Bit(text[0]); } else if (tp.encoding == XA_STRING) { result = QString::fromLocal8Bit((const char *) tp.value); } - if (text != NULL) { + if (text != nullptr) { XFreeStringList(text); } XFree(tp.value); } return result; } void KWindowSystemPrivateX11::allowExternalProcessWindowActivation(int pid) { // Normally supported by X11, but may depend on some window managers ? Q_UNUSED(pid) } void KWindowSystemPrivateX11::setBlockingCompositing(WId window, bool active) { - NETWinInfo info(QX11Info::connection(), window, QX11Info::appRootWindow(), 0, 0); + NETWinInfo info(QX11Info::connection(), window, QX11Info::appRootWindow(), nullptr, nullptr); info.setBlockingCompositing(active); } bool KWindowSystemPrivateX11::mapViewport() { NETEventFilter *const s_d = s_d_func(); if (s_d) { return s_d->mapViewport(); } // avoid creating KWindowSystemPrivate NETRootInfo infos(QX11Info::connection(), NET::Supported); if (!infos.isSupported(NET::DesktopViewport)) { return false; } NETRootInfo info(QX11Info::connection(), NET::NumberOfDesktops | NET::CurrentDesktop | NET::DesktopGeometry); if (info.numberOfDesktops(true) <= 1 && (info.desktopGeometry().width > displayWidth() || info.desktopGeometry().height > displayHeight())) { return true; } return false; } int KWindowSystemPrivateX11::viewportToDesktop(const QPoint &p) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); NETSize s = s_d->desktopGeometry(); QSize vs(displayWidth(), displayHeight()); int xs = s.width / vs.width(); int x = p.x() < 0 ? 0 : p.x() >= s.width ? xs - 1 : p.x() / vs.width(); int ys = s.height / vs.height(); int y = p.y() < 0 ? 0 : p.y() >= s.height ? ys - 1 : p.y() / vs.height(); return y * xs + x + 1; } int KWindowSystemPrivateX11::viewportWindowToDesktop(const QRect &r) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); QPoint p = r.center(); // make absolute p = QPoint(p.x() + s_d->desktopViewport(s_d->currentDesktop(true)).x, p.y() + s_d->desktopViewport(s_d->currentDesktop(true)).y); NETSize s = s_d->desktopGeometry(); QSize vs(displayWidth(), displayHeight()); int xs = s.width / vs.width(); int x = p.x() < 0 ? 0 : p.x() >= s.width ? xs - 1 : p.x() / vs.width(); int ys = s.height / vs.height(); int y = p.y() < 0 ? 0 : p.y() >= s.height ? ys - 1 : p.y() / vs.height(); return y * xs + x + 1; } QPoint KWindowSystemPrivateX11::desktopToViewport(int desktop, bool absolute) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); NETSize s = s_d->desktopGeometry(); QSize vs(displayWidth(), displayHeight()); int xs = s.width / vs.width(); int ys = s.height / vs.height(); if (desktop <= 0 || desktop > xs * ys) { return QPoint(0, 0); } --desktop; QPoint ret(vs.width() * (desktop % xs), vs.height() * (desktop / xs)); if (!absolute) { ret = QPoint(ret.x() - s_d->desktopViewport(s_d->currentDesktop(true)).x, ret.y() - s_d->desktopViewport(s_d->currentDesktop(true)).y); if (ret.x() >= s.width) { ret.setX(ret.x() - s.width); } if (ret.x() < 0) { ret.setX(ret.x() + s.width); } if (ret.y() >= s.height) { ret.setY(ret.y() - s.height); } if (ret.y() < 0) { ret.setY(ret.y() + s.height); } } return ret; } QPoint KWindowSystemPrivateX11::constrainViewportRelativePosition(const QPoint &pos) { init(INFO_BASIC); NETEventFilter *const s_d = s_d_func(); NETSize s = s_d->desktopGeometry(); NETPoint c = s_d->desktopViewport(s_d->currentDesktop(true)); int x = (pos.x() + c.x) % s.width; int y = (pos.y() + c.y) % s.height; if (x < 0) { x += s.width; } if (y < 0) { y += s.height; } return QPoint(x - c.x, y - c.y); } #include "moc_kwindowsystem_p_x11.cpp" diff --git a/src/platforms/xcb/kxerrorhandler.cpp b/src/platforms/xcb/kxerrorhandler.cpp index e42535a..54398e7 100644 --- a/src/platforms/xcb/kxerrorhandler.cpp +++ b/src/platforms/xcb/kxerrorhandler.cpp @@ -1,246 +1,246 @@ /* Copyright (c) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "kxerrorhandler_p.h" #include #include "netwm_def.h" #include class KXErrorHandlerPrivate { public: KXErrorHandlerPrivate(Display *dpy) : first_request(XNextRequest(dpy)), display(dpy), was_error(false) { } unsigned long first_request; Display *display; bool was_error; XErrorEvent error_event; }; -KXErrorHandler **KXErrorHandler::handlers = NULL; +KXErrorHandler **KXErrorHandler::handlers = nullptr; int KXErrorHandler::pos = 0; int KXErrorHandler::size = 0; KXErrorHandler::KXErrorHandler(Display *dpy) - : user_handler1(NULL), - user_handler2(NULL), + : user_handler1(nullptr), + user_handler2(nullptr), old_handler(XSetErrorHandler(handler_wrapper)), d(new KXErrorHandlerPrivate(dpy)) { addHandler(); } KXErrorHandler::KXErrorHandler(int (*handler)(Display *, XErrorEvent *), Display *dpy) - : user_handler1(NULL), + : user_handler1(nullptr), user_handler2(handler), old_handler(XSetErrorHandler(handler_wrapper)), d(new KXErrorHandlerPrivate(dpy)) { addHandler(); } KXErrorHandler::~KXErrorHandler() { XSetErrorHandler(old_handler); Q_ASSERT_X(this == handlers[ pos - 1 ], "KXErrorHandler", "out of order"); --pos; delete d; } void KXErrorHandler::addHandler() { if (size == pos) { size += 16; handlers = static_cast< KXErrorHandler ** >(realloc(handlers, size * sizeof(KXErrorHandler *))); } handlers[ pos++ ] = this; } bool KXErrorHandler::error(bool sync) const { if (sync) { XSync(d->display, False); } return d->was_error; } XErrorEvent KXErrorHandler::errorEvent() const { return d->error_event; } int KXErrorHandler::handler_wrapper(Display *dpy, XErrorEvent *e) { --pos; int ret = handlers[ pos ]->handle(dpy, e); ++pos; return ret; } int KXErrorHandler::handle(Display *dpy, XErrorEvent *e) { if (dpy == d->display // e->serial >= d->first_request , compare like X timestamps to handle wrapping && NET::timestampCompare(e->serial, d->first_request) >= 0) { // it's for us //qDebug( "Handling: %p", static_cast< void* >( this )); bool error = false; - if (user_handler1 != NULL) { + if (user_handler1 != nullptr) { if (user_handler1(e->request_code, e->error_code, e->resourceid)) { error = true; } - } else if (user_handler2 != NULL) { + } else if (user_handler2 != nullptr) { if (user_handler2(dpy, e) != 0) { error = true; } } else { // no handler set, simply set that there was an error error = true; } if (error && !d->was_error) { // only remember the first d->was_error = true; d->error_event = *e; } return 0; } //qDebug( "Going deeper: %p", static_cast< void* >( this )); return old_handler(dpy, e); } QByteArray KXErrorHandler::errorMessage(const XErrorEvent &event, Display *dpy) { // "Error: (), Request: (), Resource: " QByteArray ret; char tmp[ 256 ]; char num[ 256 ]; #if 0 // see below if (event.request_code < 128) // core request #endif { XGetErrorText(dpy, event.error_code, tmp, 255); if (char *paren = strchr(tmp, '(')) { // the explanation in parentheses just makes *paren = '\0'; // it more verbose and is not really useful } // the various casts are to get overloads non-ambiguous :-/ ret = QByteArray("error: ") + (const char *)tmp + '[' + QByteArray::number(event.error_code) + ']'; sprintf(num, "%d", event.request_code); XGetErrorDatabaseText(dpy, "XRequest", num, "", tmp, 256); ret += QByteArray(", request: ") + (const char *)tmp + '[' + QByteArray::number(event.request_code) + ']'; if (event.resourceid != 0) { ret += QByteArray(", resource: 0x") + QByteArray::number((qlonglong)event.resourceid, 16); } } #if 0 else { // extensions // XGetErrorText() currently has a bug that makes it fail to find text // for some errors (when error==error_base), also XGetErrorDatabaseText() // requires the right extension name, so it is needed to get info about // all extensions. However that is almost impossible: // - Xlib itself has it, but in internal data. // - Opening another X connection now can cause deadlock with server grabs. // - Fetching it at startup means a bunch of roundtrips. // So if this becomes more useful in the future, do the roundtrips at startup, // or fetch it in kded and export as an env.var or something. Display *dpy2 = XOpenDisplay(XDisplayString(dpy)); int nextensions; char **extensions = XListExtensions(dpy2, &nextensions); int *majors = NULL; int *error_bases = NULL; if (extensions == NULL) { nextensions = 0; } else { majors = new int[ nextensions ]; error_bases = new int[ nextensions ]; for (int i = 0; i < nextensions; ++i) { int dummy; if (!XQueryExtension(dpy2, extensions[ i ], &majors[ i ], &dummy, &error_bases[ i ])) { majors[ i ] = 0; error_bases[ i ] = 0; } } } XGetErrorText(dpy, event.error_code, tmp, 255); int index = -1; int base = 0; for (int i = 0; i < nextensions; ++i) if (error_bases[ i ] != 0 && event.error_code >= error_bases[ i ] && (index == -1 || error_bases[ i ] > base)) { index = i; base = error_bases[ i ]; } if (tmp == QString::number(event.error_code)) { // XGetErrorText() failed, // or it has a bug that causes not finding all errors, check ourselves if (index != -1) { qsnprintf(num, 255, "%s.%d", extensions[ index ], event.error_code - base); XGetErrorDatabaseText(dpy, "XProtoError", num, "", tmp, 255); } else { strcpy(tmp, ""); } } if (char *paren = strchr(tmp, '(')) { *paren = '\0'; } if (index != -1) ret = QByteArray("error: ") + (const char *)tmp + '[' + (const char *)extensions[ index ] + '+' + QByteArray::number(event.error_code - base) + ']'; else { ret = QByteArray("error: ") + (const char *)tmp + '[' + QByteArray::number(event.error_code) + ']'; } tmp[ 0 ] = '\0'; for (int i = 0; i < nextensions; ++i) if (majors[ i ] == event.request_code) { qsnprintf(num, 255, "%s.%d", extensions[ i ], event.minor_code); XGetErrorDatabaseText(dpy, "XRequest", num, "", tmp, 255); ret += QByteArray(", request: ") + (const char *)tmp + '[' + (const char *)extensions[ i ] + '+' + QByteArray::number(event.minor_code) + ']'; } if (tmp[ 0 ] == '\0') // not found??? ret += QByteArray(", request [") + QByteArray::number(event.request_code) + ':' + QByteArray::number(event.minor_code) + ']'; if (event.resourceid != 0) { ret += QByteArray(", resource: 0x") + QByteArray::number((qlonglong)event.resourceid, 16); } if (extensions != NULL) { XFreeExtensionList(extensions); } delete[] majors; delete[] error_bases; XCloseDisplay(dpy2); } #endif return ret; } diff --git a/src/platforms/xcb/kxmessages.cpp b/src/platforms/xcb/kxmessages.cpp index d2862cf..76d8516 100644 --- a/src/platforms/xcb/kxmessages.cpp +++ b/src/platforms/xcb/kxmessages.cpp @@ -1,362 +1,362 @@ /**************************************************************************** Copyright (C) 2001-2003 Lubos Lunak Copyright 2012 David Faure Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "kxmessages.h" #include "kxutils_p.h" #if KWINDOWSYSTEM_HAVE_X11 #include #include #include // WId #include #include #include #include class XcbAtom { public: explicit XcbAtom(const QByteArray &name, bool onlyIfExists = false) : m_name(name) , m_atom(XCB_ATOM_NONE) , m_connection(Q_NULLPTR) , m_retrieved(false) , m_onlyIfExists(onlyIfExists) { m_cookie.sequence = 0; } explicit XcbAtom(xcb_connection_t *c, const QByteArray &name, bool onlyIfExists = false) : m_name(name) , m_atom(XCB_ATOM_NONE) , m_cookie(xcb_intern_atom_unchecked(c, onlyIfExists, name.length(), name.constData())) , m_connection(c) , m_retrieved(false) , m_onlyIfExists(onlyIfExists) { } ~XcbAtom() { if (!m_retrieved && m_cookie.sequence && m_connection) { xcb_discard_reply(m_connection, m_cookie.sequence); } } operator xcb_atom_t() { getReply(); return m_atom; } inline const QByteArray &name() const { return m_name; } inline void setConnection(xcb_connection_t *c) { m_connection = c; } inline void fetch() { if (!m_connection || m_name.isEmpty()) { return; } m_cookie = xcb_intern_atom_unchecked(m_connection, m_onlyIfExists, m_name.length(), m_name.constData()); } private: void getReply() { if (m_retrieved || !m_cookie.sequence || !m_connection) { return; } KXUtils::ScopedCPointer reply(xcb_intern_atom_reply(m_connection, m_cookie, Q_NULLPTR)); if (!reply.isNull()) { m_atom = reply->atom; } m_retrieved = true; } QByteArray m_name; xcb_atom_t m_atom; xcb_intern_atom_cookie_t m_cookie; xcb_connection_t *m_connection; bool m_retrieved; bool m_onlyIfExists; }; class KXMessagesPrivate : public QAbstractNativeEventFilter { public: KXMessagesPrivate(KXMessages *parent, const char *acceptBroadcast, xcb_connection_t *c, xcb_window_t root) : accept_atom1(acceptBroadcast ? QByteArray(acceptBroadcast) + QByteArrayLiteral("_BEGIN") : QByteArray()) , accept_atom2(acceptBroadcast ? QByteArray(acceptBroadcast) : QByteArray()) , handle(new QWidget) , q(parent) , valid(c) , connection(c) , rootWindow(root) { if (acceptBroadcast) { accept_atom1.setConnection(c); accept_atom1.fetch(); accept_atom2.setConnection(c); accept_atom2.fetch(); QCoreApplication::instance()->installNativeEventFilter(this); } } XcbAtom accept_atom1; XcbAtom accept_atom2; QMap< WId, QByteArray > incoming_messages; QScopedPointer handle; KXMessages *q; bool valid; xcb_connection_t *connection; xcb_window_t rootWindow; bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE { Q_UNUSED(result); if (eventType != "xcb_generic_event_t") { return false; } xcb_generic_event_t *event = reinterpret_cast(message); uint response_type = event->response_type & ~0x80; if (response_type != XCB_CLIENT_MESSAGE) { return false; } xcb_client_message_event_t *cm_event = reinterpret_cast(event); if (cm_event->format != 8) { return false; } if (cm_event->type != accept_atom1 && cm_event->type != accept_atom2) { return false; } char buf[ 21 ]; // can't be longer // Copy the data in order to null-terminate it qstrncpy(buf, reinterpret_cast(cm_event->data.data8), 21); //qDebug() << cm_event->window << "buf=\"" << buf << "\" atom=" << (cm_event->type == accept_atom1 ? "atom1" : "atom2"); if (incoming_messages.contains(cm_event->window)) { if (cm_event->type == accept_atom1) // two different messages on the same window at the same time shouldn't happen anyway { incoming_messages[cm_event->window] = QByteArray(); } incoming_messages[cm_event->window] += buf; } else { if (cm_event->type == accept_atom2) { return false; // middle of message, but we don't have the beginning } incoming_messages[cm_event->window] = buf; } if (strlen(buf) < 20) { // last message fragment emit q->gotMessage(QString::fromUtf8(incoming_messages[cm_event->window].constData())); incoming_messages.remove(cm_event->window); } return false; // lets other KXMessages instances get the event too } }; #ifndef KWINDOWSYSTEM_NO_DEPRECATED static void send_message_internal(WId w_P, const QString &msg_P, long mask_P, Display *disp, Atom atom1_P, Atom atom2_P, Window handle_P); // for broadcasting static const long BROADCAST_MASK = PropertyChangeMask; // CHECKME #endif static void send_message_internal(xcb_window_t w, const QString &msg, xcb_connection_t *c, xcb_atom_t leadingMessage, xcb_atom_t followingMessage, xcb_window_t handle); KXMessages::KXMessages(const char *accept_broadcast_P, QObject *parent_P) : QObject(parent_P) , d(new KXMessagesPrivate(this, accept_broadcast_P, QX11Info::isPlatformX11() ? QX11Info::connection() : Q_NULLPTR, QX11Info::isPlatformX11() ? QX11Info::appRootWindow() : 0)) { } KXMessages::KXMessages(xcb_connection_t *connection, xcb_window_t rootWindow, const char *accept_broadcast, QObject *parent) : QObject(parent) , d(new KXMessagesPrivate(this, accept_broadcast, connection, rootWindow)) { } KXMessages::~KXMessages() { delete d; } static xcb_screen_t *defaultScreen(xcb_connection_t *c, int screen) { for (xcb_screen_iterator_t it = xcb_setup_roots_iterator(xcb_get_setup(c)); it.rem; --screen, xcb_screen_next(&it)) { if (screen == 0) { return it.data; } } return Q_NULLPTR; } void KXMessages::broadcastMessage(const char *msg_type_P, const QString &message_P, int screen_P) { if (!d->valid) { qWarning() << "KXMessages used on non-X11 platform! This is an application bug."; return; } const QByteArray msg(msg_type_P); XcbAtom a2(d->connection, msg); XcbAtom a1(d->connection, msg + QByteArrayLiteral("_BEGIN")); xcb_window_t root = screen_P == -1 ? d->rootWindow : defaultScreen(d->connection, screen_P)->root; send_message_internal(root, message_P, d->connection, a1, a2, d->handle->winId()); } #ifndef KWINDOWSYSTEM_NO_DEPRECATED bool KXMessages::broadcastMessageX(Display *disp, const char *msg_type_P, const QString &message_P, int screen_P) { - if (disp == NULL) { + if (disp == nullptr) { return false; } Atom a2 = XInternAtom(disp, msg_type_P, false); Atom a1 = XInternAtom(disp, QByteArray(QByteArray(msg_type_P) + "_BEGIN").constData(), false); Window root = screen_P == -1 ? DefaultRootWindow(disp) : RootWindow(disp, screen_P); Window win = XCreateSimpleWindow(disp, root, 0, 0, 1, 1, 0, BlackPixel(disp, screen_P == -1 ? DefaultScreen(disp) : screen_P), BlackPixel(disp, screen_P == -1 ? DefaultScreen(disp) : screen_P)); send_message_internal(root, message_P, BROADCAST_MASK, disp, a1, a2, win); XDestroyWindow(disp, win); return true; } #endif bool KXMessages::broadcastMessageX(xcb_connection_t *c, const char *msg_type_P, const QString &message, int screenNumber) { if (!c) { return false; } const QByteArray msg(msg_type_P); XcbAtom a2(c, msg); XcbAtom a1(c, msg + QByteArrayLiteral("_BEGIN")); const xcb_screen_t *screen = defaultScreen(c, screenNumber); if (!screen) { return false; } const xcb_window_t root = screen->root; const xcb_window_t win = xcb_generate_id(c); xcb_create_window(c, XCB_COPY_FROM_PARENT, win, root, 0, 0, 1, 1, 0, XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT, 0, Q_NULLPTR); send_message_internal(root, message, c, a1, a2, win); xcb_destroy_window(c, win); return true; } #if 0 // currently unused void KXMessages::sendMessage(WId w_P, const char *msg_type_P, const QString &message_P) { Atom a2 = XInternAtom(QX11Info::display(), msg_type_P, false); Atom a1 = XInternAtom(QX11Info::display(), QByteArray(QByteArray(msg_type_P) + "_BEGIN").constData(), false); send_message_internal(w_P, message_P, 0, QX11Info::display(), a1, a2, d->handle->winId()); } bool KXMessages::sendMessageX(Display *disp, WId w_P, const char *msg_type_P, const QString &message_P) { if (disp == NULL) { return false; } Atom a2 = XInternAtom(disp, msg_type_P, false); Atom a1 = XInternAtom(disp, QByteArray(QByteArray(msg_type_P) + "_BEGIN").constData(), false); Window win = XCreateSimpleWindow(disp, DefaultRootWindow(disp), 0, 0, 1, 1, 0, BlackPixelOfScreen(DefaultScreenOfDisplay(disp)), BlackPixelOfScreen(DefaultScreenOfDisplay(disp))); send_message_internal(w_P, message_P, 0, disp, a1, a2, win); XDestroyWindow(disp, win); return true; } #endif #ifndef KWINDOWSYSTEM_NO_DEPRECATED static void send_message_internal(WId w_P, const QString &msg_P, long mask_P, Display *disp, Atom atom1_P, Atom atom2_P, Window handle_P) { //qDebug() << "send_message_internal" << w_P << msg_P << mask_P << atom1_P << atom2_P << handle_P; unsigned int pos = 0; QByteArray msg = msg_P.toUtf8(); unsigned int len = strlen(msg.constData()); XEvent e; e.xclient.type = ClientMessage; e.xclient.message_type = atom1_P; // leading message e.xclient.display = disp; e.xclient.window = handle_P; e.xclient.format = 8; do { unsigned int i; for (i = 0; i < 20 && i + pos <= len; ++i) { e.xclient.data.b[ i ] = msg[ i + pos ]; } XSendEvent(disp, w_P, false, mask_P, &e); e.xclient.message_type = atom2_P; // following messages pos += i; } while (pos <= len); XFlush(disp); } #endif static void send_message_internal(xcb_window_t w, const QString &msg_P, xcb_connection_t *c, xcb_atom_t leadingMessage, xcb_atom_t followingMessage, xcb_window_t handle) { unsigned int pos = 0; QByteArray msg = msg_P.toUtf8(); const size_t len = strlen(msg.constData()); xcb_client_message_event_t event; event.response_type = XCB_CLIENT_MESSAGE; event.format = 8; event.sequence = 0; event.window = handle; event.type = leadingMessage; do { unsigned int i; for (i = 0; i < 20 && i + pos <= len; ++i) { event.data.data8[i] = msg[ i + pos ]; } for (unsigned int j = i; j < 20; ++j) { event.data.data8[j] = 0; } xcb_send_event(c, false, w, XCB_EVENT_MASK_PROPERTY_CHANGE, (const char *) &event); event.type = followingMessage; pos += i; } while (pos <= len); xcb_flush(c); } #endif diff --git a/src/platforms/xcb/kxmessages.h b/src/platforms/xcb/kxmessages.h index 7453027..5619a33 100644 --- a/src/platforms/xcb/kxmessages.h +++ b/src/platforms/xcb/kxmessages.h @@ -1,150 +1,150 @@ /**************************************************************************** Copyright (C) 2001-2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef KXMESSAGES_H #define KXMESSAGES_H #include #include #include #include // KWINDOWSYSTEM_HAVE_X11 #if KWINDOWSYSTEM_HAVE_X11 #include typedef struct _XDisplay Display; class QString; class KXMessagesPrivate; /** * Sending string messages to other applications using the X Client Messages. * * Used internally by KStartupInfo and kstart. * You usually don't want to use this, use D-Bus instead. * * @internal * * @author Lubos Lunak */ class KWINDOWSYSTEM_EXPORT KXMessages : public QObject { Q_OBJECT public: /** * Creates an instance which will receive X messages. * * @param accept_broadcast if non-NULL, all broadcast messages with * this message type will be received. * @param parent the parent of this widget */ - explicit KXMessages(const char *accept_broadcast = NULL, QObject *parent = NULL); + explicit KXMessages(const char *accept_broadcast = nullptr, QObject *parent = nullptr); /** * @overload * Overload passing in the xcb_connection_t to use instead relying on platform xcb. * * @param connection The xcb connection * @param rootWindow The rootWindow to use * @param accept_broadcast if non-NULL, all broadcast messages with * this message type will be received. * @param parent the parent of this object * @since 5.8 **/ explicit KXMessages(xcb_connection_t *connection, xcb_window_t rootWindow, const char *accept_broadcast = Q_NULLPTR, QObject *parent = Q_NULLPTR); virtual ~KXMessages(); /** * Broadcasts the given message with the given message type. * @param msg_type the type of the message * @param message the message itself * @param screen X11 screen to use, -1 for the default */ void broadcastMessage(const char *msg_type, const QString &message, int screen = -1); /** * Broadcasts the given message with the given message type. * * @param disp X11 connection which will be used instead of * QX11Info::display() * @param msg_type the type of the message * @param message the message itself * @param screen X11 screen to use, -1 for the default * @return false when an error occurred, true otherwise * @deprecated since 5.0 use xcb variant */ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED static bool broadcastMessageX(Display *disp, const char *msg_type, const QString &message, int screen = -1); #endif /** * Broadcasts the given message with the given message type. * * @param c X11 connection which will be used instead of * QX11Info::connection() * @param msg_type the type of the message * @param message the message itself * @param screenNumber X11 screen to use * @return false when an error occurred, true otherwise */ static bool broadcastMessageX(xcb_connection_t *c, const char *msg_type, const QString &message, int screenNumber); #if 0 // currently unused /** * Sends the given message with the given message type only to given * window. * * @param w X11 handle for the destination window * @param msg_type the type of the message * @param message the message itself */ void sendMessage(WId w, const char *msg_type, const QString &message); /** * Sends the given message with the given message type only to given * window. * * @param disp X11 connection which will be used instead of * QX11Info::display() * @param w X11 handle for the destination window * @param msg_type the type of the message * @param message the message itself * @return false when an error occurred, true otherwise */ static bool sendMessageX(Display *disp, WId w, const char *msg_type, const QString &message); #endif Q_SIGNALS: /** * Emitted when a message was received. * @param message the message that has been received */ void gotMessage(const QString &message); private: friend class KXMessagesPrivate; KXMessagesPrivate *const d; }; #endif #endif diff --git a/src/platforms/xcb/netwm.cpp b/src/platforms/xcb/netwm.cpp index 30c2e87..423d00b 100644 --- a/src/platforms/xcb/netwm.cpp +++ b/src/platforms/xcb/netwm.cpp @@ -1,4864 +1,4864 @@ /* Copyright (c) 2000 Troll Tech AS Copyright (c) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //#define NETWMDEBUG #include "netwm.h" #include #include #include "netwm_p.h" #include "atoms_p.h" #include #include #if KWINDOWSYSTEM_HAVE_X11 //FIXME #include #include #include #include #include #include #include // This struct is defined here to avoid a dependency on xcb-icccm struct kde_wm_hints { uint32_t flags; uint32_t input; int32_t initial_state; xcb_pixmap_t icon_pixmap; xcb_window_t icon_window; int32_t icon_x; int32_t icon_y; xcb_pixmap_t icon_mask; xcb_window_t window_group; }; typedef QHash< xcb_connection_t*, QSharedDataPointer > AtomHash; Q_GLOBAL_STATIC(AtomHash, s_gAtomsHash) static QSharedDataPointer atomsForConnection(xcb_connection_t *c) { auto it = s_gAtomsHash->constFind(c); if (it == s_gAtomsHash->constEnd()) { QSharedDataPointer atom(new Atoms(c)); s_gAtomsHash->insert(c, atom); return atom; } return it.value(); } Atoms::Atoms(xcb_connection_t *c) : QSharedData() , m_connection(c) { for (int i = 0; i < KwsAtomCount; ++i) { m_atoms[i] = XCB_ATOM_NONE; } init(); } static const uint32_t netwm_sendevent_mask = (XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY); const long MAX_PROP_SIZE = 100000; static char *nstrdup(const char *s1) { if (! s1) { - return (char *) 0; + return (char *) nullptr; } int l = strlen(s1) + 1; char *s2 = new char[l]; strncpy(s2, s1, l); return s2; } static char *nstrndup(const char *s1, int l) { if (! s1 || l == 0) { - return (char *) 0; + return (char *) nullptr; } char *s2 = new char[l + 1]; strncpy(s2, s1, l); s2[l] = '\0'; return s2; } static xcb_window_t *nwindup(const xcb_window_t *w1, int n) { if (! w1 || n == 0) { - return (xcb_window_t *) 0; + return (xcb_window_t *) nullptr; } xcb_window_t *w2 = new xcb_window_t[n]; while (n--) { w2[n] = w1[n]; } return w2; } static void refdec_nri(NETRootInfoPrivate *p) { #ifdef NETWMDEBUG fprintf(stderr, "NET: decrementing NETRootInfoPrivate::ref (%d)\n", p->ref - 1); #endif if (! --p->ref) { #ifdef NETWMDEBUG fprintf(stderr, "NET: \tno more references, deleting\n"); #endif delete [] p->name; delete [] p->stacking; delete [] p->clients; delete [] p->virtual_roots; delete [] p->temp_buf; int i; for (i = 0; i < p->desktop_names.size(); i++) { delete [] p->desktop_names[i]; } } } static void refdec_nwi(NETWinInfoPrivate *p) { #ifdef NETWMDEBUG fprintf(stderr, "NET: decrementing NETWinInfoPrivate::ref (%d)\n", p->ref - 1); #endif if (! --p->ref) { #ifdef NETWMDEBUG fprintf(stderr, "NET: \tno more references, deleting\n"); #endif delete [] p->name; delete [] p->visible_name; delete [] p->window_role; delete [] p->icon_name; delete [] p->visible_icon_name; delete [] p->startup_id; delete [] p->class_class; delete [] p->class_name; delete [] p->activities; delete [] p->client_machine; delete [] p->desktop_file; int i; for (i = 0; i < p->icons.size(); i++) { delete [] p->icons[i].data; } delete [] p->icon_sizes; } } template -T get_value_reply(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, xcb_atom_t type, T def, bool *success = 0) +T get_value_reply(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, xcb_atom_t type, T def, bool *success = nullptr) { T value = def; - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (success) { *success = false; } if (reply) { if (reply->type == type && reply->value_len == 1 && reply->format == sizeof(T) * 8) { value = *reinterpret_cast(xcb_get_property_value(reply)); if (success) { *success = true; } } free(reply); } return value; } template QVector get_array_reply(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, xcb_atom_t type) { - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (!reply) { return QVector(); } QVector vector; if (reply->type == type && reply->value_len > 0 && reply->format == sizeof(T) * 8) { T *data = reinterpret_cast(xcb_get_property_value(reply)); vector.resize(reply->value_len); memcpy((void *)&vector.first(), (void *)data, reply->value_len * sizeof(T)); } free(reply); return vector; } static QByteArray get_string_reply(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, xcb_atom_t type) { - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (!reply) { return QByteArray(); } QByteArray value; if (reply->type == type && reply->format == 8 && reply->value_len > 0) { const char *data = (const char *) xcb_get_property_value(reply); int len = reply->value_len; if (data) { value = QByteArray(data, data[len - 1] ? len : len - 1); } } free(reply); return value; } static QList get_stringlist_reply(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, xcb_atom_t type) { - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (!reply) { return QList(); } QList list; if (reply->type == type && reply->format == 8 && reply->value_len > 0) { const char *data = (const char *) xcb_get_property_value(reply); int len = reply->value_len; if (data) { const QByteArray ba = QByteArray(data, data[len - 1] ? len : len - 1); list = ba.split('\0'); } } free(reply); return list; } #ifdef NETWMDEBUG static QByteArray get_atom_name(xcb_connection_t *c, xcb_atom_t atom) { const xcb_get_atom_name_cookie_t cookie = xcb_get_atom_name(c, atom); xcb_get_atom_name_reply_t *reply = xcb_get_atom_name_reply(p->conn, cookie, 0); if (!reply) { return QByteArray(); } QByteArray ba(xcb_get_atom_name_name(reply)); free(reply); return ba; } #endif void Atoms::init() { #define ENUM_CREATE_CHAR_ARRAY 1 #include "atoms_p.h" // creates const char* array "KwsAtomStrings" // Send the intern atom requests xcb_intern_atom_cookie_t cookies[KwsAtomCount]; for (int i = 0; i < KwsAtomCount; ++i) { cookies[i] = xcb_intern_atom(m_connection, false, strlen(KwsAtomStrings[i]), KwsAtomStrings[i]); } // Get the replies for (int i = 0; i < KwsAtomCount; ++i) { - xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(m_connection, cookies[i], 0); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(m_connection, cookies[i], nullptr); if (!reply) { continue; } m_atoms[i] = reply->atom; free(reply); } } static void readIcon(xcb_connection_t *c, const xcb_get_property_cookie_t cookie, NETRArray &icons, int &icon_count) { #ifdef NETWMDEBUG fprintf(stderr, "NET: readIcon\n"); #endif // reset for (int i = 0; i < icons.size(); i++) { delete [] icons[i].data; } icons.reset(); icon_count = 0; - xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(c, cookie, nullptr); if (!reply || reply->value_len < 3 || reply->format != 32 || reply->type != XCB_ATOM_CARDINAL) { if (reply) { free(reply); } return; } uint32_t *data = (uint32_t *) xcb_get_property_value(reply); for (unsigned int i = 0, j = 0; j < reply->value_len - 2; i++) { uint32_t width = data[j++]; uint32_t height = data[j++]; uint32_t size = width * height * sizeof(uint32_t); if (j + width * height > reply->value_len) { fprintf(stderr, "Ill-encoded icon data; proposed size leads to out of bounds access. Skipping. (%d x %d)\n", width, height); break; } if (width > 1024 || height > 1024) { fprintf(stderr, "Warning: found huge icon. The icon data may be ill-encoded. (%d x %d)\n", width, height); // do not break nor continue - the data may likely be junk, but causes no harm (yet) and might actually be just a huge icon, eg. when the icon system is abused to transfer wallpapers or such. } icons[i].size.width = width; icons[i].size.height = height; icons[i].data = new unsigned char[size]; memcpy((void *)icons[i].data, (const void *)&data[j], size); j += width * height; icon_count++; } free(reply); #ifdef NETWMDEBUG fprintf(stderr, "NET: readIcon got %d icons\n", icon_count); #endif } static void send_client_message(xcb_connection_t *c, uint32_t mask, xcb_window_t destination, xcb_window_t window, xcb_atom_t message, const uint32_t data[]) { xcb_client_message_event_t event; event.response_type = XCB_CLIENT_MESSAGE; event.format = 32; event.sequence = 0; event.window = window; event.type = message; for (int i = 0; i < 5; i++) { event.data.data32[i] = data[i]; } xcb_send_event(c, false, destination, mask, (const char *) &event); } template NETRArray::NETRArray() : sz(0), capacity(2) { d = (Z *) calloc(capacity, sizeof(Z)); // allocate 2 elts and set to zero } template NETRArray::~NETRArray() { free(d); } template void NETRArray::reset() { sz = 0; capacity = 2; d = (Z *) realloc(d, sizeof(Z) * capacity); memset((void *) d, 0, sizeof(Z)*capacity); } template Z &NETRArray::operator[](int index) { if (index >= capacity) { // allocate space for the new data // open table has amortized O(1) access time // when N elements appended consecutively -- exa int newcapacity = 2 * capacity > index + 1 ? 2 * capacity : index + 1; // max // copy into new larger memory block using realloc d = (Z *) realloc(d, sizeof(Z) * newcapacity); memset((void *) &d[capacity], 0, sizeof(Z) * (newcapacity - capacity)); capacity = newcapacity; } if (index >= sz) { // at this point capacity>index sz = index + 1; } return d[index]; } /* The viewport<->desktop matching is a bit backwards, since NET* classes are the base (and were originally even created with the intention of being the reference WM spec implementation) and KWindowSystem builds on top of it. However it's simpler to add watching whether the WM uses viewport is simpler to KWindowSystem and not having this mapping in NET* classes could result in some code using it directly and not supporting viewport. So NET* classes check if mapping is needed and if yes they forward to KWindowSystem, which will forward again back to NET* classes, but to viewport calls instead of desktop calls. */ // Construct a new NETRootInfo object. NETRootInfo::NETRootInfo(xcb_connection_t *connection, xcb_window_t supportWindow, const char *wmName, NET::Properties properties, NET::WindowTypes windowTypes, NET::States states, NET::Properties2 properties2, NET::Actions actions, int screen, bool doActivate) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::NETRootInfo: using window manager constructor\n"); #endif p = new NETRootInfoPrivate; p->ref = 1; p->atoms = atomsForConnection(connection); p->name = nstrdup(wmName); p->conn = connection; - p->temp_buf = 0; + p->temp_buf = nullptr; p->temp_buf_size = 0; const xcb_setup_t *setup = xcb_get_setup(p->conn); xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup); if (screen != -1 && screen < setup->roots_len) { for (int i = 0; i < screen; i++) { xcb_screen_next(&it); } } p->root = it.data->root; p->supportwindow = supportWindow; p->number_of_desktops = p->current_desktop = 0; p->active = XCB_WINDOW_NONE; - p->clients = p->stacking = p->virtual_roots = (xcb_window_t *) 0; + p->clients = p->stacking = p->virtual_roots = (xcb_window_t *) nullptr; p->clients_count = p->stacking_count = p->virtual_roots_count = 0; p->showing_desktop = false; p->desktop_layout_orientation = OrientationHorizontal; p->desktop_layout_corner = DesktopLayoutCornerTopLeft; p->desktop_layout_columns = p->desktop_layout_rows = 0; setDefaultProperties(); p->properties = properties; p->properties2 = properties2; p->windowTypes = windowTypes; p->states = states; p->actions = actions; // force support for Supported and SupportingWMCheck for window managers p->properties |= (Supported | SupportingWMCheck); p->clientProperties = DesktopNames // the only thing that can be changed by clients | WMPing; // or they can reply to this p->clientProperties2 = WM2DesktopLayout; p->role = WindowManager; if (doActivate) { activate(); } } NETRootInfo::NETRootInfo(xcb_connection_t *connection, NET::Properties properties, NET::Properties2 properties2, int screen, bool doActivate) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::NETRootInfo: using Client constructor\n"); #endif p = new NETRootInfoPrivate; p->ref = 1; p->atoms = atomsForConnection(connection); - p->name = 0; + p->name = nullptr; p->conn = connection; - p->temp_buf = 0; + p->temp_buf = nullptr; p->temp_buf_size = 0; const xcb_setup_t *setup = xcb_get_setup(p->conn); xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup); if (screen != -1 && screen < setup->roots_len) { for (int i = 0; i < screen; i++) { xcb_screen_next(&it); } } p->root = it.data->root; p->rootSize.width = it.data->width_in_pixels; p->rootSize.height = it.data->height_in_pixels; p->supportwindow = XCB_WINDOW_NONE; p->number_of_desktops = p->current_desktop = 0; p->active = XCB_WINDOW_NONE; - p->clients = p->stacking = p->virtual_roots = (xcb_window_t *) 0; + p->clients = p->stacking = p->virtual_roots = (xcb_window_t *) nullptr; p->clients_count = p->stacking_count = p->virtual_roots_count = 0; p->showing_desktop = false; p->desktop_layout_orientation = OrientationHorizontal; p->desktop_layout_corner = DesktopLayoutCornerTopLeft; p->desktop_layout_columns = p->desktop_layout_rows = 0; setDefaultProperties(); p->clientProperties = properties; p->clientProperties2 = properties2; - p->properties = 0; - p->properties2 = 0; - p->windowTypes = 0; - p->states = 0; - p->actions = 0; + p->properties = nullptr; + p->properties2 = nullptr; + p->windowTypes = nullptr; + p->states = nullptr; + p->actions = nullptr; p->role = Client; if (doActivate) { activate(); } } // Copy an existing NETRootInfo object. NETRootInfo::NETRootInfo(const NETRootInfo &rootinfo) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::NETRootInfo: using copy constructor\n"); #endif p = rootinfo.p; p->ref++; } // Be gone with our NETRootInfo. NETRootInfo::~NETRootInfo() { refdec_nri(p); if (! p->ref) { delete p; } } void NETRootInfo::setDefaultProperties() { p->properties = Supported | SupportingWMCheck; p->windowTypes = NormalMask | DesktopMask | DockMask | ToolbarMask | MenuMask | DialogMask; p->states = Modal | Sticky | MaxVert | MaxHoriz | Shaded | SkipTaskbar | StaysOnTop; - p->properties2 = 0; - p->actions = 0; - p->clientProperties = 0; - p->clientProperties2 = 0; + p->properties2 = nullptr; + p->actions = nullptr; + p->clientProperties = nullptr; + p->clientProperties2 = nullptr; } void NETRootInfo::activate() { if (p->role == WindowManager) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::activate: setting supported properties on root\n"); #endif setSupported(); update(p->clientProperties, p->clientProperties2); } else { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::activate: updating client information\n"); #endif update(p->clientProperties, p->clientProperties2); } } void NETRootInfo::setClientList(const xcb_window_t *windows, unsigned int count) { if (p->role != WindowManager) { return; } p->clients_count = count; delete [] p->clients; p->clients = nwindup(windows, count); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setClientList: setting list with %ld windows\n", p->clients_count); #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_CLIENT_LIST), XCB_ATOM_WINDOW, 32, p->clients_count, (const void *) windows); } void NETRootInfo::setClientListStacking(const xcb_window_t *windows, unsigned int count) { if (p->role != WindowManager) { return; } p->stacking_count = count; delete [] p->stacking; p->stacking = nwindup(windows, count); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setClientListStacking: setting list with %ld windows\n", p->clients_count); #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_CLIENT_LIST_STACKING), XCB_ATOM_WINDOW, 32, p->stacking_count, (const void *) windows); } void NETRootInfo::setNumberOfDesktops(int numberOfDesktops) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setNumberOfDesktops: setting desktop count to %d (%s)\n", numberOfDesktops, (p->role == WindowManager) ? "WM" : "Client"); #endif if (p->role == WindowManager) { p->number_of_desktops = numberOfDesktops; const uint32_t d = numberOfDesktops; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_NUMBER_OF_DESKTOPS), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } else { const uint32_t data[5] = { uint32_t(numberOfDesktops), 0, 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->root, p->atom(_NET_NUMBER_OF_DESKTOPS), data); } } void NETRootInfo::setCurrentDesktop(int desktop, bool ignore_viewport) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setCurrentDesktop: setting current desktop = %d (%s)\n", desktop, (p->role == WindowManager) ? "WM" : "Client"); #endif if (p->role == WindowManager) { p->current_desktop = desktop; uint32_t d = p->current_desktop - 1; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_CURRENT_DESKTOP), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } else { if (!ignore_viewport && KWindowSystem::mapViewport()) { KWindowSystem::setCurrentDesktop(desktop); return; } const uint32_t data[5] = { uint32_t(desktop - 1), 0, 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->root, p->atom(_NET_CURRENT_DESKTOP), data); } } void NETRootInfo::setDesktopName(int desktop, const char *desktopName) { // Allow setting desktop names even for non-existent desktops, see the spec, sect.3.7. if (desktop < 1) { return; } delete [] p->desktop_names[desktop - 1]; p->desktop_names[desktop - 1] = nstrdup(desktopName); unsigned int i, proplen, num = ((p->number_of_desktops > p->desktop_names.size()) ? p->number_of_desktops : p->desktop_names.size()); for (i = 0, proplen = 0; i < num; i++) { - proplen += (p->desktop_names[i] != 0 ? strlen(p->desktop_names[i]) + 1 : 1); + proplen += (p->desktop_names[i] != nullptr ? strlen(p->desktop_names[i]) + 1 : 1); } char *prop = new char[proplen], *propp = prop; for (i = 0; i < num; i++) if (p->desktop_names[i]) { strcpy(propp, p->desktop_names[i]); propp += strlen(p->desktop_names[i]) + 1; } else { *propp++ = '\0'; } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setDesktopName(%d, '%s')\n" "NETRootInfo::setDesktopName: total property length = %d", desktop, desktopName, proplen); #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_DESKTOP_NAMES), p->atom(UTF8_STRING), 8, proplen, (const void *) prop); delete [] prop; } void NETRootInfo::setDesktopGeometry(const NETSize &geometry) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setDesktopGeometry( -- , { %d, %d }) (%s)\n", geometry.width, geometry.height, (p->role == WindowManager) ? "WM" : "Client"); #endif if (p->role == WindowManager) { p->geometry = geometry; uint32_t data[2]; data[0] = p->geometry.width; data[1] = p->geometry.height; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_DESKTOP_GEOMETRY), XCB_ATOM_CARDINAL, 32, 2, (const void *) data); } else { uint32_t data[5] = { uint32_t(geometry.width), uint32_t(geometry.height), 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->root, p->atom(_NET_DESKTOP_GEOMETRY), data); } } void NETRootInfo::setDesktopViewport(int desktop, const NETPoint &viewport) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setDesktopViewport(%d, { %d, %d }) (%s)\n", desktop, viewport.x, viewport.y, (p->role == WindowManager) ? "WM" : "Client"); #endif if (desktop < 1) { return; } if (p->role == WindowManager) { p->viewport[desktop - 1] = viewport; int d, i, l; l = p->number_of_desktops * 2; uint32_t *data = new uint32_t[l]; for (d = 0, i = 0; d < p->number_of_desktops; d++) { data[i++] = p->viewport[d].x; data[i++] = p->viewport[d].y; } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_DESKTOP_VIEWPORT), XCB_ATOM_CARDINAL, 32, l, (const void *) data); delete [] data; } else { const uint32_t data[5] = { uint32_t(viewport.x), uint32_t(viewport.y), 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->root, p->atom(_NET_DESKTOP_VIEWPORT), data); } } void NETRootInfo::setSupported() { if (p->role != WindowManager) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setSupported - role != WindowManager\n"); #endif return; } xcb_atom_t atoms[KwsAtomCount]; int pnum = 2; // Root window properties/messages atoms[0] = p->atom(_NET_SUPPORTED); atoms[1] = p->atom(_NET_SUPPORTING_WM_CHECK); if (p->properties & ClientList) { atoms[pnum++] = p->atom(_NET_CLIENT_LIST); } if (p->properties & ClientListStacking) { atoms[pnum++] = p->atom(_NET_CLIENT_LIST_STACKING); } if (p->properties & NumberOfDesktops) { atoms[pnum++] = p->atom(_NET_NUMBER_OF_DESKTOPS); } if (p->properties & DesktopGeometry) { atoms[pnum++] = p->atom(_NET_DESKTOP_GEOMETRY); } if (p->properties & DesktopViewport) { atoms[pnum++] = p->atom(_NET_DESKTOP_VIEWPORT); } if (p->properties & CurrentDesktop) { atoms[pnum++] = p->atom(_NET_CURRENT_DESKTOP); } if (p->properties & DesktopNames) { atoms[pnum++] = p->atom(_NET_DESKTOP_NAMES); } if (p->properties & ActiveWindow) { atoms[pnum++] = p->atom(_NET_ACTIVE_WINDOW); } if (p->properties & WorkArea) { atoms[pnum++] = p->atom(_NET_WORKAREA); } if (p->properties & VirtualRoots) { atoms[pnum++] = p->atom(_NET_VIRTUAL_ROOTS); } if (p->properties2 & WM2DesktopLayout) { atoms[pnum++] = p->atom(_NET_DESKTOP_LAYOUT); } if (p->properties & CloseWindow) { atoms[pnum++] = p->atom(_NET_CLOSE_WINDOW); } if (p->properties2 & WM2RestackWindow) { atoms[pnum++] = p->atom(_NET_RESTACK_WINDOW); } if (p->properties2 & WM2ShowingDesktop) { atoms[pnum++] = p->atom(_NET_SHOWING_DESKTOP); } // Application window properties/messages if (p->properties & WMMoveResize) { atoms[pnum++] = p->atom(_NET_WM_MOVERESIZE); } if (p->properties2 & WM2MoveResizeWindow) { atoms[pnum++] = p->atom(_NET_MOVERESIZE_WINDOW); } if (p->properties & WMName) { atoms[pnum++] = p->atom(_NET_WM_NAME); } if (p->properties & WMVisibleName) { atoms[pnum++] = p->atom(_NET_WM_VISIBLE_NAME); } if (p->properties & WMIconName) { atoms[pnum++] = p->atom(_NET_WM_ICON_NAME); } if (p->properties & WMVisibleIconName) { atoms[pnum++] = p->atom(_NET_WM_VISIBLE_ICON_NAME); } if (p->properties & WMDesktop) { atoms[pnum++] = p->atom(_NET_WM_DESKTOP); } if (p->properties & WMWindowType) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE); // Application window types if (p->windowTypes & NormalMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_NORMAL); } if (p->windowTypes & DesktopMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_DESKTOP); } if (p->windowTypes & DockMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_DOCK); } if (p->windowTypes & ToolbarMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_TOOLBAR); } if (p->windowTypes & MenuMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_MENU); } if (p->windowTypes & DialogMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_DIALOG); } if (p->windowTypes & UtilityMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_UTILITY); } if (p->windowTypes & SplashMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_SPLASH); } if (p->windowTypes & DropdownMenuMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU); } if (p->windowTypes & PopupMenuMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_POPUP_MENU); } if (p->windowTypes & TooltipMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_TOOLTIP); } if (p->windowTypes & NotificationMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_NOTIFICATION); } if (p->windowTypes & ComboBoxMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_COMBOBOX); } if (p->windowTypes & DNDIconMask) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_TYPE_DND); } // KDE extensions if (p->windowTypes & OverrideMask) { atoms[pnum++] = p->atom(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE); } if (p->windowTypes & TopMenuMask) { atoms[pnum++] = p->atom(_KDE_NET_WM_WINDOW_TYPE_TOPMENU); } if (p->windowTypes & OnScreenDisplayMask) { atoms[pnum++] = p->atom(_KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY); } } if (p->properties & WMState) { atoms[pnum++] = p->atom(_NET_WM_STATE); // Application window states if (p->states & Modal) { atoms[pnum++] = p->atom(_NET_WM_STATE_MODAL); } if (p->states & Sticky) { atoms[pnum++] = p->atom(_NET_WM_STATE_STICKY); } if (p->states & MaxVert) { atoms[pnum++] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); } if (p->states & MaxHoriz) { atoms[pnum++] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); } if (p->states & Shaded) { atoms[pnum++] = p->atom(_NET_WM_STATE_SHADED); } if (p->states & SkipTaskbar) { atoms[pnum++] = p->atom(_NET_WM_STATE_SKIP_TASKBAR); } if (p->states & SkipPager) { atoms[pnum++] = p->atom(_NET_WM_STATE_SKIP_PAGER); } if (p->states & Hidden) { atoms[pnum++] = p->atom(_NET_WM_STATE_HIDDEN); } if (p->states & FullScreen) { atoms[pnum++] = p->atom(_NET_WM_STATE_FULLSCREEN); } if (p->states & KeepAbove) { atoms[pnum++] = p->atom(_NET_WM_STATE_ABOVE); } if (p->states & KeepBelow) { atoms[pnum++] = p->atom(_NET_WM_STATE_BELOW); } if (p->states & DemandsAttention) { atoms[pnum++] = p->atom(_NET_WM_STATE_DEMANDS_ATTENTION); } if (p->states & StaysOnTop) { atoms[pnum++] = p->atom(_NET_WM_STATE_STAYS_ON_TOP); } } if (p->properties & WMStrut) { atoms[pnum++] = p->atom(_NET_WM_STRUT); } if (p->properties2 & WM2ExtendedStrut) { atoms[pnum++] = p->atom(_NET_WM_STRUT_PARTIAL); } if (p->properties & WMIconGeometry) { atoms[pnum++] = p->atom(_NET_WM_ICON_GEOMETRY); } if (p->properties & WMIcon) { atoms[pnum++] = p->atom(_NET_WM_ICON); } if (p->properties & WMPid) { atoms[pnum++] = p->atom(_NET_WM_PID); } if (p->properties & WMHandledIcons) { atoms[pnum++] = p->atom(_NET_WM_HANDLED_ICONS); } if (p->properties & WMPing) { atoms[pnum++] = p->atom(_NET_WM_PING); } if (p->properties2 & WM2UserTime) { atoms[pnum++] = p->atom(_NET_WM_USER_TIME); } if (p->properties2 & WM2StartupId) { atoms[pnum++] = p->atom(_NET_STARTUP_ID); } if (p->properties2 & WM2Opacity) { atoms[pnum++] = p->atom(_NET_WM_WINDOW_OPACITY); } if (p->properties2 & WM2FullscreenMonitors) { atoms[pnum++] = p->atom(_NET_WM_FULLSCREEN_MONITORS); } if (p->properties2 & WM2AllowedActions) { atoms[pnum++] = p->atom(_NET_WM_ALLOWED_ACTIONS); // Actions if (p->actions & ActionMove) { atoms[pnum++] = p->atom(_NET_WM_ACTION_MOVE); } if (p->actions & ActionResize) { atoms[pnum++] = p->atom(_NET_WM_ACTION_RESIZE); } if (p->actions & ActionMinimize) { atoms[pnum++] = p->atom(_NET_WM_ACTION_MINIMIZE); } if (p->actions & ActionShade) { atoms[pnum++] = p->atom(_NET_WM_ACTION_SHADE); } if (p->actions & ActionStick) { atoms[pnum++] = p->atom(_NET_WM_ACTION_STICK); } if (p->actions & ActionMaxVert) { atoms[pnum++] = p->atom(_NET_WM_ACTION_MAXIMIZE_VERT); } if (p->actions & ActionMaxHoriz) { atoms[pnum++] = p->atom(_NET_WM_ACTION_MAXIMIZE_HORZ); } if (p->actions & ActionFullScreen) { atoms[pnum++] = p->atom(_NET_WM_ACTION_FULLSCREEN); } if (p->actions & ActionChangeDesktop) { atoms[pnum++] = p->atom(_NET_WM_ACTION_CHANGE_DESKTOP); } if (p->actions & ActionClose) { atoms[pnum++] = p->atom(_NET_WM_ACTION_CLOSE); } } if (p->properties & WMFrameExtents) { atoms[pnum++] = p->atom(_NET_FRAME_EXTENTS); atoms[pnum++] = p->atom(_KDE_NET_WM_FRAME_STRUT); } if (p->properties2 & WM2FrameOverlap) { atoms[pnum++] = p->atom(_NET_WM_FRAME_OVERLAP); } if (p->properties2 & WM2KDETemporaryRules) { atoms[pnum++] = p->atom(_KDE_NET_WM_TEMPORARY_RULES); } if (p->properties2 & WM2FullPlacement) { atoms[pnum++] = p->atom(_NET_WM_FULL_PLACEMENT); } if (p->properties2 & WM2Activities) { atoms[pnum++] = p->atom(_KDE_NET_WM_ACTIVITIES); } if (p->properties2 & WM2BlockCompositing) { atoms[pnum++] = p->atom(_KDE_NET_WM_BLOCK_COMPOSITING); atoms[pnum++] = p->atom(_NET_WM_BYPASS_COMPOSITOR); } if (p->properties2 & WM2KDEShadow) { atoms[pnum++] = p->atom(_KDE_NET_WM_SHADOW); } if (p->properties2 & WM2OpaqueRegion) { atoms[pnum++] = p->atom(_NET_WM_OPAQUE_REGION); } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_SUPPORTED), XCB_ATOM_ATOM, 32, pnum, (const void *) atoms); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_SUPPORTING_WM_CHECK), XCB_ATOM_WINDOW, 32, 1, (const void *) & (p->supportwindow)); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setSupported: _NET_SUPPORTING_WM_CHECK = 0x%lx on 0x%lx\n" " : _NET_WM_NAME = '%s' on 0x%lx\n", p->supportwindow, p->supportwindow, p->name, p->supportwindow); #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->supportwindow, p->atom(_NET_SUPPORTING_WM_CHECK), XCB_ATOM_WINDOW, 32, 1, (const void *) & (p->supportwindow)); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->supportwindow, p->atom(_NET_WM_NAME), p->atom(UTF8_STRING), 8, strlen(p->name), (const void *) p->name); } void NETRootInfo::updateSupportedProperties(xcb_atom_t atom) { if (atom == p->atom(_NET_SUPPORTED)) { p->properties |= Supported; } else if (atom == p->atom(_NET_SUPPORTING_WM_CHECK)) { p->properties |= SupportingWMCheck; } else if (atom == p->atom(_NET_CLIENT_LIST)) { p->properties |= ClientList; } else if (atom == p->atom(_NET_CLIENT_LIST_STACKING)) { p->properties |= ClientListStacking; } else if (atom == p->atom(_NET_NUMBER_OF_DESKTOPS)) { p->properties |= NumberOfDesktops; } else if (atom == p->atom(_NET_DESKTOP_GEOMETRY)) { p->properties |= DesktopGeometry; } else if (atom == p->atom(_NET_DESKTOP_VIEWPORT)) { p->properties |= DesktopViewport; } else if (atom == p->atom(_NET_CURRENT_DESKTOP)) { p->properties |= CurrentDesktop; } else if (atom == p->atom(_NET_DESKTOP_NAMES)) { p->properties |= DesktopNames; } else if (atom == p->atom(_NET_ACTIVE_WINDOW)) { p->properties |= ActiveWindow; } else if (atom == p->atom(_NET_WORKAREA)) { p->properties |= WorkArea; } else if (atom == p->atom(_NET_VIRTUAL_ROOTS)) { p->properties |= VirtualRoots; } else if (atom == p->atom(_NET_DESKTOP_LAYOUT)) { p->properties2 |= WM2DesktopLayout; } else if (atom == p->atom(_NET_CLOSE_WINDOW)) { p->properties |= CloseWindow; } else if (atom == p->atom(_NET_RESTACK_WINDOW)) { p->properties2 |= WM2RestackWindow; } else if (atom == p->atom(_NET_SHOWING_DESKTOP)) { p->properties2 |= WM2ShowingDesktop; } // Application window properties/messages else if (atom == p->atom(_NET_WM_MOVERESIZE)) { p->properties |= WMMoveResize; } else if (atom == p->atom(_NET_MOVERESIZE_WINDOW)) { p->properties2 |= WM2MoveResizeWindow; } else if (atom == p->atom(_NET_WM_NAME)) { p->properties |= WMName; } else if (atom == p->atom(_NET_WM_VISIBLE_NAME)) { p->properties |= WMVisibleName; } else if (atom == p->atom(_NET_WM_ICON_NAME)) { p->properties |= WMIconName; } else if (atom == p->atom(_NET_WM_VISIBLE_ICON_NAME)) { p->properties |= WMVisibleIconName; } else if (atom == p->atom(_NET_WM_DESKTOP)) { p->properties |= WMDesktop; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE)) { p->properties |= WMWindowType; } // Application window types else if (atom == p->atom(_NET_WM_WINDOW_TYPE_NORMAL)) { p->windowTypes |= NormalMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_DESKTOP)) { p->windowTypes |= DesktopMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_DOCK)) { p->windowTypes |= DockMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_TOOLBAR)) { p->windowTypes |= ToolbarMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_MENU)) { p->windowTypes |= MenuMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_DIALOG)) { p->windowTypes |= DialogMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_UTILITY)) { p->windowTypes |= UtilityMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_SPLASH)) { p->windowTypes |= SplashMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU)) { p->windowTypes |= DropdownMenuMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_POPUP_MENU)) { p->windowTypes |= PopupMenuMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_TOOLTIP)) { p->windowTypes |= TooltipMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_NOTIFICATION)) { p->windowTypes |= NotificationMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_COMBOBOX)) { p->windowTypes |= ComboBoxMask; } else if (atom == p->atom(_NET_WM_WINDOW_TYPE_DND)) { p->windowTypes |= DNDIconMask; } // KDE extensions else if (atom == p->atom(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE)) { p->windowTypes |= OverrideMask; } else if (atom == p->atom(_KDE_NET_WM_WINDOW_TYPE_TOPMENU)) { p->windowTypes |= TopMenuMask; } else if (atom == p->atom(_KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY)) { p->windowTypes |= OnScreenDisplayMask; } else if (atom == p->atom(_NET_WM_STATE)) { p->properties |= WMState; } // Application window states else if (atom == p->atom(_NET_WM_STATE_MODAL)) { p->states |= Modal; } else if (atom == p->atom(_NET_WM_STATE_STICKY)) { p->states |= Sticky; } else if (atom == p->atom(_NET_WM_STATE_MAXIMIZED_VERT)) { p->states |= MaxVert; } else if (atom == p->atom(_NET_WM_STATE_MAXIMIZED_HORZ)) { p->states |= MaxHoriz; } else if (atom == p->atom(_NET_WM_STATE_SHADED)) { p->states |= Shaded; } else if (atom == p->atom(_NET_WM_STATE_SKIP_TASKBAR)) { p->states |= SkipTaskbar; } else if (atom == p->atom(_NET_WM_STATE_SKIP_PAGER)) { p->states |= SkipPager; } else if (atom == p->atom(_NET_WM_STATE_HIDDEN)) { p->states |= Hidden; } else if (atom == p->atom(_NET_WM_STATE_FULLSCREEN)) { p->states |= FullScreen; } else if (atom == p->atom(_NET_WM_STATE_ABOVE)) { p->states |= KeepAbove; } else if (atom == p->atom(_NET_WM_STATE_BELOW)) { p->states |= KeepBelow; } else if (atom == p->atom(_NET_WM_STATE_DEMANDS_ATTENTION)) { p->states |= DemandsAttention; } else if (atom == p->atom(_NET_WM_STATE_STAYS_ON_TOP)) { p->states |= StaysOnTop; } else if (atom == p->atom(_NET_WM_STRUT)) { p->properties |= WMStrut; } else if (atom == p->atom(_NET_WM_STRUT_PARTIAL)) { p->properties2 |= WM2ExtendedStrut; } else if (atom == p->atom(_NET_WM_ICON_GEOMETRY)) { p->properties |= WMIconGeometry; } else if (atom == p->atom(_NET_WM_ICON)) { p->properties |= WMIcon; } else if (atom == p->atom(_NET_WM_PID)) { p->properties |= WMPid; } else if (atom == p->atom(_NET_WM_HANDLED_ICONS)) { p->properties |= WMHandledIcons; } else if (atom == p->atom(_NET_WM_PING)) { p->properties |= WMPing; } else if (atom == p->atom(_NET_WM_USER_TIME)) { p->properties2 |= WM2UserTime; } else if (atom == p->atom(_NET_STARTUP_ID)) { p->properties2 |= WM2StartupId; } else if (atom == p->atom(_NET_WM_WINDOW_OPACITY)) { p->properties2 |= WM2Opacity; } else if (atom == p->atom(_NET_WM_FULLSCREEN_MONITORS)) { p->properties2 |= WM2FullscreenMonitors; } else if (atom == p->atom(_NET_WM_ALLOWED_ACTIONS)) { p->properties2 |= WM2AllowedActions; } // Actions else if (atom == p->atom(_NET_WM_ACTION_MOVE)) { p->actions |= ActionMove; } else if (atom == p->atom(_NET_WM_ACTION_RESIZE)) { p->actions |= ActionResize; } else if (atom == p->atom(_NET_WM_ACTION_MINIMIZE)) { p->actions |= ActionMinimize; } else if (atom == p->atom(_NET_WM_ACTION_SHADE)) { p->actions |= ActionShade; } else if (atom == p->atom(_NET_WM_ACTION_STICK)) { p->actions |= ActionStick; } else if (atom == p->atom(_NET_WM_ACTION_MAXIMIZE_VERT)) { p->actions |= ActionMaxVert; } else if (atom == p->atom(_NET_WM_ACTION_MAXIMIZE_HORZ)) { p->actions |= ActionMaxHoriz; } else if (atom == p->atom(_NET_WM_ACTION_FULLSCREEN)) { p->actions |= ActionFullScreen; } else if (atom == p->atom(_NET_WM_ACTION_CHANGE_DESKTOP)) { p->actions |= ActionChangeDesktop; } else if (atom == p->atom(_NET_WM_ACTION_CLOSE)) { p->actions |= ActionClose; } else if (atom == p->atom(_NET_FRAME_EXTENTS)) { p->properties |= WMFrameExtents; } else if (atom == p->atom(_KDE_NET_WM_FRAME_STRUT)) { p->properties |= WMFrameExtents; } else if (atom == p->atom(_NET_WM_FRAME_OVERLAP)) { p->properties2 |= WM2FrameOverlap; } else if (atom == p->atom(_KDE_NET_WM_TEMPORARY_RULES)) { p->properties2 |= WM2KDETemporaryRules; } else if (atom == p->atom(_NET_WM_FULL_PLACEMENT)) { p->properties2 |= WM2FullPlacement; } else if (atom == p->atom(_KDE_NET_WM_ACTIVITIES)) { p->properties2 |= WM2Activities; } else if (atom == p->atom(_KDE_NET_WM_BLOCK_COMPOSITING) || atom == p->atom(_NET_WM_BYPASS_COMPOSITOR)) { p->properties2 |= WM2BlockCompositing; } else if (atom == p->atom(_KDE_NET_WM_SHADOW)) { p->properties2 |= WM2KDEShadow; } else if (atom == p->atom(_NET_WM_OPAQUE_REGION)) { p->properties2 |= WM2OpaqueRegion; } } void NETRootInfo::setActiveWindow(xcb_window_t window) { setActiveWindow(window, FromUnknown, QX11Info::appUserTime(), XCB_WINDOW_NONE); } void NETRootInfo::setActiveWindow(xcb_window_t window, NET::RequestSource src, xcb_timestamp_t timestamp, xcb_window_t active_window) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setActiveWindow(0x%lx) (%s)\n", window, (p->role == WindowManager) ? "WM" : "Client"); #endif if (p->role == WindowManager) { p->active = window; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_ACTIVE_WINDOW), XCB_ATOM_WINDOW, 32, 1, (const void *) & (p->active)); } else { const uint32_t data[5] = { src, timestamp, active_window, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, window, p->atom(_NET_ACTIVE_WINDOW), data); } } void NETRootInfo::setWorkArea(int desktop, const NETRect &workarea) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setWorkArea(%d, { %d, %d, %d, %d }) (%s)\n", desktop, workarea.pos.x, workarea.pos.y, workarea.size.width, workarea.size.height, (p->role == WindowManager) ? "WM" : "Client"); #endif if (p->role != WindowManager || desktop < 1) { return; } p->workarea[desktop - 1] = workarea; uint32_t *wa = new uint32_t[p->number_of_desktops * 4]; int i, o; for (i = 0, o = 0; i < p->number_of_desktops; i++) { wa[o++] = p->workarea[i].pos.x; wa[o++] = p->workarea[i].pos.y; wa[o++] = p->workarea[i].size.width; wa[o++] = p->workarea[i].size.height; } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_WORKAREA), XCB_ATOM_CARDINAL, 32, p->number_of_desktops * 4, (const void *) wa); delete [] wa; } void NETRootInfo::setVirtualRoots(const xcb_window_t *windows, unsigned int count) { if (p->role != WindowManager) { return; } p->virtual_roots_count = count; delete[] p->virtual_roots; p->virtual_roots = nwindup(windows, count); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setVirtualRoots: setting list with %ld windows\n", p->virtual_roots_count); #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_VIRTUAL_ROOTS), XCB_ATOM_WINDOW, 32, p->virtual_roots_count, (const void *) windows); } void NETRootInfo::setDesktopLayout(NET::Orientation orientation, int columns, int rows, NET::DesktopLayoutCorner corner) { p->desktop_layout_orientation = orientation; p->desktop_layout_columns = columns; p->desktop_layout_rows = rows; p->desktop_layout_corner = corner; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setDesktopLayout: %d %d %d %d\n", orientation, columns, rows, corner); #endif uint32_t data[4]; data[0] = orientation; data[1] = columns; data[2] = rows; data[3] = corner; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_DESKTOP_LAYOUT), XCB_ATOM_CARDINAL, 32, 4, (const void *) data); } void NETRootInfo::setShowingDesktop(bool showing) { if (p->role == WindowManager) { uint32_t d = p->showing_desktop = showing; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->root, p->atom(_NET_SHOWING_DESKTOP), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } else { uint32_t data[5] = { uint32_t(showing ? 1 : 0), 0, 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->root, p->atom(_NET_SHOWING_DESKTOP), data); } } bool NETRootInfo::showingDesktop() const { return p->showing_desktop; } void NETRootInfo::closeWindowRequest(xcb_window_t window) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::closeWindowRequest: requesting close for 0x%lx\n", window); #endif const uint32_t data[5] = { 0, 0, 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, window, p->atom(_NET_CLOSE_WINDOW), data); } void NETRootInfo::moveResizeRequest(xcb_window_t window, int x_root, int y_root, Direction direction) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::moveResizeRequest: requesting resize/move for 0x%lx (%d, %d, %d)\n", window, x_root, y_root, direction); #endif const uint32_t data[5] = { uint32_t(x_root), uint32_t(y_root), uint32_t(direction), 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, window, p->atom(_NET_WM_MOVERESIZE), data); } void NETRootInfo::moveResizeWindowRequest(xcb_window_t window, int flags, int x, int y, int width, int height) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::moveResizeWindowRequest: resizing/moving 0x%lx (%d, %d, %d, %d, %d)\n", window, flags, x, y, width, height); #endif const uint32_t data[5] = { uint32_t(flags), uint32_t(x), uint32_t(y), uint32_t(width), uint32_t(height) }; send_client_message(p->conn, netwm_sendevent_mask, p->root, window, p->atom(_NET_MOVERESIZE_WINDOW), data); } void NETRootInfo::restackRequest(xcb_window_t window, RequestSource src, xcb_window_t above, int detail, xcb_timestamp_t timestamp) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::restackRequest: requesting restack for 0x%lx (%lx, %d)\n", window, above, detail); #endif const uint32_t data[5] = { uint32_t(src), uint32_t(above), uint32_t(detail), uint32_t(timestamp), 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, window, p->atom(_NET_RESTACK_WINDOW), data); } void NETRootInfo::sendPing(xcb_window_t window, xcb_timestamp_t timestamp) { if (p->role != WindowManager) { return; } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::setPing: window 0x%lx, timestamp %lu\n", window, timestamp); #endif const uint32_t data[5] = { p->atom(_NET_WM_PING), timestamp, window, 0, 0 }; send_client_message(p->conn, 0, window, window, p->atom(WM_PROTOCOLS), data); } // assignment operator const NETRootInfo &NETRootInfo::operator=(const NETRootInfo &rootinfo) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::operator=()\n"); #endif if (p != rootinfo.p) { refdec_nri(p); if (! p->ref) { delete p; } } p = rootinfo.p; p->ref++; return *this; } NET::Properties NETRootInfo::event(xcb_generic_event_t *ev) { NET::Properties props; event(ev, &props); return props; } #ifndef KWINDOWSYSTEM_NO_DEPRECATED void NETRootInfo::event(xcb_generic_event_t *ev, unsigned long *properties, int properties_size) { unsigned long props[ PROPERTIES_SIZE ] = { 0, 0, 0, 0, 0 }; assert(PROPERTIES_SIZE == 5); // add elements above NET::Properties p; NET::Properties2 p2; event(ev, &p, &p2); props[ PROTOCOLS ] = p; props[ PROTOCOLS2 ] = p2; if (properties_size > PROPERTIES_SIZE) { properties_size = PROPERTIES_SIZE; } for (int i = 0; i < properties_size; ++i) { properties[ i ] = props[ i ]; } } #endif void NETRootInfo::event(xcb_generic_event_t *event, NET::Properties *properties, NET::Properties2 *properties2) { NET::Properties dirty; NET::Properties2 dirty2; bool do_update = false; const uint8_t eventType = event->response_type & ~0x80; // the window manager will be interested in client messages... no other // client should get these messages if (p->role == WindowManager && eventType == XCB_CLIENT_MESSAGE && reinterpret_cast(event)->format == 32) { xcb_client_message_event_t *message = reinterpret_cast(event); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: handling ClientMessage event\n"); #endif if (message->type == p->atom(_NET_NUMBER_OF_DESKTOPS)) { dirty = NumberOfDesktops; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeNumberOfDesktops(%ld)\n", message->data.data32[0]); #endif changeNumberOfDesktops(message->data.data32[0]); } else if (message->type == p->atom(_NET_DESKTOP_GEOMETRY)) { dirty = DesktopGeometry; NETSize sz; sz.width = message->data.data32[0]; sz.height = message->data.data32[1]; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeDesktopGeometry( -- , { %d, %d })\n", sz.width, sz.height); #endif changeDesktopGeometry(~0, sz); } else if (message->type == p->atom(_NET_DESKTOP_VIEWPORT)) { dirty = DesktopViewport; NETPoint pt; pt.x = message->data.data32[0]; pt.y = message->data.data32[1]; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeDesktopViewport(%d, { %d, %d })\n", p->current_desktop, pt.x, pt.y); #endif changeDesktopViewport(p->current_desktop, pt); } else if (message->type == p->atom(_NET_CURRENT_DESKTOP)) { dirty = CurrentDesktop; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeCurrentDesktop(%ld)\n", message->data.data32[0] + 1); #endif changeCurrentDesktop(message->data.data32[0] + 1); } else if (message->type == p->atom(_NET_ACTIVE_WINDOW)) { dirty = ActiveWindow; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeActiveWindow(0x%lx)\n", message->window); #endif RequestSource src = FromUnknown; xcb_timestamp_t timestamp = XCB_TIME_CURRENT_TIME; xcb_window_t active_window = XCB_WINDOW_NONE; // make sure there aren't unknown values if (message->data.data32[0] >= FromUnknown && message->data.data32[0] <= FromTool) { src = static_cast< RequestSource >(message->data.data32[0]); timestamp = message->data.data32[1]; active_window = message->data.data32[2]; } changeActiveWindow(message->window, src, timestamp, active_window); } else if (message->type == p->atom(_NET_WM_MOVERESIZE)) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: moveResize(%ld, %ld, %ld, %ld)\n", message->window, message->data.data32[0], message->data.data32[1], message->data.data32[2] ); #endif moveResize(message->window, message->data.data32[0], message->data.data32[1], message->data.data32[2]); } else if (message->type == p->atom(_NET_MOVERESIZE_WINDOW)) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: moveResizeWindow(%ld, %ld, %ld, %ld, %ld, %ld)\n", message->window, message->data.data32[0], message->data.data32[1], message->data.data32[2], message->data.data32[3], message->data.data32[4] ); #endif moveResizeWindow(message->window, message->data.data32[0], message->data.data32[1], message->data.data32[2], message->data.data32[3], message->data.data32[4]); } else if (message->type == p->atom(_NET_CLOSE_WINDOW)) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: closeWindow(0x%lx)\n", message->window); #endif closeWindow(message->window); } else if (message->type == p->atom(_NET_RESTACK_WINDOW)) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: restackWindow(0x%lx)\n", message->window); #endif RequestSource src = FromUnknown; xcb_timestamp_t timestamp = XCB_TIME_CURRENT_TIME; // make sure there aren't unknown values if (message->data.data32[0] >= FromUnknown && message->data.data32[0] <= FromTool) { src = static_cast< RequestSource >(message->data.data32[0]); timestamp = message->data.data32[3]; } restackWindow(message->window, src, message->data.data32[1], message->data.data32[2], timestamp); } else if (message->type == p->atom(WM_PROTOCOLS) && (xcb_atom_t)message->data.data32[ 0 ] == p->atom(_NET_WM_PING)) { dirty = WMPing; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: gotPing(0x%lx,%lu)\n", message->window, message->data.data32[1]); #endif gotPing(message->data.data32[2], message->data.data32[1]); } else if (message->type == p->atom(_NET_SHOWING_DESKTOP)) { dirty2 = WM2ShowingDesktop; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: changeShowingDesktop(%ld)\n", message->data.data32[0]); #endif changeShowingDesktop(message->data.data32[0]); } } if (eventType == XCB_PROPERTY_NOTIFY) { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: handling PropertyNotify event\n"); #endif xcb_property_notify_event_t *pe = reinterpret_cast(event); if (pe->atom == p->atom(_NET_CLIENT_LIST)) { dirty |= ClientList; } else if (pe->atom == p->atom(_NET_CLIENT_LIST_STACKING)) { dirty |= ClientListStacking; } else if (pe->atom == p->atom(_NET_DESKTOP_NAMES)) { dirty |= DesktopNames; } else if (pe->atom == p->atom(_NET_WORKAREA)) { dirty |= WorkArea; } else if (pe->atom == p->atom(_NET_NUMBER_OF_DESKTOPS)) { dirty |= NumberOfDesktops; } else if (pe->atom == p->atom(_NET_DESKTOP_GEOMETRY)) { dirty |= DesktopGeometry; } else if (pe->atom == p->atom(_NET_DESKTOP_VIEWPORT)) { dirty |= DesktopViewport; } else if (pe->atom == p->atom(_NET_CURRENT_DESKTOP)) { dirty |= CurrentDesktop; } else if (pe->atom == p->atom(_NET_ACTIVE_WINDOW)) { dirty |= ActiveWindow; } else if (pe->atom == p->atom(_NET_SHOWING_DESKTOP)) { dirty2 |= WM2ShowingDesktop; } else if (pe->atom == p->atom(_NET_SUPPORTED)) { dirty |= Supported; // update here? } else if (pe->atom == p->atom(_NET_SUPPORTING_WM_CHECK)) { dirty |= SupportingWMCheck; } else if (pe->atom == p->atom(_NET_VIRTUAL_ROOTS)) { dirty |= VirtualRoots; } else if (pe->atom == p->atom(_NET_DESKTOP_LAYOUT)) { dirty2 |= WM2DesktopLayout; } do_update = true; } if (do_update) { update(dirty, dirty2); } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::event: handled events, returning dirty = 0x%lx, 0x%lx\n", dirty, dirty2); #endif if (properties) { *properties = dirty; } if (properties2) { *properties2 = dirty2; } } // private functions to update the data we keep void NETRootInfo::update(NET::Properties properties, NET::Properties2 properties2) { NET::Properties dirty = properties & p->clientProperties; NET::Properties2 dirty2 = properties2 & p->clientProperties2; xcb_get_property_cookie_t cookies[255]; xcb_get_property_cookie_t wm_name_cookie; int c = 0; // Send the property requests if (dirty & Supported) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_SUPPORTED), XCB_ATOM_ATOM, 0, MAX_PROP_SIZE); } if (dirty & ClientList) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_CLIENT_LIST), XCB_ATOM_WINDOW, 0, MAX_PROP_SIZE); } if (dirty & ClientListStacking) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_CLIENT_LIST_STACKING), XCB_ATOM_WINDOW, 0, MAX_PROP_SIZE); } if (dirty & NumberOfDesktops) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_NUMBER_OF_DESKTOPS), XCB_ATOM_CARDINAL, 0, 1); } if (dirty & DesktopGeometry) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_DESKTOP_GEOMETRY), XCB_ATOM_CARDINAL, 0, 2); } if (dirty & DesktopViewport) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_DESKTOP_VIEWPORT), XCB_ATOM_CARDINAL, 0, MAX_PROP_SIZE); } if (dirty & CurrentDesktop) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_CURRENT_DESKTOP), XCB_ATOM_CARDINAL, 0, 1); } if (dirty & DesktopNames) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_DESKTOP_NAMES), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & ActiveWindow) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_ACTIVE_WINDOW), XCB_ATOM_WINDOW, 0, 1); } if (dirty & WorkArea) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_WORKAREA), XCB_ATOM_CARDINAL, 0, MAX_PROP_SIZE); } if (dirty & SupportingWMCheck) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_SUPPORTING_WM_CHECK), XCB_ATOM_WINDOW, 0, 1); } if (dirty & VirtualRoots) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_VIRTUAL_ROOTS), XCB_ATOM_WINDOW, 0, 1); } if (dirty2 & WM2DesktopLayout) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_DESKTOP_LAYOUT), XCB_ATOM_CARDINAL, 0, MAX_PROP_SIZE); } if (dirty2 & WM2ShowingDesktop) { cookies[c++] = xcb_get_property(p->conn, false, p->root, p->atom(_NET_SHOWING_DESKTOP), XCB_ATOM_CARDINAL, 0, 1); } // Get the replies c = 0; if (dirty & Supported) { // Only in Client mode - p->properties = 0; - p->properties2 = 0; - p->windowTypes = 0; - p->states = 0; - p->actions = 0; + p->properties = nullptr; + p->properties2 = nullptr; + p->windowTypes = nullptr; + p->states = nullptr; + p->actions = nullptr; const QVector atoms = get_array_reply(p->conn, cookies[c++], XCB_ATOM_ATOM); Q_FOREACH (const xcb_atom_t atom, atoms) { updateSupportedProperties(atom); } } if (dirty & ClientList) { QList clientsToRemove; QList clientsToAdd; QVector clients = get_array_reply(p->conn, cookies[c++], XCB_ATOM_WINDOW); qSort(clients); if (p->clients) { if (p->role == Client) { int new_index = 0, old_index = 0; int old_count = p->clients_count; int new_count = clients.count(); while (old_index < old_count || new_index < new_count) { if (old_index == old_count) { clientsToAdd.append(clients[new_index++]); } else if (new_index == new_count) { clientsToRemove.append(p->clients[old_index++]); } else { if (p->clients[old_index] < clients[new_index]) { clientsToRemove.append(p->clients[old_index++]); } else if (clients[new_index] < p->clients[old_index]) { clientsToAdd.append(clients[new_index++]); } else { new_index++; old_index++; } } } } delete [] p->clients; - p->clients = 0; + p->clients = nullptr; } else { #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: client list null, creating\n"); #endif for (int i = 0; i < clients.count(); i++) { clientsToAdd.append(clients[i]); } } if (clients.count() > 0) { p->clients_count = clients.count(); p->clients = new xcb_window_t[clients.count()]; for (int i = 0; i < clients.count(); i++) { p->clients[i] = clients.at(i); } } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: client list updated (%ld clients)\n", p->clients_count); #endif for (int i = 0; i < clientsToRemove.size(); ++i) { removeClient(clientsToRemove.at(i)); } for (int i = 0; i < clientsToAdd.size(); ++i) { addClient(clientsToAdd.at(i)); } } if (dirty & ClientListStacking) { p->stacking_count = 0; delete[] p->stacking; - p->stacking = NULL; + p->stacking = nullptr; const QVector wins = get_array_reply(p->conn, cookies[c++], XCB_ATOM_WINDOW); if (wins.count() > 0) { p->stacking_count = wins.count(); p->stacking = new xcb_window_t[wins.count()]; for (int i = 0; i < wins.count(); i++) { p->stacking[i] = wins.at(i); } } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: client stacking updated (%ld clients)\n", p->stacking_count); #endif } if (dirty & NumberOfDesktops) { p->number_of_desktops = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: number of desktops = %d\n", p->number_of_desktops); #endif } if (dirty & DesktopGeometry) { p->geometry = p->rootSize; const QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 2) { p->geometry.width = data.at(0); p->geometry.height = data.at(1); } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: desktop geometry updated\n"); #endif } if (dirty & DesktopViewport) { for (int i = 0; i < p->viewport.size(); i++) { p->viewport[i].x = p->viewport[i].y = 0; } const QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() >= 2) { int n = data.count() / 2; for (int d = 0, i = 0; d < n; d++) { p->viewport[d].x = data[i++]; p->viewport[d].y = data[i++]; } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: desktop viewport array updated (%d entries)\n", p->viewport.size()); if (data.count() % 2 != 0) { fprintf(stderr, "NETRootInfo::update(): desktop viewport array " "size not a multiple of 2\n"); } #endif } } if (dirty & CurrentDesktop) { p->current_desktop = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0) + 1; #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: current desktop = %d\n", p->current_desktop); #endif } if (dirty & DesktopNames) { for (int i = 0; i < p->desktop_names.size(); ++i) { delete[] p->desktop_names[i]; } p->desktop_names.reset(); const QList names = get_stringlist_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); for (int i = 0; i < names.count(); i++) { p->desktop_names[i] = nstrndup(names[i].constData(), names[i].length()); } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: desktop names array updated (%d entries)\n", p->desktop_names.size()); #endif } if (dirty & ActiveWindow) { p->active = get_value_reply(p->conn, cookies[c++], XCB_ATOM_WINDOW, 0); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: active window = 0x%lx\n", p->active); #endif } if (dirty & WorkArea) { p->workarea.reset(); const QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == p->number_of_desktops * 4) { for (int i = 0, j = 0; i < p->number_of_desktops; i++) { p->workarea[i].pos.x = data[j++]; p->workarea[i].pos.y = data[j++]; p->workarea[i].size.width = data[j++]; p->workarea[i].size.height = data[j++]; } } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: work area array updated (%d entries)\n", p->workarea.size()); #endif } if (dirty & SupportingWMCheck) { delete[] p->name; - p->name = NULL; + p->name = nullptr; p->supportwindow = get_value_reply(p->conn, cookies[c++], XCB_ATOM_WINDOW, 0); // We'll get the reply for this request at the bottom of this function, // after we've processing the other pending replies if (p->supportwindow) wm_name_cookie = xcb_get_property(p->conn, false, p->supportwindow, p->atom(_NET_WM_NAME), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & VirtualRoots) { p->virtual_roots_count = 0; delete[] p->virtual_roots; - p->virtual_roots = NULL; + p->virtual_roots = nullptr; const QVector wins = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (wins.count() > 0) { p->virtual_roots_count = wins.count(); p->virtual_roots = new xcb_window_t[wins.count()]; for (int i = 0; i < wins.count(); i++) { p->virtual_roots[i] = wins.at(i); } } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::updated: virtual roots updated (%ld windows)\n", p->virtual_roots_count); #endif } if (dirty2 & WM2DesktopLayout) { p->desktop_layout_orientation = OrientationHorizontal; p->desktop_layout_corner = DesktopLayoutCornerTopLeft; p->desktop_layout_columns = p->desktop_layout_rows = 0; const QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() >= 4 && data[3] <= 3) { p->desktop_layout_corner = (NET::DesktopLayoutCorner)data[3]; } if (data.count() >= 3) { if (data[0] <= 1) { p->desktop_layout_orientation = (NET::Orientation)data[0]; } p->desktop_layout_columns = data[1]; p->desktop_layout_rows = data[2]; } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::updated: desktop layout updated (%d %d %d %d)\n", p->desktop_layout_orientation, p->desktop_layout_columns, p->desktop_layout_rows, p->desktop_layout_corner); #endif } if (dirty2 & WM2ShowingDesktop) { const uint32_t val = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0); p->showing_desktop = bool(val); #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: showing desktop = %d\n", p->showing_desktop); #endif } if ((dirty & SupportingWMCheck) && p->supportwindow) { const QByteArray ba = get_string_reply(p->conn, wm_name_cookie, p->atom(UTF8_STRING)); if (ba.length() > 0) { p->name = nstrndup((const char *) ba.constData(), ba.length()); } #ifdef NETWMDEBUG fprintf(stderr, "NETRootInfo::update: supporting window manager = '%s'\n", p->name); #endif } } xcb_connection_t *NETRootInfo::xcbConnection() const { return p->conn; } xcb_window_t NETRootInfo::rootWindow() const { return p->root; } xcb_window_t NETRootInfo::supportWindow() const { return p->supportwindow; } const char *NETRootInfo::wmName() const { return p->name; } NET::Properties NETRootInfo::supportedProperties() const { return p->properties; } NET::Properties2 NETRootInfo::supportedProperties2() const { return p->properties2; } NET::States NETRootInfo::supportedStates() const { return p->states; } NET::WindowTypes NETRootInfo::supportedWindowTypes() const { return p->windowTypes; } NET::Actions NETRootInfo::supportedActions() const { return p->actions; } NET::Properties NETRootInfo::passedProperties() const { return p->role == WindowManager ? p->properties : p->clientProperties; } NET::Properties2 NETRootInfo::passedProperties2() const { return p->role == WindowManager ? p->properties2 : p->clientProperties2; } NET::States NETRootInfo::passedStates() const { return p->role == WindowManager ? p->states - : NET::States(0); + : NET::States(nullptr); } NET::WindowTypes NETRootInfo::passedWindowTypes() const { return p->role == WindowManager ? p->windowTypes - : NET::WindowTypes(0); + : NET::WindowTypes(nullptr); } NET::Actions NETRootInfo::passedActions() const { return p->role == WindowManager ? p->actions - : NET::Actions(0); + : NET::Actions(nullptr); } void NETRootInfo::setSupported(NET::Property property, bool on) { if (p->role != WindowManager) { return; } if (on && !isSupported(property)) { p->properties |= property; setSupported(); } else if (!on && isSupported(property)) { p->properties &= ~property; setSupported(); } } void NETRootInfo::setSupported(NET::Property2 property, bool on) { if (p->role != WindowManager) { return; } if (on && !isSupported(property)) { p->properties2 |= property; setSupported(); } else if (!on && isSupported(property)) { p->properties2 &= ~property; setSupported(); } } void NETRootInfo::setSupported(NET::WindowTypeMask property, bool on) { if (p->role != WindowManager) { return; } if (on && !isSupported(property)) { p->windowTypes |= property; setSupported(); } else if (!on && isSupported(property)) { p->windowTypes &= ~property; setSupported(); } } void NETRootInfo::setSupported(NET::State property, bool on) { if (p->role != WindowManager) { return; } if (on && !isSupported(property)) { p->states |= property; setSupported(); } else if (!on && isSupported(property)) { p->states &= ~property; setSupported(); } } void NETRootInfo::setSupported(NET::Action property, bool on) { if (p->role != WindowManager) { return; } if (on && !isSupported(property)) { p->actions |= property; setSupported(); } else if (!on && isSupported(property)) { p->actions &= ~property; setSupported(); } } bool NETRootInfo::isSupported(NET::Property property) const { return p->properties & property; } bool NETRootInfo::isSupported(NET::Property2 property) const { return p->properties2 & property; } bool NETRootInfo::isSupported(NET::WindowTypeMask type) const { return p->windowTypes & type; } bool NETRootInfo::isSupported(NET::State state) const { return p->states & state; } bool NETRootInfo::isSupported(NET::Action action) const { return p->actions & action; } const xcb_window_t *NETRootInfo::clientList() const { return p->clients; } int NETRootInfo::clientListCount() const { return p->clients_count; } const xcb_window_t *NETRootInfo::clientListStacking() const { return p->stacking; } int NETRootInfo::clientListStackingCount() const { return p->stacking_count; } NETSize NETRootInfo::desktopGeometry() const { return p->geometry.width != 0 ? p->geometry : p->rootSize; } NETPoint NETRootInfo::desktopViewport(int desktop) const { if (desktop < 1) { NETPoint pt; // set to (0,0) return pt; } return p->viewport[desktop - 1]; } NETRect NETRootInfo::workArea(int desktop) const { if (desktop < 1) { NETRect rt; return rt; } return p->workarea[desktop - 1]; } const char *NETRootInfo::desktopName(int desktop) const { if (desktop < 1) { - return 0; + return nullptr; } return p->desktop_names[desktop - 1]; } const xcb_window_t *NETRootInfo::virtualRoots() const { return p->virtual_roots; } int NETRootInfo::virtualRootsCount() const { return p->virtual_roots_count; } NET::Orientation NETRootInfo::desktopLayoutOrientation() const { return p->desktop_layout_orientation; } QSize NETRootInfo::desktopLayoutColumnsRows() const { return QSize(p->desktop_layout_columns, p->desktop_layout_rows); } NET::DesktopLayoutCorner NETRootInfo::desktopLayoutCorner() const { return p->desktop_layout_corner; } int NETRootInfo::numberOfDesktops(bool ignore_viewport) const { if (!ignore_viewport && KWindowSystem::mapViewport()) { return KWindowSystem::numberOfDesktops(); } return p->number_of_desktops == 0 ? 1 : p->number_of_desktops; } int NETRootInfo::currentDesktop(bool ignore_viewport) const { if (!ignore_viewport && KWindowSystem::mapViewport()) { return KWindowSystem::currentDesktop(); } return p->current_desktop == 0 ? 1 : p->current_desktop; } xcb_window_t NETRootInfo::activeWindow() const { return p->active; } // NETWinInfo stuffs const int NETWinInfo::OnAllDesktops = NET::OnAllDesktops; NETWinInfo::NETWinInfo(xcb_connection_t *connection, xcb_window_t window, xcb_window_t rootWindow, NET::Properties properties, NET::Properties2 properties2, Role role) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::NETWinInfo: constructing object with role '%s'\n", (role == WindowManager) ? "WindowManager" : "Client"); #endif p = new NETWinInfoPrivate; p->ref = 1; p->atoms = atomsForConnection(connection); p->conn = connection; p->window = window; p->root = rootWindow; p->mapping_state = Withdrawn; p->mapping_state_dirty = true; - p->state = 0; + p->state = nullptr; p->types[ 0 ] = Unknown; - p->name = (char *) 0; - p->visible_name = (char *) 0; - p->icon_name = (char *) 0; - p->visible_icon_name = (char *) 0; + p->name = (char *) nullptr; + p->visible_name = (char *) nullptr; + p->icon_name = (char *) nullptr; + p->visible_icon_name = (char *) nullptr; p->desktop = p->pid = 0; p->handled_icons = false; p->user_time = -1U; - p->startup_id = NULL; + p->startup_id = nullptr; p->transient_for = XCB_NONE; p->opacity = 0xffffffffU; p->window_group = XCB_NONE; p->icon_pixmap = XCB_PIXMAP_NONE; p->icon_mask = XCB_PIXMAP_NONE; - p->allowed_actions = 0; + p->allowed_actions = nullptr; p->has_net_support = false; - p->class_class = (char *) 0; - p->class_name = (char *) 0; - p->window_role = (char *) 0; - p->client_machine = (char *) 0; - p->icon_sizes = NULL; - p->activities = (char *) 0; + p->class_class = (char *) nullptr; + p->class_name = (char *) nullptr; + p->window_role = (char *) nullptr; + p->client_machine = (char *) nullptr; + p->icon_sizes = nullptr; + p->activities = (char *) nullptr; p->desktop_file = Q_NULLPTR; p->blockCompositing = false; p->urgency = false; p->input = true; p->initialMappingState = NET::Withdrawn; p->protocols = NET::NoProtocol; // p->strut.left = p->strut.right = p->strut.top = p->strut.bottom = 0; // p->frame_strut.left = p->frame_strut.right = p->frame_strut.top = // p->frame_strut.bottom = 0; p->properties = properties; p->properties2 = properties2; p->icon_count = 0; p->role = role; update(p->properties, p->properties2); } #ifndef KWINDOWSYSTEM_NO_DEPRECATED NETWinInfo::NETWinInfo(xcb_connection_t *connection, xcb_window_t window, xcb_window_t rootWindow, NET::Properties properties, Role role) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::NETWinInfo: constructing object with role '%s'\n", (role == WindowManager) ? "WindowManager" : "Client"); #endif p = new NETWinInfoPrivate; p->ref = 1; p->atoms = atomsForConnection(connection); p->conn = connection; p->window = window; p->root = rootWindow; p->mapping_state = Withdrawn; p->mapping_state_dirty = true; - p->state = 0; + p->state = nullptr; p->types[ 0 ] = Unknown; - p->name = (char *) 0; - p->visible_name = (char *) 0; - p->icon_name = (char *) 0; - p->visible_icon_name = (char *) 0; + p->name = (char *) nullptr; + p->visible_name = (char *) nullptr; + p->icon_name = (char *) nullptr; + p->visible_icon_name = (char *) nullptr; p->desktop = p->pid = 0; p->handled_icons = false; p->user_time = -1U; - p->startup_id = NULL; + p->startup_id = nullptr; p->transient_for = XCB_NONE; p->opacity = 0xffffffffU; p->window_group = XCB_NONE; p->icon_pixmap = XCB_PIXMAP_NONE; p->icon_mask = XCB_PIXMAP_NONE; - p->allowed_actions = 0; + p->allowed_actions = nullptr; p->has_net_support = false; - p->class_class = (char *) 0; - p->class_name = (char *) 0; - p->window_role = (char *) 0; - p->client_machine = (char *) 0; - p->icon_sizes = NULL; - p->activities = (char *) 0; + p->class_class = (char *) nullptr; + p->class_name = (char *) nullptr; + p->window_role = (char *) nullptr; + p->client_machine = (char *) nullptr; + p->icon_sizes = nullptr; + p->activities = (char *) nullptr; p->desktop_file = Q_NULLPTR; p->blockCompositing = false; p->urgency = false; p->input = true; p->initialMappingState = NET::Withdrawn; p->protocols = NET::NoProtocol; // p->strut.left = p->strut.right = p->strut.top = p->strut.bottom = 0; // p->frame_strut.left = p->frame_strut.right = p->frame_strut.top = // p->frame_strut.bottom = 0; p->properties = properties; - p->properties2 = 0; + p->properties2 = nullptr; p->icon_count = 0; p->role = role; update(p->properties); } #endif NETWinInfo::NETWinInfo(const NETWinInfo &wininfo) { p = wininfo.p; p->ref++; } NETWinInfo::~NETWinInfo() { refdec_nwi(p); if (! p->ref) { delete p; } } // assignment operator const NETWinInfo &NETWinInfo::operator=(const NETWinInfo &wininfo) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::operator=()\n"); #endif if (p != wininfo.p) { refdec_nwi(p); if (! p->ref) { delete p; } } p = wininfo.p; p->ref++; return *this; } void NETWinInfo::setIcon(NETIcon icon, bool replace) { setIconInternal(p->icons, p->icon_count, p->atom(_NET_WM_ICON), icon, replace); } void NETWinInfo::setIconInternal(NETRArray &icons, int &icon_count, xcb_atom_t property, NETIcon icon, bool replace) { if (p->role != Client) { return; } if (replace) { for (int i = 0; i < icons.size(); i++) { delete [] icons[i].data; - icons[i].data = 0; + icons[i].data = nullptr; icons[i].size.width = 0; icons[i].size.height = 0; } icon_count = 0; } // assign icon icons[icon_count] = icon; icon_count++; // do a deep copy, we want to own the data NETIcon &ni = icons[icon_count - 1]; int sz = ni.size.width * ni.size.height; uint32_t *d = new uint32_t[sz]; ni.data = (unsigned char *) d; memcpy(d, icon.data, sz * sizeof(uint32_t)); // compute property length int proplen = 0; for (int i = 0; i < icon_count; i++) { proplen += 2 + (icons[i].size.width * icons[i].size.height); } uint32_t *prop = new uint32_t[proplen], *pprop = prop; for (int i = 0; i < icon_count; i++) { // copy size into property *pprop++ = icons[i].size.width; *pprop++ = icons[i].size.height; // copy data into property sz = (icons[i].size.width * icons[i].size.height); uint32_t *d32 = (uint32_t *) icons[i].data; for (int j = 0; j < sz; j++) { *pprop++ = *d32++; } } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, property, XCB_ATOM_CARDINAL, 32, proplen, (const void *) prop); delete [] prop; delete [] p->icon_sizes; - p->icon_sizes = NULL; + p->icon_sizes = nullptr; } void NETWinInfo::setIconGeometry(NETRect geometry) { if (p->role != Client) { return; } p->icon_geom = geometry; if (geometry.size.width == 0) { // Empty xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_ICON_GEOMETRY)); } else { uint32_t data[4]; data[0] = geometry.pos.x; data[1] = geometry.pos.y; data[2] = geometry.size.width; data[3] = geometry.size.height; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_ICON_GEOMETRY), XCB_ATOM_CARDINAL, 32, 4, (const void *) data); } } void NETWinInfo::setExtendedStrut(const NETExtendedStrut &extended_strut) { if (p->role != Client) { return; } p->extended_strut = extended_strut; uint32_t data[12]; data[0] = extended_strut.left_width; data[1] = extended_strut.right_width; data[2] = extended_strut.top_width; data[3] = extended_strut.bottom_width; data[4] = extended_strut.left_start; data[5] = extended_strut.left_end; data[6] = extended_strut.right_start; data[7] = extended_strut.right_end; data[8] = extended_strut.top_start; data[9] = extended_strut.top_end; data[10] = extended_strut.bottom_start; data[11] = extended_strut.bottom_end; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_STRUT_PARTIAL), XCB_ATOM_CARDINAL, 32, 12, (const void *) data); } void NETWinInfo::setStrut(NETStrut strut) { if (p->role != Client) { return; } p->strut = strut; uint32_t data[4]; data[0] = strut.left; data[1] = strut.right; data[2] = strut.top; data[3] = strut.bottom; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_STRUT), XCB_ATOM_CARDINAL, 32, 4, (const void *) data); } void NETWinInfo::setFullscreenMonitors(NETFullscreenMonitors topology) { if (p->role != Client) { return; } p->fullscreen_monitors = topology; uint32_t data[4]; data[0] = topology.top; data[1] = topology.bottom; data[2] = topology.left; data[3] = topology.right; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_FULLSCREEN_MONITORS), XCB_ATOM_CARDINAL, 32, 4, (const void *) data); } void NETWinInfo::setState(NET::States state, NET::States mask) { if (p->mapping_state_dirty) { updateWMState(); } // setState() needs to know the current state, so read it even if not requested if ((p->properties & WMState) == 0) { p->properties |= WMState; update(WMState); p->properties &= ~WMState; } if (p->role == Client && p->mapping_state != Withdrawn) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::setState (0x%lx, 0x%lx) (Client)\n", state, mask); #endif // NETWMDEBUG xcb_client_message_event_t event; event.response_type = XCB_CLIENT_MESSAGE; event.format = 32; event.sequence = 0; event.window = p->window; event.type = p->atom(_NET_WM_STATE); event.data.data32[3] = 0; event.data.data32[4] = 0; if ((mask & Modal) && ((p->state & Modal) != (state & Modal))) { event.data.data32[0] = (state & Modal) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MODAL); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & Sticky) && ((p->state & Sticky) != (state & Sticky))) { event.data.data32[0] = (state & Sticky) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_STICKY); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & Max) && (((p->state & mask) & Max) != (state & Max))) { NET::States wishstate = (p->state & ~mask) | (state & mask); if (((wishstate & MaxHoriz) != (p->state & MaxHoriz)) && ((wishstate & MaxVert) != (p->state & MaxVert))) { if ((wishstate & Max) == Max) { event.data.data32[0] = 1; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); event.data.data32[2] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } else if ((wishstate & Max) == 0) { event.data.data32[0] = 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); event.data.data32[2] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } else { event.data.data32[0] = (wishstate & MaxHoriz) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); event.data.data32[2] = 0; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); event.data.data32[0] = (wishstate & MaxVert) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); event.data.data32[2] = 0; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } } else if ((wishstate & MaxVert) != (p->state & MaxVert)) { event.data.data32[0] = (wishstate & MaxVert) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); event.data.data32[2] = 0; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } else if ((wishstate & MaxHoriz) != (p->state & MaxHoriz)) { event.data.data32[0] = (wishstate & MaxHoriz) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); event.data.data32[2] = 0; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } } if ((mask & Shaded) && ((p->state & Shaded) != (state & Shaded))) { event.data.data32[0] = (state & Shaded) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_SHADED); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & SkipTaskbar) && ((p->state & SkipTaskbar) != (state & SkipTaskbar))) { event.data.data32[0] = (state & SkipTaskbar) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_SKIP_TASKBAR); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & SkipPager) && ((p->state & SkipPager) != (state & SkipPager))) { event.data.data32[0] = (state & SkipPager) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_SKIP_PAGER); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & Hidden) && ((p->state & Hidden) != (state & Hidden))) { event.data.data32[0] = (state & Hidden) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_HIDDEN); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & FullScreen) && ((p->state & FullScreen) != (state & FullScreen))) { event.data.data32[0] = (state & FullScreen) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_FULLSCREEN); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & KeepAbove) && ((p->state & KeepAbove) != (state & KeepAbove))) { event.data.data32[0] = (state & KeepAbove) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_ABOVE); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & KeepBelow) && ((p->state & KeepBelow) != (state & KeepBelow))) { event.data.data32[0] = (state & KeepBelow) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_BELOW); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & StaysOnTop) && ((p->state & StaysOnTop) != (state & StaysOnTop))) { event.data.data32[0] = (state & StaysOnTop) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_STAYS_ON_TOP); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } if ((mask & DemandsAttention) && ((p->state & DemandsAttention) != (state & DemandsAttention))) { event.data.data32[0] = (state & DemandsAttention) ? 1 : 0; event.data.data32[1] = p->atom(_NET_WM_STATE_DEMANDS_ATTENTION); event.data.data32[2] = 0l; xcb_send_event(p->conn, false, p->root, netwm_sendevent_mask, (const char *) &event); } } else { p->state &= ~mask; p->state |= state; uint32_t data[50]; int count = 0; // Hints if (p->state & Modal) { data[count++] = p->atom(_NET_WM_STATE_MODAL); } if (p->state & MaxVert) { data[count++] = p->atom(_NET_WM_STATE_MAXIMIZED_VERT); } if (p->state & MaxHoriz) { data[count++] = p->atom(_NET_WM_STATE_MAXIMIZED_HORZ); } if (p->state & Shaded) { data[count++] = p->atom(_NET_WM_STATE_SHADED); } if (p->state & Hidden) { data[count++] = p->atom(_NET_WM_STATE_HIDDEN); } if (p->state & FullScreen) { data[count++] = p->atom(_NET_WM_STATE_FULLSCREEN); } if (p->state & DemandsAttention) { data[count++] = p->atom(_NET_WM_STATE_DEMANDS_ATTENTION); } // Policy if (p->state & KeepAbove) { data[count++] = p->atom(_NET_WM_STATE_ABOVE); } if (p->state & KeepBelow) { data[count++] = p->atom(_NET_WM_STATE_BELOW); } if (p->state & StaysOnTop) { data[count++] = p->atom(_NET_WM_STATE_STAYS_ON_TOP); } if (p->state & Sticky) { data[count++] = p->atom(_NET_WM_STATE_STICKY); } if (p->state & SkipTaskbar) { data[count++] = p->atom(_NET_WM_STATE_SKIP_TASKBAR); } if (p->state & SkipPager) { data[count++] = p->atom(_NET_WM_STATE_SKIP_PAGER); } #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::setState: setting state property (%d)\n", count); for (int i = 0; i < count; i++) { const QByteArray ba = get_atom_name(p->conn, data[i]); fprintf(stderr, "NETWinInfo::setState: state %ld '%s'\n", data[i], ba.constData()); } #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_STATE), XCB_ATOM_ATOM, 32, count, (const void *) data); } } void NETWinInfo::setWindowType(WindowType type) { if (p->role != Client) { return; } int len; uint32_t data[2]; switch (type) { case Override: // spec extension: override window type. we must comply with the spec // and provide a fall back (normal seems best) data[0] = p->atom(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE); data[1] = p->atom(_NET_WM_WINDOW_TYPE_NORMAL); len = 2; break; case Dialog: data[0] = p->atom(_NET_WM_WINDOW_TYPE_DIALOG); data[1] = XCB_NONE; len = 1; break; case Menu: data[0] = p->atom(_NET_WM_WINDOW_TYPE_MENU); data[1] = XCB_NONE; len = 1; break; case TopMenu: // spec extension: override window type. we must comply with the spec // and provide a fall back (dock seems best) data[0] = p->atom(_KDE_NET_WM_WINDOW_TYPE_TOPMENU); data[1] = p->atom(_NET_WM_WINDOW_TYPE_DOCK); len = 2; break; case Toolbar: data[0] = p->atom(_NET_WM_WINDOW_TYPE_TOOLBAR); data[1] = XCB_NONE; len = 1; break; case Dock: data[0] = p->atom(_NET_WM_WINDOW_TYPE_DOCK); data[1] = XCB_NONE; len = 1; break; case Desktop: data[0] = p->atom(_NET_WM_WINDOW_TYPE_DESKTOP); data[1] = XCB_NONE; len = 1; break; case Utility: data[0] = p->atom(_NET_WM_WINDOW_TYPE_UTILITY); data[1] = p->atom(_NET_WM_WINDOW_TYPE_DIALOG); // fallback for old netwm version len = 2; break; case Splash: data[0] = p->atom(_NET_WM_WINDOW_TYPE_SPLASH); data[1] = p->atom(_NET_WM_WINDOW_TYPE_DOCK); // fallback (dock seems best) len = 2; break; case DropdownMenu: data[0] = p->atom(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU); data[1] = p->atom(_NET_WM_WINDOW_TYPE_MENU); // fallback (tearoff seems to be the best) len = 1; break; case PopupMenu: data[0] = p->atom(_NET_WM_WINDOW_TYPE_POPUP_MENU); data[1] = p->atom(_NET_WM_WINDOW_TYPE_MENU); // fallback (tearoff seems to be the best) len = 1; break; case Tooltip: data[0] = p->atom(_NET_WM_WINDOW_TYPE_TOOLTIP); data[1] = XCB_NONE; len = 1; break; case Notification: data[0] = p->atom(_NET_WM_WINDOW_TYPE_NOTIFICATION); data[1] = p->atom(_NET_WM_WINDOW_TYPE_UTILITY); // fallback (utility seems to be the best) len = 1; break; case ComboBox: data[0] = p->atom(_NET_WM_WINDOW_TYPE_COMBOBOX); data[1] = XCB_NONE; len = 1; break; case DNDIcon: data[0] = p->atom(_NET_WM_WINDOW_TYPE_DND); data[1] = XCB_NONE; len = 1; break; case OnScreenDisplay: data[0] = p->atom(_KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY); data[1] = p->atom(_NET_WM_WINDOW_TYPE_NOTIFICATION); len = 1; break; default: case Normal: data[0] = p->atom(_NET_WM_WINDOW_TYPE_NORMAL); data[1] = XCB_NONE; len = 1; break; } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 32, len, (const void *) &data); } void NETWinInfo::setName(const char *name) { if (p->role != Client) { return; } delete [] p->name; p->name = nstrdup(name); if (p->name[0] != '\0') xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_NAME), p->atom(UTF8_STRING), 8, strlen(p->name), (const void *) p->name); else { xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_NAME)); } } void NETWinInfo::setVisibleName(const char *visibleName) { if (p->role != WindowManager) { return; } delete [] p->visible_name; p->visible_name = nstrdup(visibleName); if (p->visible_name[0] != '\0') xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_VISIBLE_NAME), p->atom(UTF8_STRING), 8, strlen(p->visible_name), (const void *) p->visible_name); else { xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_VISIBLE_NAME)); } } void NETWinInfo::setIconName(const char *iconName) { if (p->role != Client) { return; } delete [] p->icon_name; p->icon_name = nstrdup(iconName); if (p->icon_name[0] != '\0') xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_ICON_NAME), p->atom(UTF8_STRING), 8, strlen(p->icon_name), (const void *) p->icon_name); else { xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_ICON_NAME)); } } void NETWinInfo::setVisibleIconName(const char *visibleIconName) { if (p->role != WindowManager) { return; } delete [] p->visible_icon_name; p->visible_icon_name = nstrdup(visibleIconName); if (p->visible_icon_name[0] != '\0') xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_VISIBLE_ICON_NAME), p->atom(UTF8_STRING), 8, strlen(p->visible_icon_name), (const void *) p->visible_icon_name); else { xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_VISIBLE_ICON_NAME)); } } void NETWinInfo::setDesktop(int desktop, bool ignore_viewport) { if (p->mapping_state_dirty) { updateWMState(); } if (p->role == Client && p->mapping_state != Withdrawn) { // We only send a ClientMessage if we are 1) a client and 2) managed if (desktop == 0) { return; // We can't do that while being managed } if (!ignore_viewport && KWindowSystem::mapViewport()) { KWindowSystem::setOnDesktop(p->window, desktop); return; } const uint32_t data[5] = { desktop == OnAllDesktops ? 0xffffffff : desktop - 1, 0, 0, 0, 0 }; send_client_message(p->conn, netwm_sendevent_mask, p->root, p->window, p->atom(_NET_WM_DESKTOP), data); } else { // Otherwise we just set or remove the property directly p->desktop = desktop; if (desktop == 0) { xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_DESKTOP)); } else { uint32_t d = (desktop == OnAllDesktops ? 0xffffffff : desktop - 1); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_DESKTOP), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } } } void NETWinInfo::setPid(int pid) { if (p->role != Client) { return; } p->pid = pid; uint32_t d = pid; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_PID), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } void NETWinInfo::setHandledIcons(bool handled) { if (p->role != Client) { return; } p->handled_icons = handled; uint32_t d = handled; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_HANDLED_ICONS), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } void NETWinInfo::setStartupId(const char *id) { if (p->role != Client) { return; } delete[] p->startup_id; p->startup_id = nstrdup(id); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_STARTUP_ID), p->atom(UTF8_STRING), 8, strlen(p->startup_id), (const void *) p->startup_id); } void NETWinInfo::setOpacity(unsigned long opacity) { // if (p->role != Client) return; p->opacity = opacity; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_WINDOW_OPACITY), XCB_ATOM_CARDINAL, 32, 1, (const void *) &p->opacity); } void NETWinInfo::setAllowedActions(NET::Actions actions) { if (p->role != WindowManager) { return; } uint32_t data[50]; int count = 0; p->allowed_actions = actions; if (p->allowed_actions & ActionMove) { data[count++] = p->atom(_NET_WM_ACTION_MOVE); } if (p->allowed_actions & ActionResize) { data[count++] = p->atom(_NET_WM_ACTION_RESIZE); } if (p->allowed_actions & ActionMinimize) { data[count++] = p->atom(_NET_WM_ACTION_MINIMIZE); } if (p->allowed_actions & ActionShade) { data[count++] = p->atom(_NET_WM_ACTION_SHADE); } if (p->allowed_actions & ActionStick) { data[count++] = p->atom(_NET_WM_ACTION_STICK); } if (p->allowed_actions & ActionMaxVert) { data[count++] = p->atom(_NET_WM_ACTION_MAXIMIZE_VERT); } if (p->allowed_actions & ActionMaxHoriz) { data[count++] = p->atom(_NET_WM_ACTION_MAXIMIZE_HORZ); } if (p->allowed_actions & ActionFullScreen) { data[count++] = p->atom(_NET_WM_ACTION_FULLSCREEN); } if (p->allowed_actions & ActionChangeDesktop) { data[count++] = p->atom(_NET_WM_ACTION_CHANGE_DESKTOP); } if (p->allowed_actions & ActionClose) { data[count++] = p->atom(_NET_WM_ACTION_CLOSE); } #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::setAllowedActions: setting property (%d)\n", count); for (int i = 0; i < count; i++) { const QByteArray ba = get_atom_name(p->conn, data[i]); fprintf(stderr, "NETWinInfo::setAllowedActions: action %ld '%s'\n", data[i], ba.constData()); } #endif xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_ALLOWED_ACTIONS), XCB_ATOM_ATOM, 32, count, (const void *) data); } void NETWinInfo::setFrameExtents(NETStrut strut) { if (p->role != WindowManager) { return; } p->frame_strut = strut; uint32_t d[4]; d[0] = strut.left; d[1] = strut.right; d[2] = strut.top; d[3] = strut.bottom; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_FRAME_EXTENTS), XCB_ATOM_CARDINAL, 32, 4, (const void *) d); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_KDE_NET_WM_FRAME_STRUT), XCB_ATOM_CARDINAL, 32, 4, (const void *) d); } NETStrut NETWinInfo::frameExtents() const { return p->frame_strut; } void NETWinInfo::setFrameOverlap(NETStrut strut) { if (strut.left != -1 || strut.top != -1 || strut.right != -1 || strut.bottom != -1) { strut.left = qMax(0, strut.left); strut.top = qMax(0, strut.top); strut.right = qMax(0, strut.right); strut.bottom = qMax(0, strut.bottom); } p->frame_overlap = strut; uint32_t d[4]; d[0] = strut.left; d[1] = strut.right; d[2] = strut.top; d[3] = strut.bottom; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_FRAME_OVERLAP), XCB_ATOM_CARDINAL, 32, 4, (const void *) d); } NETStrut NETWinInfo::frameOverlap() const { return p->frame_overlap; } void NETWinInfo::kdeGeometry(NETRect &frame, NETRect &window) { if (p->win_geom.size.width == 0 || p->win_geom.size.height == 0) { const xcb_get_geometry_cookie_t geometry_cookie = xcb_get_geometry(p->conn, p->window); const xcb_translate_coordinates_cookie_t translate_cookie = xcb_translate_coordinates(p->conn, p->window, p->root, 0, 0); - xcb_get_geometry_reply_t *geometry = xcb_get_geometry_reply(p->conn, geometry_cookie, 0); + xcb_get_geometry_reply_t *geometry = xcb_get_geometry_reply(p->conn, geometry_cookie, nullptr); xcb_translate_coordinates_reply_t *translated - = xcb_translate_coordinates_reply(p->conn, translate_cookie, 0); + = xcb_translate_coordinates_reply(p->conn, translate_cookie, nullptr); if (geometry && translated) { p->win_geom.pos.x = translated->dst_x; p->win_geom.pos.y = translated->dst_y; p->win_geom.size.width = geometry->width; p->win_geom.size.height = geometry->height; } if (geometry) { free(geometry); } if (translated) { free(translated); } } // TODO try to work also without _NET_WM_FRAME_EXTENTS window = p->win_geom; frame.pos.x = window.pos.x - p->frame_strut.left; frame.pos.y = window.pos.y - p->frame_strut.top; frame.size.width = window.size.width + p->frame_strut.left + p->frame_strut.right; frame.size.height = window.size.height + p->frame_strut.top + p->frame_strut.bottom; } NETIcon NETWinInfo::icon(int width, int height) const { return iconInternal(p->icons, p->icon_count, width, height); } const int *NETWinInfo::iconSizes() const { - if (p->icon_sizes == NULL) { + if (p->icon_sizes == nullptr) { p->icon_sizes = new int[ p->icon_count * 2 + 2 ]; for (int i = 0; i < p->icon_count; ++i) { p->icon_sizes[ i * 2 ] = p->icons[ i ].size.width; p->icon_sizes[ i * 2 + 1 ] = p->icons[ i ].size.height; } p->icon_sizes[ p->icon_count * 2 ] = 0; // terminator p->icon_sizes[ p->icon_count * 2 + 1 ] = 0; } return p->icon_sizes; } NETIcon NETWinInfo::iconInternal(NETRArray &icons, int icon_count, int width, int height) const { NETIcon result; if (!icon_count) { result.size.width = 0; result.size.height = 0; - result.data = 0; + result.data = nullptr; return result; } // find the largest icon result = icons[0]; for (int i = 1; i < icons.size(); i++) { if (icons[i].size.width >= result.size.width && icons[i].size.height >= result.size.height) { result = icons[i]; } } // return the largest icon if w and h are -1 if (width == -1 && height == -1) { return result; } // find the icon that's closest in size to w x h... for (int i = 0; i < icons.size(); i++) { if ((icons[i].size.width >= width && icons[i].size.width < result.size.width) && (icons[i].size.height >= height && icons[i].size.height < result.size.height)) { result = icons[i]; } } return result; } void NETWinInfo::setUserTime(xcb_timestamp_t time) { if (p->role != Client) { return; } p->user_time = time; uint32_t d = time; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_USER_TIME), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } NET::Properties NETWinInfo::event(xcb_generic_event_t *ev) { NET::Properties properties; event(ev, &properties); return properties; } void NETWinInfo::event(xcb_generic_event_t *event, NET::Properties *properties, NET::Properties2 *properties2) { NET::Properties dirty; NET::Properties2 dirty2; bool do_update = false; const uint8_t eventType = event->response_type & ~0x80; if (p->role == WindowManager && eventType == XCB_CLIENT_MESSAGE && reinterpret_cast(event)->format == 32) { xcb_client_message_event_t *message = reinterpret_cast(event); #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::event: handling ClientMessage event\n"); #endif // NETWMDEBUG if (message->type == p->atom(_NET_WM_STATE)) { dirty = WMState; // we need to generate a change mask #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::event: state client message, getting new state/mask\n"); #endif int i; - NET::States state = 0, mask = 0; + NET::States state = nullptr, mask = nullptr; for (i = 1; i < 3; i++) { #ifdef NETWMDEBUG char *debug_txt = XGetAtomName(p->display, (xcb_atom_t) message->data.data32[i]); fprintf(stderr, "NETWinInfo::event: message %ld '%s'\n", message->data.data32[i], debug_txt); if (debug_txt) { XFree(debug_txt); } #endif if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_MODAL)) { mask |= Modal; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_STICKY)) { mask |= Sticky; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_MAXIMIZED_VERT)) { mask |= MaxVert; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_MAXIMIZED_HORZ)) { mask |= MaxHoriz; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_SHADED)) { mask |= Shaded; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_SKIP_TASKBAR)) { mask |= SkipTaskbar; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_SKIP_PAGER)) { mask |= SkipPager; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_HIDDEN)) { mask |= Hidden; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_FULLSCREEN)) { mask |= FullScreen; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_ABOVE)) { mask |= KeepAbove; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_BELOW)) { mask |= KeepBelow; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_DEMANDS_ATTENTION)) { mask |= DemandsAttention; } else if ((xcb_atom_t) message->data.data32[i] == p->atom(_NET_WM_STATE_STAYS_ON_TOP)) { mask |= StaysOnTop; } } // when removing, we just leave newstate == 0 switch (message->data.data32[0]) { case 1: // set // to set... the change state should be the same as the mask state = mask; break; case 2: // toggle // to toggle, we need to xor the current state with the new state state = (p->state & mask) ^ mask; break; default: // to clear state, the new state should stay zero ; } #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::event: calling changeState(%lx, %lx)\n", state, mask); #endif changeState(state, mask); } else if (message->type == p->atom(_NET_WM_DESKTOP)) { dirty = WMDesktop; if (message->data.data32[0] == OnAllDesktops) { changeDesktop(OnAllDesktops); } else { changeDesktop(message->data.data32[0] + 1); } } else if (message->type == p->atom(_NET_WM_FULLSCREEN_MONITORS)) { dirty2 = WM2FullscreenMonitors; NETFullscreenMonitors topology; topology.top = message->data.data32[0]; topology.bottom = message->data.data32[1]; topology.left = message->data.data32[2]; topology.right = message->data.data32[3]; #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo2::event: calling changeFullscreenMonitors" "(%ld, %ld, %ld, %ld, %ld)\n", message->window, message->data.data32[0], message->data.data32[1], message->data.data32[2], message->data.data32[3] ); #endif changeFullscreenMonitors(topology); } } if (eventType == XCB_PROPERTY_NOTIFY) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::event: handling PropertyNotify event\n"); #endif xcb_property_notify_event_t *pe = reinterpret_cast(event); if (pe->atom == p->atom(_NET_WM_NAME)) { dirty |= WMName; } else if (pe->atom == p->atom(_NET_WM_VISIBLE_NAME)) { dirty |= WMVisibleName; } else if (pe->atom == p->atom(_NET_WM_DESKTOP)) { dirty |= WMDesktop; } else if (pe->atom == p->atom(_NET_WM_WINDOW_TYPE)) { dirty |= WMWindowType; } else if (pe->atom == p->atom(_NET_WM_STATE)) { dirty |= WMState; } else if (pe->atom == p->atom(_NET_WM_STRUT)) { dirty |= WMStrut; } else if (pe->atom == p->atom(_NET_WM_STRUT_PARTIAL)) { dirty2 |= WM2ExtendedStrut; } else if (pe->atom == p->atom(_NET_WM_ICON_GEOMETRY)) { dirty |= WMIconGeometry; } else if (pe->atom == p->atom(_NET_WM_ICON)) { dirty |= WMIcon; } else if (pe->atom == p->atom(_NET_WM_PID)) { dirty |= WMPid; } else if (pe->atom == p->atom(_NET_WM_HANDLED_ICONS)) { dirty |= WMHandledIcons; } else if (pe->atom == p->atom(_NET_STARTUP_ID)) { dirty2 |= WM2StartupId; } else if (pe->atom == p->atom(_NET_WM_WINDOW_OPACITY)) { dirty2 |= WM2Opacity; } else if (pe->atom == p->atom(_NET_WM_ALLOWED_ACTIONS)) { dirty2 |= WM2AllowedActions; } else if (pe->atom == p->atom(WM_STATE)) { dirty |= XAWMState; } else if (pe->atom == p->atom(_NET_FRAME_EXTENTS)) { dirty |= WMFrameExtents; } else if (pe->atom == p->atom(_KDE_NET_WM_FRAME_STRUT)) { dirty |= WMFrameExtents; } else if (pe->atom == p->atom(_NET_WM_FRAME_OVERLAP)) { dirty2 |= WM2FrameOverlap; } else if (pe->atom == p->atom(_NET_WM_ICON_NAME)) { dirty |= WMIconName; } else if (pe->atom == p->atom(_NET_WM_VISIBLE_ICON_NAME)) { dirty |= WMVisibleIconName; } else if (pe->atom == p->atom(_NET_WM_USER_TIME)) { dirty2 |= WM2UserTime; } else if (pe->atom == XCB_ATOM_WM_HINTS) { dirty2 |= WM2GroupLeader; dirty2 |= WM2Urgency; dirty2 |= WM2Input; dirty2 |= WM2InitialMappingState; dirty2 |= WM2IconPixmap; } else if (pe->atom == XCB_ATOM_WM_TRANSIENT_FOR) { dirty2 |= WM2TransientFor; } else if (pe->atom == XCB_ATOM_WM_CLASS) { dirty2 |= WM2WindowClass; } else if (pe->atom == p->atom(WM_WINDOW_ROLE)) { dirty2 |= WM2WindowRole; } else if (pe->atom == XCB_ATOM_WM_CLIENT_MACHINE) { dirty2 |= WM2ClientMachine; } else if (pe->atom == p->atom(_KDE_NET_WM_ACTIVITIES)) { dirty2 |= WM2Activities; } else if (pe->atom == p->atom(_KDE_NET_WM_BLOCK_COMPOSITING) || pe->atom == p->atom(_NET_WM_BYPASS_COMPOSITOR)) { dirty2 |= WM2BlockCompositing; } else if (pe->atom == p->atom(_KDE_NET_WM_SHADOW)) { dirty2 |= WM2KDEShadow; } else if (pe->atom == p->atom(WM_PROTOCOLS)) { dirty2 |= WM2Protocols; } else if (pe->atom == p->atom(_NET_WM_OPAQUE_REGION)) { dirty2 |= WM2OpaqueRegion; } else if (pe->atom == p->atom(_KDE_NET_WM_DESKTOP_FILE)) { dirty2 = WM2DesktopFileName; } do_update = true; } else if (eventType == XCB_CONFIGURE_NOTIFY) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::event: handling ConfigureNotify event\n"); #endif dirty |= WMGeometry; // update window geometry xcb_configure_notify_event_t *configure = reinterpret_cast(event); p->win_geom.pos.x = configure->x; p->win_geom.pos.y = configure->y; p->win_geom.size.width = configure->width; p->win_geom.size.height = configure->height; } if (do_update) { update(dirty, dirty2); } if (properties) { *properties = dirty; } if (properties2) { *properties2 = dirty2; } } #ifndef KWINDOWSYSTEM_NO_DEPRECATED void NETWinInfo::event(xcb_generic_event_t *ev, unsigned long *properties, int properties_size) { NET::Properties p; NET::Properties2 p2; event(ev, &p, &p2); unsigned long props[ PROPERTIES_SIZE ] = { p, p2 }; assert(PROPERTIES_SIZE == 2); // add elements above if (properties_size > PROPERTIES_SIZE) { properties_size = PROPERTIES_SIZE; } for (int i = 0; i < properties_size; ++i) { properties[ i ] = props[ i ]; } } #endif void NETWinInfo::updateWMState() { update(XAWMState); } void NETWinInfo::update(NET::Properties dirtyProperties, NET::Properties2 dirtyProperties2) { Properties dirty = dirtyProperties & p->properties; Properties2 dirty2 = dirtyProperties2 & p->properties2; // We *always* want to update WM_STATE if set in dirty_props if (dirtyProperties & XAWMState) { dirty |= XAWMState; } xcb_get_property_cookie_t cookies[255]; int c = 0; if (dirty & XAWMState) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(WM_STATE), p->atom(WM_STATE), 0, 1); } if (dirty & WMState) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_STATE), XCB_ATOM_ATOM, 0, 2048); } if (dirty & WMDesktop) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_DESKTOP), XCB_ATOM_CARDINAL, 0, 1); } if (dirty & WMName) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_NAME), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & WMVisibleName) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_VISIBLE_NAME), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & WMIconName) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_ICON_NAME), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & WMVisibleIconName) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_VISIBLE_ICON_NAME), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty & WMWindowType) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_WINDOW_TYPE), XCB_ATOM_ATOM, 0, 2048); } if (dirty & WMStrut) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_STRUT), XCB_ATOM_CARDINAL, 0, 4); } if (dirty2 & WM2ExtendedStrut) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_STRUT_PARTIAL), XCB_ATOM_CARDINAL, 0, 12); } if (dirty2 & WM2FullscreenMonitors) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_FULLSCREEN_MONITORS), XCB_ATOM_CARDINAL, 0, 4); } if (dirty & WMIconGeometry) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_ICON_GEOMETRY), XCB_ATOM_CARDINAL, 0, 4); } if (dirty & WMIcon) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_ICON), XCB_ATOM_CARDINAL, 0, 0xffffffff); } if (dirty & WMFrameExtents) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_FRAME_EXTENTS), XCB_ATOM_CARDINAL, 0, 4); cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_KDE_NET_WM_FRAME_STRUT), XCB_ATOM_CARDINAL, 0, 4); } if (dirty2 & WM2FrameOverlap) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_FRAME_OVERLAP), XCB_ATOM_CARDINAL, 0, 4); } if (dirty2 & WM2Activities) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_KDE_NET_WM_ACTIVITIES), XCB_ATOM_STRING, 0, MAX_PROP_SIZE); } if (dirty2 & WM2BlockCompositing) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_KDE_NET_WM_BLOCK_COMPOSITING), XCB_ATOM_CARDINAL, 0, 1); cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_BYPASS_COMPOSITOR), XCB_ATOM_CARDINAL, 0, 1); } if (dirty & WMPid) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_PID), XCB_ATOM_CARDINAL, 0, 1); } if (dirty2 & WM2StartupId) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_STARTUP_ID), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } if (dirty2 & WM2Opacity) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_WINDOW_OPACITY), XCB_ATOM_CARDINAL, 0, 1); } if (dirty2 & WM2AllowedActions) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_ALLOWED_ACTIONS), XCB_ATOM_ATOM, 0, 2048); } if (dirty2 & WM2UserTime) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_USER_TIME), XCB_ATOM_CARDINAL, 0, 1); } if (dirty2 & WM2TransientFor) { cookies[c++] = xcb_get_property(p->conn, false, p->window, XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, 0, 1); } if (dirty2 & (WM2GroupLeader | WM2Urgency | WM2Input | WM2InitialMappingState | WM2IconPixmap)) { cookies[c++] = xcb_get_property(p->conn, false, p->window, XCB_ATOM_WM_HINTS, XCB_ATOM_WM_HINTS, 0, 9); } if (dirty2 & WM2WindowClass) { cookies[c++] = xcb_get_property(p->conn, false, p->window, XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, 0, MAX_PROP_SIZE); } if (dirty2 & WM2WindowRole) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(WM_WINDOW_ROLE), XCB_ATOM_STRING, 0, MAX_PROP_SIZE); } if (dirty2 & WM2ClientMachine) { cookies[c++] = xcb_get_property(p->conn, false, p->window, XCB_ATOM_WM_CLIENT_MACHINE, XCB_ATOM_STRING, 0, MAX_PROP_SIZE); } if (dirty2 & WM2Protocols) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(WM_PROTOCOLS), XCB_ATOM_ATOM, 0, 2048); } if (dirty2 & WM2OpaqueRegion) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_NET_WM_OPAQUE_REGION), XCB_ATOM_CARDINAL, 0, MAX_PROP_SIZE); } if (dirty2 & WM2DesktopFileName) { cookies[c++] = xcb_get_property(p->conn, false, p->window, p->atom(_KDE_NET_WM_DESKTOP_FILE), p->atom(UTF8_STRING), 0, MAX_PROP_SIZE); } c = 0; if (dirty & XAWMState) { p->mapping_state = Withdrawn; bool success; uint32_t state = get_value_reply(p->conn, cookies[c++], p->atom(WM_STATE), 0, &success); if (success) { switch (state) { case 3: // IconicState p->mapping_state = Iconic; break; case 1: // NormalState p->mapping_state = Visible; break; case 0: // WithdrawnState default: p->mapping_state = Withdrawn; break; } p->mapping_state_dirty = false; } } if (dirty & WMState) { - p->state = 0; + p->state = nullptr; const QVector states = get_array_reply(p->conn, cookies[c++], XCB_ATOM_ATOM); #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::update: updating window state (%ld)\n", states.count()); #endif Q_FOREACH (const xcb_atom_t state, states) { #ifdef NETWMDEBUG const QByteArray ba = get_atom_name(p->conn, state); fprintf(stderr, "NETWinInfo::update: adding window state %ld '%s'\n", state, ba.constData()); #endif if (state == p->atom(_NET_WM_STATE_MODAL)) { p->state |= Modal; } else if (state == p->atom(_NET_WM_STATE_STICKY)) { p->state |= Sticky; } else if (state == p->atom(_NET_WM_STATE_MAXIMIZED_VERT)) { p->state |= MaxVert; } else if (state == p->atom(_NET_WM_STATE_MAXIMIZED_HORZ)) { p->state |= MaxHoriz; } else if (state == p->atom(_NET_WM_STATE_SHADED)) { p->state |= Shaded; } else if (state == p->atom(_NET_WM_STATE_SKIP_TASKBAR)) { p->state |= SkipTaskbar; } else if (state == p->atom(_NET_WM_STATE_SKIP_PAGER)) { p->state |= SkipPager; } else if (state == p->atom(_NET_WM_STATE_HIDDEN)) { p->state |= Hidden; } else if (state == p->atom(_NET_WM_STATE_FULLSCREEN)) { p->state |= FullScreen; } else if (state == p->atom(_NET_WM_STATE_ABOVE)) { p->state |= KeepAbove; } else if (state == p->atom(_NET_WM_STATE_BELOW)) { p->state |= KeepBelow; } else if (state == p->atom(_NET_WM_STATE_DEMANDS_ATTENTION)) { p->state |= DemandsAttention; } else if (state == p->atom(_NET_WM_STATE_STAYS_ON_TOP)) { p->state |= StaysOnTop; } } } if (dirty & WMDesktop) { p->desktop = 0; bool success; uint32_t desktop = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0, &success); if (success) { if (desktop != 0xffffffff) { p->desktop = desktop + 1; } else { p->desktop = OnAllDesktops; } } } if (dirty & WMName) { delete[] p->name; - p->name = NULL; + p->name = nullptr; const QByteArray str = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (str.length() > 0) { p->name = nstrndup(str.constData(), str.length()); } } if (dirty & WMVisibleName) { delete[] p->visible_name; - p->visible_name = NULL; + p->visible_name = nullptr; const QByteArray str = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (str.length() > 0) { p->visible_name = nstrndup(str.constData(), str.length()); } } if (dirty & WMIconName) { delete[] p->icon_name; - p->icon_name = NULL; + p->icon_name = nullptr; const QByteArray str = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (str.length() > 0) { p->icon_name = nstrndup(str.constData(), str.length()); } } if (dirty & WMVisibleIconName) { delete[] p->visible_icon_name; - p->visible_icon_name = NULL; + p->visible_icon_name = nullptr; const QByteArray str = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (str.length() > 0) { p->visible_icon_name = nstrndup(str.constData(), str.length()); } } if (dirty & WMWindowType) { p->types.reset(); p->types[0] = Unknown; p->has_net_support = false; const QVector types = get_array_reply(p->conn, cookies[c++], XCB_ATOM_ATOM); if (types.count() > 0) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::update: getting window type (%ld)\n", types.count()); #endif p->has_net_support = true; int pos = 0; Q_FOREACH (const xcb_atom_t type, types) { #ifdef NETWMDEBUG const QByteArray name = get_atom_name(p->conn, type); fprintf(stderr, "NETWinInfo::update: examining window type %ld %s\n", type, name.constData()); #endif if (type == p->atom(_NET_WM_WINDOW_TYPE_NORMAL)) { p->types[pos++] = Normal; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_DESKTOP)) { p->types[pos++] = Desktop; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_DOCK)) { p->types[pos++] = Dock; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_TOOLBAR)) { p->types[pos++] = Toolbar; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_MENU)) { p->types[pos++] = Menu; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_DIALOG)) { p->types[pos++] = Dialog; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_UTILITY)) { p->types[ pos++ ] = Utility; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_SPLASH)) { p->types[pos++] = Splash; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_DROPDOWN_MENU)) { p->types[pos++] = DropdownMenu; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_POPUP_MENU)) { p->types[pos++] = PopupMenu; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_TOOLTIP)) { p->types[pos++] = Tooltip; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_NOTIFICATION)) { p->types[pos++] = Notification; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_COMBOBOX)) { p->types[pos++] = ComboBox; } else if (type == p->atom(_NET_WM_WINDOW_TYPE_DND)) { p->types[pos++] = DNDIcon; } else if (type == p->atom(_KDE_NET_WM_WINDOW_TYPE_OVERRIDE)) { p->types[pos++] = Override; } else if (type == p->atom(_KDE_NET_WM_WINDOW_TYPE_TOPMENU)) { p->types[pos++] = TopMenu; } else if (type == p->atom(_KDE_NET_WM_WINDOW_TYPE_ON_SCREEN_DISPLAY)) { p->types[pos++] = OnScreenDisplay; } } } } if (dirty & WMStrut) { p->strut = NETStrut(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 4) { p->strut.left = data[0]; p->strut.right = data[1]; p->strut.top = data[2]; p->strut.bottom = data[3]; } } if (dirty2 & WM2ExtendedStrut) { p->extended_strut = NETExtendedStrut(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 12) { p->extended_strut.left_width = data[0]; p->extended_strut.right_width = data[1]; p->extended_strut.top_width = data[2]; p->extended_strut.bottom_width = data[3]; p->extended_strut.left_start = data[4]; p->extended_strut.left_end = data[5]; p->extended_strut.right_start = data[6]; p->extended_strut.right_end = data[7]; p->extended_strut.top_start = data[8]; p->extended_strut.top_end = data[9]; p->extended_strut.bottom_start = data[10]; p->extended_strut.bottom_end = data[11]; } } if (dirty2 & WM2FullscreenMonitors) { p->fullscreen_monitors = NETFullscreenMonitors(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 4) { p->fullscreen_monitors.top = data[0]; p->fullscreen_monitors.bottom = data[1]; p->fullscreen_monitors.left = data[2]; p->fullscreen_monitors.right = data[3]; } } if (dirty & WMIconGeometry) { p->icon_geom = NETRect(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 4) { p->icon_geom.pos.x = data[0]; p->icon_geom.pos.y = data[1]; p->icon_geom.size.width = data[2]; p->icon_geom.size.height = data[3]; } } if (dirty & WMIcon) { readIcon(p->conn, cookies[c++], p->icons, p->icon_count); delete[] p->icon_sizes; - p->icon_sizes = NULL; + p->icon_sizes = nullptr; } if (dirty & WMFrameExtents) { p->frame_strut = NETStrut(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 0) { data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); } else { xcb_discard_reply(p->conn, cookies[c++].sequence); } if (data.count() == 4) { p->frame_strut.left = data[0]; p->frame_strut.right = data[1]; p->frame_strut.top = data[2]; p->frame_strut.bottom = data[3]; } } if (dirty2 & WM2FrameOverlap) { p->frame_overlap = NETStrut(); QVector data = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); if (data.count() == 4) { p->frame_overlap.left = data[0]; p->frame_overlap.right = data[1]; p->frame_overlap.top = data[2]; p->frame_overlap.bottom = data[3]; } } if (dirty2 & WM2Activities) { delete[] p->activities; - p->activities = NULL; + p->activities = nullptr; const QByteArray activities = get_string_reply(p->conn, cookies[c++], XCB_ATOM_STRING); if (activities.length() > 0) { p->activities = nstrndup(activities.constData(), activities.length()); } } if (dirty2 & WM2BlockCompositing) { bool success; p->blockCompositing = false; // _KDE_NET_WM_BLOCK_COMPOSITING uint32_t data = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0, &success); if (success) p->blockCompositing = bool(data); // _NET_WM_BYPASS_COMPOSITOR data = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0, &success); if (success) { switch (data) { case 1: p->blockCompositing = true; break; case 2: p->blockCompositing = false; break; default: break; // yes, the standard /is/ that stupid. } } } if (dirty & WMPid) { p->pid = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0); } if (dirty2 & WM2StartupId) { delete[] p->startup_id; - p->startup_id = NULL; + p->startup_id = nullptr; const QByteArray id = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (id.length() > 0) { p->startup_id = nstrndup(id.constData(), id.length()); } } if (dirty2 & WM2Opacity) { p->opacity = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0xffffffff); } if (dirty2 & WM2AllowedActions) { - p->allowed_actions = 0; + p->allowed_actions = nullptr; const QVector actions = get_array_reply(p->conn, cookies[c++], XCB_ATOM_ATOM); if (actions.count() > 0) { #ifdef NETWMDEBUG fprintf(stderr, "NETWinInfo::update: updating allowed actions (%ld)\n", actions.count()); #endif Q_FOREACH (const xcb_atom_t action, actions) { #ifdef NETWMDEBUG const QByteArray name = get_atom_name(p->conn, action); fprintf(stderr, "NETWinInfo::update: adding allowed action %ld '%s'\n", action, name.constData()); #endif if (action == p->atom(_NET_WM_ACTION_MOVE)) { p->allowed_actions |= ActionMove; } else if (action == p->atom(_NET_WM_ACTION_RESIZE)) { p->allowed_actions |= ActionResize; } else if (action == p->atom(_NET_WM_ACTION_MINIMIZE)) { p->allowed_actions |= ActionMinimize; } else if (action == p->atom(_NET_WM_ACTION_SHADE)) { p->allowed_actions |= ActionShade; } else if (action == p->atom(_NET_WM_ACTION_STICK)) { p->allowed_actions |= ActionStick; } else if (action == p->atom(_NET_WM_ACTION_MAXIMIZE_VERT)) { p->allowed_actions |= ActionMaxVert; } else if (action == p->atom(_NET_WM_ACTION_MAXIMIZE_HORZ)) { p->allowed_actions |= ActionMaxHoriz; } else if (action == p->atom(_NET_WM_ACTION_FULLSCREEN)) { p->allowed_actions |= ActionFullScreen; } else if (action == p->atom(_NET_WM_ACTION_CHANGE_DESKTOP)) { p->allowed_actions |= ActionChangeDesktop; } else if (action == p->atom(_NET_WM_ACTION_CLOSE)) { p->allowed_actions |= ActionClose; } } } } if (dirty2 & WM2UserTime) { p->user_time = -1U; bool success; uint32_t value = get_value_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL, 0, &success); if (success) { p->user_time = value; } } if (dirty2 & WM2TransientFor) { p->transient_for = get_value_reply(p->conn, cookies[c++], XCB_ATOM_WINDOW, 0); } if (dirty2 & (WM2GroupLeader | WM2Urgency | WM2Input | WM2InitialMappingState | WM2IconPixmap)) { - xcb_get_property_reply_t *reply = xcb_get_property_reply(p->conn, cookies[c++], 0); + xcb_get_property_reply_t *reply = xcb_get_property_reply(p->conn, cookies[c++], nullptr); if (reply && reply->format == 32 && reply->value_len == 9 && reply->type == XCB_ATOM_WM_HINTS) { kde_wm_hints *hints = reinterpret_cast(xcb_get_property_value(reply)); if (hints->flags & (1 << 0)/*Input*/) { p->input = hints->input; } if (hints->flags & (1 << 1)/*StateHint*/) { switch (hints->initial_state) { case 3: // IconicState p->initialMappingState = Iconic; break; case 1: // NormalState p->initialMappingState = Visible; break; case 0: // WithdrawnState default: p->initialMappingState = Withdrawn; break; } } if (hints->flags & (1 << 2)/*IconPixmapHint*/) { p->icon_pixmap = hints->icon_pixmap; } if (hints->flags & (1 << 5)/*IconMaskHint*/) { p->icon_mask = hints->icon_mask; } if (hints->flags & (1 << 6)/*WindowGroupHint*/) { p->window_group = hints->window_group; } p->urgency = (hints->flags & (1 << 8)/*UrgencyHint*/); } if (reply) { free(reply); } } if (dirty2 & WM2WindowClass) { delete[] p->class_name; delete[] p->class_class; - p->class_name = NULL; - p->class_class = NULL; + p->class_name = nullptr; + p->class_class = nullptr; const QList list = get_stringlist_reply(p->conn, cookies[c++], XCB_ATOM_STRING); if (list.count() == 2) { p->class_name = nstrdup(list.at(0).constData()); p->class_class = nstrdup(list.at(1).constData()); } } if (dirty2 & WM2WindowRole) { delete[] p->window_role; - p->window_role = NULL; + p->window_role = nullptr; const QByteArray role = get_string_reply(p->conn, cookies[c++], XCB_ATOM_STRING); if (role.length() > 0) { p->window_role = nstrndup(role.constData(), role.length()); } } if (dirty2 & WM2ClientMachine) { delete[] p->client_machine; - p->client_machine = NULL; + p->client_machine = nullptr; const QByteArray value = get_string_reply(p->conn, cookies[c++], XCB_ATOM_STRING); if (value.length() > 0) { p->client_machine = nstrndup(value.constData(), value.length()); } } if (dirty2 & WM2Protocols) { const QVector protocols = get_array_reply(p->conn, cookies[c++], XCB_ATOM_ATOM); p->protocols = NET::NoProtocol; for (auto it = protocols.begin(); it != protocols.end(); ++it) { if ((*it) == p->atom(WM_TAKE_FOCUS)) { p->protocols |= TakeFocusProtocol; } else if ((*it) == p->atom(WM_DELETE_WINDOW)) { p->protocols |= DeleteWindowProtocol; } else if ((*it) == p->atom(_NET_WM_PING)) { p->protocols |= PingProtocol; } else if ((*it) == p->atom(_NET_WM_SYNC_REQUEST)) { p->protocols |= SyncRequestProtocol; } else if ((*it) == p->atom(_NET_WM_CONTEXT_HELP)) { p->protocols |= ContextHelpProtocol; } } } if (dirty2 & WM2OpaqueRegion) { const QVector values = get_array_reply(p->conn, cookies[c++], XCB_ATOM_CARDINAL); p->opaqueRegion.clear(); p->opaqueRegion.reserve(values.count() / 4); for (int i = 0; i < values.count() - 3; i += 4) { NETRect rect; rect.pos.x = values.at(i); rect.pos.y = values.at(i + 1); rect.size.width = values.at(i + 2); rect.size.height = values.at(i + 3); p->opaqueRegion.push_back(rect); } } if (dirty2 & WM2DesktopFileName) { delete[] p->desktop_file; - p->desktop_file = NULL; + p->desktop_file = nullptr; const QByteArray id = get_string_reply(p->conn, cookies[c++], p->atom(UTF8_STRING)); if (id.length() > 0) { p->desktop_file = nstrndup(id.constData(), id.length()); } } } NETRect NETWinInfo::iconGeometry() const { return p->icon_geom; } NET::States NETWinInfo::state() const { return p->state; } NETStrut NETWinInfo::strut() const { return p->strut; } NETExtendedStrut NETWinInfo::extendedStrut() const { return p->extended_strut; } NETFullscreenMonitors NETWinInfo::fullscreenMonitors() const { return p->fullscreen_monitors; } bool NET::typeMatchesMask(WindowType type, WindowTypes mask) { switch (type) { #define CHECK_TYPE_MASK( type ) \ case type: \ if( mask & type##Mask ) \ return true; \ break; CHECK_TYPE_MASK(Normal) CHECK_TYPE_MASK(Desktop) CHECK_TYPE_MASK(Dock) CHECK_TYPE_MASK(Toolbar) CHECK_TYPE_MASK(Menu) CHECK_TYPE_MASK(Dialog) CHECK_TYPE_MASK(Override) CHECK_TYPE_MASK(TopMenu) CHECK_TYPE_MASK(Utility) CHECK_TYPE_MASK(Splash) CHECK_TYPE_MASK(DropdownMenu) CHECK_TYPE_MASK(PopupMenu) CHECK_TYPE_MASK(Tooltip) CHECK_TYPE_MASK(Notification) CHECK_TYPE_MASK(ComboBox) CHECK_TYPE_MASK(DNDIcon) CHECK_TYPE_MASK(OnScreenDisplay) #undef CHECK_TYPE_MASK default: break; } return false; } NET::WindowType NETWinInfo::windowType(WindowTypes supported_types) const { for (int i = 0; i < p->types.size(); ++i) { // return the type only if the application supports it if (typeMatchesMask(p->types[ i ], supported_types)) { return p->types[ i ]; } } return Unknown; } bool NETWinInfo::hasWindowType() const { return p->types.size() > 0; } const char *NETWinInfo::name() const { return p->name; } const char *NETWinInfo::visibleName() const { return p->visible_name; } const char *NETWinInfo::iconName() const { return p->icon_name; } const char *NETWinInfo::visibleIconName() const { return p->visible_icon_name; } int NETWinInfo::desktop(bool ignore_viewport) const { if (!ignore_viewport && KWindowSystem::mapViewport()) { const KWindowInfo info(p->window, NET::WMDesktop); return info.desktop(); } return p->desktop; } int NETWinInfo::pid() const { return p->pid; } xcb_timestamp_t NETWinInfo::userTime() const { return p->user_time; } const char *NETWinInfo::startupId() const { return p->startup_id; } unsigned long NETWinInfo::opacity() const { return p->opacity; } NET::Actions NETWinInfo::allowedActions() const { return p->allowed_actions; } bool NETWinInfo::hasNETSupport() const { return p->has_net_support; } xcb_window_t NETWinInfo::transientFor() const { return p->transient_for; } xcb_window_t NETWinInfo::groupLeader() const { return p->window_group; } bool NETWinInfo::urgency() const { return p->urgency; } bool NETWinInfo::input() const { return p->input; } NET::MappingState NETWinInfo::initialMappingState() const { return p->initialMappingState; } xcb_pixmap_t NETWinInfo::icccmIconPixmap() const { return p->icon_pixmap; } xcb_pixmap_t NETWinInfo::icccmIconPixmapMask() const { return p->icon_mask; } const char *NETWinInfo::windowClassClass() const { return p->class_class; } const char *NETWinInfo::windowClassName() const { return p->class_name; } const char *NETWinInfo::windowRole() const { return p->window_role; } const char *NETWinInfo::clientMachine() const { return p->client_machine; } const char *NETWinInfo::activities() const { return p->activities; } void NETWinInfo::setActivities(const char *activities) { delete [] p->activities; - if (activities == (char *) NULL || activities[0] == '\0') { + if (activities == (char *) nullptr || activities[0] == '\0') { // on all activities static const char nulluuid[] = KDE_ALL_ACTIVITIES_UUID; p->activities = nstrdup(nulluuid); } else { p->activities = nstrdup(activities); } xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_KDE_NET_WM_ACTIVITIES), XCB_ATOM_STRING, 8, strlen(p->activities), p->activities); } void NETWinInfo::setBlockingCompositing(bool active) { if (p->role != Client) { return; } p->blockCompositing = active; if (active) { uint32_t d = 1; xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_KDE_NET_WM_BLOCK_COMPOSITING), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_NET_WM_BYPASS_COMPOSITOR), XCB_ATOM_CARDINAL, 32, 1, (const void *) &d); } else { xcb_delete_property(p->conn, p->window, p->atom(_KDE_NET_WM_BLOCK_COMPOSITING)); xcb_delete_property(p->conn, p->window, p->atom(_NET_WM_BYPASS_COMPOSITOR)); } } bool NETWinInfo::isBlockingCompositing() const { return p->blockCompositing; } bool NETWinInfo::handledIcons() const { return p->handled_icons; } NET::Properties NETWinInfo::passedProperties() const { return p->properties; } NET::Properties2 NETWinInfo::passedProperties2() const { return p->properties2; } NET::MappingState NETWinInfo::mappingState() const { return p->mapping_state; } NET::Protocols NETWinInfo::protocols() const { return p->protocols; } bool NETWinInfo::supportsProtocol(NET::Protocol protocol) const { return p->protocols.testFlag(protocol); } std::vector< NETRect > NETWinInfo::opaqueRegion() const { return p->opaqueRegion; } xcb_connection_t *NETWinInfo::xcbConnection() const { return p->conn; } void NETWinInfo::setDesktopFileName(const char *name) { if (p->role != Client) { return; } delete[] p->desktop_file; p->desktop_file = nstrdup(name); xcb_change_property(p->conn, XCB_PROP_MODE_REPLACE, p->window, p->atom(_KDE_NET_WM_DESKTOP_FILE), p->atom(UTF8_STRING), 8, strlen(p->desktop_file), (const void *) p->desktop_file); } const char *NETWinInfo::desktopFileName() const { return p->desktop_file; } void NETRootInfo::virtual_hook(int, void *) { /*BASE::virtual_hook( id, data );*/ } void NETWinInfo::virtual_hook(int, void *) { /*BASE::virtual_hook( id, data );*/ } int NET::timestampCompare(unsigned long time1, unsigned long time2) { return KXUtils::timestampCompare(time1, time2); } int NET::timestampDiff(unsigned long time1, unsigned long time2) { return KXUtils::timestampDiff(time1, time2); } #endif diff --git a/src/platforms/xcb/netwm.h b/src/platforms/xcb/netwm.h index d62a864..c01a11d 100644 --- a/src/platforms/xcb/netwm.h +++ b/src/platforms/xcb/netwm.h @@ -1,1674 +1,1674 @@ /* Copyright (c) 2000 Troll Tech AS Copyright (c) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef netwm_h #define netwm_h #include #include #include #if KWINDOWSYSTEM_HAVE_X11 #include #include "netwm_def.h" #define KDE_ALL_ACTIVITIES_UUID "00000000-0000-0000-0000-000000000000" // forward declaration struct NETRootInfoPrivate; struct NETWinInfoPrivate; template class NETRArray; /** Common API for root window properties/protocols. The NETRootInfo class provides a common API for clients and window managers to set/read/change properties on the root window as defined by the NET Window Manager Specification.. @author Bradley T. Hughes @see NET @see NETWinInfo **/ class KWINDOWSYSTEM_EXPORT NETRootInfo : public NET { public: /** Indexes for the properties array. **/ // update also NETRootInfoPrivate::properties[] size when extending this enum { PROTOCOLS, WINDOW_TYPES, STATES, PROTOCOLS2, ACTIONS, PROPERTIES_SIZE }; /** Window Managers should use this constructor to create a NETRootInfo object, which will be used to set/update information stored on the rootWindow. The application role is automatically set to WindowManager when using this constructor. @param connection XCB connection @param supportWindow The Window id of the supportWindow. The supportWindow must be created by the window manager as a child of the rootWindow. The supportWindow must not be destroyed until the Window Manager exits. @param wmName A string which should be the window manager's name (ie. "KWin" or "Blackbox"). @param properties The properties the window manager supports @param windowTypes The window types the window manager supports @param states The states the window manager supports @param properties2 The properties2 the window manager supports @param actions The actions the window manager supports @param screen For Window Managers that support multiple screen (ie. "multiheaded") displays, the screen number may be explicitly defined. If this argument is omitted, the default screen will be used. @param doActivate true to activate the window **/ NETRootInfo(xcb_connection_t *connection, xcb_window_t supportWindow, const char *wmName, NET::Properties properties, NET::WindowTypes windowTypes, NET::States states, NET::Properties2 properties2, NET::Actions actions, int screen = -1, bool doActivate = true); /** Clients should use this constructor to create a NETRootInfo object, which will be used to query information set on the root window. The application role is automatically set to Client when using this constructor. @param connection XCB connection @param properties The properties the client is interested in. @param properties2 The properties2 the client is interested in. @param properties_size The number of elements in the properties array. @param screen For Clients that support multiple screen (ie. "multiheaded") displays, the screen number may be explicitly defined. If this argument is omitted, the default screen will be used. @param doActivate true to call activate() to do an initial data read/update of the query information. **/ - NETRootInfo(xcb_connection_t *connection, NET::Properties properties, NET::Properties2 properties2 = 0, + NETRootInfo(xcb_connection_t *connection, NET::Properties properties, NET::Properties2 properties2 = nullptr, int screen = -1, bool doActivate = true); /** Creates a shared copy of the specified NETRootInfo object. @param rootinfo the NETRootInfo object to copy **/ NETRootInfo(const NETRootInfo &rootinfo); /** Destroys the NETRootInfo object. **/ virtual ~NETRootInfo(); /** Returns the xcb connection used. @return the XCB connection **/ xcb_connection_t *xcbConnection() const; /** Returns the Window id of the rootWindow. @return the id of the root window **/ xcb_window_t rootWindow() const; /** Returns the Window id of the supportWindow. @return the id of the support window **/ xcb_window_t supportWindow() const; /** Returns the name of the Window Manager. @return the name of the window manager **/ const char *wmName() const; /** Sets the given property if on is true, and clears the property otherwise. In WindowManager mode this function updates _NET_SUPPORTED. In Client mode this function does nothing. @since 4.4 **/ void setSupported(NET::Property property, bool on = true); /** @overload @since 4.4 **/ void setSupported(NET::Property2 property, bool on = true); /** @overload @since 4.4 **/ void setSupported(NET::WindowTypeMask property, bool on = true); /** @overload @since 4.4 **/ void setSupported(NET::State property, bool on = true); /** @overload @since 4.4 **/ void setSupported(NET::Action property, bool on = true); /** Returns true if the given property is supported by the window manager. Note that for Client mode, NET::Supported needs to be passed in the properties argument for this to work. **/ bool isSupported(NET::Property property) const; /** @overload **/ bool isSupported(NET::Property2 property) const; /** @overload **/ bool isSupported(NET::WindowTypeMask type) const; /** @overload **/ bool isSupported(NET::State state) const; /** @overload **/ bool isSupported(NET::Action action) const; /** In the Window Manager mode, this is equivalent to the properties argument passed to the constructor. In the Client mode, if NET::Supported was passed in the properties argument, the returned value are all properties supported by the Window Manager. Other supported protocols and properties are returned by the specific methods. @see supportedProperties2() @see supportedStates() @see supportedWindowTypes() @see supportedActions() **/ NET::Properties supportedProperties() const; /** * In the Window Manager mode, this is equivalent to the properties2 * argument passed to the constructor. In the Client mode, if * NET::Supported was passed in the properties argument, the returned * value are all properties2 supported by the Window Manager. Other supported * protocols and properties are returned by the specific methods. * @see supportedProperties() * @see supportedStates() * @see supportedWindowTypes() * @see supportedActions() * @since 5.0 **/ NET::Properties2 supportedProperties2() const; /** * In the Window Manager mode, this is equivalent to the states * argument passed to the constructor. In the Client mode, if * NET::Supported was passed in the properties argument, the returned * value are all states supported by the Window Manager. Other supported * protocols and properties are returned by the specific methods. * @see supportedProperties() @see supportedProperties2() * @see supportedWindowTypes() * @see supportedActions() * @since 5.0 **/ NET::States supportedStates() const; /** * In the Window Manager mode, this is equivalent to the windowTypes * argument passed to the constructor. In the Client mode, if * NET::Supported was passed in the properties argument, the returned * value are all window types supported by the Window Manager. Other supported * protocols and properties are returned by the specific methods. * @see supportedProperties() @see supportedProperties2() * @see supportedStates() * @see supportedActions() * @since 5.0 **/ NET::WindowTypes supportedWindowTypes() const; /** * In the Window Manager mode, this is equivalent to the actions * argument passed to the constructor. In the Client mode, if * NET::Supported was passed in the properties argument, the returned * value are all actions supported by the Window Manager. Other supported * protocols and properties are returned by the specific methods. * @see supportedProperties() @see supportedProperties2() * @see supportedStates() * @see supportedWindowTypes() * @since 5.0 **/ NET::Actions supportedActions() const; /** * @returns the properties argument passed to the constructor. * @see passedProperties2() * @see passedStates() * @see passedWindowTypes() * @see passedActions() **/ NET::Properties passedProperties() const; /** * @returns the properties2 argument passed to the constructor. * @see passedProperties() * @see passedStates() * @see passedWindowTypes() * @see passedActions() * @since 5.0 **/ NET::Properties2 passedProperties2() const; /** * @returns the states argument passed to the constructor. * @see passedProperties() * @see passedProperties2() * @see passedWindowTypes() * @see passedActions() * @since 5.0 **/ NET::States passedStates() const; /** * @returns the windowTypes argument passed to the constructor. * @see passedProperties() * @see passedProperties2() * @see passedStates() * @see passedActions() * @since 5.0 **/ NET::WindowTypes passedWindowTypes() const; /** * @returns the actions argument passed to the constructor. * @see passedProperties() * @see passedProperties2() * @see passedStates() * @see passedWindowTypes() * @since 5.0 **/ NET::Actions passedActions() const; /** Returns an array of Window id's, which contain all managed windows. @return the array of Window id's @see clientListCount() **/ const xcb_window_t *clientList() const; /** Returns the number of managed windows in clientList array. @return the number of managed windows in the clientList array @see clientList() **/ int clientListCount() const; /** Returns an array of Window id's, which contain all managed windows in stacking order. @return the array of Window id's in stacking order @see clientListStackingCount() **/ const xcb_window_t *clientListStacking() const; /** Returns the number of managed windows in the clientListStacking array. @return the number of Window id's in the client list @see clientListStacking() **/ int clientListStackingCount() const; /** Returns the desktop geometry size. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. You should use calls for virtual desktops, viewport is mapped to them if needed. @return the size of the desktop **/ NETSize desktopGeometry() const; /** Returns the viewport of the specified desktop. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. You should use calls for virtual desktops, viewport is mapped to them if needed. @param desktop the number of the desktop @return the position of the desktop's viewport **/ NETPoint desktopViewport(int desktop) const; /** Returns the workArea for the specified desktop. @param desktop the number of the desktop @return the size of the work area **/ NETRect workArea(int desktop) const; /** Returns the name for the specified desktop. @param desktop the number of the desktop @return the name of the desktop **/ const char *desktopName(int desktop) const; /** Returns an array of Window id's, which contain the virtual root windows. @return the array of Window id's @see virtualRootsCount() **/ const xcb_window_t *virtualRoots() const; /** Returns the number of window in the virtualRoots array. @return the number of Window id's in the virtual root array @see virtualRoots() **/ int virtualRootsCount() const; /** Returns the desktop layout orientation. **/ NET::Orientation desktopLayoutOrientation() const; /** Returns the desktop layout number of columns and rows. Note that either may be 0 (see _NET_DESKTOP_LAYOUT). **/ QSize desktopLayoutColumnsRows() const; /** Returns the desktop layout starting corner. **/ NET::DesktopLayoutCorner desktopLayoutCorner() const; /** Returns the number of desktops. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. They are however mapped to virtual desktops if needed. @param ignore_viewport if false, viewport is mapped to virtual desktops @return the number of desktops **/ int numberOfDesktops(bool ignore_viewport = false) const; /** Returns the current desktop. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. They are however mapped to virtual desktops if needed. @param ignore_viewport if false, viewport is mapped to virtual desktops @return the number of the current desktop **/ int currentDesktop(bool ignore_viewport = false) const; /** Returns the active (focused) window. @return the id of the active window **/ xcb_window_t activeWindow() const; /** Window Managers must call this after creating the NETRootInfo object, and before using any other method in the class. This method sets initial data on the root window and does other post-construction duties. Clients must also call this after creating the object to do an initial data read/update. **/ void activate(); /** Sets the list of managed windows on the Root/Desktop window. @param windows The array of Window id's @param count The number of windows in the array **/ void setClientList(const xcb_window_t *windows, unsigned int count); /** Sets the list of managed windows in stacking order on the Root/Desktop window. @param windows The array of Window id's @param count The number of windows in the array. **/ void setClientListStacking(const xcb_window_t *windows, unsigned int count); /** Sets the current desktop to the specified desktop. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. It is however mapped to virtual desktops if needed. @param desktop the number of the desktop @param ignore_viewport if false, viewport is mapped to virtual desktops **/ void setCurrentDesktop(int desktop, bool ignore_viewport = false); /** Sets the desktop geometry to the specified geometry. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. You should use calls for virtual desktops, viewport is mapped to them if needed. @param geometry the new size of the desktop **/ void setDesktopGeometry(const NETSize &geometry); /** Sets the viewport for the current desktop to the specified point. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. You should use calls for virtual desktops, viewport is mapped to them if needed. @param desktop the number of the desktop @param viewport the new position of the desktop's viewport **/ void setDesktopViewport(int desktop, const NETPoint &viewport); /** Sets the number of desktops to the specified number. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. Viewport is mapped to virtual desktops if needed, but not for this call. @param numberOfDesktops the number of desktops **/ void setNumberOfDesktops(int numberOfDesktops); /** Sets the name of the specified desktop. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. Viewport is mapped to virtual desktops if needed, but not for this call. @param desktop the number of the desktop @param desktopName the new name of the desktop **/ void setDesktopName(int desktop, const char *desktopName); /** Requests that the specified window becomes the active (focused) one. @param window the id of the new active window @param src whether the request comes from normal application or from a pager or similar tool @param timestamp X server timestamp of the user action that caused the request @param active_window active window of the requesting application, if any **/ void setActiveWindow(xcb_window_t window, NET::RequestSource src, xcb_timestamp_t timestamp, xcb_window_t active_window); /** Sets the active (focused) window the specified window. This should be used only in the window manager mode. @param window the if of the new active window **/ void setActiveWindow(xcb_window_t window); /** Sets the workarea for the specified desktop @param desktop the number of the desktop @param workArea the new work area of the desktop **/ void setWorkArea(int desktop, const NETRect &workArea); /** Sets the list of virtual root windows on the root window. @param windows The array of Window id's @param count The number of windows in the array. **/ void setVirtualRoots(const xcb_window_t *windows, unsigned int count); /** Sets the desktop layout. This is set by the pager. When setting, the pager must own the _NET_DESKTOP_LAYOUT_Sn manager selection. See _NET_DESKTOP_LAYOUT for details. **/ void setDesktopLayout(NET::Orientation orientation, int columns, int rows, NET::DesktopLayoutCorner corner); /** * Sets the _NET_SHOWING_DESKTOP status (whether desktop is being shown). */ void setShowingDesktop(bool showing); /** * Returns the status of _NET_SHOWING_DESKTOP. */ bool showingDesktop() const; /** Assignment operator. Ensures that the shared data reference counts are correct. **/ const NETRootInfo &operator=(const NETRootInfo &rootinfo); /** Clients (such as pagers/taskbars) that wish to close a window should call this function. This will send a request to the Window Manager, which usually can usually decide how to react to such requests. @param window the id of the window to close **/ void closeWindowRequest(xcb_window_t window); /** Clients (such as pagers/taskbars) that wish to start a WMMoveResize (where the window manager controls the resize/movement, i.e. _NET_WM_MOVERESIZE) should call this function. This will send a request to the Window Manager. @param window The client window that would be resized/moved. @param x_root X position of the cursor relative to the root window. @param y_root Y position of the cursor relative to the root window. @param direction One of NET::Direction (see base class documentation for a description of the different directions). **/ void moveResizeRequest(xcb_window_t window, int x_root, int y_root, Direction direction); /** Clients (such as pagers/taskbars) that wish to move/resize a window using WM2MoveResizeWindow (_NET_MOVERESIZE_WINDOW) should call this function. This will send a request to the Window Manager. See _NET_MOVERESIZE_WINDOW description for details. @param window The client window that would be resized/moved. @param flags Flags specifying the operation (see _NET_MOVERESIZE_WINDOW description) @param x Requested X position for the window @param y Requested Y position for the window @param width Requested width for the window @param height Requested height for the window **/ void moveResizeWindowRequest(xcb_window_t window, int flags, int x, int y, int width, int height); /** Sends the _NET_RESTACK_WINDOW request. **/ void restackRequest(xcb_window_t window, RequestSource source, xcb_window_t above, int detail, xcb_timestamp_t timestamp); /** Sends a ping with the given timestamp to the window, using the _NET_WM_PING protocol. */ void sendPing(xcb_window_t window, xcb_timestamp_t timestamp); /** This function takes the passed XEvent and returns an OR'ed list of NETRootInfo properties that have changed in the properties argument. The new information will be read immediately by the class. The elements of the properties argument are as they would be passed to the constructor, if the array is not large enough, changed properties that don't fit in it won't be listed there (they'll be updated in the class though). @param event the event @param properties properties that changed @param properties_size size of the passed properties array @deprecated since 5.0 use event(xcb_generic_event_t*, NET::Properties*, NET::Properties2*) **/ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED void event(xcb_generic_event_t *event, unsigned long *properties, int properties_size); #endif /** * This function takes the passed xcb_generic_event_t and returns the updated properties in the passed in arguments. * * The new information will be read immediately by the class. It is possible to pass in a * null pointer in the arguments. In that case the passed in argument will obviously not * be updated, but the class will process the information nevertheless. * * @param event the event * @param properties The NET::Properties that changed * @param properties2 The NET::Properties2 that changed * @since 5.0 **/ void event(xcb_generic_event_t *event, NET::Properties *properties, NET::Properties2 *properties2 = Q_NULLPTR); /** This function takes the passed XEvent and returns an OR'ed list of NETRootInfo properties that have changed. The new information will be read immediately by the class. This overloaded version returns only a single mask, and therefore cannot check state of all properties like the other variant. @param event the event @return the properties **/ NET::Properties event(xcb_generic_event_t *event); protected: /** A Client should subclass NETRootInfo and reimplement this function when it wants to know when a window has been added. @param window the id of the window to add **/ virtual void addClient(xcb_window_t window) { Q_UNUSED(window); } /** A Client should subclass NETRootInfo and reimplement this function when it wants to know when a window has been removed. @param window the id of the window to remove **/ virtual void removeClient(xcb_window_t window) { Q_UNUSED(window); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to change the number of desktops. @param numberOfDesktops the new number of desktops **/ virtual void changeNumberOfDesktops(int numberOfDesktops) { Q_UNUSED(numberOfDesktops); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to change the specified desktop geometry. @param desktop the number of the desktop @param geom the new size **/ virtual void changeDesktopGeometry(int desktop, const NETSize &geom) { Q_UNUSED(desktop); Q_UNUSED(geom); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to change the specified desktop viewport. @param desktop the number of the desktop @param viewport the new position of the viewport **/ virtual void changeDesktopViewport(int desktop, const NETPoint &viewport) { Q_UNUSED(desktop); Q_UNUSED(viewport); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to change the current desktop. @param desktop the number of the desktop **/ virtual void changeCurrentDesktop(int desktop) { Q_UNUSED(desktop); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to close a window. @param window the id of the window to close **/ virtual void closeWindow(xcb_window_t window) { Q_UNUSED(window); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to start a move/resize. @param window The window that wants to move/resize @param x_root X position of the cursor relative to the root window. @param y_root Y position of the cursor relative to the root window. @param direction One of NET::Direction (see base class documentation for a description of the different directions). **/ virtual void moveResize(xcb_window_t window, int x_root, int y_root, unsigned long direction) { Q_UNUSED(window); Q_UNUSED(x_root); Q_UNUSED(y_root); Q_UNUSED(direction); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to receive replies to the _NET_WM_PING protocol. @param window the window from which the reply came @param timestamp timestamp of the ping */ virtual void gotPing(xcb_window_t window, xcb_timestamp_t timestamp) { Q_UNUSED(window); Q_UNUSED(timestamp); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to change the active (focused) window. @param window the id of the window to activate @param src the source from which the request came @param timestamp the timestamp of the user action causing this request @param active_window active window of the requesting application, if any **/ virtual void changeActiveWindow(xcb_window_t window, NET::RequestSource src, xcb_timestamp_t timestamp, xcb_window_t active_window) { Q_UNUSED(window); Q_UNUSED(src); Q_UNUSED(timestamp); Q_UNUSED(active_window); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a pager made a request to move/resize a window. See _NET_MOVERESIZE_WINDOW for details. @param window the id of the window to more/resize @param flags Flags specifying the operation (see _NET_MOVERESIZE_WINDOW description) @param x Requested X position for the window @param y Requested Y position for the window @param width Requested width for the window @param height Requested height for the window **/ virtual void moveResizeWindow(xcb_window_t window, int flags, int x, int y, int width, int height) { Q_UNUSED(window); Q_UNUSED(flags); Q_UNUSED(x); Q_UNUSED(y); Q_UNUSED(width); Q_UNUSED(height); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a Client made a request to restack a window. See _NET_RESTACK_WINDOW for details. @param window the id of the window to restack @param source the source of the request @param above other window in the restack request @param detail restack detail @param timestamp the timestamp of the request **/ virtual void restackWindow(xcb_window_t window, RequestSource source, xcb_window_t above, int detail, xcb_timestamp_t timestamp) { Q_UNUSED(window); Q_UNUSED(source); Q_UNUSED(above); Q_UNUSED(detail); Q_UNUSED(timestamp); } /** A Window Manager should subclass NETRootInfo and reimplement this function when it wants to know when a pager made a request to change showing the desktop. See _NET_SHOWING_DESKTOP for details. @param showing whether to activate the showing desktop mode **/ virtual void changeShowingDesktop(bool showing) { Q_UNUSED(showing); } private: void update(NET::Properties properties, NET::Properties2 properties2); void setSupported(); void setDefaultProperties(); void updateSupportedProperties(xcb_atom_t atom); protected: /** Virtual hook, used to add new "virtual" functions while maintaining binary compatibility. Unused in this class. */ virtual void virtual_hook(int id, void *data); private: NETRootInfoPrivate *p; // krazy:exclude=dpointer (implicitly shared) }; /** Common API for application window properties/protocols. The NETWinInfo class provides a common API for clients and window managers to set/read/change properties on an application window as defined by the NET Window Manager Specification. @author Bradley T. Hughes @see NET @see NETRootInfo @see http://www.freedesktop.org/standards/wm-spec/ **/ class KWINDOWSYSTEM_EXPORT NETWinInfo : public NET { public: /** Indexes for the properties array. **/ // update also NETWinInfoPrivate::properties[] size when extending this enum { PROTOCOLS, PROTOCOLS2, PROPERTIES_SIZE }; /** Create a NETWinInfo object, which will be used to set/read/change information stored on an application window. @param connection XCB connection @param window The Window id of the application window. @param rootWindow The Window id of the root window. @param properties The NET::Properties flags @param properties2 The NET::Properties2 flags @param role Select the application role. If this argument is omitted, the role will default to Client. **/ NETWinInfo(xcb_connection_t *connection, xcb_window_t window, xcb_window_t rootWindow, NET::Properties properties, NET::Properties2 properties2, Role role = Client); /** This constructor differs from the above one only in the way it accepts the list of properties the client is interested in. @deprecated since 5.0 use above ctor **/ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED NETWinInfo(xcb_connection_t *connection, xcb_window_t window, xcb_window_t rootWindow, NET::Properties properties, Role role = Client); #endif /** Creates a shared copy of the specified NETWinInfo object. @param wininfo the NETWinInfo to copy **/ NETWinInfo(const NETWinInfo &wininfo); /** Destroys the NETWinInfo object. **/ virtual ~NETWinInfo(); /** Assignment operator. Ensures that the shared data reference counts are correct. **/ const NETWinInfo &operator=(const NETWinInfo &wintinfo); /** Returns the xcb connection used. @return the XCB connection **/ xcb_connection_t *xcbConnection() const; /** Returns true if the window has any window type set, even if the type itself is not known to this implementation. Presence of a window type as specified by the NETWM spec is considered as the window supporting this specification. @return true if the window has support for the NETWM spec **/ bool hasNETSupport() const; /** @returns the properties argument passed to the constructor. @see passedProperties2() **/ NET::Properties passedProperties() const; /** * @returns the properties2 argument passed to the constructor. * @see passedProperties() * @since 5.0 **/ NET::Properties2 passedProperties2() const; /** Returns the icon geometry. @return the geometry of the icon **/ NETRect iconGeometry() const; /** Returns the state of the window (see the NET base class documentation for a description of the various states). @return the state of the window **/ NET::States state() const; /** Returns the extended (partial) strut specified by this client. See _NET_WM_STRUT_PARTIAL in the spec. **/ NETExtendedStrut extendedStrut() const; /** @deprecated use strutPartial() Returns the strut specified by this client. @return the strut of the window **/ NETStrut strut() const; /** Returns the window type for this client (see the NET base class documentation for a description of the various window types). Since clients may specify several windows types for a window in order to support backwards compatibility and extensions not available in the NETWM spec, you should specify all window types you application supports (see the NET::WindowTypeMask mask values for various window types). This method will return the first window type that is listed in the supported types, or NET::Unknown if none of the window types is supported. @return the type of the window **/ WindowType windowType(WindowTypes supported_types) const; /** This function returns false if the window has not window type specified at all. Used by KWindowInfo::windowType() to return either NET::Normal or NET::Dialog as appropriate as a fallback. **/ bool hasWindowType() const; /** Returns the name of the window in UTF-8 format. @return the name of the window **/ const char *name() const; /** Returns the visible name as set by the window manager in UTF-8 format. @return the visible name of the window **/ const char *visibleName() const; /** Returns the iconic name of the window in UTF-8 format. Note that this has nothing to do with icons, but it's for "iconic" representations of the window (taskbars etc.), that should be shown when the window is in iconic state. See description of _NET_WM_ICON_NAME for details. @return the iconic name **/ const char *iconName() const; /** Returns the visible iconic name as set by the window manager in UTF-8 format. Note that this has nothing to do with icons, but it's for "iconic" representations of the window (taskbars etc.), that should be shown when the window is in iconic state. See description of _NET_WM_VISIBLE_ICON_NAME for details. @return the visible iconic name **/ const char *visibleIconName() const; /** Returns the desktop where the window is residing. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. It is however mapped to virtual desktops if needed. @param ignore_viewport if false, viewport is mapped to virtual desktops @return the number of the window's desktop @see OnAllDesktops() **/ int desktop(bool ignore_viewport = false) const; /** Returns the process id for the client window. @return the process id of the window **/ int pid() const; /** Returns whether or not this client handles icons. @return true if this client handles icons, false otherwise **/ bool handledIcons() const; /** Returns the mapping state for the window (see the NET base class documentation for a description of mapping state). @return the mapping state **/ MappingState mappingState() const; /** Set icons for the application window. If replace is True, then the specified icon is defined to be the only icon. If replace is False, then the specified icon is added to a list of icons. @param icon the new icon @param replace true to replace, false to append to the list of icons **/ void setIcon(NETIcon icon, bool replace = true); /** Set the icon geometry for the application window. @param geometry the new icon geometry **/ void setIconGeometry(NETRect geometry); /** Set the extended (partial) strut for the application window. @param extended_strut the new strut **/ void setExtendedStrut(const NETExtendedStrut &extended_strut); /** @deprecated use setExtendedStrut() Set the strut for the application window. @param strut the new strut **/ void setStrut(NETStrut strut); /** Set the state for the application window (see the NET base class documentation for a description of window state). @param state the name state @param mask the mask for the state **/ void setState(NET::States state, NET::States mask); /** Sets the window type for this client (see the NET base class documentation for a description of the various window types). @param type the window type **/ void setWindowType(WindowType type); /** Sets the name for the application window. @param name the new name of the window **/ void setName(const char *name); /** For Window Managers only: set the visible name ( i.e. xterm, xterm <2>, xterm <3>, ... ) @param visibleName the new visible name **/ void setVisibleName(const char *visibleName); /** Sets the iconic name for the application window. @param name the new iconic name **/ void setIconName(const char *name); /** For Window Managers only: set the visible iconic name ( i.e. xterm, xterm <2>, xterm <3>, ... ) @param name the new visible iconic name **/ void setVisibleIconName(const char *name); /** Set which window the desktop is (should be) on. NOTE: KDE uses virtual desktops and does not directly support viewport in any way. It is however mapped to virtual desktops if needed. @param desktop the number of the new desktop @param ignore_viewport if false, viewport is mapped to virtual desktops @see OnAllDesktops() **/ void setDesktop(int desktop, bool ignore_viewport = false); /** Set the application window's process id. @param pid the window's process id **/ void setPid(int pid); /** Set whether this application window handles icons. @param handled true if the window handles icons, false otherwise **/ void setHandledIcons(bool handled); /** Set the frame decoration strut, i.e. the width of the decoration borders. @param strut the new strut **/ void setFrameExtents(NETStrut strut); /** Returns the frame decoration strut, i.e. the width of the decoration borders. @since 4.3 **/ NETStrut frameExtents() const; /** Sets the window frame overlap strut, i.e. how far the window frame extends behind the client area on each side. Set the strut values to -1 if you want the window frame to cover the whole client area. The default values are 0. @since 4.4 **/ void setFrameOverlap(NETStrut strut); /** Returns the frame overlap strut, i.e. how far the window frame extends behind the client area on each side. @since 4.4 **/ NETStrut frameOverlap() const; /** Returns an icon. If width and height are passed, the icon returned will be the closest it can find (the next biggest). If width and height are omitted, then the largest icon in the list is returned. @param width the preferred width for the icon, -1 to ignore @param height the preferred height for the icon, -1 to ignore @return the icon **/ NETIcon icon(int width = -1, int height = -1) const; /** Returns a list of provided icon sizes. Each size is pair width,height, terminated with pair 0,0. @since 4.3 **/ const int *iconSizes() const; /** * Sets user timestamp @p time on the window (property _NET_WM_USER_TIME). * The timestamp is expressed as XServer time. If a window * is shown with user timestamp older than the time of the last * user action, it won't be activated after being shown, with the special * value 0 meaning not to activate the window after being shown. */ void setUserTime(xcb_timestamp_t time); /** * Returns the time of last user action on the window, or -1 if not set. */ xcb_timestamp_t userTime() const; /** * Sets the startup notification id @p id on the window. */ void setStartupId(const char *startup_id); /** * Returns the startup notification id of the window. */ const char *startupId() const; /** * Sets opacity (0 = transparent, 0xffffffff = opaque ) on the window. */ void setOpacity(unsigned long opacity); /** * Returns the opacity of the window. */ unsigned long opacity() const; /** * Sets actions that the window manager allows for the window. */ void setAllowedActions(NET::Actions actions); /** * Returns actions that the window manager allows for the window. */ NET::Actions allowedActions() const; /** * Returns the WM_TRANSIENT_FOR property for the window, i.e. the mainwindow * for this window. */ xcb_window_t transientFor() const; /** * Returns the leader window for the group the window is in, if any. */ xcb_window_t groupLeader() const; /** * Returns whether the UrgencyHint is set in the WM_HINTS.flags. * See ICCCM 4.1.2.4. * * @since 5.3 **/ bool urgency() const; /** * Returns whether the Input flag is set in WM_HINTS. * See ICCCM 4.1.2.4 and 4.1.7. * * The default value is @c true in case the Client is mapped without a WM_HINTS property. * * @since 5.3 **/ bool input() const; /** * Returns the initial mapping state as set in WM_HINTS. * See ICCCM 4.1.2.4 and 4.1.4. * * The default value if @c Withdrawn in case the Client is mapped without * a WM_HINTS property or without the initial state hint set. * * @since 5.5 **/ MappingState initialMappingState() const; /** * Returns the icon pixmap as set in WM_HINTS. * See ICCCM 4.1.2.4. * * The default value is @c XCB_PIXMAP_NONE. * * Using the ICCCM variant for the icon is deprecated and only * offers a limited functionality compared to @link {icon}. * Only use this variant as a fallback. * * @see icccmIconPixmapMask * @see icon * @since 5.7 **/ xcb_pixmap_t icccmIconPixmap() const; /** * Returns the mask for the icon pixmap as set in WM_HINTS. * See ICCCM 4.1.2.4. * * The default value is @c XCB_PIXMAP_NONE. * * @see icccmIconPixmap * @since 5.7 **/ xcb_pixmap_t icccmIconPixmapMask() const; /** * Returns the class component of the window class for the window * (i.e. WM_CLASS property). */ const char *windowClassClass() const; /** * Returns the name component of the window class for the window * (i.e. WM_CLASS property). */ const char *windowClassName() const; /** * Returns the window role for the window (i.e. WM_WINDOW_ROLE property). */ const char *windowRole() const; /** * Returns the client machine for the window (i.e. WM_CLIENT_MACHINE property). */ const char *clientMachine() const; /** * returns a comma-separated list of the activities the window is associated with. * FIXME this might be better as a NETRArray ? * @since 4.6 */ const char *activities() const; /** * Sets the comma-separated list of activities the window is associated with. * @since 5.1 */ void setActivities(const char *activities); /** * Sets whether the client wishes to block compositing (for better performance) * @since 4.7 */ void setBlockingCompositing(bool active); /** * Returns whether the client wishes to block compositing (for better performance) * @since 4.7 */ bool isBlockingCompositing() const; /** Places the window frame geometry in frame, and the application window geometry in window. Both geometries are relative to the root window. @param frame the geometry for the frame @param window the geometry for the window **/ void kdeGeometry(NETRect &frame, NETRect &window); /** Sets the desired multiple-monitor topology (4 monitor indices indicating the top, bottom, left, and right edges of the window) when the fullscreen state is enabled. The indices are from the set returned by the Xinerama extension. See _NET_WM_FULLSCREEN_MONITORS for details. @param topology A struct that models the desired monitor topology, namely: top is the monitor whose top edge defines the top edge of the fullscreen window, bottom is the monitor whose bottom edge defines the bottom edge of the fullscreen window, left is the monitor whose left edge defines the left edge of the fullscreen window, and right is the monitor whose right edge defines the right edge of the fullscreen window. **/ void setFullscreenMonitors(NETFullscreenMonitors topology); /** Returns the desired fullscreen monitor topology for this client, should it be in fullscreen state. See _NET_WM_FULLSCREEN_MONITORS in the spec. **/ NETFullscreenMonitors fullscreenMonitors() const; /** This function takes the passed XEvent and returns an OR'ed list of NETWinInfo properties that have changed in the properties argument. The new information will be read immediately by the class. The elements of the properties argument are as they would be passed to the constructor, if the array is not large enough, changed properties that don't fit in it won't be listed there (they'll be updated in the class though). @param event the event @param properties properties that changed @param properties_size size of the passed properties array @deprecated since 5.0 use event(xcb_generic_event_t*, NET::Properties*, NET::Properties2*) **/ #ifndef KWINDOWSYSTEM_NO_DEPRECATED KWINDOWSYSTEM_DEPRECATED void event(xcb_generic_event_t *event, unsigned long *properties, int properties_size); #endif /** * This function takes the passed in xcb_generic_event_t and returns the updated properties * in the passed in arguments. * * The new information will be read immediately by the class. It is possible to pass in a * null pointer in the arguments. In that case the passed in * argument will obviously not be updated, but the class will process the information * nevertheless. * * @param event the event * @param properties The NET::Properties that changed * @param properties2 The NET::Properties2 that changed * @since 5.0 **/ void event(xcb_generic_event_t *event, NET::Properties *properties, NET::Properties2 *properties2 = Q_NULLPTR); /** This function takes the pass XEvent and returns an OR'ed list of NETWinInfo properties that have changed. The new information will be read immediately by the class. This overloaded version returns only a single mask, and therefore cannot check state of all properties like the other variant. @param event the event @return the properties **/ NET::Properties event(xcb_generic_event_t *event); /** * @returns The window manager protocols this Client supports. * @since 5.3 **/ NET::Protocols protocols() const; /** * @returns @c true if the Client supports the @p protocol. * @param protocol The window manager protocol to test for * @since 5.3 **/ bool supportsProtocol(NET::Protocol protocol) const; /** * @returns The opaque region as specified by the Client. * @since 5.7 **/ std::vector opaqueRegion() const; /** * Sets the @p name as the desktop file name. * * This is either the base name without full path and without file extension of the * desktop file for the window's application (e.g. "org.kde.foo"). * * If the application's desktop file name is not at a standard location it should be * the full path to the desktop file name (e.g. "/opt/kde/share/org.kde.foo.desktop"). * * If the window does not know the desktop file name, it should not set the name at all. * * @since 5.28 **/ void setDesktopFileName(const char *name); /** * @returns The desktop file name of the window's application if present. * @since 5.28 * @see setDesktopFileName **/ const char *desktopFileName() const; /** Sentinel value to indicate that the client wishes to be visible on all desktops. @return the value to be on all desktops **/ static const int OnAllDesktops; protected: /** A Window Manager should subclass NETWinInfo and reimplement this function when it wants to know when a Client made a request to change desktops (ie. move to another desktop). @param desktop the number of the desktop **/ virtual void changeDesktop(int desktop) { Q_UNUSED(desktop); } /** A Window Manager should subclass NETWinInfo and reimplement this function when it wants to know when a Client made a request to change state (ie. to Shade / Unshade). @param state the new state @param mask the mask for the state **/ virtual void changeState(NET::States state, NET::States mask) { Q_UNUSED(state); Q_UNUSED(mask); } /** A Window Manager should subclass NETWinInfo2 and reimplement this function when it wants to know when a Client made a request to change the fullscreen monitor topology for its fullscreen state. @param topology A structure (top, bottom, left, right) representing the fullscreen monitor topology. **/ virtual void changeFullscreenMonitors(NETFullscreenMonitors topology) { Q_UNUSED(topology); } private: - void update(NET::Properties dirtyProperties, NET::Properties2 dirtyProperties2 = 0); + void update(NET::Properties dirtyProperties, NET::Properties2 dirtyProperties2 = nullptr); void updateWMState(); void setIconInternal(NETRArray &icons, int &icon_count, xcb_atom_t property, NETIcon icon, bool replace); NETIcon iconInternal(NETRArray &icons, int icon_count, int width, int height) const; protected: /** Virtual hook, used to add new "virtual" functions while maintaining binary compatibility. Unused in this class. */ virtual void virtual_hook(int id, void *data); private: NETWinInfoPrivate *p; // krazy:exclude=dpointer (implicitly shared) }; //#define KWIN_FOCUS #endif #endif // netwm_h diff --git a/src/platforms/xcb/plugin.h b/src/platforms/xcb/plugin.h index 5b92dda..5bcbdfa 100644 --- a/src/platforms/xcb/plugin.h +++ b/src/platforms/xcb/plugin.h @@ -1,40 +1,40 @@ /* * Copyright 2015 Martin Gräßlin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #ifndef KWINDOWSYSTEM_X11_PLUGIN_H #define KWINDOWSYSTEM_X11_PLUGIN_H #include "kwindowsystemplugininterface_p.h" class X11Plugin : public KWindowSystemPluginInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.kwindowsystem.KWindowSystemPluginInterface" FILE "xcb.json") Q_INTERFACES(KWindowSystemPluginInterface) public: - explicit X11Plugin(QObject *parent = 0); + explicit X11Plugin(QObject *parent = nullptr); virtual ~X11Plugin(); KWindowEffectsPrivate *createEffects() Q_DECL_OVERRIDE; KWindowSystemPrivate *createWindowSystem() Q_DECL_OVERRIDE; KWindowInfoPrivate *createWindowInfo(WId window, NET::Properties properties, NET::Properties2 properties2) Q_DECL_OVERRIDE; }; #endif diff --git a/tests/createpixmapfromhandletest.cpp b/tests/createpixmapfromhandletest.cpp index c5d640d..6a8704c 100644 --- a/tests/createpixmapfromhandletest.cpp +++ b/tests/createpixmapfromhandletest.cpp @@ -1,38 +1,38 @@ /* This file is part of the KDE libraries Copyright 2013 Martin Gräßlin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #include #include #include #include int main(int argc, char **argv) { QApplication app(argc, argv); QCommandLineParser parser; parser.addPositionalArgument(QStringLiteral("WId"), QStringLiteral("window id for the window to take the icon from"), QStringLiteral("[WId]")); parser.addHelpOption(); parser.process(app); QLabel label; label.setMinimumSize(250, 250); label.show(); QString wId = parser.positionalArguments().first(); - label.setPixmap(KWindowSystem::icon(wId.toULongLong(0, 0), 250, 250, false, KWindowSystem::WMHints)); + label.setPixmap(KWindowSystem::icon(wId.toULongLong(nullptr, 0), 250, 250, false, KWindowSystem::WMHints)); return app.exec(); }