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
qwasmwindow.cpp
Go to the documentation of this file.
1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include <qpa/qwindowsysteminterface.h>
6#include <private/qguiapplication_p.h>
7#include <QtCore/qfile.h>
8#include <QtCore/qtimer.h>
9#include <QtCore/qpointer.h>
10#include <QtGui/private/qwindow_p.h>
11#include <QtGui/private/qhighdpiscaling_p.h>
12#include <private/qpixmapcache_p.h>
13#include <QtGui/qopenglfunctions.h>
14#include <QBuffer>
15
17#include "qwasmdom.h"
18#if QT_CONFIG(clipboard)
19#include "qwasmclipboard.h"
20#endif
24#include "qwasmwindow.h"
25#include "qwasmscreen.h"
27#include "qwasmevent.h"
30#if QT_CONFIG(draganddrop)
31#include "qwasmdrag.h"
32#endif
34
35#include <iostream>
36#include <sstream>
37#include <utility>
38
39#include <emscripten/val.h>
40
41#include <QtCore/private/qstdweb_p.h>
42
44
46
48 QWasmCompositor *compositor, QWasmBackingStore *backingStore,
49 WId nativeHandle)
51 m_compositor(compositor),
52 m_backingStore(backingStore),
54 m_decoratedWindow(m_document.call<emscripten::val>("createElement", emscripten::val("div"))),
55 m_window(m_document.call<emscripten::val>("createElement", emscripten::val("div"))),
56 m_a11yContainer(m_document.call<emscripten::val>("createElement", emscripten::val("div"))),
59 m_canvas(m_document.call<emscripten::val>("createElement", emscripten::val("canvas"))),
60 m_focusHelper(m_document.call<emscripten::val>("createElement", emscripten::val("div"))),
61 m_inputElement(m_document.call<emscripten::val>("createElement", emscripten::val("input")))
62
63{
64 m_decoratedWindow.set("className", "qt-decorated-window");
65 m_decoratedWindow["style"].set("display", std::string("none"));
66
67 m_nonClientArea = std::make_unique<NonClientArea>(this, m_decoratedWindow);
68 m_nonClientArea->titleBar()->setTitle(window()->title());
69
70 // If we are wrapping a foregin window, a.k.a. a native html element then that element becomes
71 // the m_window element. In this case setting up event handlers and accessibility etc is not
72 // needed since that is (presumably) handled by the native html element.
73 //
74 // The WId is an emscripten::val *, owned by QWindow user code. We dereference and make
75 // a copy of the val here and don't strictly need it to be kept alive, but that's an
76 // implementation detail. The pointer will be dereferenced again if the window is destroyed
77 // and recreated.
78 if (nativeHandle) {
79 m_window = *(emscripten::val *)(nativeHandle);
80 m_winId = nativeHandle;
81 m_hasNativeHandle = true;
82 m_decoratedWindow.set("id", "qt-window-" + std::to_string(m_winId));
83 m_decoratedWindow.call<void>("appendChild", m_window);
84 return;
85 }
86
87 m_window.set("className", "qt-window");
88 m_window.call<void>("setAttribute", emscripten::val("role"), emscripten::val("application"));
89 m_decoratedWindow.call<void>("appendChild", m_window);
90
91 m_canvas["classList"].call<void>("add", emscripten::val("qt-window-canvas"));
92
93#if QT_CONFIG(clipboard)
94 // The window is the only ancestor of every focusable child element.
95 m_cutCallback = QWasmEventHandler(m_window, "cut", QWasmClipboard::cut);
96 m_copyCallback = QWasmEventHandler(m_window, "copy", QWasmClipboard::copy);
97 m_pasteCallback = QWasmEventHandler(m_window, "paste", QWasmClipboard::paste);
98#endif
99
100 // Set up m_focusHelper, which is an invisible child element of the window which takes
101 // focus on behalf of the window any time the window has focus in general, but none
102 // of the special child elements such as the inputElment or a11y elements have focus.
103 // Set inputMode=none set to prevent the virtual keyboard from popping up.
104 m_focusHelper["classList"].call<void>("add", emscripten::val("qt-window-focus-helper"));
105 m_focusHelper.set("inputMode", std::string("none"));
106 m_focusHelper.call<void>("setAttribute", std::string("contenteditable"), std::string("true"));
107 m_focusHelper["style"].set("position", "absolute");
108 m_focusHelper["style"].set("left", 0);
109 m_focusHelper["style"].set("top", 0);
110 m_focusHelper["style"].set("width", "1px");
111 m_focusHelper["style"].set("height", "1px");
112 m_focusHelper["style"].set("z-index", -2);
113 m_focusHelper["style"].set("opacity", 0);
114 m_focusHelper.set("tabIndex", -1); // focusable only via .focus(), not browser Tab
115 m_window.call<void>("appendChild", m_focusHelper);
116
117 // Set up m_inputElement, which takes focus whenever a Qt text input UI element has
118 // foucus.
119 m_inputElement["classList"].call<void>("add", emscripten::val("qt-window-input-element"));
120 m_inputElement.call<void>("setAttribute", std::string("contenteditable"), std::string("true"));
121 m_inputElement.set("type", "text");
122 m_inputElement["style"].set("position", "absolute");
123 m_inputElement["style"].set("left", 0);
124 m_inputElement["style"].set("top", 0);
125 m_inputElement["style"].set("width", "1px");
126 m_inputElement["style"].set("height", "1px");
127 m_inputElement["style"].set("z-index", -2);
128 m_inputElement["style"].set("opacity", 0);
129 m_inputElement["style"].set("display", "");
130 m_inputElement.set("tabIndex", -1); // focusable only via .focus(), not browser Tab
131 m_window.call<void>("appendChild", m_inputElement);
132
133 // The canvas displays graphics only, and is not accessible or an event target
134 m_canvas.call<void>("setAttribute", std::string("aria-hidden"), std::string("true"));
135 m_canvas["style"].set("pointerEvents", "none");
136
137 m_window.call<void>("appendChild", m_canvas);
138
139 m_a11yContainer["classList"].call<void>("add", emscripten::val("qt-window-a11y-container"));
140 m_a11yElementContainer["classList"].call<void>(
141 "add", emscripten::val("qt-window-a11y-elements-container"));
142 m_a11yDescribedByContainer["classList"].call<void>(
143 "add", emscripten::val("qt-window-a11y-describedby-container"));
144 m_a11yContainer.call<void>("appendChild", m_a11yElementContainer);
145 m_a11yContainer.call<void>("appendChild", m_a11yDescribedByContainer);
146 m_window.call<void>("appendChild", m_a11yContainer);
147
148 if (QWasmAccessibility::isEnabled())
150
151 const bool rendersTo2dContext = w->surfaceType() != QSurface::OpenGLSurface;
152 if (rendersTo2dContext)
153 m_context2d = m_canvas.call<emscripten::val>("getContext", emscripten::val("2d"));
154
155 m_winId = WId(&m_window);
156 m_decoratedWindow.set("id", "qt-window-" + std::to_string(m_winId));
157 emscripten::val::module_property("specialHTMLTargets").set(canvasSelector(), m_canvas);
158
159 m_flags = window()->flags();
160
162
163 m_transientWindowChangedConnection =
164 QObject::connect(
165 window(), &QWindow::transientParentChanged,
166 window(), [this](QWindow *tp) { onTransientParentChanged(tp); });
167
168 m_modalityChangedConnection =
169 QObject::connect(
170 window(), &QWindow::modalityChanged,
171 window(), [this](Qt::WindowModality) { onModalityChanged(); });
172}
173
175{
176 m_pointerDownCallback = QWasmEventHandler(m_window, "pointerdown",
177 [this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerDown, event)); }
178 );
179 m_pointerMoveCallback = QWasmEventHandler(m_window, "pointermove",
180 [this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerMove, event)); }
181 );
182 m_pointerUpCallback = QWasmEventHandler(m_window, "pointerup",
183 [this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerUp, event)); }
184 );
185 m_pointerCancelCallback = QWasmEventHandler(m_window, "pointercancel",
186 [this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerCancel, event)); }
187 );
188 m_pointerEnterCallback = QWasmEventHandler(m_window, "pointerenter",
189 [this](emscripten::val event) { this->handlePointerEnterLeaveEvent(PointerEvent(EventType::PointerEnter, event)); }
190 );
191 m_pointerLeaveCallback = QWasmEventHandler(m_window, "pointerleave",
192 [this](emscripten::val event) { this->handlePointerEnterLeaveEvent(PointerEvent(EventType::PointerLeave, event)); }
193 );
194
195#if QT_CONFIG(draganddrop)
196 m_window.call<void>("setAttribute", emscripten::val("draggable"), emscripten::val("true"));
197 m_dragStartCallback = QWasmEventHandler(m_window, "dragstart",
198 [this](emscripten::val event) {
199 DragEvent dragEvent(EventType::DragStart, event, window());
200 QWasmDrag::instance()->onNativeDragStarted(&dragEvent);
201 }
202 );
203 m_dragOverCallback = QWasmEventHandler(m_window, "dragover",
204 [this](emscripten::val event) {
205 DragEvent dragEvent(EventType::DragOver, event, window());
206 QWasmDrag::instance()->onNativeDragOver(&dragEvent);
207 }
208 );
209 m_dropCallback = QWasmEventHandler(m_window, "drop",
210 [this](emscripten::val event) {
211 DragEvent dragEvent(EventType::Drop, event, window());
212 QWasmDrag::instance()->onNativeDrop(&dragEvent);
213 }
214 );
215 m_dragEndCallback = QWasmEventHandler(m_window, "dragend",
216 [this](emscripten::val event) {
217 DragEvent dragEvent(EventType::DragEnd, event, window());
218 QWasmDrag::instance()->onNativeDragFinished(&dragEvent, platformScreen());
219 releasePointerGrab(dragEvent);
220 }
221 );
222 m_dragEnterCallback = QWasmEventHandler(m_window, "dragenter",
223 [this](emscripten::val event) {
224 DragEvent dragEvent(EventType::DragEnter, event, window());
225 QWasmDrag::instance()->onNativeDragEnter(&dragEvent);
226 }
227 );
228 m_dragLeaveCallback = QWasmEventHandler(m_window, "dragleave",
229 [this](emscripten::val event) {
230 DragEvent dragEvent(EventType::DragLeave, event, window());
231 QWasmDrag::instance()->onNativeDragLeave(&dragEvent);
232 }
233 );
234#endif // QT_CONFIG(draganddrop)
235
236 m_wheelEventCallback = QWasmEventHandler(m_window, "wheel",
237 [this](emscripten::val event) { this->handleWheelEvent(event); });
238
239 m_keyDownCallback = QWasmEventHandler(m_window, "keydown",
240 [this](emscripten::val event) { this->handleKeyEvent(KeyEvent(EventType::KeyDown, event)); });
241 m_keyUpCallback =QWasmEventHandler(m_window, "keyup",
242 [this](emscripten::val event) {this->handleKeyEvent(KeyEvent(EventType::KeyUp, event)); });
243
244 m_inputCallback = QWasmEventHandler(m_window, "input",
245 [this](emscripten::val event){ handleInputEvent(event); });
246 m_compositionUpdateCallback = QWasmEventHandler(m_window, "compositionupdate",
247 [this](emscripten::val event){ handleCompositionUpdateEvent(event); });
248 m_compositionStartCallback = QWasmEventHandler(m_window, "compositionstart",
249 [this](emscripten::val event){ handleCompositionStartEvent(event); });
250 m_compositionEndCallback = QWasmEventHandler(m_window, "compositionend",
251 [this](emscripten::val event){ handleCompositionEndEvent(event); });
252 m_beforeInputCallback = QWasmEventHandler(m_window, "beforeinput",
253 [this](emscripten::val event){ handleBeforeInputEvent(event); });
254
255 m_focusinCallback = QWasmEventHandler(m_window, "focusin",
256 [this](emscripten::val event) { handleFocusinEvent(event); });
257 m_focusoutCallback = QWasmEventHandler(m_window, "focusout",
258 [this](emscripten::val event) { handleFocusoutEvent(event); });
259 }
260
262{
264
265#if QT_CONFIG(accessibility)
266 QWasmAccessibility::onRemoveWindow(window());
267#endif
268 QObject::disconnect(m_transientWindowChangedConnection);
269 QObject::disconnect(m_modalityChangedConnection);
270
271 transferFocus();
272
273 emscripten::val::module_property("specialHTMLTargets").delete_(canvasSelector());
274 m_window.call<void>("removeChild", m_canvas);
275 m_window.call<void>("removeChild", m_a11yContainer);
276 m_context2d = emscripten::val::undefined();
277 commitParent(nullptr);
278 if (m_requestAnimationFrameId > -1)
279 emscripten_cancel_animation_frame(m_requestAnimationFrameId);
280}
281
282void QWasmWindow::transferFocus()
283{
284 if (!window() ||
285 (QGuiApplication::focusWindow() && // Don't act if we have a focus window different from this
286 QGuiApplication::focusWindow() != window()))
287 return;
288
289 // Make a list of all windows sorted on active index.
290 // Skip windows with active index 0 as they have
291 // never been active.
292 std::map<uint64_t, QWasmWindow *> allWindows;
293 for (const auto &w : platformScreen()->allWindows()) {
294 if (w->getActiveIndex() > 0 && w->isVisible())
295 allWindows.insert({w->getActiveIndex(), w});
296 }
297
298 // window is not in all windows
299 if (getActiveIndex() > 0)
300 allWindows.insert({getActiveIndex(), this});
301
302 if (allWindows.size() >= 2) {
303 const auto lastIt = std::prev(allWindows.end());
304 const auto prevIt = std::prev(lastIt);
305 const auto lastW = lastIt->second;
306 const auto prevW = prevIt->second;
307
308 if (lastW == this) // Only act if window is last to be active
309 prevW->requestActivateWindow();
310 }
311}
312
314{
315 return window()->requestedFormat();
316}
317
318QWasmWindow *QWasmWindow::fromWindow(const QWindow *window)
319{
320 if (!window ||!window->handle())
321 return nullptr;
322 return static_cast<QWasmWindow *>(window->handle());
323}
324
326{
327 return fromWindow(QGuiApplication::focusWindow());
328}
329
331{
332 QWasmWindow *window = focusWindow();
333 return window ? window->inputElement() : emscripten::val::null();
334}
335
337{
338 if (!window())
339 return nullptr;
340
341 return fromWindow(window()->transientParent());
342}
343
345{
346 return window()->flags();
347}
348
349bool QWasmWindow::isModal() const
350{
351 return window()->isModal();
352}
353
355{
356 window()->setWindowState(Qt::WindowNoState);
357}
358
360{
361 window()->setWindowState(Qt::WindowMaximized);
362}
363
365{
366 window()->setWindowState(m_state.testFlag(Qt::WindowMaximized) ? Qt::WindowNoState
367 : Qt::WindowMaximized);
368}
369
371{
372 window()->close();
373}
374
376{
378 QGuiApplicationPrivate::instance()->closeAllPopups();
379}
380
382{
383 QPointF pointInScreen = platformScreen()->mapFromLocal(
384 dom::mapPoint(event.target(), platformScreen()->element(), event.localPoint));
385 return QWindowSystemInterface::handleMouseEvent(
386 window(), QWasmIntegration::getTimestamp(), window()->mapFromGlobal(pointInScreen),
387 pointInScreen, event.mouseButtons, event.mouseButton,
388 MouseEvent::mouseEventTypeFromEventType(event.type, WindowArea::NonClient),
389 event.modifiers);
390}
391
393{
394 // Adds the window to the window tree once QWindow::handle() is set,
395 // since adding it can activate the window synchronously.
396 setParent(parent());
397
398 auto initialGeometry = QPlatformWindow::initialGeometry(window(),
399 windowGeometry(), defaultWindowSize, defaultWindowSize);
400 m_normalGeometry = initialGeometry;
401
402 setWindowState(window()->windowStates());
403 setWindowFlags(window()->flags());
404 setWindowTitle(window()->title());
405 setMask(QHighDpi::toNativeLocalRegion(window()->mask(), window()));
406
407 if (window()->isTopLevel())
408 setWindowIcon(window()->icon());
409 QPlatformWindow::setGeometry(m_normalGeometry);
410
411#if QT_CONFIG(accessibility)
412 // Add accessibility-enable button. The user can activate this
413 // button to opt-in to accessibility.
414 if (window()->isTopLevel())
415 QWasmAccessibility::addAccessibilityEnableButton(window());
416#endif
417}
418
420{
421 return static_cast<QWasmScreen *>(window()->screen()->handle());
422}
423
425{
426 if (!m_backingStore || !isVisible() || m_context2d.isUndefined())
427 return;
428
429 auto image = m_backingStore->getUpdatedWebImage(this);
430 if (image.isUndefined())
431 return;
432 m_context2d.call<void>("putImageData", image, emscripten::val(0), emscripten::val(0));
433}
434
436{
437 m_decoratedWindow["style"].set("zIndex", std::to_string(z));
438}
439
440void QWasmWindow::setWindowCursor(QByteArray cssCursorName)
441{
442 m_window["style"].set("cursor", emscripten::val(cssCursorName.constData()));
443}
444
445void QWasmWindow::setGeometry(const QRect &rect)
446{
447 const auto margins = frameMargins();
448
449 const QRect clientAreaRect = ([this, &rect, &margins]() {
450 if (m_state.testFlag(Qt::WindowFullScreen))
451 return platformScreen()->geometry();
452 if (m_state.testFlag(Qt::WindowMaximized))
453 return platformScreen()->availableGeometry().marginsRemoved(frameMargins());
454
455 auto offset = rect.topLeft() - (!parent() ? screen()->geometry().topLeft() : QPoint());
456
457 // In viewport
458 auto containerGeometryInViewport =
459 QRectF::fromDOMRect(parentNode()->containerElement().call<emscripten::val>(
460 "getBoundingClientRect"))
461 .toRect();
462
463 auto rectInViewport = QRect(containerGeometryInViewport.topLeft() + offset, rect.size());
464
465 QRect cappedGeometry(rectInViewport);
466 if (!parent()) {
467 // Clamp top level windows top position to the screen bounds
468 cappedGeometry.moveTop(
469 std::max(std::min(rectInViewport.y(), containerGeometryInViewport.bottom()),
470 containerGeometryInViewport.y() + margins.top()));
471 }
472 cappedGeometry.setSize(
473 cappedGeometry.size().expandedTo(windowMinimumSize()).boundedTo(windowMaximumSize()));
474 return QRect(QPoint(rect.x(), rect.y() + cappedGeometry.y() - rectInViewport.y()),
475 rect.size());
476 })();
477 m_nonClientArea->onClientAreaWidthChange(clientAreaRect.width());
478
479 const auto frameRect =
480 clientAreaRect
481 .adjusted(-margins.left(), -margins.top(), margins.right(), margins.bottom())
482 .translated(!parent() ? -screen()->geometry().topLeft() : QPoint());
483
484 m_decoratedWindow["style"].set("left", std::to_string(frameRect.left()) + "px");
485 m_decoratedWindow["style"].set("top", std::to_string(frameRect.top()) + "px");
486 m_canvas["style"].set("width", std::to_string(clientAreaRect.width()) + "px");
487 m_canvas["style"].set("height", std::to_string(clientAreaRect.height()) + "px");
488 m_a11yContainer["style"].set("width", std::to_string(clientAreaRect.width()) + "px");
489 m_a11yContainer["style"].set("height", std::to_string(clientAreaRect.height()) + "px");
490
491 // Important for the title bar and decorated window to size correctly
492 m_window["style"].set("width", std::to_string(clientAreaRect.width()) + "px");
493 m_window["style"].set("height", std::to_string(clientAreaRect.height()) + "px");
494
495 QSizeF canvasSize = clientAreaRect.size() * devicePixelRatio();
496
497 m_canvas.set("width", canvasSize.width());
498 m_canvas.set("height", canvasSize.height());
499
500 bool shouldInvalidate = true;
501 if (!m_state.testFlag(Qt::WindowFullScreen) && !m_state.testFlag(Qt::WindowMaximized)) {
502 shouldInvalidate = m_normalGeometry.size() != clientAreaRect.size();
503 m_normalGeometry = clientAreaRect;
504 }
505
506 QWindowSystemInterface::handleGeometryChange(window(), clientAreaRect);
507 if (shouldInvalidate)
508 invalidate();
509 else
510 m_compositor->requestUpdateWindow(this, QRect(QPoint(0, 0), geometry().size()));
511}
512
513void QWasmWindow::setVisible(bool visible)
514{
515 // TODO(mikolajboc): isVisible()?
516 const bool nowVisible = m_decoratedWindow["style"]["display"].as<std::string>() == "block";
517 if (visible == nowVisible)
518 return;
519
520 m_compositor->requestUpdateWindow(this, QRect(QPoint(0, 0), geometry().size()), QWasmCompositor::ExposeEventDelivery);
521 m_decoratedWindow["style"].set("display", visible ? "block" : "none");
522
523 // Handle focus on window visiblity transition; bring focus to this window
524 // or transfer it to a different window.
525 if (visible) {
526
527 // Some window configs should not take focus
528 const auto flags = windowFlags();
529 const bool isTooltip = ((flags & Qt::ToolTip) == Qt::ToolTip);
530 const auto showWithoutActivatingProp = window()->property("_q_showWithoutActivating");
531 const bool showWithoutActivating = showWithoutActivatingProp.isValid() && showWithoutActivatingProp.toBool();
532 const bool dontFocus = isTooltip || showWithoutActivating;
533
534 // Sync focus: make the window take native focus it is the focus window.
535 const bool hasFocus = window() == QGuiApplication::focusWindow();
536
537 // Take focus if this window is a top-level window becoming visible.
538 // This is window manager level behavior: QPlatformWindow subclasses
539 // usually do not implement auto-focus on show; however for wasm we
540 // are the window manager as well.
541 const bool takeFocus = window()->isTopLevel();
542
543 if (!dontFocus && (hasFocus || takeFocus))
544 focus();
545 } else {
546 if (window()->isTopLevel())
547 transferFocus();
548 }
549
550 if (visible) {
551 raise();
552 applyWindowState();
553#if QT_CONFIG(accessibility)
554 QWasmAccessibility::onShowWindow(window());
555#endif
556 }
557}
558
560{
561 return window()->isVisible();
562}
563
565{
566 const auto frameRect =
567 QRectF::fromDOMRect(m_decoratedWindow.call<emscripten::val>("getBoundingClientRect"));
568 const auto canvasRect =
569 QRectF::fromDOMRect(m_window.call<emscripten::val>("getBoundingClientRect"));
570 return QMarginsF(canvasRect.left() - frameRect.left(), canvasRect.top() - frameRect.top(),
571 frameRect.right() - canvasRect.right(),
572 frameRect.bottom() - canvasRect.bottom())
573 .toMargins();
574}
575
577{
578 bringToTop();
579 invalidate();
580}
581
583{
584 sendToBottom();
585 invalidate();
586}
587
589{
590 return m_winId;
591}
592
594{
595 // setGeometry() will take care of minimum and maximum size constraints
596 setGeometry(windowGeometry());
597 m_nonClientArea->propagateSizeHints();
598}
599
600void QWasmWindow::setOpacity(qreal level)
601{
602 m_decoratedWindow["style"].set("opacity", qBound(0.0, level, 1.0));
603}
604
605void QWasmWindow::invalidate()
606{
607 m_compositor->requestUpdateWindow(this, QRect(QPoint(0, 0), geometry().size()));
608}
609
611{
612 dom::syncCSSClassWith(m_decoratedWindow, "inactive", !active);
613}
614
615void QWasmWindow::setWindowFlags(Qt::WindowFlags flags)
616{
617 flags = fixTopLevelWindowFlags(flags);
618
619 // Note: This function is also called from the constructor,
620 // and in this case we should not call onPositionPreferenceChanged
621 // since we haven't inserted the window yet.
622 if (std::find(childStack().begin(), childStack().end(), this) != childStack().end()) {
623 if ((flags.testFlag(Qt::WindowStaysOnTopHint) != m_flags.testFlag(Qt::WindowStaysOnTopHint))
624 || (flags.testFlag(Qt::WindowStaysOnBottomHint)
625 != m_flags.testFlag(Qt::WindowStaysOnBottomHint))
626 || shouldBeAboveTransientParentFlags(flags) != shouldBeAboveTransientParentFlags(m_flags)) {
627 onPositionPreferenceChanged(positionPreferenceFromWindowFlags(flags));
628 }
629 }
630 m_flags = flags;
631 dom::syncCSSClassWith(m_decoratedWindow, "frameless", !hasFrame() || !window()->isTopLevel());
632 dom::syncCSSClassWith(m_decoratedWindow, "has-border", hasBorder());
633 dom::syncCSSClassWith(m_decoratedWindow, "has-shadow", hasShadow());
634 dom::syncCSSClassWith(m_decoratedWindow, "has-title", hasTitleBar());
635 dom::syncCSSClassWith(m_decoratedWindow, "transparent-for-input",
636 flags.testFlag(Qt::WindowTransparentForInput));
637
638 m_nonClientArea->titleBar()->setMaximizeVisible(hasMaximizeButton());
639 m_nonClientArea->titleBar()->setCloseVisible(m_flags.testFlag(Qt::WindowCloseButtonHint));
640
641 // Depends on the flags, and on whether the window is a child window.
642 setBrowserTabStop(true);
643}
644
645void QWasmWindow::setWindowState(Qt::WindowStates newState)
646{
647 // Child windows can not have window states other than Qt::WindowActive
648 if (parent())
649 newState &= Qt::WindowActive;
650
651 const Qt::WindowStates oldState = m_state;
652
653 if (newState.testFlag(Qt::WindowMinimized)) {
654 newState.setFlag(Qt::WindowMinimized, false);
655 qWarning("Qt::WindowMinimized is not implemented in wasm");
656 window()->setWindowStates(newState);
657 return;
658 }
659
660 if (newState == oldState)
661 return;
662
663 m_state = newState;
664 m_previousWindowState = oldState;
665
666 applyWindowState();
667}
668
669void QWasmWindow::setWindowTitle(const QString &title)
670{
671 m_nonClientArea->titleBar()->setTitle(title);
672}
673
674void QWasmWindow::setWindowIcon(const QIcon &icon)
675{
676 const auto dpi = screen()->devicePixelRatio();
677 auto pixmap = icon.pixmap(10 * dpi, 10 * dpi);
678 if (pixmap.isNull()) {
679 m_nonClientArea->titleBar()->setIcon(
680 Base64IconStore::get()->getIcon(Base64IconStore::IconType::QtLogo), "svg+xml");
681 return;
682 }
683
684 QByteArray bytes;
685 QBuffer buffer(&bytes);
686 pixmap.save(&buffer, "png");
687 m_nonClientArea->titleBar()->setIcon(bytes.toBase64().toStdString(), "png");
688}
689
690void QWasmWindow::applyWindowState()
691{
692 QRect newGeom;
693
694 const bool isFullscreen = m_state.testFlag(Qt::WindowFullScreen);
695 const bool isMaximized = m_state.testFlag(Qt::WindowMaximized);
696
697 // The screen ResizeObserver updates the geometry asynchronously, so a container
698 // just revealed may still read as empty here. Re-read it for fullscreen and maximized.
699 if ((isFullscreen || isMaximized) && platformScreen()->geometry().size().isEmpty())
701
702 if (isFullscreen)
703 newGeom = platformScreen()->geometry();
704 else if (isMaximized)
705 newGeom = platformScreen()->availableGeometry().marginsRemoved(frameMargins());
706 else
707 newGeom = normalGeometry();
708
709 dom::syncCSSClassWith(m_decoratedWindow, "has-border", hasBorder());
710 dom::syncCSSClassWith(m_decoratedWindow, "maximized", isMaximized);
711
712 m_nonClientArea->titleBar()->setRestoreVisible(isMaximized);
713 m_nonClientArea->titleBar()->setMaximizeVisible(hasMaximizeButton());
714
715 if (isVisible())
716 QWindowSystemInterface::handleWindowStateChanged(window(), m_state, m_previousWindowState);
717 setGeometry(newGeom);
718}
719
720void QWasmWindow::commitParent(QWasmWindowTreeNode *parent)
721{
722 onParentChanged(m_commitedParent, parent, positionPreferenceFromWindowFlags(window()->flags()));
723 m_commitedParent = parent;
724}
725
726// Returns whether the window takes part in browser Tab navigation. Only
727// top-level windows which accept focus do: child windows are reached through
728// the Qt focus chain of their parent window, and popups, tool tips, splash
729// screens and Qt::WindowDoesNotAcceptFocus windows are not tab stops on
730// other platforms either.
731bool QWasmWindow::isBrowserTabNavigable() const
732{
733 if (!window()->isTopLevel() || m_flags.testFlag(Qt::WindowDoesNotAcceptFocus))
734 return false;
735 switch (m_flags & Qt::WindowType_Mask) {
736 case Qt::Popup:
737 case Qt::ToolTip:
738 case Qt::SplashScreen:
739 return false;
740 default:
741 return true;
742 }
743}
744
745// Sets whether the window is a browser Tab stop reachable by tab navigation.
746// Windows which do not take part in browser Tab navigation are never Tab stops.
747void QWasmWindow::setBrowserTabStop(bool isTabStop)
748{
749 // The native element is owned by user code, which also manages its tabindex
750 if (m_hasNativeHandle)
751 return;
752 if (!isBrowserTabNavigable()) {
753 m_window.call<void>("removeAttribute", std::string("tabindex"));
754 return;
755 }
756 m_window.set("tabIndex", isTabStop ? 0 : -1);
757}
758
759// Handles Tab and Backtab keys: Qt moves focus between its own tab stops, and
760// past the first or last one focus is released to the browser, whose
761// default action then moves it to the next or previous element of the page.
762// Returns false for other keys.
763bool QWasmWindow::handleTabKey(const KeyEvent &event)
764{
765 if (event.key != Qt::Key_Tab && event.key != Qt::Key_Backtab)
766 return false;
767
768 // Qt reports focus chain wrapping to the top-level window (see
769 // windowEvent()), also when the Tab key is handled by a child window:
770 // a Qt Quick child window passes focus on to its parent window when
771 // it has no next tab stop.
772 QWasmWindow *topLevel = this;
773 while (topLevel->parent())
774 topLevel = static_cast<QWasmWindow *>(topLevel->parent());
775
776 topLevel->m_handlingTabKey = true;
777 const bool accepted = processKey(event);
778 topLevel->m_handlingTabKey = false;
779 const bool wrapped = std::exchange(topLevel->m_focusChainWrapped, false);
780
781 if (accepted && !wrapped) {
782 // Qt moved focus; keep the browser from moving it as well
783 event.webEvent.call<void>("preventDefault");
784 event.webEvent.call<void>("stopPropagation");
785 } else if (accepted) {
786 // The user tabbed past all of Qt's tab stops. Release focus to the
787 // browser, and keep parent windows from processing the key again.
788 topLevel->setBrowserTabStop(false);
789 event.webEvent.call<void>("stopPropagation");
790 } else if (event.type == EventType::KeyDown && isBrowserTabNavigable()) {
791 // Qt has no tab stop in this direction
792 setBrowserTabStop(false);
793 }
794 // A Tab key not accepted by a child window propagates to the parent window
795 return true;
796}
797
798// Returns Tab or Backtab focus reason if focus moved to target by keyboard
799// navigation from relatedTarget, else ActiveWindowFocusReason.
800Qt::FocusReason QWasmWindow::tabFocusReason(emscripten::val target, emscripten::val relatedTarget)
801{
802 if (relatedTarget.isNull() || relatedTarget.isUndefined())
803 return Qt::ActiveWindowFocusReason;
804
805 // The browser shows a focus indicator (:focus-visible) for focus moved by
806 // the keyboard, but not for focus moved by e.g. a mouse click.
807 if (!target.call<bool>("matches", std::string(":focus-visible")))
808 return Qt::ActiveWindowFocusReason;
809
810 // Focus moved forward if relatedTarget comes before target in the document.
811 // compareDocumentPosition() only compares nodes of the same tree, so compare
812 // with the shadow host of target which is in the tree of relatedTarget.
813 const emscripten::val relatedRoot = relatedTarget.call<emscripten::val>("getRootNode");
814 emscripten::val node = target;
815 while (!node.call<emscripten::val>("getRootNode").strictlyEquals(relatedRoot)) {
816 node = node.call<emscripten::val>("getRootNode")["host"];
817 if (node.isNull() || node.isUndefined())
818 return Qt::ActiveWindowFocusReason;
819 }
820 constexpr int DocumentPositionPreceding = 0x02;
821 constexpr int DocumentPositionFollowing = 0x04;
822 const int position = node.call<int>("compareDocumentPosition", relatedTarget);
823 if (position & DocumentPositionPreceding)
824 return Qt::TabFocusReason;
825 if (position & DocumentPositionFollowing)
826 return Qt::BacktabFocusReason;
827 return Qt::ActiveWindowFocusReason;
828}
829
830void QWasmWindow::handleKeyEvent(const KeyEvent &event)
831{
832 qCDebug(qLcQpaWasmInputContext) << "handleKeyEvent";
833
834 if (QWasmInputContext *inputContext = activeWasmInputContext()) {
835 // Don't send Qt key events that are part of input composition; let the
836 // input event handler deal with those (keyCode 229 / isComposing).
837 if (event.isComposing || event.keyCode == 229)
838 return;
839 if (!handleTabKey(event) && processKey(event)) {
840 // The key is already handled in Qt; flag the following input event
841 // so it is ignored by inputCallback (it still reaches it, to keep
842 // word suggestions working) instead of inserting the text twice.
843 inputContext->m_ignoreNextInput = true;
844 }
845 event.webEvent.call<void>("stopImmediatePropagation");
846 } else {
847 if (!handleTabKey(event) && processKey(event)) {
848 event.webEvent.call<void>("preventDefault");
849 event.webEvent.call<void>("stopPropagation");
850 }
851 }
852}
853
854bool QWasmWindow::processKey(const KeyEvent &event)
855{
856 constexpr bool ProceedToNativeEvent = false;
857 Q_ASSERT(event.type == EventType::KeyDown || event.type == EventType::KeyUp);
858
859 // Copy/cut/paste shortcuts are partly serviced by the browser's native
860 // clipboard, which decides whether the event should be handed to the
861 // browser instead of (or in addition to) sending the Qt key event.
862#if QT_CONFIG(clipboard)
863 const auto clipboardResult =
864 QWasmIntegration::get()->getWasmClipboard()->processKeyboard(event);
865
866 using ProcessKeyboardResult = QWasmClipboard::ProcessKeyboardResult;
867 if (clipboardResult == ProcessKeyboardResult::NativeClipboardEventNeeded)
868 return ProceedToNativeEvent;
869#endif
870
871 const auto result = QWindowSystemInterface::handleKeyEvent(
872 0, event.type == EventType::KeyDown ? QEvent::KeyPress : QEvent::KeyRelease, event.key,
873 event.modifiers, event.text, event.autoRepeat);
874
875#if QT_CONFIG(clipboard)
876 if (clipboardResult == ProcessKeyboardResult::NativeClipboardEventAndCopiedDataNeeded)
877 return ProceedToNativeEvent;
878#endif
879
880 return result;
881}
882
883void QWasmWindow::handleInputEvent(emscripten::val event)
884{
885 if (QWasmInputContext *inputContext = activeWasmInputContext())
886 inputContext->inputCallback(event);
887 else
888 m_focusHelper.set("innerHTML", std::string());
889}
890
891void QWasmWindow::handleCompositionStartEvent(emscripten::val event)
892{
893 if (QWasmInputContext *inputContext = activeWasmInputContext())
894 inputContext->compositionStartCallback(event);
895 else
896 m_focusHelper.set("innerHTML", std::string());
897}
898
899void QWasmWindow::handleCompositionUpdateEvent(emscripten::val event)
900{
901 if (QWasmInputContext *inputContext = activeWasmInputContext())
902 inputContext->compositionUpdateCallback(event);
903 else
904 m_focusHelper.set("innerHTML", std::string());
905}
906
907void QWasmWindow::handleCompositionEndEvent(emscripten::val event)
908{
909 if (QWasmInputContext *inputContext = activeWasmInputContext())
910 inputContext->compositionEndCallback(event);
911 else
912 m_focusHelper.set("innerHTML", std::string());
913}
914
915void QWasmWindow::handleBeforeInputEvent(emscripten::val event)
916{
917 if (QWasmInputContext *inputContext = activeWasmInputContext())
918 inputContext->beforeInputCallback(event);
919 else
920 m_focusHelper.set("innerHTML", std::string());
921}
922
923// Returns whether target belongs to this window, and not to one of its child
924// windows. The html elements of child windows are nested in the element of
925// the parent window, and their focus events bubble up to the parent window.
926bool QWasmWindow::isOwnEventTarget(emscripten::val target) const
927{
928 return target.call<emscripten::val>("closest", std::string(".qt-window"))
929 .strictlyEquals(m_window);
930}
931
932void QWasmWindow::handleFocusinEvent(emscripten::val event)
933{
934 // Focus moved to a child window, which handles the event itself
935 if (!isOwnEventTarget(event["target"]))
936 return;
937
938 // Determine if the focus moved from outside the html tree for the window
939 emscripten::val relatedTarget = event["relatedTarget"];
940 bool enteringWindow = relatedTarget.isNull() || relatedTarget.isUndefined()
941 || !m_window.call<bool>("contains", relatedTarget);
942
943 // Tab or Backtab if focus arrived from outside by browser keyboard
944 // navigation. Child windows are not browser Tab stops: Qt moves focus
945 // to them and has already picked the focus target within the window.
946 const Qt::FocusReason reason = enteringWindow && isBrowserTabNavigable()
947 ? tabFocusReason(event["target"], relatedTarget)
948 : Qt::ActiveWindowFocusReason;
949
950 // When focus moves internally (e.g. to the focus-helper element), and this
951 // window is already the focus window, skip re-notifying Qt. This preserves
952 // the original focus reason (e.g. TabFocusReason) which widgets use to
953 // decide whether to show focus rectangles.
954 if (!enteringWindow && QGuiApplication::focusWindow() == window())
955 return;
956
957 setAsActiveNode();
958 QWindowSystemInterface::handleFocusWindowChanged(window(), reason);
959}
960
961void QWasmWindow::handleFocusoutEvent(emscripten::val event)
962{
963 // Determine if focus now has moved outside of this window's html element tree.
964 emscripten::val relatedTarget = event["relatedTarget"];
965 bool leavingWindow = relatedTarget.isNull() || relatedTarget.isUndefined()
966 || !m_window.call<bool>("contains", relatedTarget);
967 if (!leavingWindow)
968 return;
969
970 // A browser Tab stop again, for the next Tab-in. Also when focus left
971 // from a child window, e.g. by Tab past the last tab stop of the child.
972 setBrowserTabStop(true);
973
974 // Send FocusWindowChanged (with null window), unless focus moved from a
975 // child window, which handles the event itself.
976 if (isOwnEventTarget(event["target"]))
977 QWindowSystemInterface::handleFocusWindowChanged(nullptr, Qt::ActiveWindowFocusReason);
978}
979
980void QWasmWindow::handlePointerEnterLeaveEvent(const PointerEvent &event)
981{
982 if (processPointerEnterLeave(event))
983 event.webEvent.call<void>("preventDefault");
984}
985
986bool QWasmWindow::processPointerEnterLeave(const PointerEvent &event)
987{
989 return false;
990
991 switch (event.type) {
993 const auto pointInScreen = platformScreen()->mapFromLocal(
994 dom::mapPoint(event.target(), platformScreen()->element(), event.localPoint));
995 QWindowSystemInterface::handleEnterEvent(
996 window(), mapFromGlobal(pointInScreen.toPoint()), pointInScreen);
997 break;
998 }
1001 break;
1002 default:
1003 break;
1004 }
1005
1006 return false;
1007}
1008
1009void QWasmWindow::releasePointerGrab(const MouseEvent &event)
1010{
1011 // We check hasPointerCapture due to the implicit release
1012 // browsers do.
1013 if (m_capturedPointerId && event.isTargetedForElement(m_window) &&
1014 m_window.call<bool>("hasPointerCapture", *m_capturedPointerId)) {
1015 m_window.call<void>("releasePointerCapture", *m_capturedPointerId);
1016 m_capturedPointerId = std::nullopt;
1017 }
1018}
1019
1020void QWasmWindow::processPointer(const PointerEvent &event)
1021{
1022 // Process pointer events targeted at the window only, and not
1023 // for instance events for the accessibility elements.
1024 if (!event.isTargetedForElement(m_window))
1025 return;
1026
1027 switch (event.type) {
1028 case EventType::PointerDown:
1029 m_capturedPointerId = event.pointerId;
1030 m_window.call<void>("setPointerCapture", event.pointerId);
1031
1032 // Activate (focus) the top-level window for this window on click
1033 if (!window()->flags().testFlag(Qt::WindowDoesNotAcceptFocus)
1034 && QGuiApplication::focusWindow() != window()) {
1035 QWindow *win = window();
1036 while (!win->isTopLevel())
1037 win = win->parent(QWindow::ExcludeTransients);
1038 win->requestActivate();
1039 }
1040
1041 // Prevent the browser's default focus handling from
1042 // moving focus away from the focus helper element.
1043 event.webEvent.call<void>("preventDefault");
1044
1045 break;
1047 releasePointerGrab(event);
1048 break;
1049 default:
1050 break;
1051 };
1052
1053 const bool eventAccepted = deliverPointerEvent(event);
1054 if (!eventAccepted && event.type == EventType::PointerDown)
1055 QGuiApplicationPrivate::instance()->closeAllPopups();
1056
1057 if (eventAccepted) {
1058 event.webEvent.call<void>("preventDefault");
1059 event.webEvent.call<void>("stopPropagation");
1060 }
1061}
1062
1063bool QWasmWindow::deliverPointerEvent(const PointerEvent &event)
1064{
1065 const auto pointInScreen = platformScreen()->mapFromLocal(
1066 dom::mapPoint(event.target(), platformScreen()->element(), event.localPoint));
1067
1068 const auto geometryF = platformScreen()->geometry().toRectF();
1069 const QPointF targetPointClippedToScreen(
1070 qBound(geometryF.left(), pointInScreen.x(), geometryF.right()),
1071 qBound(geometryF.top(), pointInScreen.y(), geometryF.bottom()));
1072
1073 if (event.pointerType == PointerType::Mouse) {
1074 const QEvent::Type eventType =
1075 MouseEvent::mouseEventTypeFromEventType(event.type, WindowArea::Client);
1076
1077 return eventType != QEvent::None
1078 && QWindowSystemInterface::handleMouseEvent(
1079 window(), QWasmIntegration::getTimestamp(),
1080 window()->mapFromGlobal(targetPointClippedToScreen),
1081 targetPointClippedToScreen, event.mouseButtons, event.mouseButton,
1082 eventType, event.modifiers);
1083 }
1084
1085 if (event.pointerType == PointerType::Pen) {
1086 qreal pressure;
1087 switch (event.type) {
1090 pressure = event.pressure;
1091 break;
1093 pressure = 0.0;
1094 break;
1095 default:
1096 return false;
1097 }
1098 // Tilt in the browser is in the range +-90, but QTabletEvent only goes to +-60.
1099 qreal xTilt = qBound(-60.0, event.tiltX, 60.0);
1100 qreal yTilt = qBound(-60.0, event.tiltY, 60.0);
1101 // Barrel rotation is reported as 0 to 359, but QTabletEvent wants a signed value.
1102 qreal rotation = event.twist > 180.0 ? 360.0 - event.twist : event.twist;
1103 return QWindowSystemInterface::handleTabletEvent(
1104 window(), QWasmIntegration::getTimestamp(), platformScreen()->tabletDevice(),
1105 window()->mapFromGlobal(targetPointClippedToScreen),
1106 targetPointClippedToScreen, event.mouseButtons, pressure, xTilt, yTilt,
1107 event.tangentialPressure, rotation, event.modifiers);
1108 }
1109
1110 QWindowSystemInterface::TouchPoint *touchPoint;
1111
1112 QPointF pointInTargetWindowCoords =
1113 QPointF(window()->mapFromGlobal(targetPointClippedToScreen));
1114 QPointF normalPosition(pointInTargetWindowCoords.x() / window()->width(),
1115 pointInTargetWindowCoords.y() / window()->height());
1116
1117 const auto tp = m_pointerIdToTouchPoints.find(event.pointerId);
1118 if (event.pointerType != PointerType::Pen && tp != m_pointerIdToTouchPoints.end()) {
1119 touchPoint = &tp.value();
1120 } else {
1121 touchPoint = &m_pointerIdToTouchPoints
1122 .insert(event.pointerId, QWindowSystemInterface::TouchPoint())
1123 .value();
1124
1125 // Assign touch point id. TouchPoint::id is int, but QGuiApplicationPrivate::processTouchEvent()
1126 // will not synthesize mouse events for touch points with negative id; use the absolute value for
1127 // the touch point id.
1128 touchPoint->id = qAbs(event.pointerId);
1129
1130 touchPoint->state = QEventPoint::State::Pressed;
1131 }
1132
1133 const bool stationaryTouchPoint = (normalPosition == touchPoint->normalPosition);
1134 touchPoint->normalPosition = normalPosition;
1135 touchPoint->area = QRectF(targetPointClippedToScreen, QSizeF(event.width, event.height))
1136 .translated(-event.width / 2, -event.height / 2);
1137 touchPoint->pressure = event.pressure;
1138
1139 switch (event.type) {
1141 touchPoint->state = QEventPoint::State::Released;
1142 break;
1144 touchPoint->state = (stationaryTouchPoint ? QEventPoint::State::Stationary
1145 : QEventPoint::State::Updated);
1146 break;
1147 default:
1148 break;
1149 }
1150
1151 QList<QWindowSystemInterface::TouchPoint> touchPointList;
1152 touchPointList.reserve(m_pointerIdToTouchPoints.size());
1153 std::transform(m_pointerIdToTouchPoints.begin(), m_pointerIdToTouchPoints.end(),
1154 std::back_inserter(touchPointList),
1155 [](const QWindowSystemInterface::TouchPoint &val) { return val; });
1156
1157 if (event.type == EventType::PointerUp || event.type == EventType::PointerCancel)
1158 m_pointerIdToTouchPoints.remove(event.pointerId);
1159
1160 return event.type == EventType::PointerCancel
1161 ? QWindowSystemInterface::handleTouchCancelEvent(
1162 window(), QWasmIntegration::getTimestamp(), platformScreen()->touchDevice(),
1163 event.modifiers)
1164 : QWindowSystemInterface::handleTouchEvent(
1165 window(), QWasmIntegration::getTimestamp(), platformScreen()->touchDevice(),
1166 touchPointList, event.modifiers);
1167}
1168
1169void QWasmWindow::handleWheelEvent(const emscripten::val &event)
1170{
1171 if (processWheel(WheelEvent(EventType::Wheel, event)))
1172 event.call<void>("preventDefault");
1173}
1174
1175bool QWasmWindow::processWheel(const WheelEvent &event)
1176{
1177 // Web scroll deltas are inverted from Qt deltas - negate.
1178 const int scrollFactor = -([&event]() {
1179 switch (event.deltaMode) {
1180 case DeltaMode::Pixel:
1181 return 1;
1182 case DeltaMode::Line:
1183 return 12;
1184 case DeltaMode::Page:
1185 return 20;
1186 };
1187 })();
1188
1189 const auto pointInScreen = platformScreen()->mapFromLocal(
1190 dom::mapPoint(event.target(), platformScreen()->element(), event.localPoint));
1191
1192 return QWindowSystemInterface::handleWheelEvent(
1193 window(), QWasmIntegration::getTimestamp(), window()->mapFromGlobal(pointInScreen),
1194 pointInScreen, (event.delta * scrollFactor).toPoint(),
1195 (event.delta * scrollFactor).toPoint(), event.modifiers, Qt::NoScrollPhase,
1196 Qt::MouseEventNotSynthesized, event.webkitDirectionInvertedFromDevice);
1197}
1198
1199// Fix top level window flags in case only the type flags are passed.
1200Qt::WindowFlags QWasmWindow::fixTopLevelWindowFlags(Qt::WindowFlags flags) const
1201{
1202 if (!(flags.testFlag(Qt::CustomizeWindowHint))) {
1203 if (flags.testFlag(Qt::Window)) {
1204 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint
1205 |Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint;
1206 }
1207 if (flags.testFlag(Qt::Dialog) || flags.testFlag(Qt::Tool))
1208 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1209
1210 if ((flags & Qt::WindowType_Mask) == Qt::SplashScreen)
1211 flags |= Qt::FramelessWindowHint;
1212 }
1213 return flags;
1214}
1215
1216bool QWasmWindow::shouldBeAboveTransientParentFlags(Qt::WindowFlags flags) const
1217{
1218 if (!transientParent())
1219 return false;
1220
1221 if (isModal())
1222 return true;
1223
1224 if (flags.testFlag(Qt::Tool) ||
1225 flags.testFlag(Qt::SplashScreen) ||
1226 flags.testFlag(Qt::ToolTip) ||
1227 flags.testFlag(Qt::Popup))
1228 {
1229 return true;
1230 }
1231
1232 return false;
1233}
1234
1235QWasmWindowStack<>::PositionPreference QWasmWindow::positionPreferenceFromWindowFlags(Qt::WindowFlags flags) const
1236{
1237 flags = fixTopLevelWindowFlags(flags);
1238
1239 if (flags.testFlag(Qt::WindowStaysOnTopHint))
1240 return QWasmWindowStack<>::PositionPreference::StayOnTop;
1241 if (flags.testFlag(Qt::WindowStaysOnBottomHint))
1242 return QWasmWindowStack<>::PositionPreference::StayOnBottom;
1243 if (shouldBeAboveTransientParentFlags(flags))
1244 return QWasmWindowStack<>::PositionPreference::StayAboveTransientParent;
1245 return QWasmWindowStack<>::PositionPreference::Regular;
1246}
1247
1248// Returns the wasm input context if it exists and is active, otherwise nullptr.
1249QWasmInputContext *QWasmWindow::activeWasmInputContext() const
1250{
1251 // The input context is switched off while accessibility is enabled. Its key
1252 // path does not prevent the browser default, so Tab in a text field moved
1253 // focus in the browser on top of the move Qt had just made.
1254 if (QWasmAccessibility::isEnabled())
1255 return nullptr;
1256 QWasmInputContext *inputContext = QWasmIntegration::get()->wasmInputContext();
1257 return inputContext && inputContext->isActive() ? inputContext : nullptr;
1258}
1259
1261{
1262 return m_normalGeometry;
1263}
1264
1266{
1267 return screen()->devicePixelRatio();
1268}
1269
1271{
1272 m_compositor->requestUpdateWindow(this, QRect(QPoint(0, 0), geometry().size()), QWasmCompositor::UpdateRequestDelivery);
1273}
1274
1275bool QWasmWindow::hasFrame() const
1276{
1277 return !m_flags.testFlag(Qt::FramelessWindowHint);
1278}
1279
1280bool QWasmWindow::hasBorder() const
1281{
1282 return hasFrame() && !m_state.testFlag(Qt::WindowFullScreen) && !m_flags.testFlag(Qt::SubWindow)
1283 && !windowIsPopupType(m_flags) && !parent();
1284}
1285
1286bool QWasmWindow::hasTitleBar() const
1287{
1288 return hasBorder() && m_flags.testFlag(Qt::WindowTitleHint);
1289}
1290
1291bool QWasmWindow::hasShadow() const
1292{
1293 return hasBorder() && !m_flags.testFlag(Qt::NoDropShadowWindowHint);
1294}
1295
1296bool QWasmWindow::hasMaximizeButton() const
1297{
1298 return !m_state.testFlag(Qt::WindowMaximized) && m_flags.testFlag(Qt::WindowMaximizeButtonHint);
1299}
1300
1301bool QWasmWindow::windowIsPopupType(Qt::WindowFlags flags) const
1302{
1303 if (flags.testFlag(Qt::Tool))
1304 return false; // Qt::Tool has the Popup bit set but isn't an actual Popup window
1305
1306 return (flags.testFlag(Qt::Popup));
1307}
1308
1310{
1311 QWindow *modalWindow;
1312 if (QGuiApplicationPrivate::instance()->isWindowBlocked(window(), &modalWindow)) {
1313 static_cast<QWasmWindow *>(modalWindow->handle())->requestActivateWindow();
1314 return;
1315 }
1316
1317 raise();
1318 focus();
1319
1320 // Don't call base class requestActivateWindow() or send a focus
1321 // changed event here; that is done in the focusin event handler
1322 // when native focus actually moves.
1323}
1324
1325// Moves native focus to this window, via the foucus helper or the input element.
1327{
1328 // Ask Qt for the focus object while accessibility is enabled. The application
1329 // focus object may still belong to the window that focus is leaving, so use
1330 // the one of this window.
1331 if (QWasmAccessibility::isEnabled()) {
1332 if (QWasmAccessibility::setFocusObject(window()->focusObject()))
1333 return;
1334 // The focus object may have no element that can take the focus, a tab bar
1335 // for instance. The input context calls this for every focus change, also
1336 // for the ones the browser made, so keep a focus that is already here.
1337 if (m_window.call<bool>("matches", std::string(":focus-within")))
1338 return;
1339 // Bring the focus into the window so that it activates. The container is
1340 // not hidden from assistive technology, unlike the focus helper.
1341 m_a11yElementContainer.call<void>("focus");
1342 return;
1343 }
1344
1345 emscripten::val &element = target == InputFocus ? m_inputElement : m_focusHelper;
1346 element.call<void>("focus");
1347}
1348
1350{
1351 m_focusHelper.call<void>("setAttribute", std::string("aria-hidden"), std::string("true"));
1352 m_inputElement.call<void>("setAttribute", std::string("aria-hidden"), std::string("true"));
1353
1354 // The container takes the focus when no element of the window can, so the
1355 // window still activates. A negative tabindex keeps it out of the tab order.
1356 m_a11yElementContainer.call<void>("setAttribute", std::string("tabindex"), std::string("-1"));
1357}
1358
1360{
1361 Q_UNUSED(grab);
1362 return false;
1363}
1364
1365bool QWasmWindow::windowEvent(QEvent *event)
1366{
1367 switch (event->type()) {
1368 case QEvent::WindowBlocked:
1369 m_decoratedWindow["classList"].call<void>("add", emscripten::val("blocked"));
1370 // A blocked window is outside the Qt focus chain, inert keeps the browser
1371 // from tabbing into its accessibility elements.
1372 m_decoratedWindow.call<void>("setAttribute", std::string("inert"), std::string(""));
1373 return false; // Propagate further
1374 case QEvent::WindowUnblocked:;
1375 m_decoratedWindow["classList"].call<void>("remove", emscripten::val("blocked"));
1376 m_decoratedWindow.call<void>("removeAttribute", std::string("inert"));
1377 return false; // Propagate further
1378 case QEvent::FocusIn: {
1379 auto *focusEvent = static_cast<QFocusEvent *>(event);
1380 if (focusEvent->reason() == Qt::TabFocusReason
1381 || focusEvent->reason() == Qt::BacktabFocusReason) {
1382 // The focus chain has wrapped: Qt is trying to focus the platform
1383 // window itself, meaning the user has tabbed past all internal
1384 // tab stops. Set a flag so the key handler can release focus to
1385 // the browser. Let Qt wrap the focus chain if there is no Tab key
1386 // to release focus with, e.g. for QWidget::focusNextPrevChild()
1387 // called by the application.
1388 if (!m_handlingTabKey)
1389 return QPlatformWindow::windowEvent(event);
1390 m_focusChainWrapped = true;
1391 event->accept();
1392 return true;
1393 }
1394 return QPlatformWindow::windowEvent(event);
1395 }
1396 default:
1397 return QPlatformWindow::windowEvent(event);
1398 }
1399}
1400
1401void QWasmWindow::setMask(const QRegion &region)
1402{
1403 if (region.isEmpty()) {
1404 m_decoratedWindow["style"].set("clipPath", emscripten::val(""));
1405 return;
1406 }
1407
1408 std::ostringstream cssClipPath;
1409 cssClipPath << "path('";
1410 for (const auto &rect : region) {
1411 const auto cssRect = rect.adjusted(0, 0, 1, 1);
1412 cssClipPath << "M " << cssRect.left() << " " << cssRect.top() << " ";
1413 cssClipPath << "L " << cssRect.right() << " " << cssRect.top() << " ";
1414 cssClipPath << "L " << cssRect.right() << " " << cssRect.bottom() << " ";
1415 cssClipPath << "L " << cssRect.left() << " " << cssRect.bottom() << " z ";
1416 }
1417 cssClipPath << "')";
1418 m_decoratedWindow["style"].set("clipPath", emscripten::val(cssClipPath.str()));
1419}
1420
1421void QWasmWindow::onTransientParentChanged(QWindow *newTransientParent)
1422{
1423 Q_UNUSED(newTransientParent);
1424
1425 const auto positionPreference = positionPreferenceFromWindowFlags(window()->flags());
1426 QWasmWindowTreeNode::onParentChanged(parentNode(), nullptr, positionPreference);
1427 QWasmWindowTreeNode::onParentChanged(nullptr, parentNode(), positionPreference);
1428}
1429
1431{
1432 const auto positionPreference = positionPreferenceFromWindowFlags(window()->flags());
1433 QWasmWindowTreeNode::onParentChanged(parentNode(), nullptr, positionPreference);
1434 QWasmWindowTreeNode::onParentChanged(nullptr, parentNode(), positionPreference);
1435}
1436
1437void QWasmWindow::setParent(const QPlatformWindow *)
1438{
1439 // The window flags depend on whether we are a
1440 // child window or not, so update them here.
1441 setWindowFlags(window()->flags());
1442
1443 commitParent(parentNode());
1444}
1445
1447{
1448 return "!qtwindow" + std::to_string(m_winId);
1449}
1450
1452{
1453 return m_window;
1454}
1455
1457{
1458 if (parent())
1459 return static_cast<QWasmWindow *>(parent());
1460 return platformScreen();
1461}
1462
1464{
1465 return this;
1466}
1467
1468void QWasmWindow::onParentChanged(QWasmWindowTreeNode *previous, QWasmWindowTreeNode *current,
1469 QWasmWindowStack<>::PositionPreference positionPreference)
1470{
1471 if (previous)
1472 previous->containerElement().call<void>("removeChild", m_decoratedWindow);
1473 if (current)
1474 current->containerElement().call<void>("appendChild", m_decoratedWindow);
1475 QWasmWindowTreeNode::onParentChanged(previous, current, positionPreference);
1476
1477 QWasmScreen *screen = platformScreen();
1478 if (previous)
1479 m_compositor->onWindowRemoved(this);
1480 if (current) {
1481 m_compositor->onWindowAdded(this);
1482
1483 // The first top-level window inserted as maximized/fullscreen stays on bottom.
1484 const auto state = window()->windowState();
1485 const bool isMaxFull = state & (Qt::WindowMaximized | Qt::WindowFullScreen);
1486 if (current == screen && screen->topLevelWindowCount() == 1 && isMaxFull)
1487 window()->setFlag(Qt::WindowStaysOnBottomHint);
1488 }
1489}
1490
1491QT_END_NAMESPACE
QRect window() const
Returns the window rectangle.
void onWindowAdded(QWasmWindow *window)
void onWindowRemoved(QWasmWindow *window)
QWasmCompositor(QWasmScreen *screen)
static QWasmIntegration * get()
QWasmInputContext * wasmInputContext() const
static void destroyWebGLContext(QPlatformSurface *surface)
emscripten::val element() const
void updateQScreenSize()
QRect geometry() const override
Reimplement in subclass to return the pixel geometry of the screen.
void setVisible(bool visible) override
Reimplemented in subclasses to show the surface if visible is true, and hide it if visible is false.
qreal devicePixelRatio() const override
Reimplement this function in subclass to return the device pixel ratio for the window.
QRect normalGeometry() const override
Returns the geometry of a window in 'normal' state (neither maximized, fullscreen nor minimized) for ...
void focus(FocusTarget target=WindowFocus)
QSurfaceFormat format() const override
Returns the actual surface format of the window.
void setParent(const QPlatformWindow *window) final
This function is called to enable native child window in QPA.
static QWasmWindow * fromWindow(const QWindow *window)
void raise() override
Reimplement to be able to let Qt raise windows to the top of the desktop.
void setWindowTitle(const QString &title) override
Reimplement to set the window title to title.
void requestActivateWindow() override
Reimplement to let Qt be able to request activation/focus for a window.
WId winId() const override
Reimplement in subclasses to return a handle to the native window.
static emscripten::val focusedWindowInputElement()
void onToggleMaximized()
std::string canvasSelector() const
static QWasmWindow * focusWindow()
QWasmWindow(QWindow *w, QWasmCompositor *compositor, QWasmBackingStore *backingStore, WId nativeHandle)
friend class QWasmCompositor
void onNonClientAreaInteraction()
void setGeometry(const QRect &) override
This function is called by Qt whenever a window is moved or resized using the QWindow API.
bool setMouseGrabEnabled(bool grab) final
bool onNonClientEvent(const PointerEvent &event)
void setWindowCursor(QByteArray cssCursorName)
void setZOrder(int order)
void setMask(const QRegion &region) final
Reimplement to be able to let Qt set the mask of a window.
QWasmWindow * transientParent() const
QWasmWindowTreeNode * parentNode() final
void onModalityChanged()
void initialize() override
Called as part of QWindow::create(), after constructing the window.
bool isModal() const
Qt::WindowFlags windowFlags() const
bool isVisible() const
void registerEventHandlers()
~QWasmWindow() final
void onMaximizeClicked()
void requestUpdate() override
Requests an QEvent::UpdateRequest event.
void lower() override
Reimplement to be able to let Qt lower windows to the bottom of the desktop.
void onParentChanged(QWasmWindowTreeNode *previous, QWasmWindowTreeNode *current, QWasmWindowStack<>::PositionPreference positionPreference) final
void onRestoreClicked()
void setOpacity(qreal level) override
Reimplement to be able to let Qt set the opacity level of a window.
void onActivationChanged(bool active)
void onAccessibilityEnable()
void setWindowState(Qt::WindowStates state) override
Requests setting the window state of this surface to type.
void setWindowIcon(const QIcon &icon) override
Reimplement to set the window icon to icon.
void propagateSizeHints() override
Reimplement to propagate the size hints of the QWindow.
QMargins frameMargins() const override
void onCloseClicked()
QWasmWindow * asWasmWindow() final
bool windowEvent(QEvent *event) final
Reimplement this method to be able to do any platform specific event handling.
QWasmScreen * platformScreen() const
emscripten::val containerElement() final
void setWindowFlags(Qt::WindowFlags flags) override
Requests setting the window flags of this surface to flags.
Definition qwasmdom.h:30
Q_GUI_EXPORT int qt_defaultDpiX()
Definition qfont.cpp:134
QDebug Q_GUI_EXPORT & operator<<(QDebug &s, const QVectorPath &path)
DeltaMode
Definition qwasmevent.h:53
PointerType
Definition qwasmevent.h:41
EventType
Definition qwasmevent.h:23
WindowArea
Definition qwasmevent.h:48
bool isTargetedForElement(emscripten::val element) const
int keyCode
Definition qwasmevent.h:78
bool isComposing
Definition qwasmevent.h:77
PointerType pointerType
Definition qwasmevent.h:132
DeltaMode deltaMode
Definition qwasmevent.h:161