aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmltooling/qmldbg_preview/qqmlpreviewhandler.cpp
blob: f32954ed34affcfadc43ed0ee4c75a4e1f5121a8 (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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qqmlpreviewhandler.h"

#include <QtCore/qtimer.h>
#include <QtCore/qsettings.h>
#include <QtCore/qlibraryinfo.h>

#include <QtGui/qwindow.h>
#include <QtGui/qguiapplication.h>
#include <QtQuick/qquickwindow.h>
#include <QtQuick/qquickitem.h>
#include <QtQml/qqmlcomponent.h>

#include <private/qquickpixmap_p.h>
#include <private/qquickview_p.h>
#include <private/qhighdpiscaling_p.h>

QT_BEGIN_NAMESPACE

struct QuitLockDisabler
{
    const bool quitLockEnabled;

    Q_NODISCARD_CTOR QuitLockDisabler()
        : quitLockEnabled(QCoreApplication::isQuitLockEnabled())
    {
        QCoreApplication::setQuitLockEnabled(false);
    }

    ~QuitLockDisabler()
    {
        QCoreApplication::setQuitLockEnabled(quitLockEnabled);
    }
};

QQmlPreviewHandler::QQmlPreviewHandler(QObject *parent) : QObject(parent)
{
    m_dummyItem.reset(new QQuickItem);

    // TODO: Is there a better way to determine this? We want to keep the window alive when possible
    //       as otherwise it will reappear in a different place when (re)loading a file. However,
    //       the file we load might create another window, in which case the eglfs plugin (and
    //       others?) will do a qFatal as it only supports a single window.
    const QString platformName = QGuiApplication::platformName();
    m_supportsMultipleWindows = (platformName == QStringLiteral("windows")
                                 || platformName == QStringLiteral("cocoa")
                                 || platformName == QStringLiteral("xcb")
                                 || platformName == QStringLiteral("wayland"));

    QCoreApplication::instance()->installEventFilter(this);

    m_fpsTimer.setInterval(1000);
    connect(&m_fpsTimer, &QTimer::timeout, this, &QQmlPreviewHandler::fpsTimerHit);
}

QQmlPreviewHandler::~QQmlPreviewHandler()
{
    clear();
}

static void closeAllWindows()
{
    const QWindowList windows = QGuiApplication::allWindows();
    for (QWindow *window : windows)
        window->close();
}

bool QQmlPreviewHandler::eventFilter(QObject *obj, QEvent *event)
{
    if (m_currentWindow && (event->type() == QEvent::Move) &&
            qobject_cast<QQuickWindow*>(obj) == m_currentWindow) {
        m_lastPosition.takePosition(m_currentWindow);
    }

    return QObject::eventFilter(obj, event);
}

QQuickItem *QQmlPreviewHandler::currentRootItem()
{
    return m_currentRootItem;
}

void QQmlPreviewHandler::addEngine(QQmlEngine *qmlEngine)
{
    m_engines.append(qmlEngine);
}

void QQmlPreviewHandler::removeEngine(QQmlEngine *qmlEngine)
{
    const bool found = m_engines.removeOne(qmlEngine);
    Q_ASSERT(found);
    for (QObject *obj : m_createdObjects)
    if (obj && ::qmlEngine(obj) == qmlEngine)
      delete obj;
    m_createdObjects.removeAll(nullptr);
}

void QQmlPreviewHandler::loadUrl(const QUrl &url)
{
    QSharedPointer<QuitLockDisabler> disabler(new QuitLockDisabler);

    clear();
    m_component.reset(nullptr);
    QQuickPixmap::purgeCache();

    const int numEngines = m_engines.size();
    if (numEngines > 1) {
        emit error(QString::fromLatin1("%1 QML engines available. We cannot decide which one "
                                       "should load the component.").arg(numEngines));
        return;
    } else if (numEngines == 0) {
        emit error(QLatin1String("No QML engines found."));
        return;
    }
    m_lastPosition.loadWindowPositionSettings(url);

    QQmlEngine *engine = m_engines.front();
    engine->clearComponentCache();
    m_component.reset(new QQmlComponent(engine, url, this));

    auto onStatusChanged = [disabler, this](QQmlComponent::Status status) {
        switch (status) {
        case QQmlComponent::Null:
        case QQmlComponent::Loading:
            return true; // try again later
        case QQmlComponent::Ready:
            tryCreateObject();
            break;
        case QQmlComponent::Error:
            emit error(m_component->errorString());
            break;
        default:
            Q_UNREACHABLE();
            break;
        }

        disconnect(m_component.data(), &QQmlComponent::statusChanged, this, nullptr);
        return false; // we're done
    };

    if (onStatusChanged(m_component->status()))
        connect(m_component.data(), &QQmlComponent::statusChanged, this, onStatusChanged);
}

void QQmlPreviewHandler::rerun()
{
    if (m_component.isNull() || !m_component->isReady())
        emit error(QLatin1String("Component is not ready."));

    QuitLockDisabler disabler;
    Q_UNUSED(disabler);
    clear();
    tryCreateObject();
}

void QQmlPreviewHandler::zoom(qreal newFactor)
{
    m_zoomFactor = newFactor;
    QTimer::singleShot(0, this, &QQmlPreviewHandler::doZoom);
}

void QQmlPreviewHandler::doZoom()
{
    if (!m_currentWindow)
        return;
    if (qFuzzyIsNull(m_zoomFactor)) {
        emit error(QString::fromLatin1("Zooming with factor: %1 will result in nothing " \
                                       "so it will be ignored.").arg(m_zoomFactor));
        return;
    }

    bool resetZoom = false;
    if (m_zoomFactor < 0) {
        resetZoom = true;
        m_zoomFactor = 1.0;
    }

    m_currentWindow->setGeometry(m_currentWindow->geometry());

    m_lastPosition.takePosition(m_currentWindow, QQmlPreviewPosition::InitializePosition);
    m_currentWindow->destroy();

    for (QScreen *screen : QGuiApplication::screens())
        QHighDpiScaling::setScreenFactor(screen, m_zoomFactor);
    if (resetZoom)
        QHighDpiScaling::updateHighDpiScaling();

    m_currentWindow->show();
    m_lastPosition.initLastSavedWindowPosition(m_currentWindow);
}

void QQmlPreviewHandler::clear()
{
    qDeleteAll(m_createdObjects);
    m_createdObjects.clear();
    setCurrentWindow(nullptr);
}

Qt::WindowFlags fixFlags(Qt::WindowFlags flags)
{
    // If only the type flag is given, some other window flags are automatically assumed. When we
    // add a flag, we need to make those explicit.
    switch (flags) {
    case Qt::Window:
        return flags | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint
                | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint;
    case Qt::Dialog:
    case Qt::Tool:
        return flags | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
    default:
        return flags;
    }
}

void QQmlPreviewHandler::showObject(QObject *object)
{
    if (QWindow *window = qobject_cast<QWindow *>(object)) {
        setCurrentWindow(qobject_cast<QQuickWindow *>(window));
        for (QWindow *otherWindow : QGuiApplication::allWindows()) {
            if (QQuickWindow *quickWindow = qobject_cast<QQuickWindow *>(otherWindow)) {
                if (quickWindow == m_currentWindow)
                    continue;
                quickWindow->setVisible(false);
                quickWindow->setFlags(quickWindow->flags() & ~Qt::WindowStaysOnTopHint);
            }
        }
    } else if (QQuickItem *item = qobject_cast<QQuickItem *>(object)) {
        setCurrentWindow(nullptr);
        for (QWindow *window : QGuiApplication::allWindows()) {
            if (QQuickWindow *quickWindow = qobject_cast<QQuickWindow *>(window)) {
                if (m_currentWindow != nullptr) {
                    emit error(QLatin1String("Multiple QQuickWindows available. We cannot "
                                             "decide which one to use."));
                    return;
                }
                setCurrentWindow(quickWindow);
            } else {
                window->setVisible(false);
                window->setFlag(Qt::WindowStaysOnTopHint, false);
            }
        }

        if (m_currentWindow == nullptr) {
            setCurrentWindow(new QQuickWindow);
            m_createdObjects.append(m_currentWindow.data());
        }

        for (QQuickItem *oldItem : m_currentWindow->contentItem()->childItems())
            oldItem->setParentItem(m_dummyItem.data());

        // Special case for QQuickView, as that keeps a "root" pointer around, and uses it to
        // automatically resize the window or the item.
        if (QQuickView *view = qobject_cast<QQuickView *>(m_currentWindow))
            QQuickViewPrivate::get(view)->setRootObject(item);
        else
            item->setParentItem(m_currentWindow->contentItem());

        m_currentWindow->resize(item->size().toSize());
        // used by debug translation service to get the states
        m_currentRootItem = item;
    } else {
        emit error(QLatin1String("Created object is neither a QWindow nor a QQuickItem."));
    }

    if (m_currentWindow) {
        m_lastPosition.initLastSavedWindowPosition(m_currentWindow);
        m_currentWindow->setFlags(fixFlags(m_currentWindow->flags()) | Qt::WindowStaysOnTopHint);
        m_currentWindow->setVisible(true);
    }
}

void QQmlPreviewHandler::setCurrentWindow(QQuickWindow *window)
{
    if (window == m_currentWindow.data())
        return;

    if (m_currentWindow) {
        disconnect(m_currentWindow.data(), &QQuickWindow::beforeSynchronizing,
                   this, &QQmlPreviewHandler::beforeSynchronizing);
        disconnect(m_currentWindow.data(), &QQuickWindow::afterSynchronizing,
                   this, &QQmlPreviewHandler::afterSynchronizing);
        disconnect(m_currentWindow.data(), &QQuickWindow::beforeRendering,
                   this, &QQmlPreviewHandler::beforeRendering);
        disconnect(m_currentWindow.data(), &QQuickWindow::frameSwapped,
                   this, &QQmlPreviewHandler::frameSwapped);
        m_fpsTimer.stop();
        m_rendering = FrameTime();
        m_synchronizing = FrameTime();
    }

    m_currentWindow = window;

    if (m_currentWindow) {
        connect(m_currentWindow.data(), &QQuickWindow::beforeSynchronizing,
                this, &QQmlPreviewHandler::beforeSynchronizing, Qt::DirectConnection);
        connect(m_currentWindow.data(), &QQuickWindow::afterSynchronizing,
                this, &QQmlPreviewHandler::afterSynchronizing, Qt::DirectConnection);
        connect(m_currentWindow.data(), &QQuickWindow::beforeRendering,
                this, &QQmlPreviewHandler::beforeRendering, Qt::DirectConnection);
        connect(m_currentWindow.data(), &QQuickWindow::frameSwapped,
                this, &QQmlPreviewHandler::frameSwapped, Qt::DirectConnection);
        m_fpsTimer.start();
    }
}

void QQmlPreviewHandler::beforeSynchronizing()
{
    m_synchronizing.beginFrame();
}

void QQmlPreviewHandler::afterSynchronizing()
{

    if (m_rendering.elapsed >= 0)
        m_rendering.endFrame();
    m_synchronizing.recordFrame();
    m_synchronizing.endFrame();
}

void QQmlPreviewHandler::beforeRendering()
{
    m_rendering.beginFrame();
}

void QQmlPreviewHandler::frameSwapped()
{
    m_rendering.recordFrame();
}

void QQmlPreviewHandler::FrameTime::beginFrame()
{
    timer.start();
}

void QQmlPreviewHandler::FrameTime::recordFrame()
{
    elapsed = timer.elapsed();
}

void QQmlPreviewHandler::FrameTime::endFrame()
{
    if (elapsed < min)
        min = static_cast<quint16>(qMax(0ll, elapsed));
    if (elapsed > max)
        max = static_cast<quint16>(qMin(qint64(std::numeric_limits<quint16>::max()), elapsed));
    total = static_cast<quint16>(qBound(0ll, qint64(std::numeric_limits<quint16>::max()),
                                        elapsed + total));
    ++number;
    elapsed = -1;
}

void QQmlPreviewHandler::FrameTime::reset()
{
    min = std::numeric_limits<quint16>::max();
    max = 0;
    total = 0;
    number = 0;
}

void QQmlPreviewHandler::fpsTimerHit()
{
    const FpsInfo info = {
        m_synchronizing.number,
        m_synchronizing.min,
        m_synchronizing.max,
        m_synchronizing.total,

        m_rendering.number,
        m_rendering.min,
        m_rendering.max,
        m_rendering.total
    };

    emit fps(info);

    m_rendering.reset();
    m_synchronizing.reset();
}

void QQmlPreviewHandler::tryCreateObject()
{
    if (!m_supportsMultipleWindows)
        closeAllWindows();
    QObject *object = m_component->create();
    m_createdObjects.append(object);
    showObject(object);
}

QT_END_NAMESPACE

#include "moc_qqmlpreviewhandler.cpp"