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
qqmlinplacepreviewhandler.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
7
8#include <QtGui/qguiapplication.h>
9#include <QtQml/qqmlcomponent.h>
10#include <QtQuick/qquickwindow.h>
11#include <QtQuick/qquickitem.h>
12
13#include <private/qqmlmetatype_p.h>
14#include <private/qv4compileddata_p.h>
15#include <private/qqmlpreviewobjectpatch_p.h>
16#include <private/qv4mm_p.h>
17#include <private/qqmlcomponent_p.h>
18#include <private/qv4resolvedtypereference_p.h>
19
21
29
31{
32 InplaceUpdate(QQmlInPlacePreviewHandler *handler, QQmlEngine *engine)
33 : engine(engine), handler(handler)
34 {
35 }
36
37 QQmlEngine *engine = nullptr;
41
42 void emitReloadFailure(const QString &message) { emit handler->hotReloadFailure(message); }
43
44 void emitError(const QString &message) { emit handler->error(message); }
45
46private:
47 // Sending a signal is fine from a different thread. Anything else not so much.
48 QQmlInPlacePreviewHandler *handler = nullptr;
49};
50
51QQmlInPlacePreviewHandler::QQmlInPlacePreviewHandler(QObject *parent) : QQmlPreviewHandler(parent)
52{
53}
54
55QQmlInPlacePreviewHandler::~QQmlInPlacePreviewHandler() = default;
56
57void QQmlInPlacePreviewHandler::connectToService(QQmlPreviewServiceImpl *service)
58{
59 QQmlPreviewHandler::connectToService(service);
60 connect(this, &QQmlInPlacePreviewHandler::hotReloadFailure, service,
61 &QQmlPreviewServiceImpl::forwardHotReloadFailure, Qt::DirectConnection);
62 connect(service, &QQmlPreviewServiceImpl::drop, this, [this](const QUrl &url) {
63 if (!m_droppedUrls.contains(url))
64 m_droppedUrls.push_back(url);
65 });
66 connect(service, &QQmlPreviewServiceImpl::rerun, this, [this]() {
67 emit error(QLatin1String("You cannot rerun if in-place updates are enabled."));
68 });
69 connect(service, &QQmlPreviewServiceImpl::zoom, this, [this](qreal zoomFactor) {
70 QQmlPreviewPosition position;
71 zoomWindow(currentWindow(), zoomFactor, &position);
72 });
73}
74
75QQuickWindow *findCurrentWindow()
76{
77 QQuickWindow *found = nullptr;
78 for (QWindow *window : QGuiApplication::allWindows()) {
79 if (QQuickWindow *quickWindow = qobject_cast<QQuickWindow *>(window)) {
80 if (std::exchange(found, quickWindow))
81 return nullptr; // Multiple windows available. We can't decide
82 }
83 }
84
85 return found;
86}
87
88void findCurrentRootObject(QQmlEngine *engine, const QUrl &url, QQmlPreviewHandler *receiver)
89{
90 // Schedule this on the engine's thread
91 QMetaObject::invokeMethod(engine, [engine, url, receiver]() {
92 QV4::ExecutionEngine *v4 = engine->handle();
93 const QQmlRefPointer<QV4::ExecutableCompilationUnit> unit = v4->compilationUnitForUrl(url);
94 if (!unit)
95 return;
96
97 const std::vector<QObject *> objects =
98 v4->memoryManager->findObjectsForCompilationUnits({ unit->baseCompilationUnit() });
99 QPointer<QObject> found;
100 for (QObject *object : objects) {
101 QQmlData *ddata = QQmlData::get(object);
102 if (ddata && ddata->compilationUnit == unit && ddata->cuObjectIndex == 0) {
103 if (std::exchange(found, object))
104 return; // Multiple candidates. We can't decide
105 }
106 }
107
108 // Schedule reply on the debug server thread
109 QMetaObject::invokeMethod(receiver, [receiver, currentRoot = std::move(found)]() {
110 if (QQuickItem *rootItem = qobject_cast<QQuickItem *>(currentRoot)) {
111 receiver->setCurrentRootItem(rootItem);
112 receiver->setCurrentWindow(findCurrentWindow());
113 return;
114 }
115
116 if (QQuickWindow *window = qobject_cast<QQuickWindow *>(currentRoot)) {
117 receiver->setCurrentWindow(window);
118 receiver->setCurrentRootItem(nullptr);
119 return;
120 }
121
122 receiver->setCurrentRootItem(nullptr);
123 receiver->setCurrentWindow(findCurrentWindow());
124 });
125 });
126}
127
128// Replace resolved type references that still point to any of the dropped (old) base CUs with
129// freshly compiled ones.
131 QV4::ExecutionEngine *v4,
132 const QList<QQmlRefPointer<QV4::CompiledData::CompilationUnit>> &droppedUnits)
133{
134 for (const auto &oldCU : droppedUnits) {
135 if (const auto newCU = QQmlMetaType::obtainCompilationUnit(oldCU->finalUrl()))
136 QQmlPreview::redirectResolvedTypeReferences(v4, oldCU, newCU);
137 }
138}
139
140static void updateInplace(QQmlComponent *component, std::shared_ptr<InplaceUpdate> inplaceUpdate)
141{
142 ComponentUpdate componentUpdate;
143 const auto componentUpdateIt =
144 std::find_if(inplaceUpdate->pendingComponentUpdates.begin(),
145 inplaceUpdate->pendingComponentUpdates.end(),
146 [component](const ComponentUpdate &engineUpdate) {
147 return engineUpdate.component.get() == component;
148 });
149
150 if (componentUpdateIt == inplaceUpdate->pendingComponentUpdates.end())
151 return;
152
153 componentUpdate = std::move(*componentUpdateIt);
154 inplaceUpdate->pendingComponentUpdates.erase(componentUpdateIt);
155
156 switch (component->status()) {
157 case QQmlComponent::Null:
158 case QQmlComponent::Loading:
159 Q_UNREACHABLE_RETURN();
160 case QQmlComponent::Ready:
161 break;
162 case QQmlComponent::Error:
163 inplaceUpdate->emitError(component->errorString());
164 return;
165 }
166
167 QV4::ExecutionEngine *v4 = component->engine()->handle();
168
169 if (const auto oldExecCU = componentUpdate.oldUnit) {
170 const auto newExecCU = QQmlComponentPrivate::get(component)->compilationUnit();
171 std::vector<QObject *> objects = v4->memoryManager->findObjectsForCompilationUnits(
172 { oldExecCU->baseCompilationUnit() });
173
174 const QQmlPreview::PatchResult result =
175 QQmlPreview::applyDiff(objects, oldExecCU, newExecCU);
176 if (result == QQmlPreview::PatchResult::Failed)
177 inplaceUpdate->emitReloadFailure("Could not apply diff");
178
179 componentUpdate.newUnit = newExecCU;
180 componentUpdate.patchResult = result;
181 inplaceUpdate->processedComponentUpdates.push_back(std::move(componentUpdate));
182 }
183
184 // Once all components have been handled, update resolved type references in all
185 // compilation units and refresh all bindings
186 if (inplaceUpdate->pendingComponentUpdates.empty()) {
187 updateResolvedTypeReferences(v4, inplaceUpdate->droppedUnits);
188 for (const ComponentUpdate &update : inplaceUpdate->processedComponentUpdates) {
189 // Objects patched in place keep their original (still-live) expressions; translate
190 // those to the new unit. Rebuilt roots only leave dead expressions behind; null them.
191 QQmlPreview::refreshBindings(
192 update.oldUnit,
193 update.patchResult == QQmlPreview::PatchResult::PatchedInPlace ? update.newUnit
194 : nullptr);
195 }
196 }
197}
198
199void updateEngine(std::shared_ptr<InplaceUpdate> inplaceUpdate, const QList<QUrl> &urls)
200{
201 QV4::ExecutionEngine *v4 = inplaceUpdate->engine->handle();
202 std::vector<QQmlComponent *> components;
203 for (const QUrl &url : urls) {
204 // First remove any cached instance of the CU
205 // NB: Don't remove from the ExecutionEngine's list of CUs. We need those for the GC.
206 if (!v4->typeLoader()->removeFromCache(url))
207 continue;
208
209 // Hold on to the old unit.
210 QQmlRefPointer<QV4::ExecutableCompilationUnit> oldUnit = v4->compilationUnitForUrl(url);
211
212 // Then have it re-compile with updated source code. newUnit and patchResult are filled
213 // in by updateInplace() once the component has recompiled and the diff has been applied.
214 inplaceUpdate->pendingComponentUpdates.push_back({
215 std::make_unique<QQmlComponent>(inplaceUpdate->engine, url),
216 std::move(oldUnit),
217 {},
218 QQmlPreview::PatchResult::Failed,
219 });
220
221 // Additionally store in another vector since updateInplace deletes from inplaceUpdate
222 components.push_back(inplaceUpdate->pendingComponentUpdates.back().component.get());
223 }
224
225 for (QQmlComponent *component : components) {
226 switch (component->status()) {
227 case QQmlComponent::Null:
228 case QQmlComponent::Loading:
229 QObject::connect(component, &QQmlComponent::statusChanged, component,
230 [component, inplaceUpdate]() {
231 switch (component->status()) {
232 case QQmlComponent::Ready:
233 case QQmlComponent::Error:
234 updateInplace(component, inplaceUpdate);
235 break;
236 default:
237 break;
238 }
239 });
240 break;
241 case QQmlComponent::Ready:
242 case QQmlComponent::Error:
243 updateInplace(component, inplaceUpdate);
244 break;
245 }
246 }
247}
248
249void QQmlInPlacePreviewHandler::load(const QUrl &url)
250{
251 // Find the updated objects from the URLs we were asked to drop. Those are the ones that have
252 // been updated.
253
254 const QList<QQmlEngine *> seenEngines = engines();
255 const QList<QUrl> urls = std::exchange(m_droppedUrls, {});
256
257 QList<QQmlRefPointer<QV4::CompiledData::CompilationUnit>> droppedUnits;
258 for (const QUrl &droppedUrl : urls) {
259 while (const auto cu = QQmlMetaType::obtainCompilationUnit(droppedUrl)) {
260 droppedUnits.append(cu);
261 QQmlMetaType::deepClearCompositeType(cu);
262 }
263 }
264 for (QQmlEngine *engine : seenEngines) {
265 std::shared_ptr<InplaceUpdate> inplaceUpdate =
266 std::make_shared<InplaceUpdate>(this, engine);
267 inplaceUpdate->droppedUnits = droppedUnits;
268
269 // Schedule this on the engine's thread. The shared pointer keeps the update alive as
270 // long as necessary.
271 QMetaObject::invokeMethod(engine, [update = std::move(inplaceUpdate), urls]() {
272 updateEngine(update, urls);
273 });
274 }
275
276 // Update current window and root item based on passed URL
277 // so that we can zoom and report FPS.
278 // We can only do that if we have an unambiguous root item or window.
279
280 if (seenEngines.size() == 1) {
281 findCurrentRootObject(seenEngines[0], url, this);
282 } else {
283 setCurrentRootItem(nullptr);
284 setCurrentWindow(findCurrentWindow());
285 return;
286 }
287}
288
289QT_END_NAMESPACE
290
291#include "moc_qqmlinplacepreviewhandler.cpp"
Combined button and popup list for selecting options.
static void updateResolvedTypeReferences(QV4::ExecutionEngine *v4, const QList< QQmlRefPointer< QV4::CompiledData::CompilationUnit > > &droppedUnits)
static void updateInplace(QQmlComponent *component, std::shared_ptr< InplaceUpdate > inplaceUpdate)
void findCurrentRootObject(QQmlEngine *engine, const QUrl &url, QQmlPreviewHandler *receiver)
QQuickWindow * findCurrentWindow()
void updateEngine(std::shared_ptr< InplaceUpdate > inplaceUpdate, const QList< QUrl > &urls)
QQmlRefPointer< QV4::ExecutableCompilationUnit > newUnit
std::unique_ptr< QQmlComponent > component
QQmlRefPointer< QV4::ExecutableCompilationUnit > oldUnit
QQmlPreview::PatchResult patchResult
std::vector< ComponentUpdate > pendingComponentUpdates
QList< QQmlRefPointer< QV4::CompiledData::CompilationUnit > > droppedUnits
InplaceUpdate(QQmlInPlacePreviewHandler *handler, QQmlEngine *engine)
void emitError(const QString &message)
void emitReloadFailure(const QString &message)
std::vector< ComponentUpdate > processedComponentUpdates