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
qeventdispatcher_glib.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7
8#include <private/qthread_p.h>
9
12
13#include <QtCore/qlist.h>
14
15#include <QtCore/q20memory.h>
16#include <QtCore/q26numeric.h>
17
18#include <glib.h>
19
20using namespace std::chrono;
21using namespace std::chrono_literals;
22
23QT_BEGIN_NAMESPACE
24
25struct GPollFDWithQSocketNotifier
26{
27 GPollFD pollfd;
28 QSocketNotifier *socketNotifier;
29};
30
37
39{
40 if (timeout)
41 *timeout = -1;
42 return false;
43}
44
46{
47 GSocketNotifierSource *src = reinterpret_cast<GSocketNotifierSource *>(source);
48
49 bool pending = false;
50 for (qsizetype i = 0; !pending && i < src->pollfds.size(); ++i) {
51 GPollFDWithQSocketNotifier *p = src->pollfds.at(i);
52
53 if (p->pollfd.revents & G_IO_NVAL) {
54 // disable the invalid socket notifier
55 const char * const t[] = { "Read", "Write", "Exception" };
56 qWarning("QSocketNotifier: Invalid socket %d and type '%s', disabling...",
57 p->pollfd.fd, t[p->socketNotifier->type()]);
58 // ### note, modifies src->pollfds, turning this loop quadratic (QTBUG-143853)!
59 p->socketNotifier->setEnabled(false);
60 i--;
61 } else {
62 pending = pending || ((p->pollfd.revents & p->pollfd.events) != 0);
63 }
64 }
65
66 return pending;
67}
68
70{
71 QEvent event(QEvent::SockAct);
72
73 GSocketNotifierSource *src = reinterpret_cast<GSocketNotifierSource *>(source);
74 for (src->activeNotifierPos = 0; src->activeNotifierPos < src->pollfds.size();
75 ++src->activeNotifierPos) {
76 GPollFDWithQSocketNotifier *p = src->pollfds.at(src->activeNotifierPos);
77
78 if ((p->pollfd.revents & p->pollfd.events) != 0)
79 QCoreApplication::sendEvent(p->socketNotifier, &event);
80 }
81
82 return true; // ??? don't remove, right?
83}
84
85Q_CONSTINIT static GSourceFuncs socketNotifierSourceFuncs = {
86 socketNotifierSourcePrepare,
87 socketNotifierSourceCheck,
88 socketNotifierSourceDispatch,
89 nullptr,
90 nullptr,
91 nullptr
92};
93
101
103{
104 if (src->processEventsFlags & QEventLoop::X11ExcludeTimers) {
105 *timeout = -1;
106 return true;
107 }
108
109 auto remaining = src->timerList.timerWait().value_or(-1ms);
110 *timeout = q26::saturating_cast<gint>(ceil<milliseconds>(remaining).count());
111
112 return (*timeout == 0);
113}
114
116{
117 if (src->timerList.isEmpty()
118 || (src->processEventsFlags & QEventLoop::X11ExcludeTimers))
119 return false;
120
121 return !src->timerList.hasPendingTimers();
122}
123
124static gboolean timerSourcePrepare(GSource *source, gint *timeout)
125{
126 gint dummy;
127 if (!timeout)
128 timeout = &dummy;
129
130 GTimerSource *src = reinterpret_cast<GTimerSource *>(source);
131 if (src->runWithIdlePriority) {
132 if (timeout)
133 *timeout = -1;
134 return false;
135 }
136
137 return timerSourcePrepareHelper(src, timeout);
138}
139
141{
142 GTimerSource *src = reinterpret_cast<GTimerSource *>(source);
144 return false;
145 return timerSourceCheckHelper(src);
146}
147
149{
150 GTimerSource *timerSource = reinterpret_cast<GTimerSource *>(source);
151 if (timerSource->processEventsFlags & QEventLoop::X11ExcludeTimers)
152 return true;
153 timerSource->runWithIdlePriority = true;
154 (void) timerSource->timerList.activateTimers();
155 return true; // ??? don't remove, right again?
156}
157
158Q_CONSTINIT static GSourceFuncs timerSourceFuncs = {
159 timerSourcePrepare,
160 timerSourceCheck,
161 timerSourceDispatch,
162 nullptr,
163 nullptr,
164 nullptr
165};
166
172
173static gboolean idleTimerSourcePrepare(GSource *source, gint *timeout)
174{
175 GIdleTimerSource *idleTimerSource = reinterpret_cast<GIdleTimerSource *>(source);
176 GTimerSource *timerSource = idleTimerSource->timerSource;
177 if (!timerSource->runWithIdlePriority) {
178 // Yield to the normal priority timer source
179 if (timeout)
180 *timeout = -1;
181 return false;
182 }
183
184 return timerSourcePrepareHelper(timerSource, timeout);
185}
186
188{
189 GIdleTimerSource *idleTimerSource = reinterpret_cast<GIdleTimerSource *>(source);
190 GTimerSource *timerSource = idleTimerSource->timerSource;
191 if (!timerSource->runWithIdlePriority) {
192 // Yield to the normal priority timer source
193 return false;
194 }
195 return timerSourceCheckHelper(timerSource);
196}
197
199{
200 GTimerSource *timerSource = reinterpret_cast<GIdleTimerSource *>(source)->timerSource;
201 (void) timerSourceDispatch(&timerSource->source, nullptr, nullptr);
202 return true;
203}
204
205Q_CONSTINIT static GSourceFuncs idleTimerSourceFuncs = {
206 idleTimerSourcePrepare,
207 idleTimerSourceCheck,
208 idleTimerSourceDispatch,
209 nullptr,
210 nullptr,
211 nullptr
212};
213
222
223static gboolean postEventSourcePrepare(GSource *s, gint *timeout)
224{
225 QThreadData *data = QThreadData::current();
226 if (!data)
227 return false;
228
229 gint dummy;
230 if (!timeout)
231 timeout = &dummy;
232 const bool canWait = data->canWaitLocked();
233 *timeout = canWait ? -1 : 0;
234
235 GPostEventSource *source = reinterpret_cast<GPostEventSource *>(s);
236 source->d->wakeUpCalled = source->serialNumber.loadRelaxed() != source->lastSerialNumber;
237 return !canWait || source->d->wakeUpCalled;
238}
239
241{
242 return postEventSourcePrepare(source, nullptr);
243}
244
246{
247 GPostEventSource *source = reinterpret_cast<GPostEventSource *>(s);
248 source->pendingSerialNumber = source->serialNumber.loadRelaxed();
249 QCoreApplication::sendPostedEvents();
251 source->d->runTimersOnceWithNormalPriority();
252 return true; // i dunno, george...
253}
254
255Q_CONSTINIT static GSourceFuncs postEventSourceFuncs = {
256 postEventSourcePrepare,
257 postEventSourceCheck,
258 postEventSourceDispatch,
259 nullptr,
260 nullptr,
261 nullptr
262};
263
264
265QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(GMainContext *context)
266 : mainContext(context)
267{
268#if GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 32
269 if (qEnvironmentVariableIsEmpty("QT_NO_THREADED_GLIB")) {
270 Q_CONSTINIT static QBasicMutex mutex;
271 QMutexLocker locker(&mutex);
272 if (!g_thread_supported())
273 g_thread_init(NULL);
274 }
275#endif
276
277 if (mainContext) {
278 g_main_context_ref(mainContext);
279 } else {
280 QCoreApplication *app = QCoreApplication::instance();
281 if (app && QThread::isMainThread()) {
282 mainContext = g_main_context_default();
283 g_main_context_ref(mainContext);
284 } else {
285 mainContext = g_main_context_new();
286 }
287 }
288
289#if GLIB_CHECK_VERSION (2, 22, 0)
290 g_main_context_push_thread_default (mainContext);
291#endif
292
293 // setup post event source
294 GSource *source = g_source_new(&postEventSourceFuncs, sizeof(GPostEventSource));
295 postEventSource = reinterpret_cast<GPostEventSource *>(source);
296
297 // atomic ints (Q or std) can't be initialized from raw memory w/o C++20's atomic_ref
298 q20::construct_at(&postEventSource->serialNumber, 1);
299 postEventSource->d = this;
300 attachSource(source, "[Qt] GPostEventSource");
301
302 // setup socketNotifierSource
303 source = g_source_new(&socketNotifierSourceFuncs, sizeof(GSocketNotifierSource));
304 socketNotifierSource = reinterpret_cast<GSocketNotifierSource *>(source);
305 (void) new (&socketNotifierSource->pollfds) QList<GPollFDWithQSocketNotifier *>();
306 attachSource(source, "[Qt] GSocketNotifierSource");
307
308 // setup normal and idle timer sources
309 source = g_source_new(&timerSourceFuncs, sizeof(GTimerSource));
310 timerSource = reinterpret_cast<GTimerSource *>(source);
311 (void) new (&timerSource->timerList) QTimerInfoList();
312 timerSource->processEventsFlags = QEventLoop::AllEvents;
313 timerSource->runWithIdlePriority = false;
314 attachSource(source, "[Qt] GTimerSource");
315
316 source = g_source_new(&idleTimerSourceFuncs, sizeof(GIdleTimerSource));
317 idleTimerSource = reinterpret_cast<GIdleTimerSource *>(source);
318 idleTimerSource->timerSource = timerSource;
319 attachSource(source, "[Qt] GIdleTimerSource");
320}
321
322QEventDispatcherGlibPrivate::~QEventDispatcherGlibPrivate()
323 = default;
324
325void QEventDispatcherGlibPrivate::attachSource(GSource *source, const char *name)
326{
327 Q_ASSERT(source);
328 Q_ASSERT(g_source_get_priority(source) == G_PRIORITY_DEFAULT);
329 g_source_set_name(source, name);
330 g_source_set_can_recurse(source, true);
331 g_source_attach(source, mainContext);
332}
333
334void QEventDispatcherGlibPrivate::destroySource(GSource *source)
335{
336 Q_ASSERT(source);
337 g_source_destroy(source);
338 g_source_unref(source);
339}
340void QEventDispatcherGlibPrivate::runTimersOnceWithNormalPriority()
341{
342 timerSource->runWithIdlePriority = false;
343}
344
345QEventDispatcherGlib::QEventDispatcherGlib(QObject *parent)
346 : QAbstractEventDispatcherV2(*(new QEventDispatcherGlibPrivate), parent)
347{
348}
349
350QEventDispatcherGlib::QEventDispatcherGlib(GMainContext *mainContext, QObject *parent)
351 : QAbstractEventDispatcherV2(*(new QEventDispatcherGlibPrivate(mainContext)), parent)
352{ }
353
354QEventDispatcherGlib::~QEventDispatcherGlib()
355{
356 Q_D(QEventDispatcherGlib);
357
358 // destroy all timer sources
359 d->timerSource->timerList.clearTimers();
360 d->timerSource->timerList.~QTimerInfoList();
361 d->destroySource(&d->timerSource->source);
362 d->timerSource = nullptr;
363 d->destroySource(&d->idleTimerSource->source);
364 d->idleTimerSource = nullptr;
365
366 // destroy socket notifier source
367 for (qsizetype i = 0; i < d->socketNotifierSource->pollfds.size(); ++i) {
368 GPollFDWithQSocketNotifier *p = d->socketNotifierSource->pollfds.at(i);
369 g_source_remove_poll(&d->socketNotifierSource->source, &p->pollfd);
370 delete p;
371 }
372 d->socketNotifierSource->pollfds.~QList<GPollFDWithQSocketNotifier *>();
373 d->destroySource(&d->socketNotifierSource->source);
374 d->socketNotifierSource = nullptr;
375
376 // destroy post event source
377 d->destroySource(&d->postEventSource->source);
378 d->postEventSource = nullptr;
379
380 Q_ASSERT(d->mainContext != nullptr);
381#if GLIB_CHECK_VERSION (2, 22, 0)
382 g_main_context_pop_thread_default (d->mainContext);
383#endif
384 g_main_context_unref(d->mainContext);
385 d->mainContext = nullptr;
386}
387
388bool QEventDispatcherGlib::processEvents(QEventLoop::ProcessEventsFlags flags)
389{
390 Q_D(QEventDispatcherGlib);
391
392 const bool canWait = flags.testAnyFlag(QEventLoop::WaitForMoreEvents);
393 if (canWait)
394 emit aboutToBlock();
395 else
396 emit awake();
397
398 // tell postEventSourcePrepare() and timerSource about any new flags
399 QEventLoop::ProcessEventsFlags savedFlags = d->timerSource->processEventsFlags;
400 d->timerSource->processEventsFlags = flags;
401
402 if (!(flags & QEventLoop::EventLoopExec)) {
403 // force timers to be sent at normal priority
404 d->timerSource->runWithIdlePriority = false;
405 }
406
407 bool result = g_main_context_iteration(d->mainContext, canWait);
408 while (!result && canWait)
409 result = g_main_context_iteration(d->mainContext, canWait);
410
411 d->timerSource->processEventsFlags = savedFlags;
412
413 if (canWait)
414 emit awake();
415
416 return result;
417}
418
419void QEventDispatcherGlib::registerSocketNotifier(QSocketNotifier *notifier)
420{
421 Q_ASSERT(notifier);
422 int sockfd = int(notifier->socket());
423 const auto type = notifier->type();
424#ifndef QT_NO_DEBUG
425 if (sockfd < 0) {
426 qWarning("QSocketNotifier: Internal error");
427 return;
428 } else if (notifier->thread() != thread()
429 || thread() != QThread::currentThread()) {
430 qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
431 return;
432 }
433#endif
434
435 Q_D(QEventDispatcherGlib);
436
437
438 GPollFDWithQSocketNotifier *p = new GPollFDWithQSocketNotifier;
439 p->pollfd.fd = sockfd;
440 switch (type) {
441 case QSocketNotifier::Read:
442 p->pollfd.events = G_IO_IN | G_IO_HUP | G_IO_ERR;
443 break;
444 case QSocketNotifier::Write:
445 p->pollfd.events = G_IO_OUT | G_IO_HUP | G_IO_ERR;
446 break;
447 case QSocketNotifier::Exception:
448 p->pollfd.events = G_IO_PRI | G_IO_HUP | G_IO_ERR;
449 break;
450 }
451 p->socketNotifier = notifier;
452
453 d->socketNotifierSource->pollfds.append(p);
454
455 g_source_add_poll(&d->socketNotifierSource->source, &p->pollfd);
456}
457
458void QEventDispatcherGlib::unregisterSocketNotifier(QSocketNotifier *notifier)
459{
460 Q_ASSERT(notifier);
461#ifndef QT_NO_DEBUG
462 if (notifier->socket() < 0) {
463 qWarning("QSocketNotifier: Internal error");
464 return;
465 } else if (notifier->thread() != thread()
466 || thread() != QThread::currentThread()) {
467 qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
468 return;
469 }
470#endif
471
472 Q_D(QEventDispatcherGlib);
473
474 for (qsizetype i = 0; i < d->socketNotifierSource->pollfds.size(); ++i) {
475 GPollFDWithQSocketNotifier *p = d->socketNotifierSource->pollfds.at(i);
476 if (p->socketNotifier == notifier) {
477 // found it
478 g_source_remove_poll(&d->socketNotifierSource->source, &p->pollfd);
479
480 d->socketNotifierSource->pollfds.removeAt(i);
481 delete p;
482
483 // Keep a position in the list for the next item.
484 if (i <= d->socketNotifierSource->activeNotifierPos)
485 --d->socketNotifierSource->activeNotifierPos;
486
487 return;
488 }
489 }
490}
491
492void QEventDispatcherGlib::registerTimer(Qt::TimerId timerId, Duration interval,
493 Qt::TimerType timerType, QObject *object)
494{
495#ifndef QT_NO_DEBUG
496 if (qToUnderlying(timerId) < 1 || interval < 0ns || !object) {
497 qWarning("QEventDispatcherGlib::registerTimer: invalid arguments");
498 return;
499 } else if (object->thread() != thread() || thread() != QThread::currentThread()) {
500 qWarning("QEventDispatcherGlib::registerTimer: timers cannot be started from another thread");
501 return;
502 }
503#endif
504
505 Q_D(QEventDispatcherGlib);
506 d->timerSource->timerList.registerTimer(timerId, interval, timerType, object);
507}
508
509bool QEventDispatcherGlib::unregisterTimer(Qt::TimerId timerId)
510{
511#ifndef QT_NO_DEBUG
512 if (qToUnderlying(timerId) < 1) {
513 qWarning("QEventDispatcherGlib::unregisterTimer: invalid argument");
514 return false;
515 } else if (thread() != QThread::currentThread()) {
516 qWarning("QEventDispatcherGlib::unregisterTimer: timers cannot be stopped from another thread");
517 return false;
518 }
519#endif
520
521 Q_D(QEventDispatcherGlib);
522 return d->timerSource->timerList.unregisterTimer(timerId);
523}
524
525bool QEventDispatcherGlib::unregisterTimers(QObject *object)
526{
527#ifndef QT_NO_DEBUG
528 if (!object) {
529 qWarning("QEventDispatcherGlib::unregisterTimers: invalid argument");
530 return false;
531 } else if (object->thread() != thread() || thread() != QThread::currentThread()) {
532 qWarning("QEventDispatcherGlib::unregisterTimers: timers cannot be stopped from another thread");
533 return false;
534 }
535#endif
536
537 Q_D(QEventDispatcherGlib);
538 return d->timerSource->timerList.unregisterTimers(object);
539}
540
541QList<QEventDispatcherGlib::TimerInfoV2> QEventDispatcherGlib::timersForObject(QObject *object) const
542{
543#ifndef QT_NO_DEBUG
544 if (!object) {
545 qWarning("QEventDispatcherGlib:timersForObject: invalid argument");
546 return {};
547 }
548#endif
549
550 Q_D(const QEventDispatcherGlib);
551 return d->timerSource->timerList.registeredTimers(object);
552}
553
554QEventDispatcherGlib::Duration QEventDispatcherGlib::remainingTime(Qt::TimerId timerId) const
555{
556#ifndef QT_NO_DEBUG
557 if (qToUnderlying(timerId) < 1) {
558 qWarning("QEventDispatcherGlib::remainingTimeTime: invalid argument");
559 return Duration::min();
560 }
561#endif
562
563 Q_D(const QEventDispatcherGlib);
564 return d->timerSource->timerList.remainingDuration(timerId);
565}
566
567void QEventDispatcherGlib::interrupt()
568{
569 wakeUp();
570}
571
572void QEventDispatcherGlib::wakeUp()
573{
574 Q_D(QEventDispatcherGlib);
575 d->postEventSource->serialNumber.ref();
576 g_main_context_wakeup(d->mainContext);
577}
578
579bool QEventDispatcherGlib::versionSupported()
580{
581#if !defined(GLIB_MAJOR_VERSION) || !defined(GLIB_MINOR_VERSION) || !defined(GLIB_MICRO_VERSION)
582 return false;
583#else
584 return ((GLIB_MAJOR_VERSION << 16) + (GLIB_MINOR_VERSION << 8) + GLIB_MICRO_VERSION) >= 0x020301;
585#endif
586}
587
588QEventDispatcherGlib::QEventDispatcherGlib(QEventDispatcherGlibPrivate &dd, QObject *parent)
589 : QAbstractEventDispatcherV2(dd, parent)
590{
591}
592
593QT_END_NAMESPACE
594
595#include "moc_qeventdispatcher_glib_p.cpp"
static gboolean timerSourcePrepareHelper(GTimerSource *src, gint *timeout)
static gboolean postEventSourceDispatch(GSource *s, GSourceFunc, gpointer)
static gboolean timerSourceCheck(GSource *source)
static gboolean idleTimerSourcePrepare(GSource *source, gint *timeout)
static gboolean socketNotifierSourcePrepare(GSource *, gint *timeout)
static gboolean idleTimerSourceDispatch(GSource *source, GSourceFunc, gpointer)
static gboolean postEventSourcePrepare(GSource *s, gint *timeout)
static gboolean idleTimerSourceCheck(GSource *source)
static gboolean timerSourceCheckHelper(GTimerSource *src)
static gboolean socketNotifierSourceCheck(GSource *source)
static gboolean postEventSourceCheck(GSource *source)
static gboolean socketNotifierSourceDispatch(GSource *source, GSourceFunc, gpointer)
static gboolean timerSourcePrepare(GSource *source, gint *timeout)
static gboolean timerSourceDispatch(GSource *source, GSourceFunc, gpointer)
struct _GSource GSource
QEventDispatcherGlibPrivate * d
QList< GPollFDWithQSocketNotifier * > pollfds
QTimerInfoList timerList
QEventLoop::ProcessEventsFlags processEventsFlags