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>
18#if QT_CONFIG(clipboard)
19#include "qwasmclipboard.h"
30#if QT_CONFIG(draganddrop)
39#include <emscripten/val.h>
41#include <QtCore/private/qstdweb_p.h>
51 m_compositor(compositor),
52 m_backingStore(backingStore),
64 m_decoratedWindow.set(
"className",
"qt-decorated-window");
65 m_decoratedWindow[
"style"].set(
"display", std::string(
"none"));
67 m_nonClientArea = std::make_unique<NonClientArea>(
this, m_decoratedWindow);
68 m_nonClientArea->titleBar()->setTitle(window()->title());
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);
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);
91 m_canvas[
"classList"].call<
void>(
"add", emscripten::val(
"qt-window-canvas"));
93#if QT_CONFIG(clipboard)
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);
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);
115 m_window.call<
void>(
"appendChild", m_focusHelper);
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);
131 m_window.call<
void>(
"appendChild", m_inputElement);
134 m_canvas.call<
void>(
"setAttribute", std::string(
"aria-hidden"), std::string(
"true"));
135 m_canvas[
"style"].set(
"pointerEvents",
"none");
137 m_window.call<
void>(
"appendChild", m_canvas);
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);
148 if (QWasmAccessibility::isEnabled())
151 const bool rendersTo2dContext = w->surfaceType() != QSurface::OpenGLSurface;
152 if (rendersTo2dContext)
153 m_context2d = m_canvas.call<emscripten::val>(
"getContext", emscripten::val(
"2d"));
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);
159 m_flags = window()->flags();
163 m_transientWindowChangedConnection =
165 window(), &QWindow::transientParentChanged,
166 window(), [
this](QWindow *tp) { onTransientParentChanged(tp); });
168 m_modalityChangedConnection =
170 window(), &QWindow::modalityChanged,
171 window(), [
this](Qt::WindowModality) { onModalityChanged(); });
176 m_pointerDownCallback = QWasmEventHandler(m_window,
"pointerdown",
177 [
this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerDown, event)); }
179 m_pointerMoveCallback = QWasmEventHandler(m_window,
"pointermove",
180 [
this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerMove, event)); }
182 m_pointerUpCallback = QWasmEventHandler(m_window,
"pointerup",
183 [
this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerUp, event)); }
185 m_pointerCancelCallback = QWasmEventHandler(m_window,
"pointercancel",
186 [
this](emscripten::val event){ processPointer(PointerEvent(EventType::PointerCancel, event)); }
188 m_pointerEnterCallback = QWasmEventHandler(m_window,
"pointerenter",
189 [
this](emscripten::val event) {
this->handlePointerEnterLeaveEvent(PointerEvent(EventType::PointerEnter, event)); }
191 m_pointerLeaveCallback = QWasmEventHandler(m_window,
"pointerleave",
192 [
this](emscripten::val event) {
this->handlePointerEnterLeaveEvent(PointerEvent(EventType::PointerLeave, event)); }
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);
203 m_dragOverCallback = QWasmEventHandler(m_window,
"dragover",
204 [
this](emscripten::val event) {
205 DragEvent dragEvent(EventType::DragOver, event, window());
206 QWasmDrag::instance()->onNativeDragOver(&dragEvent);
209 m_dropCallback = QWasmEventHandler(m_window,
"drop",
210 [
this](emscripten::val event) {
211 DragEvent dragEvent(EventType::Drop, event, window());
212 QWasmDrag::instance()->onNativeDrop(&dragEvent);
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);
222 m_dragEnterCallback = QWasmEventHandler(m_window,
"dragenter",
223 [
this](emscripten::val event) {
224 DragEvent dragEvent(EventType::DragEnter, event, window());
225 QWasmDrag::instance()->onNativeDragEnter(&dragEvent);
228 m_dragLeaveCallback = QWasmEventHandler(m_window,
"dragleave",
229 [
this](emscripten::val event) {
230 DragEvent dragEvent(EventType::DragLeave, event, window());
231 QWasmDrag::instance()->onNativeDragLeave(&dragEvent);
236 m_wheelEventCallback = QWasmEventHandler(m_window,
"wheel",
237 [
this](emscripten::val event) {
this->handleWheelEvent(event); });
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)); });
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); });
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); });
265#if QT_CONFIG(accessibility)
266 QWasmAccessibility::onRemoveWindow(window());
268 QObject::disconnect(m_transientWindowChangedConnection);
269 QObject::disconnect(m_modalityChangedConnection);
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);
285 (QGuiApplication::focusWindow() &&
286 QGuiApplication::focusWindow() != window()))
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});
299 if (getActiveIndex() > 0)
300 allWindows.insert({getActiveIndex(),
this});
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;
309 prevW->requestActivateWindow();
315 return window()->requestedFormat();
320 if (!window ||!window->handle())
322 return static_cast<
QWasmWindow *>(window->handle());
327 return fromWindow(QGuiApplication::focusWindow());
333 return window ? window->inputElement() : emscripten::val::null();
346 return window()->flags();
351 return window()->isModal();
356 window()->setWindowState(Qt::WindowNoState);
361 window()->setWindowState(Qt::WindowMaximized);
366 window()->setWindowState(m_state.testFlag(Qt::WindowMaximized) ? Qt::WindowNoState
367 : Qt::WindowMaximized);
378 QGuiApplicationPrivate::instance()->closeAllPopups();
385 return QWindowSystemInterface::handleMouseEvent(
386 window(), QWasmIntegration::getTimestamp(), window()->mapFromGlobal(pointInScreen),
387 pointInScreen, event.mouseButtons, event.mouseButton,
388 MouseEvent::mouseEventTypeFromEventType(event.type, WindowArea::NonClient),
398 auto initialGeometry = QPlatformWindow::initialGeometry(window(),
399 windowGeometry(), defaultWindowSize, defaultWindowSize);
400 m_normalGeometry = initialGeometry;
402 setWindowState(window()->windowStates());
403 setWindowFlags(window()->flags());
404 setWindowTitle(window()->title());
405 setMask(QHighDpi::toNativeLocalRegion(window()->mask(), window()));
407 if (window()->isTopLevel())
408 setWindowIcon(window()->icon());
409 QPlatformWindow::setGeometry(m_normalGeometry);
411#if QT_CONFIG(accessibility)
414 if (window()->isTopLevel())
415 QWasmAccessibility::addAccessibilityEnableButton(window());
421 return static_cast<
QWasmScreen *>(window()->screen()->handle());
426 if (!m_backingStore || !isVisible() || m_context2d.isUndefined())
429 auto image = m_backingStore->getUpdatedWebImage(
this);
430 if (image.isUndefined())
432 m_context2d.call<
void>(
"putImageData", image, emscripten::val(0), emscripten::val(0));
437 m_decoratedWindow[
"style"].set(
"zIndex", std::to_string(z));
442 m_window[
"style"].set(
"cursor", emscripten::val(cssCursorName.constData()));
447 const auto margins = frameMargins();
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());
455 auto offset = rect.topLeft() - (!parent() ? screen()->geometry().topLeft() : QPoint());
458 auto containerGeometryInViewport =
459 QRectF::fromDOMRect(parentNode()->containerElement().call<emscripten::val>(
460 "getBoundingClientRect"))
463 auto rectInViewport = QRect(containerGeometryInViewport.topLeft() + offset, rect.size());
465 QRect cappedGeometry(rectInViewport);
468 cappedGeometry.moveTop(
469 std::max(std::min(rectInViewport.y(), containerGeometryInViewport.bottom()),
470 containerGeometryInViewport.y() + margins.top()));
472 cappedGeometry.setSize(
473 cappedGeometry.size().expandedTo(windowMinimumSize()).boundedTo(windowMaximumSize()));
474 return QRect(QPoint(rect.x(), rect.y() + cappedGeometry.y() - rectInViewport.y()),
477 m_nonClientArea->onClientAreaWidthChange(clientAreaRect.width());
479 const auto frameRect =
481 .adjusted(-margins.left(), -margins.top(), margins.right(), margins.bottom())
482 .translated(!parent() ? -screen()->geometry().topLeft() : QPoint());
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");
492 m_window[
"style"].set(
"width", std::to_string(clientAreaRect.width()) +
"px");
493 m_window[
"style"].set(
"height", std::to_string(clientAreaRect.height()) +
"px");
495 QSizeF canvasSize = clientAreaRect.size() * devicePixelRatio();
497 m_canvas.set(
"width", canvasSize.width());
498 m_canvas.set(
"height", canvasSize.height());
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;
506 QWindowSystemInterface::handleGeometryChange(window(), clientAreaRect);
507 if (shouldInvalidate)
510 m_compositor->requestUpdateWindow(
this, QRect(QPoint(0, 0), geometry().size()));
516 const bool nowVisible = m_decoratedWindow[
"style"][
"display"].as<std::string>() ==
"block";
517 if (visible == nowVisible)
521 m_decoratedWindow[
"style"].set(
"display", visible ?
"block" :
"none");
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;
535 const bool hasFocus = window() == QGuiApplication::focusWindow();
541 const bool takeFocus = window()->isTopLevel();
543 if (!dontFocus && (hasFocus || takeFocus))
546 if (window()->isTopLevel())
553#if QT_CONFIG(accessibility)
554 QWasmAccessibility::onShowWindow(window());
561 return window()->isVisible();
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())
597 m_nonClientArea->propagateSizeHints();
602 m_decoratedWindow[
"style"].set(
"opacity", qBound(0.0, level, 1.0));
607 m_compositor->requestUpdateWindow(
this, QRect(QPoint(0, 0), geometry().size()));
612 dom::syncCSSClassWith(m_decoratedWindow,
"inactive", !active);
617 flags = fixTopLevelWindowFlags(flags);
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));
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));
638 m_nonClientArea->titleBar()->setMaximizeVisible(hasMaximizeButton());
639 m_nonClientArea->titleBar()->setCloseVisible(m_flags.testFlag(Qt::WindowCloseButtonHint));
642 setBrowserTabStop(
true);
649 newState &= Qt::WindowActive;
651 const Qt::WindowStates oldState = m_state;
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);
660 if (newState == oldState)
664 m_previousWindowState = oldState;
671 m_nonClientArea->titleBar()->setTitle(title);
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");
685 QBuffer buffer(&bytes);
686 pixmap.save(&buffer,
"png");
687 m_nonClientArea->titleBar()->setIcon(bytes.toBase64().toStdString(),
"png");
694 const bool isFullscreen = m_state.testFlag(Qt::WindowFullScreen);
695 const bool isMaximized = m_state.testFlag(Qt::WindowMaximized);
704 else if (isMaximized)
705 newGeom =
platformScreen()->availableGeometry().marginsRemoved(frameMargins());
709 dom::syncCSSClassWith(m_decoratedWindow,
"has-border", hasBorder());
710 dom::syncCSSClassWith(m_decoratedWindow,
"maximized", isMaximized);
712 m_nonClientArea->titleBar()->setRestoreVisible(isMaximized);
713 m_nonClientArea->titleBar()->setMaximizeVisible(hasMaximizeButton());
716 QWindowSystemInterface::handleWindowStateChanged(window(), m_state, m_previousWindowState);
720void QWasmWindow::commitParent(QWasmWindowTreeNode *parent)
722 onParentChanged(m_commitedParent, parent, positionPreferenceFromWindowFlags(window()->flags()));
723 m_commitedParent = parent;
733 if (!window()->isTopLevel() || m_flags.testFlag(Qt::WindowDoesNotAcceptFocus))
735 switch (m_flags & Qt::WindowType_Mask) {
738 case Qt::SplashScreen:
750 if (m_hasNativeHandle)
752 if (!isBrowserTabNavigable()) {
753 m_window.call<
void>(
"removeAttribute", std::string(
"tabindex"));
756 m_window.set(
"tabIndex", isTabStop ? 0 : -1);
765 if (event.key != Qt::Key_Tab && event.key != Qt::Key_Backtab)
773 while (topLevel->parent())
774 topLevel =
static_cast<
QWasmWindow *>(topLevel->parent());
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);
781 if (accepted && !wrapped) {
783 event.webEvent.call<
void>(
"preventDefault");
784 event.webEvent.call<
void>(
"stopPropagation");
785 }
else if (accepted) {
788 topLevel->setBrowserTabStop(
false);
789 event.webEvent.call<
void>(
"stopPropagation");
792 setBrowserTabStop(
false);
802 if (relatedTarget.isNull() || relatedTarget.isUndefined())
803 return Qt::ActiveWindowFocusReason;
807 if (!target.call<
bool>(
"matches", std::string(
":focus-visible")))
808 return Qt::ActiveWindowFocusReason;
813 const emscripten::val relatedRoot = relatedTarget.call<emscripten::val>(
"getRootNode");
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;
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;
832 qCDebug(qLcQpaWasmInputContext) <<
"handleKeyEvent";
834 if (QWasmInputContext *inputContext = activeWasmInputContext()) {
839 if (!handleTabKey(event) && processKey(event)) {
843 inputContext->m_ignoreNextInput =
true;
845 event.webEvent.call<
void>(
"stopImmediatePropagation");
847 if (!handleTabKey(event) && processKey(event)) {
848 event.webEvent.call<
void>(
"preventDefault");
849 event.webEvent.call<
void>(
"stopPropagation");
856 constexpr bool ProceedToNativeEvent =
false;
862#if QT_CONFIG(clipboard)
863 const auto clipboardResult =
864 QWasmIntegration::get()->getWasmClipboard()->processKeyboard(event);
866 using ProcessKeyboardResult = QWasmClipboard::ProcessKeyboardResult;
867 if (clipboardResult == ProcessKeyboardResult::NativeClipboardEventNeeded)
868 return ProceedToNativeEvent;
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);
875#if QT_CONFIG(clipboard)
876 if (clipboardResult == ProcessKeyboardResult::NativeClipboardEventAndCopiedDataNeeded)
877 return ProceedToNativeEvent;
885 if (QWasmInputContext *inputContext = activeWasmInputContext())
886 inputContext->inputCallback(event);
888 m_focusHelper.set(
"innerHTML", std::string());
893 if (QWasmInputContext *inputContext = activeWasmInputContext())
894 inputContext->compositionStartCallback(event);
896 m_focusHelper.set(
"innerHTML", std::string());
901 if (QWasmInputContext *inputContext = activeWasmInputContext())
902 inputContext->compositionUpdateCallback(event);
904 m_focusHelper.set(
"innerHTML", std::string());
909 if (QWasmInputContext *inputContext = activeWasmInputContext())
910 inputContext->compositionEndCallback(event);
912 m_focusHelper.set(
"innerHTML", std::string());
917 if (QWasmInputContext *inputContext = activeWasmInputContext())
918 inputContext->beforeInputCallback(event);
920 m_focusHelper.set(
"innerHTML", std::string());
928 return target.call<
emscripten::val>(
"closest", std::string(
".qt-window"))
929 .strictlyEquals(m_window);
935 if (!isOwnEventTarget(event[
"target"]))
939 emscripten::val relatedTarget = event[
"relatedTarget"];
940 bool enteringWindow = relatedTarget.isNull() || relatedTarget.isUndefined()
941 || !m_window.call<
bool>(
"contains", relatedTarget);
946 const Qt::FocusReason reason = enteringWindow && isBrowserTabNavigable()
947 ? tabFocusReason(event[
"target"], relatedTarget)
948 : Qt::ActiveWindowFocusReason;
954 if (!enteringWindow && QGuiApplication::focusWindow() == window())
958 QWindowSystemInterface::handleFocusWindowChanged(window(), reason);
964 emscripten::val relatedTarget = event[
"relatedTarget"];
965 bool leavingWindow = relatedTarget.isNull() || relatedTarget.isUndefined()
966 || !m_window.call<
bool>(
"contains", relatedTarget);
972 setBrowserTabStop(
true);
976 if (isOwnEventTarget(event[
"target"]))
977 QWindowSystemInterface::handleFocusWindowChanged(
nullptr, Qt::ActiveWindowFocusReason);
982 if (processPointerEnterLeave(event))
983 event.webEvent.call<
void>(
"preventDefault");
991 switch (event.type) {
995 QWindowSystemInterface::handleEnterEvent(
996 window(), mapFromGlobal(pointInScreen.toPoint()), pointInScreen);
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;
1027 switch (event.type) {
1028 case EventType::PointerDown:
1029 m_capturedPointerId = event.pointerId;
1030 m_window.call<
void>(
"setPointerCapture", event.pointerId);
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();
1043 event.webEvent.call<
void>(
"preventDefault");
1047 releasePointerGrab(event);
1053 const bool eventAccepted = deliverPointerEvent(event);
1054 if (!eventAccepted && event.type == EventType::PointerDown)
1055 QGuiApplicationPrivate::instance()->closeAllPopups();
1057 if (eventAccepted) {
1058 event.webEvent.call<
void>(
"preventDefault");
1059 event.webEvent.call<
void>(
"stopPropagation");
1069 const QPointF targetPointClippedToScreen(
1070 qBound(geometryF.left(), pointInScreen.x(), geometryF.right()),
1071 qBound(geometryF.top(), pointInScreen.y(), geometryF.bottom()));
1074 const QEvent::Type eventType =
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);
1087 switch (event.type) {
1090 pressure = event.pressure;
1099 qreal xTilt = qBound(-60.0, event.tiltX, 60.0);
1100 qreal yTilt = qBound(-60.0, event.tiltY, 60.0);
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);
1110 QWindowSystemInterface::TouchPoint *touchPoint;
1112 QPointF pointInTargetWindowCoords =
1113 QPointF(window()->mapFromGlobal(targetPointClippedToScreen));
1114 QPointF normalPosition(pointInTargetWindowCoords.x() / window()->width(),
1115 pointInTargetWindowCoords.y() / window()->height());
1117 const auto tp = m_pointerIdToTouchPoints.find(event.pointerId);
1118 if (event.pointerType != PointerType::Pen && tp != m_pointerIdToTouchPoints.end()) {
1119 touchPoint = &tp.value();
1121 touchPoint = &m_pointerIdToTouchPoints
1122 .insert(event.pointerId, QWindowSystemInterface::TouchPoint())
1130 touchPoint->state = QEventPoint::State::Pressed;
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;
1139 switch (event.type) {
1141 touchPoint->state = QEventPoint::State::Released;
1144 touchPoint->state = (stationaryTouchPoint ? QEventPoint::State::Stationary
1145 : QEventPoint::State::Updated);
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; });
1157 if (event.type == EventType::PointerUp || event.type == EventType::PointerCancel)
1158 m_pointerIdToTouchPoints.remove(event.pointerId);
1160 return event.type == EventType::PointerCancel
1161 ? QWindowSystemInterface::handleTouchCancelEvent(
1162 window(), QWasmIntegration::getTimestamp(), platformScreen()->touchDevice(),
1164 : QWindowSystemInterface::handleTouchEvent(
1165 window(), QWasmIntegration::getTimestamp(), platformScreen()->touchDevice(),
1166 touchPointList, event.modifiers);
1172 event.call<
void>(
"preventDefault");
1178 const int scrollFactor = -([&event]() {
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);
1200Qt::WindowFlags
QWasmWindow::fixTopLevelWindowFlags(Qt::WindowFlags flags)
const
1202 if (!(flags.testFlag(Qt::CustomizeWindowHint))) {
1203 if (flags.testFlag(Qt::Window)) {
1204 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint
1205 |Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint;
1207 if (flags.testFlag(Qt::Dialog) || flags.testFlag(Qt::Tool))
1208 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1210 if ((flags & Qt::WindowType_Mask) == Qt::SplashScreen)
1211 flags |= Qt::FramelessWindowHint;
1216bool QWasmWindow::shouldBeAboveTransientParentFlags(Qt::WindowFlags flags)
const
1224 if (flags.testFlag(Qt::Tool) ||
1225 flags.testFlag(Qt::SplashScreen) ||
1226 flags.testFlag(Qt::ToolTip) ||
1227 flags.testFlag(Qt::Popup))
1235QWasmWindowStack<>::PositionPreference
QWasmWindow::positionPreferenceFromWindowFlags(Qt::WindowFlags flags)
const
1237 flags = fixTopLevelWindowFlags(flags);
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;
1249QWasmInputContext *
QWasmWindow::activeWasmInputContext()
const
1254 if (QWasmAccessibility::isEnabled())
1257 return inputContext && inputContext->isActive() ? inputContext :
nullptr;
1262 return m_normalGeometry;
1267 return screen()->devicePixelRatio();
1277 return !m_flags.testFlag(Qt::FramelessWindowHint);
1282 return hasFrame() && !m_state.testFlag(Qt::WindowFullScreen) && !m_flags.testFlag(Qt::SubWindow)
1283 && !windowIsPopupType(m_flags) && !parent();
1288 return hasBorder() && m_flags.testFlag(Qt::WindowTitleHint);
1293 return hasBorder() && !m_flags.testFlag(Qt::NoDropShadowWindowHint);
1298 return !m_state.testFlag(Qt::WindowMaximized) && m_flags.testFlag(Qt::WindowMaximizeButtonHint);
1301bool QWasmWindow::windowIsPopupType(Qt::WindowFlags flags)
const
1303 if (flags.testFlag(Qt::Tool))
1306 return (flags.testFlag(Qt::Popup));
1311 QWindow *modalWindow;
1312 if (QGuiApplicationPrivate::instance()->isWindowBlocked(window(), &modalWindow)) {
1331 if (QWasmAccessibility::isEnabled()) {
1332 if (QWasmAccessibility::setFocusObject(window()->focusObject()))
1337 if (m_window.call<
bool>(
"matches", std::string(
":focus-within")))
1341 m_a11yElementContainer.call<
void>(
"focus");
1345 emscripten::val &element = target == InputFocus ? m_inputElement : m_focusHelper;
1346 element.call<
void>(
"focus");
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"));
1356 m_a11yElementContainer.call<
void>(
"setAttribute", std::string(
"tabindex"), std::string(
"-1"));
1367 switch (event->type()) {
1368 case QEvent::WindowBlocked:
1369 m_decoratedWindow[
"classList"].call<
void>(
"add", emscripten::val(
"blocked"));
1372 m_decoratedWindow.call<
void>(
"setAttribute", std::string(
"inert"), std::string(
""));
1374 case QEvent::WindowUnblocked:;
1375 m_decoratedWindow[
"classList"].call<
void>(
"remove", emscripten::val(
"blocked"));
1376 m_decoratedWindow.call<
void>(
"removeAttribute", std::string(
"inert"));
1378 case QEvent::FocusIn: {
1379 auto *focusEvent =
static_cast<QFocusEvent *>(event);
1380 if (focusEvent->reason() == Qt::TabFocusReason
1381 || focusEvent->reason() == Qt::BacktabFocusReason) {
1388 if (!m_handlingTabKey)
1389 return QPlatformWindow::windowEvent(event);
1390 m_focusChainWrapped =
true;
1394 return QPlatformWindow::windowEvent(event);
1397 return QPlatformWindow::windowEvent(event);
1403 if (region.isEmpty()) {
1404 m_decoratedWindow[
"style"].set(
"clipPath", emscripten::val(
""));
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 ";
1417 cssClipPath <<
"')";
1418 m_decoratedWindow[
"style"].set(
"clipPath", emscripten::val(cssClipPath.str()));
1421void QWasmWindow::onTransientParentChanged(QWindow *newTransientParent)
1423 Q_UNUSED(newTransientParent);
1425 const auto positionPreference = positionPreferenceFromWindowFlags(window()->flags());
1426 QWasmWindowTreeNode::onParentChanged(parentNode(),
nullptr, positionPreference);
1427 QWasmWindowTreeNode::onParentChanged(
nullptr, parentNode(), positionPreference);
1432 const auto positionPreference = positionPreferenceFromWindowFlags(window()->flags());
1433 QWasmWindowTreeNode::onParentChanged(parentNode(),
nullptr, positionPreference);
1434 QWasmWindowTreeNode::onParentChanged(
nullptr, parentNode(), positionPreference);
1441 setWindowFlags(window()->flags());
1443 commitParent(parentNode());
1448 return "!qtwindow" +
std::to_string(m_winId);
1469 QWasmWindowStack<>::PositionPreference positionPreference)
1472 previous->containerElement().call<
void>(
"removeChild", m_decoratedWindow);
1474 current->containerElement().call<
void>(
"appendChild", m_decoratedWindow);
1475 QWasmWindowTreeNode::onParentChanged(previous, current, positionPreference);
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);
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
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()
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 ®ion) final
Reimplement to be able to let Qt set the mask of a window.
QWasmWindow * transientParent() const
QWasmWindowTreeNode * parentNode() final
void initialize() override
Called as part of QWindow::create(), after constructing the window.
Qt::WindowFlags windowFlags() const
void registerEventHandlers()
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 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
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.
Q_GUI_EXPORT int qt_defaultDpiX()
QDebug Q_GUI_EXPORT & operator<<(QDebug &s, const QVectorPath &path)
bool isTargetedForElement(emscripten::val element) const