1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
|
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qeventdispatcher_wasm_p.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qthread.h>
#include <QtCore/qscopedvaluerollback.h>
#include <QtCore/private/qobject_p.h>
#include <QtCore/private/qwasmglobal_p.h>
#include <QtCore/private/qstdweb_p.h>
#include <QtCore/private/qwasmsocket_p.h>
using namespace std::chrono;
using namespace std::chrono_literals;
QT_BEGIN_NAMESPACE
using emscripten::val;
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher");
Q_LOGGING_CATEGORY(lcEventDispatcherTimers, "qt.eventdispatcher.timers");
#if QT_CONFIG(thread)
#define LOCK_GUARD(M) std::lock_guard<std::mutex> lock(M)
#else
#define LOCK_GUARD(M)
#endif
#if defined(QT_STATIC)
static bool useAsyncify()
{
return qstdweb::haveAsyncify();
}
#else
// EM_JS is not supported for side modules; disable asyncify
static bool useAsyncify()
{
return false;
}
#endif // defined(QT_STATIC)
Q_CONSTINIT QEventDispatcherWasm *QEventDispatcherWasm::g_mainThreadEventDispatcher = nullptr;
Q_CONSTINIT std::shared_ptr<QWasmSuspendResumeControl> QEventDispatcherWasm::g_mainThreadSuspendResumeControl;
#if QT_CONFIG(thread)
Q_CONSTINIT QVector<QEventDispatcherWasm *> QEventDispatcherWasm::g_secondaryThreadEventDispatchers;
Q_CONSTINIT std::mutex QEventDispatcherWasm::g_staticDataMutex;
#endif
QEventDispatcherWasm::QEventDispatcherWasm(std::shared_ptr<QWasmSuspendResumeControl> suspendResumeControl)
{
// QEventDispatcherWasm operates in two main modes:
// - On the main thread:
// The event dispatcher can process native events but can't
// block and wait for new events, unless asyncify is used.
// - On a secondary thread:
// The event dispatcher can't process native events but can
// block and wait for new events.
//
// Which mode is determined by the calling thread: construct
// the event dispatcher object on the thread where it will live.
qCDebug(lcEventDispatcher) << "Creating QEventDispatcherWasm instance" << this
<< "is main thread" << emscripten_is_main_runtime_thread();
if (emscripten_is_main_runtime_thread()) {
// There can be only one main thread event dispatcher at a time; in
// addition the main instance is used by the secondary thread event
// dispatchers so we set a global pointer to it.
Q_ASSERT(g_mainThreadEventDispatcher == nullptr);
g_mainThreadEventDispatcher = this;
if (suspendResumeControl) {
g_mainThreadSuspendResumeControl = suspendResumeControl;
} else {
g_mainThreadSuspendResumeControl = std::make_shared<QWasmSuspendResumeControl>();
}
// Zero-timer used on wake() calls
m_wakeupTimer = std::make_unique<QWasmTimer>(g_mainThreadSuspendResumeControl.get(), [](){ onWakeup(); });
// Timer set to fire at the next Qt timer timeout
m_nativeTimer = std::make_unique<QWasmTimer>(g_mainThreadSuspendResumeControl.get(), []() { onTimer(); });
// Timer used when suspending to process native events
m_suspendTimer = std::make_unique<QWasmTimer>(g_mainThreadSuspendResumeControl.get(), []() { onProcessNativeEventsResume(); });
} else {
#if QT_CONFIG(thread)
std::lock_guard<std::mutex> lock(g_staticDataMutex);
g_secondaryThreadEventDispatchers.append(this);
#endif
}
m_timerInfo = std::make_unique<QTimerInfoList>();
}
QEventDispatcherWasm::~QEventDispatcherWasm()
{
qCDebug(lcEventDispatcher) << "Destroying QEventDispatcherWasm instance" << this;
// Reset to ensure destruction before g_mainThreadSuspendResumeControl
m_wakeupTimer.reset();
m_nativeTimer.reset();
m_suspendTimer.reset();
#if QT_CONFIG(thread)
if (isSecondaryThreadEventDispatcher()) {
std::lock_guard<std::mutex> lock(g_staticDataMutex);
g_secondaryThreadEventDispatchers.remove(g_secondaryThreadEventDispatchers.indexOf(this));
} else
#endif
{
QWasmSocket::clearSocketNotifiers();
g_mainThreadEventDispatcher = nullptr;
g_mainThreadSuspendResumeControl.reset();
}
}
bool QEventDispatcherWasm::isMainThreadEventDispatcher()
{
return this == g_mainThreadEventDispatcher;
}
bool QEventDispatcherWasm::isSecondaryThreadEventDispatcher()
{
return this != g_mainThreadEventDispatcher;
}
bool QEventDispatcherWasm::isValidEventDispatcher()
{
return isValidEventDispatcherPointer(this);
}
bool QEventDispatcherWasm::isValidEventDispatcherPointer(QEventDispatcherWasm *eventDispatcher)
{
if (eventDispatcher == g_mainThreadEventDispatcher)
return true;
#if QT_CONFIG(thread)
if (g_secondaryThreadEventDispatchers.contains(eventDispatcher))
return true;
#endif
return false;
}
bool QEventDispatcherWasm::processEvents(QEventLoop::ProcessEventsFlags flags)
{
emit awake();
if (!useAsyncify() && isMainThreadEventDispatcher())
handleNonAsyncifyErrorCases(flags);
bool didSendEvents = false;
didSendEvents |= sendPostedEvents();
if (!isValidEventDispatcher())
return false;
didSendEvents |= sendNativeEvents(flags);
if (!isValidEventDispatcher())
return false;
didSendEvents |= sendTimerEvents();
if (!isValidEventDispatcher())
return false;
if (m_interrupted) {
m_interrupted = false;
return false;
}
if (flags & QEventLoop::WaitForMoreEvents)
processEventsWait();
return didSendEvents;
}
bool QEventDispatcherWasm::sendNativeEvents(QEventLoop::ProcessEventsFlags flags)
{
// TODO: support ExcludeUserInputEvents and ExcludeSocketNotifiers
// Secondary threads do not support native events
if (!isMainThreadEventDispatcher())
return false;
// Can't suspend without asyncify
if (!useAsyncify())
return false;
// Send any pending events, and
bool didSendEvents = false;
didSendEvents|= g_mainThreadSuspendResumeControl->sendPendingEvents();
// if the processEvents() call is made from an exec() call then we assume
// that the main thread has just resumed, and that it will suspend again
// at the end of processEvents(). This makes the suspend loop below superfluous.
if (flags & QEventLoop::EventLoopExec)
return didSendEvents;
// Run a suspend-resume loop until all pending native events have
// been processed. Suspending returns control to the browsers'event
// loop and makes it process events. If any event was for us then
// the wasm instance will resume (via event handling code in QWasmSuspendResumeControl
// and process the event.
//
// Set a zero-timer to exit the loop via the m_wakeFromSuspendTimer flag.
// This timer will be added to the end of the native event queue and
// ensures that all pending (at the time of this sendNativeEvents() call)
// native events are processed.
m_wakeFromSuspendTimer = false;
do {
m_suspendTimer->setTimeout(0ms);
g_mainThreadSuspendResumeControl->suspend();
QScopedValueRollback scoped(m_isSendingNativeEvents, true);
didSendEvents |= g_mainThreadSuspendResumeControl->sendPendingEvents();
} while (!m_wakeFromSuspendTimer);
return didSendEvents;
}
bool QEventDispatcherWasm::sendPostedEvents()
{
QCoreApplication::sendPostedEvents();
return false;
}
bool QEventDispatcherWasm::sendTimerEvents()
{
int activatedTimers = m_timerInfo->activateTimers();
if (activatedTimers > 0)
updateNativeTimer();
return activatedTimers > 0;
}
void QEventDispatcherWasm::registerTimer(Qt::TimerId timerId, Duration interval, Qt::TimerType timerType, QObject *object)
{
#ifndef QT_NO_DEBUG
if (qToUnderlying(timerId) < 1 || interval < 0ns || !object) {
qWarning("QEventDispatcherWasm::registerTimer: invalid arguments");
return;
} else if (object->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QEventDispatcherWasm::registerTimer: timers cannot be started from another "
"thread");
return;
}
#endif
qCDebug(lcEventDispatcherTimers) << "registerTimer" << int(timerId) << interval << timerType << object;
m_timerInfo->registerTimer(timerId, interval, timerType, object);
updateNativeTimer();
}
bool QEventDispatcherWasm::unregisterTimer(Qt::TimerId timerId)
{
#ifndef QT_NO_DEBUG
if (qToUnderlying(timerId) < 1) {
qWarning("QEventDispatcherWasm::unregisterTimer: invalid argument");
return false;
} else if (thread() != QThread::currentThread()) {
qWarning("QEventDispatcherWasm::unregisterTimer: timers cannot be stopped from another "
"thread");
return false;
}
#endif
qCDebug(lcEventDispatcherTimers) << "unregisterTimer" << int(timerId);
bool ans = m_timerInfo->unregisterTimer(timerId);
updateNativeTimer();
return ans;
}
bool QEventDispatcherWasm::unregisterTimers(QObject *object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QEventDispatcherWasm::unregisterTimers: invalid argument");
return false;
} else if (object->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QEventDispatcherWasm::unregisterTimers: timers cannot be stopped from another "
"thread");
return false;
}
#endif
qCDebug(lcEventDispatcherTimers) << "registerTimer" << object;
bool ans = m_timerInfo->unregisterTimers(object);
updateNativeTimer();
return ans;
}
QList<QAbstractEventDispatcher::TimerInfoV2>
QEventDispatcherWasm::timersForObject(QObject *object) const
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QEventDispatcherWasm:registeredTimers: invalid argument");
return {};
}
#endif
return m_timerInfo->registeredTimers(object);
}
QEventDispatcherWasm::Duration QEventDispatcherWasm::remainingTime(Qt::TimerId timerId) const
{
return m_timerInfo->remainingDuration(timerId);
}
void QEventDispatcherWasm::interrupt()
{
m_interrupted = true;
wakeUp();
}
void QEventDispatcherWasm::wakeUp()
{
#if QT_CONFIG(thread)
if (isSecondaryThreadEventDispatcher()) {
std::lock_guard<std::mutex> lock(m_mutex);
m_wakeUpCalled = true;
m_moreEvents.notify_one();
} else
#endif
{
QEventDispatcherWasm *eventDispatcher = this;
qwasmglobal::runOnMainThreadAsync([eventDispatcher]() {
if (isValidEventDispatcherPointer(eventDispatcher)) {
if (!eventDispatcher->m_wakeupTimer->hasTimeout())
eventDispatcher->m_wakeupTimer->setTimeout(0ms);
}
});
}
}
void QEventDispatcherWasm::handleNonAsyncifyErrorCases(QEventLoop::ProcessEventsFlags flags)
{
Q_ASSERT(!useAsyncify());
if (flags & QEventLoop::ApplicationExec) {
// Start the main loop, and then stop it on the first callback. This
// is done for the "simulateInfiniteLoop" functionality where
// emscripten_set_main_loop() throws a JS exception which returns
// control to the browser while preserving the C++ stack.
const bool simulateInfiniteLoop = true;
emscripten_set_main_loop([](){
emscripten_pause_main_loop();
}, 0, simulateInfiniteLoop);
} else if (flags & QEventLoop::DialogExec) {
qFatal() << "Calling exec() is not supported on Qt for WebAssembly in this configuration. Please build"
<< "with asyncify support, or use an asynchronous API like QDialog::open()";
} else if (flags & QEventLoop::WaitForMoreEvents) {
qFatal("QEventLoop::WaitForMoreEvents is not supported on the main thread without asyncify");
}
}
// Blocks or suspends the current thread for the given amount of time.
// The event dispatcher does not process events while blocked. TODO:
// make it not process events while blocked.
bool QEventDispatcherWasm::wait(int timeout)
{
auto tim = timeout > 0 ? std::optional<std::chrono::milliseconds>(timeout) : std::nullopt;
if (isSecondaryThreadEventDispatcher())
return secondaryThreadWait(tim);
if (useAsyncify())
asyncifyWait(tim);
return true;
}
// Waits for more events by blocking or suspending the current thread. Should be called from
// processEvents() only.
void QEventDispatcherWasm::processEventsWait()
{
if (isMainThreadEventDispatcher()) {
asyncifyWait(std::nullopt);
} else {
auto nanoWait = m_timerInfo->timerWait();
std::optional<std::chrono::milliseconds> milliWait;
if (nanoWait.has_value())
milliWait = std::chrono::duration_cast<std::chrono::milliseconds>(*nanoWait);
secondaryThreadWait(milliWait);
}
}
void QEventDispatcherWasm::asyncifyWait(std::optional<std::chrono::milliseconds> timeout)
{
Q_ASSERT(emscripten_is_main_runtime_thread());
Q_ASSERT(isMainThreadEventDispatcher());
Q_ASSERT(useAsyncify());
if (timeout.has_value())
m_suspendTimer->setTimeout(timeout.value());
g_mainThreadSuspendResumeControl->suspend();
}
bool QEventDispatcherWasm::secondaryThreadWait(std::optional<std::chrono::milliseconds> timeout)
{
#if QT_CONFIG(thread)
Q_ASSERT(QThread::currentThread() == thread());
using namespace std::chrono_literals;
std::unique_lock<std::mutex> lock(m_mutex);
// If wakeUp() was called there might be pending events in the event
// queue which should be processed. Don't block, instead return
// so that the event loop can spin and call processEvents() again.
if (m_wakeUpCalled) {
m_wakeUpCalled = false;
return true;
}
auto waitTime = timeout.value_or(std::chrono::milliseconds::max());
bool wakeUpCalled = m_moreEvents.wait_for(lock, waitTime, [this] { return m_wakeUpCalled; });
m_wakeUpCalled = false;
return wakeUpCalled;
#else
Q_UNREACHABLE();
return false;
#endif
}
void QEventDispatcherWasm::onTimer()
{
Q_ASSERT(emscripten_is_main_runtime_thread());
if (!g_mainThreadEventDispatcher)
return;
g_mainThreadEventDispatcher->sendTimerEvents();
}
void QEventDispatcherWasm::onWakeup()
{
Q_ASSERT(emscripten_is_main_runtime_thread());
if (!g_mainThreadEventDispatcher)
return;
// In the case where we are suspending from sendNativeEvents() we don't want
// to call processEvents() again, since we are then already in processEvents()
// and are already awake.
if (g_mainThreadEventDispatcher->m_isSendingNativeEvents)
return;
g_mainThreadEventDispatcher->processEvents(QEventLoop::AllEvents);
}
void QEventDispatcherWasm::onProcessNativeEventsResume()
{
Q_ASSERT(emscripten_is_main_runtime_thread());
if (!g_mainThreadEventDispatcher)
return;
g_mainThreadEventDispatcher->m_wakeFromSuspendTimer = true;
}
// Updates the native timer based on currently registered Qt timers,
// by setting a timeout equivalent to the shortest timer.
// Must be called on the event dispatcher thread.
void QEventDispatcherWasm::updateNativeTimer()
{
#if QT_CONFIG(thread)
Q_ASSERT(QThread::currentThread() == thread());
#endif
// On secondary threads, the timeout is managed by setting the WaitForMoreEvents
// timeout in processEventsWait().
if (!isMainThreadEventDispatcher())
return;
// Clear any timer if there are no active timers
const std::optional<std::chrono::nanoseconds> nanoWait = m_timerInfo->timerWait();
if (!nanoWait.has_value()) {
m_nativeTimer->clearTimeout();
return;
}
auto milliWait = std::chrono::duration_cast<std::chrono::milliseconds>(*nanoWait);
const auto newTargetTime = m_timerInfo->currentTime + milliWait;
// Keep existing timer if the timeout has not changed.
if (m_nativeTimer->hasTimeout() && newTargetTime == m_timerTargetTime)
return;
// Clear current and set new timer
qCDebug(lcEventDispatcherTimers)
<< "Created new native timer timeout" << milliWait.count() << "ms"
<< "previous target time" << m_timerTargetTime.time_since_epoch()
<< "new target time" << newTargetTime.time_since_epoch();
m_nativeTimer->clearTimeout();
m_nativeTimer->setTimeout(milliWait);
m_timerTargetTime = newTargetTime;
}
namespace {
int g_startupTasks = 0;
}
// The following functions manages sending the "qtLoaded" event/callback
// from qtloader.js on startup, once Qt initialization has been completed
// and the application is ready to display the first frame. This can be
// either as soon as the event loop is running, or later, if additional
// startup tasks (e.g. local font loading) have been registered.
void QEventDispatcherWasm::registerStartupTask()
{
++g_startupTasks;
}
void QEventDispatcherWasm::completeStarupTask()
{
--g_startupTasks;
callOnLoadedIfRequired();
}
void QEventDispatcherWasm::callOnLoadedIfRequired()
{
if (g_startupTasks > 0)
return;
static bool qtLoadedCalled = false;
if (qtLoadedCalled)
return;
qtLoadedCalled = true;
}
void QEventDispatcherWasm::onLoaded()
{
// TODO: call qtloader.js onLoaded from here, in order to delay
// hiding the "Loading..." message until the app is ready to paint
// the first frame. Currently onLoaded must be called early before
// main() in order to ensure that the screen/container elements
// have valid geometry at startup.
}
void QEventDispatcherWasm::registerSocketNotifier(QSocketNotifier *notifier)
{
QWasmSocket::registerSocketNotifier(notifier);
}
void QEventDispatcherWasm::unregisterSocketNotifier(QSocketNotifier *notifier)
{
QWasmSocket::unregisterSocketNotifier(notifier);
}
void QEventDispatcherWasm::socketSelect(int timeout, int socket, bool waitForRead, bool waitForWrite,
bool *selectForRead, bool *selectForWrite, bool *socketDisconnect)
{
QEventDispatcherWasm *eventDispatcher = static_cast<QEventDispatcherWasm *>(
QAbstractEventDispatcher::instance(QThread::currentThread()));
if (!eventDispatcher) {
qWarning("QEventDispatcherWasm::socketSelect called without eventdispatcher instance");
return;
}
QWasmSocket::waitForSocketState(eventDispatcher, timeout, socket, waitForRead, waitForWrite,
selectForRead, selectForWrite, socketDisconnect);
}
QT_END_NAMESPACE
#include "moc_qeventdispatcher_wasm_p.cpp"
|