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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include "qcoreapplication.h"
#include "qpair.h"
#include "qsocketnotifier.h"
#include "qthread.h"
#include "qelapsedtimer.h"
#include "qeventdispatcher_unix_p.h"
#include <private/qthread_p.h>
#include <private/qcoreapplication_p.h>
#include <private/qcore_unix_p.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
// VxWorks doesn't correctly set the _POSIX_... options
#if defined(Q_OS_VXWORKS)
# if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK <= 0)
# undef _POSIX_MONOTONIC_CLOCK
# define _POSIX_MONOTONIC_CLOCK 1
# endif
# include <pipeDrv.h>
# include <selectLib.h>
#endif
#if (_POSIX_MONOTONIC_CLOCK-0 <= 0) || defined(QT_BOOTSTRAPPED)
# include <sys/times.h>
#endif
QT_BEGIN_NAMESPACE
Q_CORE_EXPORT bool qt_disable_lowpriority_timers=false;
/*****************************************************************************
UNIX signal handling
*****************************************************************************/
static sig_atomic_t signal_received;
static sig_atomic_t signals_fired[NSIG];
static void signalHandler(int sig)
{
signals_fired[sig] = 1;
signal_received = 1;
}
#if defined(Q_OS_INTEGRITY) || defined(Q_OS_VXWORKS)
static void initThreadPipeFD(int fd)
{
int ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
if (ret == -1)
perror("QEventDispatcherUNIXPrivate: Unable to init thread pipe");
int flags = fcntl(fd, F_GETFL);
if (flags == -1)
perror("QEventDispatcherUNIXPrivate: Unable to get flags on thread pipe");
ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (ret == -1)
perror("QEventDispatcherUNIXPrivate: Unable to set flags on thread pipe");
}
#endif
QEventDispatcherUNIXPrivate::QEventDispatcherUNIXPrivate()
{
extern Qt::HANDLE qt_application_thread_id;
mainThread = (QThread::currentThreadId() == qt_application_thread_id);
bool pipefail = false;
// initialize the common parts of the event loop
#if defined(Q_OS_INTEGRITY)
// INTEGRITY doesn't like a "select" on pipes, so use socketpair instead
if (socketpair(AF_INET, SOCK_STREAM, PF_INET, thread_pipe) == -1) {
perror("QEventDispatcherUNIXPrivate(): Unable to create socket pair");
pipefail = true;
} else {
initThreadPipeFD(thread_pipe[0]);
initThreadPipeFD(thread_pipe[1]);
}
#elif defined(Q_OS_VXWORKS)
char name[20];
qsnprintf(name, sizeof(name), "/pipe/qt_%08x", int(taskIdCurrent));
// make sure there is no pipe with this name
pipeDevDelete(name, true);
// create the pipe
if (pipeDevCreate(name, 128 /*maxMsg*/, 1 /*maxLength*/) != OK) {
perror("QEventDispatcherUNIXPrivate(): Unable to create thread pipe device");
pipefail = true;
} else {
if ((thread_pipe[0] = open(name, O_RDWR, 0)) < 0) {
perror("QEventDispatcherUNIXPrivate(): Unable to create thread pipe");
pipefail = true;
} else {
initThreadPipeFD(thread_pipe[0]);
thread_pipe[1] = thread_pipe[0];
}
}
#else
if (qt_safe_pipe(thread_pipe, O_NONBLOCK) == -1) {
perror("QEventDispatcherUNIXPrivate(): Unable to create thread pipe");
pipefail = true;
}
#endif
if (pipefail)
qFatal("QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe");
sn_highest = -1;
interrupt = false;
}
QEventDispatcherUNIXPrivate::~QEventDispatcherUNIXPrivate()
{
#if defined(Q_OS_VXWORKS)
close(thread_pipe[0]);
char name[20];
qsnprintf(name, sizeof(name), "/pipe/qt_%08x", int(taskIdCurrent));
pipeDevDelete(name, true);
#else
// cleanup the common parts of the event loop
close(thread_pipe[0]);
close(thread_pipe[1]);
#endif
// cleanup timers
qDeleteAll(timerList);
}
int QEventDispatcherUNIXPrivate::doSelect(QEventLoop::ProcessEventsFlags flags, timeval *timeout)
{
Q_Q(QEventDispatcherUNIX);
// needed in QEventDispatcherUNIX::select()
timerList.updateCurrentTime();
int nsel;
do {
if (mainThread) {
while (signal_received) {
signal_received = 0;
for (int i = 0; i < NSIG; ++i) {
if (signals_fired[i]) {
signals_fired[i] = 0;
emit QCoreApplication::instance()->unixSignal(i);
}
}
}
}
// Process timers and socket notifiers - the common UNIX stuff
int highest = 0;
if (! (flags & QEventLoop::ExcludeSocketNotifiers) && (sn_highest >= 0)) {
// return the highest fd we can wait for input on
sn_vec[0].select_fds = sn_vec[0].enabled_fds;
sn_vec[1].select_fds = sn_vec[1].enabled_fds;
sn_vec[2].select_fds = sn_vec[2].enabled_fds;
highest = sn_highest;
} else {
FD_ZERO(&sn_vec[0].select_fds);
FD_ZERO(&sn_vec[1].select_fds);
FD_ZERO(&sn_vec[2].select_fds);
}
FD_SET(thread_pipe[0], &sn_vec[0].select_fds);
highest = qMax(highest, thread_pipe[0]);
nsel = q->select(highest + 1,
&sn_vec[0].select_fds,
&sn_vec[1].select_fds,
&sn_vec[2].select_fds,
timeout);
} while (nsel == -1 && (errno == EINTR || errno == EAGAIN));
if (nsel == -1) {
if (errno == EBADF) {
// it seems a socket notifier has a bad fd... find out
// which one it is and disable it
fd_set fdset;
timeval tm;
tm.tv_sec = tm.tv_usec = 0l;
for (int type = 0; type < 3; ++type) {
QSockNotType::List &list = sn_vec[type].list;
if (list.size() == 0)
continue;
for (int i = 0; i < list.size(); ++i) {
QSockNot *sn = list[i];
FD_ZERO(&fdset);
FD_SET(sn->fd, &fdset);
int ret = -1;
do {
switch (type) {
case 0: // read
ret = select(sn->fd + 1, &fdset, 0, 0, &tm);
break;
case 1: // write
ret = select(sn->fd + 1, 0, &fdset, 0, &tm);
break;
case 2: // except
ret = select(sn->fd + 1, 0, 0, &fdset, &tm);
break;
}
} while (ret == -1 && (errno == EINTR || errno == EAGAIN));
if (ret == -1 && errno == EBADF) {
// disable the invalid socket notifier
static const char *t[] = { "Read", "Write", "Exception" };
qWarning("QSocketNotifier: Invalid socket %d and type '%s', disabling...",
sn->fd, t[type]);
sn->obj->setEnabled(false);
}
}
}
} else {
// EINVAL... shouldn't happen, so let's complain to stderr
// and hope someone sends us a bug report
perror("select");
}
}
// some other thread woke us up... consume the data on the thread pipe so that
// select doesn't immediately return next time
int nevents = 0;
if (nsel > 0 && FD_ISSET(thread_pipe[0], &sn_vec[0].select_fds)) {
#if defined(Q_OS_VXWORKS)
char c[16];
::read(thread_pipe[0], c, sizeof(c));
::ioctl(thread_pipe[0], FIOFLUSH, 0);
#else
char c[16];
while (::read(thread_pipe[0], c, sizeof(c)) > 0)
;
#endif
if (!wakeUps.testAndSetRelease(1, 0)) {
// hopefully, this is dead code
qWarning("QEventDispatcherUNIX: internal error, wakeUps.testAndSetRelease(1, 0) failed!");
}
++nevents;
}
// activate socket notifiers
if (! (flags & QEventLoop::ExcludeSocketNotifiers) && nsel > 0 && sn_highest >= 0) {
// if select says data is ready on any socket, then set the socket notifier
// to pending
for (int i=0; i<3; i++) {
QSockNotType::List &list = sn_vec[i].list;
for (int j = 0; j < list.size(); ++j) {
QSockNot *sn = list[j];
if (FD_ISSET(sn->fd, &sn_vec[i].select_fds))
q->setSocketNotifierPending(sn->obj);
}
}
}
return (nevents + q->activateSocketNotifiers());
}
/*
* Internal functions for manipulating timer data structures. The
* timerBitVec array is used for keeping track of timer identifiers.
*/
QTimerInfoList::QTimerInfoList()
{
#if (_POSIX_MONOTONIC_CLOCK-0 <= 0) && !defined(Q_OS_MAC)
if (!QElapsedTimer::isMonotonic()) {
// not using monotonic timers, initialize the timeChanged() machinery
previousTime = qt_gettime();
tms unused;
previousTicks = times(&unused);
ticksPerSecond = sysconf(_SC_CLK_TCK);
msPerTick = 1000/ticksPerSecond;
} else {
// detected monotonic timers
previousTime.tv_sec = previousTime.tv_usec = 0;
previousTicks = 0;
ticksPerSecond = 0;
msPerTick = 0;
}
#endif
firstTimerInfo = 0;
}
timeval QTimerInfoList::updateCurrentTime()
{
return (currentTime = qt_gettime());
}
#if ((_POSIX_MONOTONIC_CLOCK-0 <= 0) && !defined(Q_OS_MAC)) || defined(QT_BOOTSTRAPPED)
template <>
timeval qAbs(const timeval &t)
{
timeval tmp = t;
if (tmp.tv_sec < 0) {
tmp.tv_sec = -tmp.tv_sec - 1;
tmp.tv_usec -= 1000000;
}
if (tmp.tv_sec == 0 && tmp.tv_usec < 0) {
tmp.tv_usec = -tmp.tv_usec;
}
return normalizedTimeval(tmp);
}
/*
Returns true if the real time clock has changed by more than 10%
relative to the processor time since the last time this function was
called. This presumably means that the system time has been changed.
If /a delta is nonzero, delta is set to our best guess at how much the system clock was changed.
*/
bool QTimerInfoList::timeChanged(timeval *delta)
{
struct tms unused;
clock_t currentTicks = times(&unused);
clock_t elapsedTicks = currentTicks - previousTicks;
timeval elapsedTime = currentTime - previousTime;
timeval elapsedTimeTicks;
elapsedTimeTicks.tv_sec = elapsedTicks / ticksPerSecond;
elapsedTimeTicks.tv_usec = (((elapsedTicks * 1000) / ticksPerSecond) % 1000) * 1000;
timeval dummy;
if (!delta)
delta = &dummy;
*delta = elapsedTime - elapsedTimeTicks;
previousTicks = currentTicks;
previousTime = currentTime;
// If tick drift is more than 10% off compared to realtime, we assume that the clock has
// been set. Of course, we have to allow for the tick granularity as well.
timeval tickGranularity;
tickGranularity.tv_sec = 0;
tickGranularity.tv_usec = msPerTick * 1000;
return elapsedTimeTicks < ((qAbs(*delta) - tickGranularity) * 10);
}
void QTimerInfoList::repairTimersIfNeeded()
{
if (QElapsedTimer::isMonotonic())
return;
timeval delta;
if (timeChanged(&delta))
timerRepair(delta);
}
#else // !(_POSIX_MONOTONIC_CLOCK-0 <= 0) && !defined(QT_BOOTSTRAPPED)
void QTimerInfoList::repairTimersIfNeeded()
{
}
#endif
/*
insert timer info into list
*/
void QTimerInfoList::timerInsert(QTimerInfo *ti)
{
int index = size();
while (index--) {
register const QTimerInfo * const t = at(index);
if (!(ti->timeout < t->timeout))
break;
}
insert(index+1, ti);
}
/*
repair broken timer
*/
void QTimerInfoList::timerRepair(const timeval &diff)
{
// repair all timers
for (int i = 0; i < size(); ++i) {
register QTimerInfo *t = at(i);
t->timeout = t->timeout + diff;
}
}
/*
Returns the time to wait for the next timer, or null if no timers
are waiting.
*/
bool QTimerInfoList::timerWait(timeval &tm)
{
timeval currentTime = updateCurrentTime();
repairTimersIfNeeded();
// Find first waiting timer not already active
QTimerInfo *t = 0;
for (QTimerInfoList::const_iterator it = constBegin(); it != constEnd(); ++it) {
if (!(*it)->activateRef) {
t = *it;
break;
}
}
if (!t)
return false;
if (currentTime < t->timeout) {
// time to wait
tm = t->timeout - currentTime;
} else {
// no time to wait
tm.tv_sec = 0;
tm.tv_usec = 0;
}
return true;
}
void QTimerInfoList::registerTimer(int timerId, int interval, QObject *object)
{
QTimerInfo *t = new QTimerInfo;
t->id = timerId;
t->interval.tv_sec = interval / 1000;
t->interval.tv_usec = (interval % 1000) * 1000;
t->timeout = updateCurrentTime() + t->interval;
t->obj = object;
t->activateRef = 0;
timerInsert(t);
}
bool QTimerInfoList::unregisterTimer(int timerId)
{
// set timer inactive
for (int i = 0; i < count(); ++i) {
register QTimerInfo *t = at(i);
if (t->id == timerId) {
// found it
removeAt(i);
if (t == firstTimerInfo)
firstTimerInfo = 0;
if (t->activateRef)
*(t->activateRef) = 0;
// release the timer id
if (!QObjectPrivate::get(t->obj)->inThreadChangeEvent)
QAbstractEventDispatcherPrivate::releaseTimerId(timerId);
delete t;
return true;
}
}
// id not found
return false;
}
bool QTimerInfoList::unregisterTimers(QObject *object)
{
if (isEmpty())
return false;
for (int i = 0; i < count(); ++i) {
register QTimerInfo *t = at(i);
if (t->obj == object) {
// object found
removeAt(i);
if (t == firstTimerInfo)
firstTimerInfo = 0;
if (t->activateRef)
*(t->activateRef) = 0;
// release the timer id
if (!QObjectPrivate::get(t->obj)->inThreadChangeEvent)
QAbstractEventDispatcherPrivate::releaseTimerId(t->id);
delete t;
// move back one so that we don't skip the new current item
--i;
}
}
return true;
}
QList<QPair<int, int> > QTimerInfoList::registeredTimers(QObject *object) const
{
QList<QPair<int, int> > list;
for (int i = 0; i < count(); ++i) {
register const QTimerInfo * const t = at(i);
if (t->obj == object)
list << QPair<int, int>(t->id, t->interval.tv_sec * 1000 + t->interval.tv_usec / 1000);
}
return list;
}
/*
Activate pending timers, returning how many where activated.
*/
int QTimerInfoList::activateTimers()
{
if (qt_disable_lowpriority_timers || isEmpty())
return 0; // nothing to do
int n_act = 0, maxCount = 0;
firstTimerInfo = 0;
timeval currentTime = updateCurrentTime();
repairTimersIfNeeded();
// Find out how many timer have expired
for (QTimerInfoList::const_iterator it = constBegin(); it != constEnd(); ++it) {
if (currentTime < (*it)->timeout)
break;
maxCount++;
}
//fire the timers.
while (maxCount--) {
if (isEmpty())
break;
QTimerInfo *currentTimerInfo = first();
if (currentTime < currentTimerInfo->timeout)
break; // no timer has expired
if (!firstTimerInfo) {
firstTimerInfo = currentTimerInfo;
} else if (firstTimerInfo == currentTimerInfo) {
// avoid sending the same timer multiple times
break;
} else if (currentTimerInfo->interval < firstTimerInfo->interval
|| currentTimerInfo->interval == firstTimerInfo->interval) {
firstTimerInfo = currentTimerInfo;
}
// remove from list
removeFirst();
// determine next timeout time
currentTimerInfo->timeout += currentTimerInfo->interval;
if (currentTimerInfo->timeout < currentTime)
currentTimerInfo->timeout = currentTime + currentTimerInfo->interval;
// reinsert timer
timerInsert(currentTimerInfo);
if (currentTimerInfo->interval.tv_usec > 0 || currentTimerInfo->interval.tv_sec > 0)
n_act++;
if (!currentTimerInfo->activateRef) {
// send event, but don't allow it to recurse
currentTimerInfo->activateRef = ¤tTimerInfo;
QTimerEvent e(currentTimerInfo->id);
QCoreApplication::sendEvent(currentTimerInfo->obj, &e);
if (currentTimerInfo)
currentTimerInfo->activateRef = 0;
}
}
firstTimerInfo = 0;
return n_act;
}
QEventDispatcherUNIX::QEventDispatcherUNIX(QObject *parent)
: QAbstractEventDispatcher(*new QEventDispatcherUNIXPrivate, parent)
{ }
QEventDispatcherUNIX::QEventDispatcherUNIX(QEventDispatcherUNIXPrivate &dd, QObject *parent)
: QAbstractEventDispatcher(dd, parent)
{ }
QEventDispatcherUNIX::~QEventDispatcherUNIX()
{
Q_D(QEventDispatcherUNIX);
d->threadData->eventDispatcher = 0;
}
int QEventDispatcherUNIX::select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
timeval *timeout)
{
return qt_safe_select(nfds, readfds, writefds, exceptfds, timeout);
}
/*!
\internal
*/
void QEventDispatcherUNIX::registerTimer(int timerId, int interval, QObject *obj)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !obj) {
qWarning("QEventDispatcherUNIX::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(QEventDispatcherUNIX);
d->timerList.registerTimer(timerId, interval, obj);
}
/*!
\internal
*/
bool QEventDispatcherUNIX::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("QEventDispatcherUNIX::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(QEventDispatcherUNIX);
return d->timerList.unregisterTimer(timerId);
}
/*!
\internal
*/
bool QEventDispatcherUNIX::unregisterTimers(QObject *object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("QEventDispatcherUNIX::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(QEventDispatcherUNIX);
return d->timerList.unregisterTimers(object);
}
QList<QEventDispatcherUNIX::TimerInfo>
QEventDispatcherUNIX::registeredTimers(QObject *object) const
{
if (!object) {
qWarning("QEventDispatcherUNIX:registeredTimers: invalid argument");
return QList<TimerInfo>();
}
Q_D(const QEventDispatcherUNIX);
return d->timerList.registeredTimers(object);
}
/*****************************************************************************
Socket notifier type
*****************************************************************************/
QSockNotType::QSockNotType()
{
FD_ZERO(&select_fds);
FD_ZERO(&enabled_fds);
FD_ZERO(&pending_fds);
}
QSockNotType::~QSockNotType()
{
for (int i = 0; i < list.size(); ++i)
delete list[i];
}
/*****************************************************************************
QEventDispatcher implementations for UNIX
*****************************************************************************/
void QEventDispatcherUNIX::registerSocketNotifier(QSocketNotifier *notifier)
{
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(QEventDispatcherUNIX);
QSockNotType::List &list = d->sn_vec[type].list;
fd_set *fds = &d->sn_vec[type].enabled_fds;
QSockNot *sn;
sn = new QSockNot;
sn->obj = notifier;
sn->fd = sockfd;
sn->queue = &d->sn_vec[type].pending_fds;
int i;
for (i = 0; i < list.size(); ++i) {
QSockNot *p = list[i];
if (p->fd < sockfd)
break;
if (p->fd == sockfd) {
static const char *t[] = { "Read", "Write", "Exception" };
qWarning("QSocketNotifier: Multiple socket notifiers for "
"same socket %d and type %s", sockfd, t[type]);
}
}
list.insert(i, sn);
FD_SET(sockfd, fds);
d->sn_highest = qMax(d->sn_highest, sockfd);
}
void QEventDispatcherUNIX::unregisterSocketNotifier(QSocketNotifier *notifier)
{
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(QEventDispatcherUNIX);
QSockNotType::List &list = d->sn_vec[type].list;
fd_set *fds = &d->sn_vec[type].enabled_fds;
QSockNot *sn = 0;
int i;
for (i = 0; i < list.size(); ++i) {
sn = list[i];
if(sn->obj == notifier && sn->fd == sockfd)
break;
}
if (i == list.size()) // not found
return;
FD_CLR(sockfd, fds); // clear fd bit
FD_CLR(sockfd, sn->queue);
d->sn_pending_list.removeAll(sn); // remove from activation list
list.removeAt(i); // remove notifier found above
delete sn;
if (d->sn_highest == sockfd) { // find highest fd
d->sn_highest = -1;
for (int i=0; i<3; i++) {
if (!d->sn_vec[i].list.isEmpty())
d->sn_highest = qMax(d->sn_highest, // list is fd-sorted
d->sn_vec[i].list[0]->fd);
}
}
}
void QEventDispatcherUNIX::setSocketNotifierPending(QSocketNotifier *notifier)
{
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;
}
Q_ASSERT(notifier->thread() == thread() && thread() == QThread::currentThread());
#endif
Q_D(QEventDispatcherUNIX);
QSockNotType::List &list = d->sn_vec[type].list;
QSockNot *sn = 0;
int i;
for (i = 0; i < list.size(); ++i) {
sn = list[i];
if(sn->obj == notifier && sn->fd == sockfd)
break;
}
if (i == list.size()) // not found
return;
// We choose a random activation order to be more fair under high load.
// If a constant order is used and a peer early in the list can
// saturate the IO, it might grab our attention completely.
// Also, if we're using a straight list, the callback routines may
// delete other entries from the list before those other entries are
// processed.
if (! FD_ISSET(sn->fd, sn->queue)) {
if (d->sn_pending_list.isEmpty()) {
d->sn_pending_list.append(sn);
} else {
d->sn_pending_list.insert((qrand() & 0xff) %
(d->sn_pending_list.size()+1), sn);
}
FD_SET(sn->fd, sn->queue);
}
}
int QEventDispatcherUNIX::activateTimers()
{
Q_ASSERT(thread() == QThread::currentThread());
Q_D(QEventDispatcherUNIX);
return d->timerList.activateTimers();
}
int QEventDispatcherUNIX::activateSocketNotifiers()
{
Q_D(QEventDispatcherUNIX);
if (d->sn_pending_list.isEmpty())
return 0;
// activate entries
int n_act = 0;
QEvent event(QEvent::SockAct);
while (!d->sn_pending_list.isEmpty()) {
QSockNot *sn = d->sn_pending_list.takeFirst();
if (FD_ISSET(sn->fd, sn->queue)) {
FD_CLR(sn->fd, sn->queue);
QCoreApplication::sendEvent(sn->obj, &event);
++n_act;
}
}
return n_act;
}
bool QEventDispatcherUNIX::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(QEventDispatcherUNIX);
d->interrupt = false;
// we are awake, broadcast it
emit awake();
QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
int nevents = 0;
const bool canWait = (d->threadData->canWait
&& !d->interrupt
&& (flags & QEventLoop::WaitForMoreEvents));
if (canWait)
emit aboutToBlock();
if (!d->interrupt) {
// return the maximum time we can wait for an event.
timeval *tm = 0;
timeval wait_tm = { 0l, 0l };
if (!(flags & QEventLoop::X11ExcludeTimers)) {
if (d->timerList.timerWait(wait_tm))
tm = &wait_tm;
}
if (!canWait) {
if (!tm)
tm = &wait_tm;
// no time to wait
tm->tv_sec = 0l;
tm->tv_usec = 0l;
}
nevents = d->doSelect(flags, tm);
// activate timers
if (! (flags & QEventLoop::X11ExcludeTimers)) {
nevents += activateTimers();
}
}
// return true if we handled events, false otherwise
return (nevents > 0);
}
bool QEventDispatcherUNIX::hasPendingEvents()
{
extern uint qGlobalPostedEventsCount(); // from qapplication.cpp
return qGlobalPostedEventsCount();
}
void QEventDispatcherUNIX::wakeUp()
{
Q_D(QEventDispatcherUNIX);
if (d->wakeUps.testAndSetAcquire(0, 1)) {
char c = 0;
qt_safe_write( d->thread_pipe[1], &c, 1 );
}
}
void QEventDispatcherUNIX::interrupt()
{
Q_D(QEventDispatcherUNIX);
d->interrupt = true;
wakeUp();
}
void QEventDispatcherUNIX::flush()
{ }
void QCoreApplication::watchUnixSignal(int sig, bool watch)
{
if (sig < NSIG) {
struct sigaction sa;
sigemptyset(&(sa.sa_mask));
sa.sa_flags = 0;
if (watch)
sa.sa_handler = signalHandler;
else
sa.sa_handler = SIG_DFL;
sigaction(sig, &sa, 0);
}
}
QT_END_NAMESPACE
|