Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlpreviewhandler.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
6
7#include <QtCore/qtimer.h>
8#include <QtCore/qsettings.h>
9#include <QtCore/qlibraryinfo.h>
10
11#include <QtGui/qwindow.h>
12#include <QtGui/qguiapplication.h>
13#include <QtQuick/qquickwindow.h>
14#include <QtQuick/qquickitem.h>
15#include <QtQml/qqmlcomponent.h>
16
17#include <private/qabstractanimation_p.h>
18#include <private/qhighdpiscaling_p.h>
19#include <private/qqmlmetatype_p.h>
20#include <private/qquickpixmap_p.h>
21#include <private/qquickview_p.h>
22#include <private/qv4compileddata_p.h>
23
24QT_BEGIN_NAMESPACE
25
26struct QuitLockDisabler
27{
28 const bool quitLockEnabled;
29
30 Q_NODISCARD_CTOR QuitLockDisabler()
31 : quitLockEnabled(QCoreApplication::isQuitLockEnabled())
32 {
33 QCoreApplication::setQuitLockEnabled(false);
34 }
35
36 ~QuitLockDisabler()
37 {
38 QCoreApplication::setQuitLockEnabled(quitLockEnabled);
39 }
40};
41
42QQmlPreviewHandler::QQmlPreviewHandler(QObject *parent) : QObject(parent)
43{
44 m_dummyItem.reset(new QQuickItem);
45
46 // TODO: Is there a better way to determine this? We want to keep the window alive when possible
47 // as otherwise it will reappear in a different place when (re)loading a file. However,
48 // the file we load might create another window, in which case the eglfs plugin (and
49 // others?) will do a qFatal as it only supports a single window.
50 const QString platformName = QGuiApplication::platformName();
51 m_supportsMultipleWindows = (platformName == QStringLiteral("windows")
52 || platformName == QStringLiteral("cocoa")
53 || platformName == QStringLiteral("xcb")
54 || platformName == QStringLiteral("wayland"));
55
56 QCoreApplication::instance()->installEventFilter(this);
57
58 m_fpsTimer.setInterval(1000);
59 connect(&m_fpsTimer, &QTimer::timeout, this, &QQmlPreviewHandler::fpsTimerHit);
60}
61
66
67static void closeAllWindows()
68{
69 const QWindowList windows = QGuiApplication::allWindows();
70 for (QWindow *window : windows)
71 window->close();
72}
73
74bool QQmlPreviewHandler::eventFilter(QObject *obj, QEvent *event)
75{
76 if (m_currentWindow && (event->type() == QEvent::Move) &&
77 qobject_cast<QQuickWindow*>(obj) == m_currentWindow) {
78 m_lastPosition.takePosition(m_currentWindow);
79 }
80
81 return QObject::eventFilter(obj, event);
82}
83
85{
86 return m_currentRootItem;
87}
88
89void QQmlPreviewHandler::addEngine(QQmlEngine *qmlEngine)
90{
91 m_engines.append(qmlEngine);
92}
93
94void QQmlPreviewHandler::removeEngine(QQmlEngine *qmlEngine)
95{
96 const bool found = m_engines.removeOne(qmlEngine);
97 Q_ASSERT(found);
98 for (QObject *obj : m_createdObjects)
99 if (obj && ::qmlEngine(obj) == qmlEngine)
100 delete obj;
101 m_createdObjects.removeAll(nullptr);
102}
103
104void QQmlPreviewHandler::loadUrl(const QUrl &url)
105{
106 QSharedPointer<QuitLockDisabler> disabler(new QuitLockDisabler);
107
108 clear();
109 m_component.reset(nullptr);
110 QQuickPixmap::purgeCache();
111
112 const int numEngines = m_engines.size();
113 if (numEngines > 1) {
114 emit error(QString::fromLatin1("%1 QML engines available. We cannot decide which one "
115 "should load the component.").arg(numEngines));
116 return;
117 } else if (numEngines == 0) {
118 emit error(QLatin1String("No QML engines found."));
119 return;
120 }
121 m_lastPosition.loadWindowPositionSettings(url);
122
123 QQmlEngine *engine = m_engines.front();
124 engine->clearSingletons();
125 engine->clearComponentCache();
126 m_component.reset(new QQmlComponent(engine, url, this));
127
128 auto onStatusChanged = [disabler, this](QQmlComponent::Status status) {
129 switch (status) {
130 case QQmlComponent::Null:
131 case QQmlComponent::Loading:
132 return true; // try again later
133 case QQmlComponent::Ready:
134 tryCreateObject();
135 break;
136 case QQmlComponent::Error:
137 emit error(m_component->errorString());
138 break;
139 default:
140 Q_UNREACHABLE();
141 break;
142 }
143
144 disconnect(m_component.data(), &QQmlComponent::statusChanged, this, nullptr);
145 return false; // we're done
146 };
147
148 if (onStatusChanged(m_component->status()))
149 connect(m_component.data(), &QQmlComponent::statusChanged, this, onStatusChanged);
150}
151
152void QQmlPreviewHandler::dropCU(const QUrl &url)
153{
154 // Drop any existing compilation units for this URL from the type registry.
155 // There can be multiple, one for each engine.
156 while (const auto cu = QQmlMetaType::obtainCompilationUnit(url))
157 QQmlMetaType::unregisterInternalCompositeType(cu);
158}
159
161{
162 if (m_component.isNull() || !m_component->isReady())
163 emit error(QLatin1String("Component is not ready."));
164
165 QuitLockDisabler disabler;
166 Q_UNUSED(disabler);
167 clear();
168 tryCreateObject();
169}
170
171void QQmlPreviewHandler::zoom(qreal newFactor)
172{
173 m_zoomFactor = newFactor;
174 QTimer::singleShot(0, this, &QQmlPreviewHandler::doZoom);
175}
176
178{
179 QUnifiedTimer::instance()->setSpeedModifier(newFactor);
180}
181
182void QQmlPreviewHandler::doZoom()
183{
184 if (!m_currentWindow)
185 return;
186 if (qFuzzyIsNull(m_zoomFactor)) {
187 emit error(QString::fromLatin1("Zooming with factor: %1 will result in nothing "
188 "so it will be ignored.").arg(m_zoomFactor));
189 return;
190 }
191
192 bool resetZoom = false;
193 if (m_zoomFactor < 0) {
194 resetZoom = true;
195 m_zoomFactor = 1.0;
196 }
197
198 m_currentWindow->setGeometry(m_currentWindow->geometry());
199
200 m_lastPosition.takePosition(m_currentWindow, QQmlPreviewPosition::InitializePosition);
201 m_currentWindow->destroy();
202
203 for (QScreen *screen : QGuiApplication::screens())
204 QHighDpiScaling::setScreenFactor(screen, m_zoomFactor);
205 if (resetZoom)
206 QHighDpiScaling::updateHighDpiScaling();
207
208 m_currentWindow->show();
209 m_lastPosition.initLastSavedWindowPosition(m_currentWindow);
210}
211
213{
214 qDeleteAll(m_createdObjects);
215 m_createdObjects.clear();
216 setCurrentWindow(nullptr);
217}
218
219Qt::WindowFlags fixFlags(Qt::WindowFlags flags)
220{
221 // If only the type flag is given, some other window flags are automatically assumed. When we
222 // add a flag, we need to make those explicit.
223 switch (flags) {
224 case Qt::Window:
225 return flags | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint
226 | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint;
227 case Qt::Dialog:
228 case Qt::Tool:
229 return flags | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
230 default:
231 return flags;
232 }
233}
234
235void QQmlPreviewHandler::showObject(QObject *object)
236{
237 if (QWindow *window = qobject_cast<QWindow *>(object)) {
238 setCurrentWindow(qobject_cast<QQuickWindow *>(window));
239 for (QWindow *otherWindow : QGuiApplication::allWindows()) {
240 if (QQuickWindow *quickWindow = qobject_cast<QQuickWindow *>(otherWindow)) {
241 if (quickWindow == m_currentWindow)
242 continue;
243 quickWindow->setVisible(false);
244 quickWindow->setFlags(quickWindow->flags() & ~Qt::WindowStaysOnTopHint);
245 }
246 }
247 } else if (QQuickItem *item = qobject_cast<QQuickItem *>(object)) {
248 setCurrentWindow(nullptr);
249 for (QWindow *window : QGuiApplication::allWindows()) {
250 if (QQuickWindow *quickWindow = qobject_cast<QQuickWindow *>(window)) {
251 if (m_currentWindow != nullptr) {
252 emit error(QLatin1String("Multiple QQuickWindows available. We cannot "
253 "decide which one to use."));
254 return;
255 }
256 setCurrentWindow(quickWindow);
257 } else {
258 window->setVisible(false);
259 window->setFlag(Qt::WindowStaysOnTopHint, false);
260 }
261 }
262
263 if (m_currentWindow == nullptr) {
264 setCurrentWindow(new QQuickWindow);
265 m_createdObjects.append(m_currentWindow.data());
266 }
267
268 for (QQuickItem *oldItem : m_currentWindow->contentItem()->childItems())
269 oldItem->setParentItem(m_dummyItem.data());
270
271 // Special case for QQuickView, as that keeps a "root" pointer around, and uses it to
272 // automatically resize the window or the item.
273 if (QQuickView *view = qobject_cast<QQuickView *>(m_currentWindow))
274 QQuickViewPrivate::get(view)->setRootObject(item);
275 else
276 item->setParentItem(m_currentWindow->contentItem());
277
278 m_currentWindow->resize(item->size().toSize());
279 // used by debug translation service to get the states
280 m_currentRootItem = item;
281 } else {
282 emit error(QLatin1String("Created object is neither a QWindow nor a QQuickItem."));
283 }
284
285 if (m_currentWindow) {
286 m_lastPosition.initLastSavedWindowPosition(m_currentWindow);
287 m_currentWindow->setFlags(fixFlags(m_currentWindow->flags()) | Qt::WindowStaysOnTopHint);
288 m_currentWindow->setVisible(true);
289 }
290}
291
292void QQmlPreviewHandler::setCurrentWindow(QQuickWindow *window)
293{
294 if (window == m_currentWindow.data())
295 return;
296
297 if (m_currentWindow) {
298 disconnect(m_currentWindow.data(), &QQuickWindow::beforeSynchronizing,
299 this, &QQmlPreviewHandler::beforeSynchronizing);
300 disconnect(m_currentWindow.data(), &QQuickWindow::afterSynchronizing,
301 this, &QQmlPreviewHandler::afterSynchronizing);
302 disconnect(m_currentWindow.data(), &QQuickWindow::beforeRendering,
303 this, &QQmlPreviewHandler::beforeRendering);
304 disconnect(m_currentWindow.data(), &QQuickWindow::frameSwapped,
305 this, &QQmlPreviewHandler::frameSwapped);
306 m_fpsTimer.stop();
307 m_rendering = FrameTime();
308 m_synchronizing = FrameTime();
309 }
310
311 m_currentWindow = window;
312
313 if (m_currentWindow) {
314 connect(m_currentWindow.data(), &QQuickWindow::beforeSynchronizing,
315 this, &QQmlPreviewHandler::beforeSynchronizing, Qt::DirectConnection);
316 connect(m_currentWindow.data(), &QQuickWindow::afterSynchronizing,
317 this, &QQmlPreviewHandler::afterSynchronizing, Qt::DirectConnection);
318 connect(m_currentWindow.data(), &QQuickWindow::beforeRendering,
319 this, &QQmlPreviewHandler::beforeRendering, Qt::DirectConnection);
320 connect(m_currentWindow.data(), &QQuickWindow::frameSwapped,
321 this, &QQmlPreviewHandler::frameSwapped, Qt::DirectConnection);
322 m_fpsTimer.start();
323 }
324}
325
326void QQmlPreviewHandler::beforeSynchronizing()
327{
328 m_synchronizing.beginFrame();
329}
330
331void QQmlPreviewHandler::afterSynchronizing()
332{
333
334 if (m_rendering.elapsed >= 0)
335 m_rendering.endFrame();
336 m_synchronizing.recordFrame();
337 m_synchronizing.endFrame();
338}
339
340void QQmlPreviewHandler::beforeRendering()
341{
342 m_rendering.beginFrame();
343}
344
345void QQmlPreviewHandler::frameSwapped()
346{
347 m_rendering.recordFrame();
348}
349
350void QQmlPreviewHandler::FrameTime::beginFrame()
351{
352 timer.start();
353}
354
355void QQmlPreviewHandler::FrameTime::recordFrame()
356{
357 elapsed = timer.elapsed();
358}
359
360void QQmlPreviewHandler::FrameTime::endFrame()
361{
362 if (elapsed < min)
363 min = static_cast<quint16>(qMax(0ll, elapsed));
364 if (elapsed > max)
365 max = static_cast<quint16>(qMin(qint64(std::numeric_limits<quint16>::max()), elapsed));
366 total = static_cast<quint16>(qBound(0ll, qint64(std::numeric_limits<quint16>::max()),
367 elapsed + total));
368 ++number;
369 elapsed = -1;
370}
371
372void QQmlPreviewHandler::FrameTime::reset()
373{
374 min = std::numeric_limits<quint16>::max();
375 max = 0;
376 total = 0;
377 number = 0;
378}
379
380void QQmlPreviewHandler::fpsTimerHit()
381{
382 const FpsInfo info = {
383 m_synchronizing.number,
384 m_synchronizing.min,
385 m_synchronizing.max,
386 m_synchronizing.total,
387
388 m_rendering.number,
389 m_rendering.min,
390 m_rendering.max,
391 m_rendering.total
392 };
393
394 emit fps(info);
395
396 m_rendering.reset();
397 m_synchronizing.reset();
398}
399
400void QQmlPreviewHandler::tryCreateObject()
401{
402 if (!m_supportsMultipleWindows)
404 QObject *object = m_component->create();
405 m_createdObjects.append(object);
406 showObject(object);
407}
408
409QT_END_NAMESPACE
410
411#include "moc_qqmlpreviewhandler.cpp"
void dropCU(const QUrl &url)
void zoom(qreal newFactor)
QQuickItem * currentRootItem()
bool eventFilter(QObject *obj, QEvent *event) override
Filters events if this object has been installed as an event filter for the watched object.
void setAnimationSpeed(qreal newFactor)
void removeEngine(QQmlEngine *engine)
void addEngine(QQmlEngine *engine)
void loadUrl(const QUrl &url)
static void closeAllWindows()
Qt::WindowFlags fixFlags(Qt::WindowFlags flags)