-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathqasioeventdispatcher.cpp
468 lines (403 loc) · 13.9 KB
/
qasioeventdispatcher.cpp
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
#include "qasioeventdispatcher.h"
#include <boost/asio/io_service.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/bind.hpp>
#include <qpa/qwindowsysteminterface.h>
//#include "qplatformdefs.h"
#include "qcoreapplication.h"
#include "qpair.h"
#include "qsocketnotifier.h"
#include "qthread.h"
#include "qelapsedtimer.h"
#include "private/qtimerinfo_unix_p.h"
#define LOG(expr) #expr": " << (expr) << "; "
/* TODO:
* - error types of sockets
* - handling flags passed to processEvents
*/
// One object per fd; three QSocketNotifier's may be connected to it;
struct QAsioSockNotifier
{
QAsioSockNotifier()
: pending_operations(0)
{
for(int i=0; i<3; ++i) {
notif[i]=0;
revision[i]=0;
}
}
QSocketNotifier *notif[3]; //notifiers for {Read, Write, Exception}
int revision[3]; //revision[x] is incremented each time notif[i] is changed (therefore a new completion handler loop is started)
int fd;
boost::asio::posix::stream_descriptor *sd;
int pending_operations;
};
class Q_CORE_EXPORT QAsioEventDispatcherPrivate : public QAbstractEventDispatcherPrivate
{
Q_DECLARE_PUBLIC(QAsioEventDispatcher)
public:
QAsioEventDispatcherPrivate(boost::asio::io_service &io_service);
~QAsioEventDispatcherPrivate();
boost::asio::io_service &io_service;
boost::asio::steady_timer nearest_timer;
QList<QAsioSockNotifier *> socketNotifiers;
QTimerInfoList timerList;
QAtomicInt interrupt;
QAsioSockNotifier *socketNotifierForFd(int fd, bool createIfNotFound);
void cleanupSocketNotifiers(bool forceRemoveAll);
void timerTimeout(const boost::system::error_code &error);
void timerStart();
void timerCancel();
};
QAsioEventDispatcherPrivate::QAsioEventDispatcherPrivate(boost::asio::io_service &io_service_)
: io_service(io_service_)
, nearest_timer(io_service)
{
}
QAsioEventDispatcherPrivate::~QAsioEventDispatcherPrivate()
{
cleanupSocketNotifiers(true);
Q_ASSERT(socketNotifiers.empty());
// cleanup timers
qDeleteAll(timerList);
}
QAsioEventDispatcher::QAsioEventDispatcher(boost::asio::io_service &io_service, QObject *parent)
: QAbstractEventDispatcher(*new QAsioEventDispatcherPrivate(io_service), parent)
{
}
QAsioEventDispatcher::QAsioEventDispatcher(QAsioEventDispatcherPrivate &dd, QObject *parent)
: QAbstractEventDispatcher(dd, parent)
{ }
QAsioEventDispatcher::~QAsioEventDispatcher()
{
}
void QAsioEventDispatcherPrivate::timerTimeout(const boost::system::error_code& error)
{
if(!error) {
(void) timerList.activateTimers();
}
}
void QAsioEventDispatcherPrivate::timerStart()
{
timespec tv = { 0l, 0l };
#if BOOST_ASIO_HAS_STD_CHRONO
using namespace std::chrono;
#else
using namespace boost::chrono;
#endif
if (/*FIXME: !(src->processEventsFlags & QEventLoop::X11ExcludeTimers) && */timerList.timerWait(tv)) {
nearest_timer.cancel();
nearest_timer.expires_from_now(seconds(tv.tv_sec) + nanoseconds(tv.tv_nsec ));
nearest_timer.async_wait(boost::bind(&QAsioEventDispatcherPrivate::timerTimeout, this, _1));
}
}
void QAsioEventDispatcherPrivate::timerCancel()
{
nearest_timer.cancel();
}
void QAsioEventDispatcher::registerTimer(int timerId, int interval, Qt::TimerType timerType, QObject *obj)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !obj) {
qWarning("QAsioEventDispatcher::registerTimer: invalid arguments");
return;
} else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::startTimer: timers cannot be started from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
d->timerList.registerTimer(timerId, interval, timerType, obj);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::unregisterTimer: invalid argument");
return false;
} else if (thread() != QThread::currentThread()) {
qWarning("QObject::killTimer: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimer(timerId);
}
/*!
\internal
*/
bool QAsioEventDispatcher::unregisterTimers(QObject *object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QAsioEventDispatcher::unregisterTimers: invalid argument");
return false;
} else if (object->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QObject::killTimers: timers cannot be stopped from another thread");
return false;
}
#endif
Q_D(QAsioEventDispatcher);
return d->timerList.unregisterTimers(object);
}
QList<QAsioEventDispatcher::TimerInfo>
QAsioEventDispatcher::registeredTimers(QObject *object) const
{
if (!object) {
qWarning("QAsioEventDispatcher:registeredTimers: invalid argument");
return QList<TimerInfo>();
}
Q_D(const QAsioEventDispatcher);
return d->timerList.registeredTimers(object);
}
int QAsioEventDispatcher::remainingTime(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QAsioEventDispatcher::remainingTime: invalid argument");
return -1;
}
#endif
//FIXME
Q_D(QAsioEventDispatcher);
return d->timerList.timerRemainingTime(timerId);
}
QAsioSockNotifier *QAsioEventDispatcherPrivate::socketNotifierForFd(int fd, bool createIfNotFound)
{
for(int i = 0; i < socketNotifiers.count(); ++i) {
QAsioSockNotifier *n = socketNotifiers.at(i);
if(n->fd == fd) return n;
}
if(createIfNotFound)
{
QAsioSockNotifier *sn = new QAsioSockNotifier;
sn->fd = fd;
sn->sd = new boost::asio::posix::stream_descriptor(io_service, fd);
socketNotifiers.push_back(sn);
return sn;
}
return 0;
}
void QAsioEventDispatcherPrivate::cleanupSocketNotifiers(bool forceRemoveAll = false)
{
for(int i = 0; i < socketNotifiers.count();) {
QAsioSockNotifier *sn = socketNotifiers.at(i);
if(sn->pending_operations == 0 || forceRemoveAll) {
if(!forceRemoveAll) {
Q_ASSERT(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0);
}
//removeAll, but there should be only one instance in the list
socketNotifiers.removeAll(sn);
delete sn->sd;
delete sn;
}
else {
++i;
}
}
}
static void fdReadStart(QAsioSockNotifier *sn);
static void fdWriteStart(QAsioSockNotifier *sn);
static void fdReadReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Read;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdReadStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdWriteReady(QAsioSockNotifier *sn, const boost::system::error_code& error, int revision)
{
sn->pending_operations--;
int type = (int)QSocketNotifier::Write;
bool sn_changed = sn->revision[type] != revision;
if(!sn_changed && !error) {
fdWriteStart(sn);
QEvent event(QEvent::SockAct);
QCoreApplication::sendEvent(sn->notif[type], &event);
}
else {
}
}
static void fdReadStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Read;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_read_some(boost::asio::null_buffers(), boost::bind(fdReadReady, sn, _1, sn->revision[type]));
}
static void fdWriteStart(QAsioSockNotifier *sn)
{
int type = (int)QSocketNotifier::Write;
sn->pending_operations++;
Q_ASSERT(sn->notif[type]);
sn->sd->async_write_some(boost::asio::null_buffers(), boost::bind(fdWriteReady, sn, _1, sn->revision[type]));
}
void QAsioEventDispatcher::registerSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
//std::clog << LOG(d->socketNotifiers.size()) << std::endl;
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, true);
Q_ASSERT(sn);
Q_ASSERT(type<3 && type>=0);
Q_ASSERT(sn->notif[type] == 0);
sn->notif[type] = notifier;
sn->revision[type]++;
switch(type)
{
case QSocketNotifier::Read:
fdReadStart(sn);
break;
case QSocketNotifier::Write:
fdWriteStart(sn);
break;
default:
qFatal("Not supported socket type");
//TODO: write, error...
}
}
void QAsioEventDispatcher::unregisterSocketNotifier(QSocketNotifier *notifier)
{
//std::clog<< __PRETTY_FUNCTION__ << LOG(notifier->type()) << LOG(notifier->socket()) << std::endl;
Q_ASSERT(notifier);
int sockfd = notifier->socket();
int type = notifier->type();
#ifndef QT_NO_DEBUG
if (sockfd < 0
|| unsigned(sockfd) >= FD_SETSIZE) {
qWarning("QSocketNotifier: Internal error");
return;
} else if (notifier->thread() != thread()
|| thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
Q_D(QAsioEventDispatcher);
QAsioSockNotifier *sn = d->socketNotifierForFd(sockfd, false);
Q_ASSERT(sn);
if(sn)
{
Q_ASSERT(sn->notif[type] == notifier);
sn->notif[type] = 0;
sn->revision[type]++;
if(sn->notif[0] == 0
&& sn->notif[1] == 0
&& sn->notif[2] == 0
) {
//if no more socket notifiers on given fd are pending, we don't need it anymore
//but we cannot delete "sn" yet, since some handlers that use it may be pending (see fdMaybeCleanup())
sn->sd->cancel();
//sn->sd->close();
//d->removeSocketNotifier(sn);
//FIXME: what if we create a new sn on the same fd soon (while handlers are still pending)?
}
//if not all notifiers are unregistered, we don't cancel pending handler, since we cannot do it selectively (i.e. cancel only read or only write)
//however, it's not a problem, since it will notice that sn->revision doesn't match and will "cancel" itself during the next call
}
}
bool QAsioEventDispatcher::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(0);
//QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData); //unix dispatcher use this
QCoreApplication::sendPostedEvents(); //glib dispatcher call this after every call of "awake".
const bool canWait = (/*d->threadData->canWaitLocked()
&&*/ !d->interrupt.load() //it may have been set during the call of QCoreApplication::sendPostedEvents()
&& (flags & QEventLoop::WaitForMoreEvents));
if (d->interrupt.load())
{
return false; //unix event dispatcher returns false if nothing more than "postedEvents" were dispatched
}
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
int total_events = 0; /* FIXME: +1 for stop? */
if (canWait) {
//run at least one handler - may block
emit aboutToBlock();
d->io_service.reset();
total_events += d->io_service.run_one();
emit awake();
}
int events;
do
{
if (!(flags & QEventLoop::X11ExcludeTimers)) {
d->timerStart();
}
d->io_service.reset();
//run all ready handlers
events = d->io_service.poll();
if ((flags & QEventLoop::ExcludeSocketNotifiers)) {
//FIXME: ignore stream descriptors
}
if ((flags & QEventLoop::X11ExcludeTimers)) {
//FIXME: ignore timers?
}
total_events += events;
QCoreApplication::sendPostedEvents();
total_events += QWindowSystemInterface::sendWindowSystemEvents(flags) ? 1 : 0;
} while(events>0);
d->cleanupSocketNotifiers();
// return true if we handled events, false otherwise
return (total_events > 0);
}
bool QAsioEventDispatcher::hasPendingEvents()
{
//This is copy-pasted from QUnixEventDispatcherQPA. I don't really understand how it works.
extern uint qGlobalPostedEventsCount(); // from qapplication.cpp
return qGlobalPostedEventsCount() || QWindowSystemInterface::windowSystemEventsQueued();
}
void QAsioEventDispatcher::wakeUp()
{
Q_D(QAsioEventDispatcher);
//I don't know what a logic stays behind it, but qeventdispatcher_glib works in such a way, that after every "wakeUp", the following function is called
//io_service.post(QCoreApplication::sendPostedEvents);
d->io_service.stop(); //exit from run_one
}
void QAsioEventDispatcher::interrupt()
{
Q_D(QAsioEventDispatcher);
d->interrupt.store(1);
wakeUp();
}
void QAsioEventDispatcher::flush()
{
/* It does nothing in glib event dispatcher.
*
* QUnixEventDispatcherQPA calls QCoreApplication::instance()->sendPostedEvents here.
*
* But the docs of QAbstractEventDispatcher says:
* "flushes the event queue. This normally returns almost immediately. Does nothing on platforms other than X11"
*
* I'm a bit confused. FIXME
*/
}
QT_END_NAMESPACE