summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/wasm/qwasmscreen.cpp
blob: ddf8140c48d192c9bcc3a6a45c2f9d299c83140f (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
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "qwasmscreen.h"

#include "qwasmcompositor.h"
#include "qwasmcssstyle.h"
#include "qwasmintegration.h"
#include "qwasmkeytranslator.h"
#include "qwasmwindow.h"

#include <emscripten/bind.h>
#include <emscripten/val.h>

#include <qpa/qwindowsysteminterface.h>
#include <QtCore/qcoreapplication.h>
#include <QtGui/qguiapplication.h>
#include <private/qhighdpiscaling_p.h>

#include <tuple>

QT_BEGIN_NAMESPACE

using namespace emscripten;

const char *QWasmScreen::m_canvasResizeObserverCallbackContextPropertyName =
        "data-qtCanvasResizeObserverCallbackContext";

QWasmScreen::QWasmScreen(const emscripten::val &containerOrCanvas)
    : m_container(containerOrCanvas),
      m_intermediateContainer(emscripten::val::undefined()),
      m_shadowContainer(emscripten::val::undefined()),
      m_compositor(new QWasmCompositor(this)),
      m_deadKeySupport(std::make_unique<QWasmDeadKeySupport>())
{
    auto document = m_container["ownerDocument"];
    // Each screen is represented by a div container. All of the windows exist therein as
    // its children. Qt versions < 6.5 used to represent screens as canvas. Support that by
    // transforming the canvas into a div.
    if (m_container["tagName"].call<std::string>("toLowerCase") == "canvas") {
        qWarning() << "Support for canvas elements as an element backing screen is deprecated. The "
                      "canvas provided for the screen will be transformed into a div.";
        auto container = document.call<emscripten::val>("createElement", emscripten::val("div"));
        m_container["parentNode"].call<void>("replaceChild", container, m_container);
        m_container = container;
    }

    // Create an intermediate container which we can remove during cleanup in ~QWasmScreen().
    // This is required due to the attachShadow() call below; there is no corresponding
    // "detachShadow()" API to return the container to its previous state.
    m_intermediateContainer = document.call<emscripten::val>("createElement", emscripten::val("div"));
    m_intermediateContainer.set("id", std::string("qt-shadow-container"));
    emscripten::val intermediateContainerStyle = m_intermediateContainer["style"];
    intermediateContainerStyle.set("width", std::string("100%"));
    intermediateContainerStyle.set("height", std::string("100%"));
    m_container.call<void>("appendChild", m_intermediateContainer);

    auto shadowOptions = emscripten::val::object();
    shadowOptions.set("mode", "open");
    auto shadow = m_intermediateContainer.call<emscripten::val>("attachShadow", shadowOptions);

    m_shadowContainer = document.call<emscripten::val>("createElement", emscripten::val("div"));

    shadow.call<void>("appendChild", QWasmCSSStyle::createStyleElement(m_shadowContainer));

    shadow.call<void>("appendChild", m_shadowContainer);

    m_shadowContainer.set("id", std::string("qt-screen-") + std::to_string(uintptr_t(this)));

    m_shadowContainer["classList"].call<void>("add", std::string("qt-screen"));

    // Disable the default context menu; Qt applications typically
    // provide custom right-click behavior.
    m_onContextMenu = std::make_unique<qstdweb::EventCallback>(
            m_shadowContainer, "contextmenu",
            [](emscripten::val event) { event.call<void>("preventDefault"); });
    // Create "specialHTMLTargets" mapping for the canvas - the element  might be unreachable based
    // on its id only under some conditions, like the target being embedded in a shadow DOM or a
    // subframe.
    emscripten::val::module_property("specialHTMLTargets")
            .set(eventTargetId().toStdString(), m_shadowContainer);

    emscripten::val::module_property("specialHTMLTargets")
            .set(outerScreenId().toStdString(), m_container);

    updateQScreenAndCanvasRenderSize();
    m_shadowContainer.call<void>("focus");

    m_touchDevice = std::make_unique<QPointingDevice>(
            "touchscreen", 1, QInputDevice::DeviceType::TouchScreen,
            QPointingDevice::PointerType::Finger,
            QPointingDevice::Capability::Position | QPointingDevice::Capability::Area
                    | QPointingDevice::Capability::NormalizedPosition,
            10, 0);
    m_tabletDevice = std::make_unique<QPointingDevice>(
            "stylus", 2, QInputDevice::DeviceType::Stylus,
            QPointingDevice::PointerType::Pen,
            QPointingDevice::Capability::Position | QPointingDevice::Capability::Pressure
                | QPointingDevice::Capability::NormalizedPosition
                | QInputDevice::Capability::MouseEmulation
                | QInputDevice::Capability::Hover | QInputDevice::Capability::Rotation
                | QInputDevice::Capability::XTilt | QInputDevice::Capability::YTilt
                | QInputDevice::Capability::TangentialPressure,
            0, 0);

    QWindowSystemInterface::registerInputDevice(m_touchDevice.get());
}

QWasmScreen::~QWasmScreen()
{
    m_intermediateContainer.call<void>("remove");

    emscripten::val::module_property("specialHTMLTargets")
            .set(eventTargetId().toStdString(), emscripten::val::undefined());

    m_shadowContainer.set(m_canvasResizeObserverCallbackContextPropertyName,
                          emscripten::val(intptr_t(0)));
}

void QWasmScreen::deleteScreen()
{
    // Deletes |this|!
    QWindowSystemInterface::handleScreenRemoved(this);
}

QWasmScreen *QWasmScreen::get(QPlatformScreen *screen)
{
    return static_cast<QWasmScreen *>(screen);
}

QWasmScreen *QWasmScreen::get(QScreen *screen)
{
    if (!screen)
        return nullptr;
    return get(screen->handle());
}

QWasmCompositor *QWasmScreen::compositor()
{
    return m_compositor.get();
}

emscripten::val QWasmScreen::element() const
{
    return m_shadowContainer;
}

QString QWasmScreen::eventTargetId() const
{
    // Return a globally unique id for the canvas. We can choose any string,
    // as long as it starts with a "!".
    return QString("!qtcanvas_%1").arg(uintptr_t(this));
}

QString QWasmScreen::outerScreenId() const
{
    return QString("!outerscreen_%1").arg(uintptr_t(this));
}

QRect QWasmScreen::geometry() const
{
    return m_geometry;
}

int QWasmScreen::depth() const
{
    return m_depth;
}

QImage::Format QWasmScreen::format() const
{
    return m_format;
}

QDpi QWasmScreen::logicalDpi() const
{
    emscripten::val dpi = emscripten::val::module_property("qtFontDpi");
    if (!dpi.isUndefined()) {
        qreal dpiValue = dpi.as<qreal>();
        return QDpi(dpiValue, dpiValue);
    }
    const qreal defaultDpi = 96;
    return QDpi(defaultDpi, defaultDpi);
}

qreal QWasmScreen::devicePixelRatio() const
{
    // window.devicePixelRatio gives us the scale factor between CSS and device pixels.
    // This property reflects hardware configuration, and also browser zoom on desktop.
    //
    // window.visualViewport.scale gives us the zoom factor on mobile. If the html page is
    // configured with "<meta name="viewport" content="width=device-width">" then this scale
    // factor will be 1. Omitting the viewport configuration typically results on a zoomed-out
    // viewport, with a scale factor <1. User pinch-zoom will change the scale factor; an event
    // handler is installed in the QWasmIntegration constructor. Changing zoom level on desktop
    // does not appear to change visualViewport.scale.
    //
    // The effective devicePixelRatio is the product of these two scale factors, upper-bounded
    // by window.devicePixelRatio in order to avoid e.g. allocating a 10x widget backing store.
    double dpr = emscripten::val::global("window")["devicePixelRatio"].as<double>();
    emscripten::val visualViewport = emscripten::val::global("window")["visualViewport"];
    double scale = visualViewport.isUndefined() ? 1.0 : visualViewport["scale"].as<double>();
    double effectiveDevicePixelRatio = std::min(dpr * scale, dpr);
    return qreal(effectiveDevicePixelRatio);
}

QString QWasmScreen::name() const
{
    return QString::fromEcmaString(m_shadowContainer["id"]);
}

QPlatformCursor *QWasmScreen::cursor() const
{
    return const_cast<QWasmCursor *>(&m_cursor);
}

void QWasmScreen::resizeMaximizedWindows()
{
    if (!screen())
        return;
    QPlatformScreen::resizeMaximizedWindows();
}

QWindow *QWasmScreen::topWindow() const
{
    return activeChild() ? activeChild()->window() : nullptr;
}

QWindow *QWasmScreen::topLevelAt(const QPoint &p) const
{
    const auto found =
            std::find_if(childStack().begin(), childStack().end(), [&p](const QWasmWindow *window) {
                const QRect geometry = window->windowFrameGeometry();

                return window->isVisible() && geometry.contains(p);
            });
    return found != childStack().end() ? (*found)->window() : nullptr;
}

QPointF QWasmScreen::mapFromLocal(const QPointF &p) const
{
    return geometry().topLeft() + p;
}

QPointF QWasmScreen::clipPoint(const QPointF &p) const
{
    const auto geometryF = screen()->geometry().toRectF();
    return QPointF(qBound(geometryF.left(), p.x(), geometryF.right()),
                   qBound(geometryF.top(), p.y(), geometryF.bottom()));
}

void QWasmScreen::invalidateSize()
{
    m_geometry = QRect();
}

void QWasmScreen::setGeometry(const QRect &rect)
{
    m_geometry = rect;
    QWindowSystemInterface::handleScreenGeometryChange(QPlatformScreen::screen(), geometry(),
                                                       availableGeometry());
    resizeMaximizedWindows();
}

void QWasmScreen::onSubtreeChanged(QWasmWindowTreeNodeChangeType changeType,
                                   QWasmWindowTreeNode *parent, QWasmWindow *child)
{
    Q_UNUSED(parent);
    if (changeType == QWasmWindowTreeNodeChangeType::NodeInsertion && parent == this
        && childStack().size() == 1) {
        child->window()->setFlag(Qt::WindowStaysOnBottomHint);
    }
    QWasmWindowTreeNode::onSubtreeChanged(changeType, parent, child);
    m_compositor->onWindowTreeChanged(changeType, child);
}

void QWasmScreen::updateQScreenAndCanvasRenderSize()
{
    // The HTML canvas has two sizes: the CSS size and the canvas render size.
    // The CSS size is determined according to standard CSS rules, while the
    // render size is set using the "width" and "height" attributes. The render
    // size must be set manually and is not auto-updated on CSS size change.
    // Setting the render size to a value larger than the CSS size enables high-dpi
    // rendering.
    double css_width;
    double css_height;
    emscripten_get_element_css_size(outerScreenId().toUtf8().constData(), &css_width, &css_height);
    QSizeF cssSize(css_width, css_height);

    QSizeF canvasSize = cssSize * devicePixelRatio();

    m_shadowContainer.set("width", canvasSize.width());
    m_shadowContainer.set("height", canvasSize.height());

    // Returns the html elements document/body position
    auto getElementBodyPosition = [](const emscripten::val &element) -> QPoint {
        emscripten::val bodyRect =
                element["ownerDocument"]["body"].call<emscripten::val>("getBoundingClientRect");
        emscripten::val canvasRect = element.call<emscripten::val>("getBoundingClientRect");
        return QPoint(canvasRect["left"].as<int>() - bodyRect["left"].as<int>(),
                      canvasRect["top"].as<int>() - bodyRect["top"].as<int>());
    };

    setGeometry(QRect(getElementBodyPosition(m_shadowContainer), cssSize.toSize()));
}

void QWasmScreen::canvasResizeObserverCallback(emscripten::val entries, emscripten::val)
{
    int count = entries["length"].as<int>();
    if (count == 0)
        return;
    emscripten::val entry = entries[0];
    QWasmScreen *screen = reinterpret_cast<QWasmScreen *>(
            entry["target"][m_canvasResizeObserverCallbackContextPropertyName].as<intptr_t>());
    if (!screen) {
        qWarning() << "QWasmScreen::canvasResizeObserverCallback: missing screen pointer";
        return;
    }

    // We could access contentBoxSize|contentRect|devicePixelContentBoxSize on the entry here, but
    // these are not universally supported across all browsers. Get the sizes from the canvas
    // instead.
    screen->updateQScreenAndCanvasRenderSize();
}

EMSCRIPTEN_BINDINGS(qtCanvasResizeObserverCallback)
{
    emscripten::function("qtCanvasResizeObserverCallback",
                         &QWasmScreen::canvasResizeObserverCallback);
}

void QWasmScreen::installCanvasResizeObserver()
{
    emscripten::val ResizeObserver = emscripten::val::global("ResizeObserver");
    if (ResizeObserver == emscripten::val::undefined())
        return; // ResizeObserver API is not available
    emscripten::val resizeObserver =
            ResizeObserver.new_(emscripten::val::module_property("qtCanvasResizeObserverCallback"));
    if (resizeObserver == emscripten::val::undefined())
        return; // Something went horribly wrong

    // We need to get back to this instance from the (static) resize callback;
    // set a "data-" property on the canvas element.
    m_shadowContainer.set(m_canvasResizeObserverCallbackContextPropertyName,
                          emscripten::val(intptr_t(this)));

    resizeObserver.call<void>("observe", m_shadowContainer);
}

emscripten::val QWasmScreen::containerElement()
{
    return m_shadowContainer;
}

QWasmWindowTreeNode *QWasmScreen::parentNode()
{
    return nullptr;
}

QList<QWasmWindow *> QWasmScreen::allWindows()
{
    QList<QWasmWindow *> windows;
    for (auto *child : childStack()) {
        QWindowList list = child->window()->findChildren<QWindow *>(Qt::FindChildrenRecursively);
        std::transform(
                list.begin(), list.end(), std::back_inserter(windows),
                [](const QWindow *window) { return static_cast<QWasmWindow *>(window->handle()); });
        windows.push_back(child);
    }
    return windows;
}

QT_END_NAMESPACE