summaryrefslogtreecommitdiffstats
path: root/tests/manual/foreignwindows/main.cpp
blob: 1fb4b0c167f70c13536239c157ad986a13a7859a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include <QtGui/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QToolBar>

#include <QtGui/QScreen>
#include <QtGui/QWindow>

#include <QtCore/QCommandLineOption>
#include <QtCore/QCommandLineParser>
#include <QtCore/QDebug>
#include <QtCore/QSharedPointer>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>
#include <QtCore/QTimer>

#ifdef Q_OS_WIN
#  include <QtCore/qt_windows.h>
#endif

#include <eventfilter.h> // diaglib
#include <nativewindowdump.h>
#include <qwidgetdump.h>
#include <qwindowdump.h>

#include <iostream>
#include <algorithm>

QT_USE_NAMESPACE

using WidgetPtr = QSharedPointer<QWidget>;
using WidgetPtrList = QList<WidgetPtr>;
using WIdList = QList<WId>;

// Create some pre-defined Windows controls by class name
static WId createInternalWindow(const QString &name)
{
    WId result = 0;
#ifdef Q_OS_WIN
    if (name == QLatin1String("BUTTON") || name == QLatin1String("COMBOBOX")
        || name == QLatin1String("EDIT") || name.startsWith(QLatin1String("RICHEDIT"))) {
        const HWND hwnd =
            CreateWindowEx(0, reinterpret_cast<const wchar_t *>(name.utf16()),
                          L"NativeCtrl", WS_OVERLAPPEDWINDOW,
                          CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                          nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
        if (hwnd) {
            SetWindowText(hwnd, L"Demo");
            result = WId(hwnd);
        } else {
            qErrnoWarning("Cannot create window \"%s\"", qPrintable(name));
        }
    }
#else // Q_OS_WIN
    Q_UNUSED(name);
#endif
    return result;
}

// Embed a foreign window using createWindowContainer() providing
// menu actions to dump information.
class EmbeddingWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit EmbeddingWindow(QWindow *window);

public slots:
    void releaseForeignWindow();

private:
    QWindow *m_window;
    QAction *m_releaseAction;
};

EmbeddingWindow::EmbeddingWindow(QWindow *window) : m_window(window)
{
    const QString title = QLatin1String("Qt ") + QLatin1String(QT_VERSION_STR)
        + QLatin1String(" 0x") + QString::number(window->winId(), 16);
    setWindowTitle(title);
    setObjectName("MainWindow");
    QWidget *container = QWidget::createWindowContainer(window, nullptr, Qt::Widget);
    container->setObjectName("Container");
    setCentralWidget(container);

    QMenu *fileMenu = menuBar()->addMenu("File");
    fileMenu->setObjectName("FileMenu");
    QToolBar *toolbar = new QToolBar;
    addToolBar(Qt::TopToolBarArea, toolbar);

    // Manipulation
    QAction *action = fileMenu->addAction("Visible");
    action->setCheckable(true);
    action->setChecked(true);
    connect(action, &QAction::toggled, m_window, &QWindow::setVisible);
    toolbar->addAction(action);

    m_releaseAction = fileMenu->addAction("Release", this, &EmbeddingWindow::releaseForeignWindow);
    toolbar->addAction(m_releaseAction);

    fileMenu->addSeparator(); // Diaglib actions
    action = fileMenu->addAction("Dump Widgets",
                                 this, [] () { QtDiag::dumpAllWidgets(); });
    toolbar->addAction(action);
    action = fileMenu->addAction("Dump Windows",
                                 this, [] () { QtDiag::dumpAllWindows(); });
    toolbar->addAction(action);
    action = fileMenu->addAction("Dump Native Windows",
                                 this, [this] () { QtDiag::dumpNativeWindows(winId()); });
    toolbar->addAction(action);

    fileMenu->addSeparator();
    action = fileMenu->addAction("Quit", qApp, &QCoreApplication::quit);
    toolbar->addAction(action);
    action->setShortcut(Qt::CTRL | Qt::Key_Q);
}

void EmbeddingWindow::releaseForeignWindow()
{
    if (m_window) {
        m_window->setParent(nullptr);
        m_window = nullptr;
        m_releaseAction->setEnabled(false);
    }
}

// Dump information about foreign windows.
class WindowDumper : public QObject {
    Q_OBJECT
public:
    explicit WindowDumper(const QWindowList &watchedWindows)
        : m_watchedWindows(watchedWindows) {}

public slots:
    void dump() const;

private:
    const QWindowList m_watchedWindows;
};

void WindowDumper::dump() const
{
    static int n = 0;
    QString s;
    QDebug debug(&s);
    debug.nospace();
    debug.setVerbosity(3);
    debug << '#' << n++;
    if (m_watchedWindows.size() > 1)
        debug << '\n';
    for (const QWindow *w : m_watchedWindows) {
        const QPoint globalPos = w->mapToGlobal(QPoint());
        debug << "  " << w << " pos=" << globalPos.x() << ',' << globalPos.y() << '\n';
    }

    std::cout << qPrintable(s);
}

static QString description(const QString &appName)
{
    QString result;
    QTextStream(&result)
        << "\nDumps information about foreign windows passed on the command line or\n"
        "tests embedding foreign windows into Qt.\n\nUse cases:\n\n"
        << appName << " -a          Dump a list of all native window ids.\n"
        << appName << " <winid>     Dump information on the window.\n"
        << appName << " -m <winid>  Move window to top left corner\n"
        << QByteArray(appName.size(), ' ')
        <<            "             (recover lost windows after changing monitor setups).\n"
        << appName << " -c <winid>  Dump information on the window continuously.\n"
        << appName << " -e <winid>  Embed window into a Qt widget.\n"
        << "\nOn Windows, class names of well known controls (EDIT, BUTTON...) can be\n"
           "passed as <winid> along with -e, which will create the control.\n";
    return result;
}

struct EventFilterOption
{
    const char *name;
    const char *description;
    QtDiag::EventFilter::EventCategories categories;
};

static EventFilterOption eventFilterOptions[] = {
{"mouse-events", "Dump mouse events.", QtDiag::EventFilter::MouseEvents},
{"keyboard-events", "Dump keyboard events.", QtDiag::EventFilter::KeyEvents},
{"state-events", "Dump state/focus change events.", QtDiag::EventFilter::StateChangeEvents | QtDiag::EventFilter::FocusEvents}
};

static inline bool isOptionSet(int argc, char *argv[], const char *option)
{
    return (argv + argc) !=
        std::find_if(argv + 1, argv + argc,
                     [option] (const char *arg) { return !qstrcmp(arg, option); });
}

int main(int argc, char *argv[])
{
    QCoreApplication::setApplicationVersion(QLatin1String(QT_VERSION_STR));
    QGuiApplication::setApplicationDisplayName("Foreign window tester");

    QApplication app(argc, argv);

    QCommandLineParser parser;
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    parser.setApplicationDescription(description(QCoreApplication::applicationName()));
    parser.addHelpOption();
    parser.addVersionOption();
    QCommandLineOption noScalingDummy(QStringLiteral("s"),
                                      QStringLiteral("Disable High DPI scaling."));
    parser.addOption(noScalingDummy);
    QCommandLineOption outputAllOption(QStringList() << QStringLiteral("a") << QStringLiteral("all"),
                                       QStringLiteral("Output all native window ids (requires diaglib)."));
    parser.addOption(outputAllOption);
    QCommandLineOption continuousOption(QStringList() << QStringLiteral("c") << QStringLiteral("continuous"),
                                        QStringLiteral("Output continuously."));
    parser.addOption(continuousOption);
    QCommandLineOption moveOption(QStringList() << QStringLiteral("m") << QStringLiteral("move"),
                                  QStringLiteral("Move window to top left corner."));
    parser.addOption(moveOption);
    QCommandLineOption embedOption(QStringList() << QStringLiteral("e") << QStringLiteral("embed"),
                                   QStringLiteral("Embed a foreign window into a Qt widget."));
    parser.addOption(embedOption);
    const int eventFilterOptionCount = int(sizeof(eventFilterOptions) / sizeof(eventFilterOptions[0]));
    for (int i = 0; i < eventFilterOptionCount; ++i) {
        parser.addOption(QCommandLineOption(QLatin1String(eventFilterOptions[i].name),
                                            QLatin1String(eventFilterOptions[i].description)));
    }
    parser.addPositionalArgument(QStringLiteral("[windows]"), QStringLiteral("Window IDs."));

    parser.process(QCoreApplication::arguments());

    if (parser.isSet(outputAllOption)) {
        QtDiag::dumpNativeWindows();
        return 0;
    }

    QWindowList windows;
    for (const QString &argument : parser.positionalArguments()) {
        bool ok = true;
        WId wid = createInternalWindow(argument);
        if (!wid)
            wid = argument.toULongLong(&ok, 0);
        if (!wid || !ok) {
            std::cerr << "Invalid window id: \"" << qPrintable(argument) << "\"\n";
            return -1;
        }
        QWindow *foreignWindow = QWindow::fromWinId(wid);
        if (!foreignWindow)
            return -1;
        foreignWindow->setObjectName("ForeignWindow" + QString::number(wid, 16));
        windows.append(foreignWindow);
        if (parser.isSet(moveOption))
            foreignWindow->setFramePosition(QGuiApplication::primaryScreen()->availableGeometry().topLeft());
    }

    if (windows.isEmpty())
        parser.showHelp(0);

    int exitCode = 0;

    if (parser.isSet(embedOption)) {
        QtDiag::EventFilter::EventCategories eventCategories;
        for (int i = 0; i < eventFilterOptionCount; ++i) {
            if (parser.isSet(QLatin1String(eventFilterOptions[i].name)))
                eventCategories |= eventFilterOptions[i].categories;
        }
        if (eventCategories)
            app.installEventFilter(new QtDiag::EventFilter(eventCategories, &app));

        const QRect availableGeometry = QGuiApplication::primaryScreen()->availableGeometry();
        QPoint pos = availableGeometry.topLeft() + QPoint(availableGeometry.width(), availableGeometry.height()) / 3;

        WidgetPtrList mainWindows;
        for (QWindow *window : std::as_const(windows)) {
            WidgetPtr mainWindow(new EmbeddingWindow(window));
            mainWindow->move(pos);
            mainWindow->resize(availableGeometry.size() / 4);
            mainWindow->show();
            pos += QPoint(40, 40);
            mainWindows.append(mainWindow);
        }
        exitCode = app.exec();

    } else if (parser.isSet(continuousOption)) {
        WindowDumper dumper(windows);
        dumper.dump();
        QTimer *timer = new QTimer(&dumper);
        QObject::connect(timer, &QTimer::timeout, &dumper, &WindowDumper::dump);
        timer->start(1000);
        exitCode = app.exec();
    } else {
        WindowDumper(windows).dump();
    }

    return exitCode;
}

#include "main.moc"