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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
|
/****************************************************************************
**
** 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 "qeventdispatcher_symbian_p.h"
#include <private/qthread_p.h>
#include <qcoreapplication.h>
#include <private/qcoreapplication_p.h>
#include <unistd.h>
#include <errno.h>
#include <net/if.h>
QT_BEGIN_NAMESPACE
#ifdef SYMBIAN_GRAPHICS_WSERV_QT_EFFECTS
// when the system UI is Qt based, priority drop is not needed as CPU starved processes will not be killed.
#undef QT_SYMBIAN_PRIORITY_DROP
#else
#define QT_SYMBIAN_PRIORITY_DROP
#endif
#define WAKE_UP_PRIORITY CActive::EPriorityStandard
#define TIMER_PRIORITY CActive::EPriorityHigh
#define NULLTIMER_PRIORITY CActive::EPriorityLow
#define COMPLETE_DEFERRED_ACTIVE_OBJECTS_PRIORITY CActive::EPriorityIdle
static inline int qt_pipe_write(int socket, const char *data, qint64 len)
{
return ::write(socket, data, len);
}
#if defined(write)
# undef write
#endif
static inline int qt_pipe_close(int socket)
{
return ::close(socket);
}
#if defined(close)
# undef close
#endif
static inline int qt_pipe_fcntl(int socket, int command)
{
return ::fcntl(socket, command);
}
static inline int qt_pipe2_fcntl(int socket, int command, int option)
{
return ::fcntl(socket, command, option);
}
#if defined(fcntl)
# undef fcntl
#endif
static inline int qt_socket_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
return ::select(nfds, readfds, writefds, exceptfds, timeout);
}
// This simply interrupts the select and locks the mutex until destroyed.
class QSelectMutexGrabber
{
public:
QSelectMutexGrabber(int fd, QMutex *mutex)
: m_mutex(mutex)
{
if (m_mutex->tryLock())
return;
char dummy = 0;
qt_pipe_write(fd, &dummy, 1);
m_mutex->lock();
}
~QSelectMutexGrabber()
{
m_mutex->unlock();
}
private:
QMutex *m_mutex;
};
/*
* This class is designed to aid in implementing event handling in a more round robin fashion. We
* cannot change active objects that we do not own, but the active objects that Qt owns will use
* this as a base class with convenience functions.
*
* Here is how it works: On every RunL, the deriving class should call okToRun(). This will allow
* exactly one run of the active object, and mark it as such. If it is called again, it will return
* false, and add the object to a queue so it can be run later.
*
* The QCompleteDeferredAOs class is a special object that runs after all others, which will
* reactivate the objects that were previously not run.
*/
inline QActiveObject::QActiveObject(TInt priority, QEventDispatcherSymbian *dispatcher)
: CActive(priority),
m_dispatcher(dispatcher),
m_hasAlreadyRun(false),
m_hasRunAgain(false),
m_iterationCount(1)
{
}
QActiveObject::~QActiveObject()
{
if (m_hasRunAgain)
m_dispatcher->removeDeferredActiveObject(this);
}
bool QActiveObject::okToRun()
{
Q_ASSERT(!m_hasRunAgain);
if (!m_hasAlreadyRun || m_dispatcher->iterationCount() != m_iterationCount) {
// First occurrence of this event in this iteration.
m_hasAlreadyRun = true;
m_iterationCount = m_dispatcher->iterationCount();
return true;
} else {
// The event has already occurred.
m_dispatcher->addDeferredActiveObject(this);
m_hasRunAgain = true;
return false;
}
}
void QActiveObject::reactivateAndComplete()
{
iStatus = KRequestPending;
SetActive();
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
m_hasRunAgain = false;
m_hasAlreadyRun = false;
}
QWakeUpActiveObject::QWakeUpActiveObject(QEventDispatcherSymbian *dispatcher)
: CActive(WAKE_UP_PRIORITY),
m_dispatcher(dispatcher)
{
CActiveScheduler::Add(this);
iStatus = KRequestPending;
SetActive();
}
QWakeUpActiveObject::~QWakeUpActiveObject()
{
Cancel();
}
void QWakeUpActiveObject::DoCancel()
{
if (iStatus.Int() == KRequestPending) {
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
void QWakeUpActiveObject::RunL()
{
iStatus = KRequestPending;
SetActive();
QT_TRYCATCH_LEAVING(m_dispatcher->wakeUpWasCalled());
}
QTimerActiveObject::QTimerActiveObject(QEventDispatcherSymbian *dispatcher, SymbianTimerInfo *timerInfo)
: QActiveObject((timerInfo->interval) ? TIMER_PRIORITY : NULLTIMER_PRIORITY , dispatcher),
m_timerInfo(timerInfo)
{
}
QTimerActiveObject::~QTimerActiveObject()
{
Cancel();
}
void QTimerActiveObject::DoCancel()
{
if (m_timerInfo->interval > 0) {
m_rTimer.Cancel();
m_rTimer.Close();
} else {
if (iStatus.Int() == KRequestPending) {
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
}
void QTimerActiveObject::RunL()
{
int error;
QT_TRYCATCH_ERROR(error, Run());
// All Symbian error codes are negative.
if (error < 0) {
CActiveScheduler::Current()->Error(error); // stop and report here, as this timer will be deleted on scope exit
}
}
#define MAX_SYMBIAN_TIMEOUT_MS 2000000
void QTimerActiveObject::StartTimer()
{
if (m_timerInfo->msLeft > MAX_SYMBIAN_TIMEOUT_MS) {
//There is loss of accuracy anyway due to needing to restart the timer every 33 minutes,
//so the 1/64s res of After() is acceptable for these very long timers.
m_rTimer.After(iStatus, MAX_SYMBIAN_TIMEOUT_MS * 1000);
m_timerInfo->msLeft -= MAX_SYMBIAN_TIMEOUT_MS;
} else {
//HighRes gives the 1ms accuracy expected by Qt, the +1 is to ensure that
//"Timers will never time out earlier than the specified timeout value"
//condition is always met.
m_rTimer.HighRes(iStatus, (m_timerInfo->msLeft + 1) * 1000);
m_timerInfo->msLeft = 0;
}
SetActive();
}
void QTimerActiveObject::Run()
{
//restart timer immediately, if the timeout has been split because it overflows max for platform.
if (m_timerInfo->msLeft > 0) {
StartTimer();
return;
}
if (!okToRun())
return;
if (m_timerInfo->interval > 0) {
// Start a new timer immediately so that we don't lose time.
m_timerInfo->msLeft = m_timerInfo->interval;
StartTimer();
m_timerInfo->dispatcher->timerFired(m_timerInfo->timerId);
} else {
// However, we only complete zero timers after the event has finished,
// in order to prevent busy looping when doing nested loops.
// Keep the refpointer around in order to avoid deletion until the end of this function.
SymbianTimerInfoPtr timerInfoPtr(m_timerInfo);
m_timerInfo->dispatcher->timerFired(m_timerInfo->timerId);
iStatus = KRequestPending;
SetActive();
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
void QTimerActiveObject::Start()
{
CActiveScheduler::Add(this);
m_timerInfo->msLeft = m_timerInfo->interval;
if (m_timerInfo->interval > 0) {
m_rTimer.CreateLocal();
StartTimer();
} else {
iStatus = KRequestPending;
SetActive();
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
SymbianTimerInfo::SymbianTimerInfo()
: timerAO(0)
{
}
SymbianTimerInfo::~SymbianTimerInfo()
{
delete timerAO;
}
QCompleteDeferredAOs::QCompleteDeferredAOs(QEventDispatcherSymbian *dispatcher)
: CActive(COMPLETE_DEFERRED_ACTIVE_OBJECTS_PRIORITY),
m_dispatcher(dispatcher)
{
CActiveScheduler::Add(this);
iStatus = KRequestPending;
SetActive();
}
QCompleteDeferredAOs::~QCompleteDeferredAOs()
{
Cancel();
}
void QCompleteDeferredAOs::complete()
{
if (iStatus.Int() == KRequestPending) {
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
void QCompleteDeferredAOs::DoCancel()
{
if (iStatus.Int() == KRequestPending) {
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
void QCompleteDeferredAOs::RunL()
{
iStatus = KRequestPending;
SetActive();
QT_TRYCATCH_LEAVING(m_dispatcher->reactivateDeferredActiveObjects());
}
QSelectThread::QSelectThread()
: m_quit(false)
{
if (::pipe(m_pipeEnds) != 0) {
qWarning("Select thread was unable to open a pipe, errno: %i", errno);
} else {
int flags0 = qt_pipe_fcntl(m_pipeEnds[0], F_GETFL);
int flags1 = qt_pipe_fcntl(m_pipeEnds[1], F_GETFL);
// We should check the error code here, but Open C has a bug that returns
// failure even though the operation was successful.
qt_pipe2_fcntl(m_pipeEnds[0], F_SETFL, flags0 | O_NONBLOCK);
qt_pipe2_fcntl(m_pipeEnds[1], F_SETFL, flags1 | O_NONBLOCK);
}
}
QSelectThread::~QSelectThread()
{
qt_pipe_close(m_pipeEnds[1]);
qt_pipe_close(m_pipeEnds[0]);
}
void QSelectThread::run()
{
Q_D(QThread);
m_mutex.lock();
while (!m_quit) {
fd_set readfds;
fd_set writefds;
fd_set exceptionfds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptionfds);
int maxfd = 0;
maxfd = qMax(maxfd, updateSocketSet(QSocketNotifier::Read, &readfds));
maxfd = qMax(maxfd, updateSocketSet(QSocketNotifier::Write, &writefds));
maxfd = qMax(maxfd, updateSocketSet(QSocketNotifier::Exception, &exceptionfds));
maxfd = qMax(maxfd, m_pipeEnds[0]);
maxfd++;
FD_SET(m_pipeEnds[0], &readfds);
int ret;
int savedSelectErrno;
ret = qt_socket_select(maxfd, &readfds, &writefds, &exceptionfds, 0);
savedSelectErrno = errno;
char buffer;
while (::read(m_pipeEnds[0], &buffer, 1) > 0) {}
if(ret == 0) {
// do nothing
} else if (ret < 0) {
switch (savedSelectErrno) {
case EBADF:
case EINVAL:
case ENOMEM:
case EFAULT:
qWarning("::select() returned an error: %i", savedSelectErrno);
break;
case ECONNREFUSED:
case EPIPE:
qWarning("::select() returned an error: %i (go through sockets)", savedSelectErrno);
// prepare to go through all sockets
// mark in fd sets both:
// good ones
// ones that return -1 in select
// after loop update notifiers for all of them
// as we dont have "exception" notifier type
// we should force monitoring fd_set of this
// type as well
// clean @ start
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptionfds);
for (QHash<QSocketNotifier *, TRequestStatus *>::const_iterator i = m_AOStatuses.begin();
i != m_AOStatuses.end(); ++i) {
fd_set onefds;
FD_ZERO(&onefds);
FD_SET(i.key()->socket(), &onefds);
fd_set excfds;
FD_ZERO(&excfds);
FD_SET(i.key()->socket(), &excfds);
maxfd = i.key()->socket() + 1;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
ret = 0;
if(i.key()->type() == QSocketNotifier::Read) {
ret = ::select(maxfd, &onefds, 0, &excfds, &timeout);
if(ret != 0) FD_SET(i.key()->socket(), &readfds);
} else if(i.key()->type() == QSocketNotifier::Write) {
ret = ::select(maxfd, 0, &onefds, &excfds, &timeout);
if(ret != 0) FD_SET(i.key()->socket(), &writefds);
}
} // end for
// traversed all, so update
updateActivatedNotifiers(QSocketNotifier::Read, &readfds);
updateActivatedNotifiers(QSocketNotifier::Write, &writefds);
updateActivatedNotifiers(QSocketNotifier::Exception, &exceptionfds);
break;
case EINTR: // Should never occur on Symbian, but this is future proof!
default:
qWarning("::select() returned an unknown error: %i", savedSelectErrno);
break;
}
} else {
updateActivatedNotifiers(QSocketNotifier::Read, &readfds);
updateActivatedNotifiers(QSocketNotifier::Write, &writefds);
updateActivatedNotifiers(QSocketNotifier::Exception, &exceptionfds);
}
m_waitCond.wait(&m_mutex);
}
m_mutex.unlock();
}
void QSelectThread::requestSocketEvents ( QSocketNotifier *notifier, TRequestStatus *status )
{
Q_D(QThread);
if (!isRunning()) {
start();
}
QSelectMutexGrabber lock(m_pipeEnds[1], &m_mutex);
Q_ASSERT(!m_AOStatuses.contains(notifier));
m_AOStatuses.insert(notifier, status);
m_waitCond.wakeAll();
}
void QSelectThread::cancelSocketEvents ( QSocketNotifier *notifier )
{
QSelectMutexGrabber lock(m_pipeEnds[1], &m_mutex);
m_AOStatuses.remove(notifier);
m_waitCond.wakeAll();
}
void QSelectThread::restart()
{
QSelectMutexGrabber lock(m_pipeEnds[1], &m_mutex);
m_waitCond.wakeAll();
}
int QSelectThread::updateSocketSet(QSocketNotifier::Type type, fd_set *fds)
{
int maxfd = 0;
if(m_AOStatuses.isEmpty()) {
/*
* Wonder if should return -1
* to signal that no descriptors
* added to fds
*/
return maxfd;
}
for ( QHash<QSocketNotifier *, TRequestStatus *>::const_iterator i = m_AOStatuses.begin();
i != m_AOStatuses.end(); ++i) {
if (i.key()->type() == type) {
FD_SET(i.key()->socket(), fds);
maxfd = qMax(maxfd, i.key()->socket());
} else if(type == QSocketNotifier::Exception) {
/*
* We are registering existing sockets
* always to exception set
*
* Doing double FD_SET shouldn't
* matter
*/
FD_SET(i.key()->socket(), fds);
maxfd = qMax(maxfd, i.key()->socket());
}
}
return maxfd;
}
void QSelectThread::updateActivatedNotifiers(QSocketNotifier::Type type, fd_set *fds)
{
Q_D(QThread);
if(m_AOStatuses.isEmpty()) {
return;
}
QList<QSocketNotifier *> toRemove;
for (QHash<QSocketNotifier *, TRequestStatus *>::const_iterator i = m_AOStatuses.begin();
i != m_AOStatuses.end(); ++i) {
if (i.key()->type() == type && FD_ISSET(i.key()->socket(), fds)) {
toRemove.append(i.key());
TRequestStatus *status = i.value();
// Thread data is still owned by the main thread.
QEventDispatcherSymbian::RequestComplete(d->threadData->symbian_thread_handle, status, KErrNone);
} else if(type == QSocketNotifier::Exception && FD_ISSET(i.key()->socket(), fds)) {
/*
* check if socket is in exception set
* then signal RequestComplete for it
*/
qWarning("exception on %d [will do setdefaultif(0) - hack]", i.key()->socket());
// quick fix; there is a bug
// when doing read on socket
// errors not preoperly mapped
// after offline-ing the device
// on some devices we do get exception
// close all exiting sockets
// and reset default IAP
if(::setdefaultif(0) != KErrNone) // well we can't do much about it
qWarning("setdefaultif(0) failed");
toRemove.append(i.key());
TRequestStatus *status = i.value();
QEventDispatcherSymbian::RequestComplete(d->threadData->symbian_thread_handle, status, KErrNone);
}
}
for (int c = 0; c < toRemove.size(); ++c) {
m_AOStatuses.remove(toRemove[c]);
}
}
void QSelectThread::stop()
{
m_quit = true;
restart();
wait();
}
QSocketActiveObject::QSocketActiveObject(QEventDispatcherSymbian *dispatcher, QSocketNotifier *notifier)
: QActiveObject(CActive::EPriorityStandard, dispatcher),
m_notifier(notifier),
m_inSocketEvent(false),
m_deleteLater(false)
{
CActiveScheduler::Add(this);
iStatus = KRequestPending;
SetActive();
}
QSocketActiveObject::~QSocketActiveObject()
{
Cancel();
}
void QSocketActiveObject::DoCancel()
{
if (iStatus.Int() == KRequestPending) {
TRequestStatus *status = &iStatus;
QEventDispatcherSymbian::RequestComplete(status, KErrNone);
}
}
void QSocketActiveObject::RunL()
{
if (!okToRun())
return;
QT_TRYCATCH_LEAVING(m_dispatcher->socketFired(this));
}
void QSocketActiveObject::deleteLater()
{
if (m_inSocketEvent) {
m_deleteLater = true;
} else {
delete this;
}
}
#ifdef QT_SYMBIAN_PRIORITY_DROP
class QIdleDetectorThread
{
public:
QIdleDetectorThread()
: m_state(STATE_RUN), m_stop(false)
{
qt_symbian_throwIfError(m_lock.CreateLocal(0));
TInt err = m_idleDetectorThread.Create(KNullDesC(), &idleDetectorThreadFunc, 1024, NULL, this);
if (err != KErrNone)
m_lock.Close();
qt_symbian_throwIfError(err);
m_idleDetectorThread.SetPriority(EPriorityAbsoluteBackgroundNormal);
m_idleDetectorThread.Resume();
}
~QIdleDetectorThread()
{
// close down the idle thread because if corelib is loaded temporarily, this would leak threads into the host process
m_stop = true;
m_lock.Signal();
m_idleDetectorThread.SetPriority(EPriorityNormal);
TRequestStatus s;
m_idleDetectorThread.Logon(s);
User::WaitForRequest(s);
m_idleDetectorThread.Close();
m_lock.Close();
}
void kick()
{
m_state = STATE_KICKED;
m_lock.Signal();
}
bool hasRun()
{
return m_state == STATE_RUN;
}
private:
static TInt idleDetectorThreadFunc(TAny* self)
{
static_cast<QIdleDetectorThread*>(self)->IdleLoop();
return KErrNone;
}
void IdleLoop()
{
while (!m_stop) {
m_lock.Wait();
m_state = STATE_RUN;
}
}
private:
enum IdleStates {STATE_KICKED, STATE_RUN} m_state;
bool m_stop;
RThread m_idleDetectorThread;
RSemaphore m_lock;
};
Q_GLOBAL_STATIC(QIdleDetectorThread, idleDetectorThread);
const int maxBusyTime = 2000; // maximum time we allow idle detector to be blocked before worrying, in milliseconds
const int baseDelay = 1000; // minimum delay time used when backing off to allow idling, in microseconds
#endif
QEventDispatcherSymbian::QEventDispatcherSymbian(QObject *parent)
: QAbstractEventDispatcher(parent),
m_selectThread(0),
m_activeScheduler(0),
m_wakeUpAO(0),
m_completeDeferredAOs(0),
m_interrupt(false),
m_wakeUpDone(0),
m_iterationCount(0),
m_noSocketEvents(false)
{
#ifdef QT_SYMBIAN_PRIORITY_DROP
m_delay = baseDelay;
m_avgEventTime = 0;
idleDetectorThread();
#endif
}
QEventDispatcherSymbian::~QEventDispatcherSymbian()
{
}
void QEventDispatcherSymbian::startingUp()
{
if( !CActiveScheduler::Current() ) {
m_activeScheduler = q_check_ptr(new CQtActiveScheduler()); // CBase derived class needs to be checked on new
CActiveScheduler::Install(m_activeScheduler);
}
m_wakeUpAO = q_check_ptr(new QWakeUpActiveObject(this));
m_completeDeferredAOs = q_check_ptr(new QCompleteDeferredAOs(this));
// We already might have posted events, wakeup once to process them
wakeUp();
}
QSelectThread& QEventDispatcherSymbian::selectThread() {
if (!m_selectThread)
m_selectThread = new QSelectThread;
return *m_selectThread;
}
void QEventDispatcherSymbian::closingDown()
{
if (m_selectThread && m_selectThread->isRunning()) {
m_selectThread->stop();
}
delete m_selectThread;
m_selectThread = 0;
delete m_completeDeferredAOs;
delete m_wakeUpAO;
if (m_activeScheduler) {
delete m_activeScheduler;
}
}
bool QEventDispatcherSymbian::processEvents ( QEventLoop::ProcessEventsFlags flags )
{
bool handledAnyEvent = false;
bool oldNoSocketEventsValue = m_noSocketEvents;
QT_TRY {
Q_D(QAbstractEventDispatcher);
// It is safe if this counter overflows. The main importance is that each
// iteration count is different from the last.
m_iterationCount++;
RThread &thread = d->threadData->symbian_thread_handle;
bool block;
if (flags & QEventLoop::WaitForMoreEvents) {
block = true;
emit aboutToBlock();
} else {
block = false;
}
if (flags & QEventLoop::ExcludeSocketNotifiers) {
m_noSocketEvents = true;
} else {
m_noSocketEvents = false;
handledAnyEvent = sendDeferredSocketEvents();
}
bool handledSymbianEvent = false;
m_interrupt = false;
#ifdef QT_SYMBIAN_PRIORITY_DROP
QTime eventTimer;
#endif
while (1) {
if (block) {
// This is where Qt will spend most of its time.
CActiveScheduler::Current()->WaitForAnyRequest();
} else {
if (thread.RequestCount() == 0) {
break;
}
// This one should return without delay.
CActiveScheduler::Current()->WaitForAnyRequest();
}
#ifdef QT_SYMBIAN_PRIORITY_DROP
if (idleDetectorThread()->hasRun()) {
if (m_delay > baseDelay)
m_delay -= baseDelay;
m_lastIdleRequestTimer.start();
idleDetectorThread()->kick();
} else if (m_lastIdleRequestTimer.elapsed() > maxBusyTime) {
User::AfterHighRes(m_delay);
// allow delay to be up to 1/4 of execution time
if (!idleDetectorThread()->hasRun() && m_delay*3 < m_avgEventTime)
m_delay += baseDelay;
}
eventTimer.start();
#endif
TInt error;
handledSymbianEvent = CActiveScheduler::RunIfReady(error, KMinTInt);
if (error) {
qWarning("CActiveScheduler::RunIfReady() returned error: %i\n", error);
CActiveScheduler::Current()->Error(error);
}
#ifdef QT_SYMBIAN_PRIORITY_DROP
int eventDur = eventTimer.elapsed()*1000;
// average is calcualted as a 5% decaying exponential average
m_avgEventTime = (m_avgEventTime * 95 + eventDur * 5) / 100;
#endif
if (!handledSymbianEvent) {
qFatal("QEventDispatcherSymbian::processEvents(): Caught Symbian stray signal");
}
handledAnyEvent = true;
if (m_interrupt) {
break;
}
block = false;
};
emit awake();
} QT_CATCH (const std::exception& ex) {
#ifndef QT_NO_EXCEPTIONS
CActiveScheduler::Current()->Error(qt_symbian_exception2Error(ex));
#endif
}
m_noSocketEvents = oldNoSocketEventsValue;
return handledAnyEvent;
}
void QEventDispatcherSymbian::timerFired(int timerId)
{
QHash<int, SymbianTimerInfoPtr>::iterator i = m_timerList.find(timerId);
if (i == m_timerList.end()) {
// The timer has been deleted. Ignore this event.
return;
}
SymbianTimerInfoPtr timerInfo = *i;
// Prevent infinite timer recursion.
if (timerInfo->inTimerEvent) {
return;
}
timerInfo->inTimerEvent = true;
QTimerEvent event(timerInfo->timerId);
QCoreApplication::sendEvent(timerInfo->receiver, &event);
timerInfo->inTimerEvent = false;
return;
}
void QEventDispatcherSymbian::socketFired(QSocketActiveObject *socketAO)
{
if (m_noSocketEvents) {
m_deferredSocketEvents.append(socketAO);
return;
}
QEvent e(QEvent::SockAct);
socketAO->m_inSocketEvent = true;
QCoreApplication::sendEvent(socketAO->m_notifier, &e);
socketAO->m_inSocketEvent = false;
if (socketAO->m_deleteLater) {
delete socketAO;
} else {
socketAO->iStatus = KRequestPending;
socketAO->SetActive();
reactivateSocketNotifier(socketAO->m_notifier);
}
}
void QEventDispatcherSymbian::wakeUpWasCalled()
{
// The reactivation should happen in RunL, right before the call to this function.
// This is because m_wakeUpDone is the "signal" that the object can be completed
// once more.
// Also, by dispatching the posted events after resetting m_wakeUpDone, we guarantee
// that no posted event notification will be lost. If we did it the other way
// around, it would be possible for another thread to post an event right after
// the sendPostedEvents was done, but before the object was ready to be completed
// again. This could deadlock the application if there are no other posted events.
m_wakeUpDone.fetchAndStoreOrdered(0);
sendPostedEvents();
}
void QEventDispatcherSymbian::interrupt()
{
m_interrupt = true;
wakeUp();
}
void QEventDispatcherSymbian::wakeUp()
{
Q_D(QAbstractEventDispatcher);
if (m_wakeUpAO && m_wakeUpDone.testAndSetAcquire(0, 1)) {
TRequestStatus *status = &m_wakeUpAO->iStatus;
QEventDispatcherSymbian::RequestComplete(d->threadData->symbian_thread_handle, status, KErrNone);
}
}
bool QEventDispatcherSymbian::sendPostedEvents()
{
Q_D(QAbstractEventDispatcher);
// moveToThread calls this and canWait == true -> Events will never get processed
// if we check for d->threadData->canWait
//
// QCoreApplication::postEvent sets canWait = false, but after the object and events
// are moved to a new thread, the canWait in new thread is true i.e. not changed to reflect
// the flag on old thread. That's why events in a new thread will not get processed.
// This migth be actually bug in moveToThread functionality, but because other platforms
// do not check canWait in wakeUp (where we essentially are now) - decided to remove it from
// here as well.
//if (!d->threadData->canWait) {
QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
return true;
//}
//return false;
}
inline void QEventDispatcherSymbian::addDeferredActiveObject(QActiveObject *object)
{
if (m_deferredActiveObjects.isEmpty()) {
m_completeDeferredAOs->complete();
}
m_deferredActiveObjects.append(object);
}
inline void QEventDispatcherSymbian::removeDeferredActiveObject(QActiveObject *object)
{
m_deferredActiveObjects.removeAll(object);
}
void QEventDispatcherSymbian::reactivateDeferredActiveObjects()
{
while (!m_deferredActiveObjects.isEmpty()) {
QActiveObject *object = m_deferredActiveObjects.takeFirst();
object->reactivateAndComplete();
}
// We do this because we want to return from processEvents. This is because
// each invocation of processEvents should only run each active object once.
// The active scheduler should run them continously, however.
m_interrupt = true;
}
bool QEventDispatcherSymbian::sendDeferredSocketEvents()
{
bool sentAnyEvents = false;
while (!m_deferredSocketEvents.isEmpty()) {
sentAnyEvents = true;
socketFired(m_deferredSocketEvents.takeFirst());
}
return sentAnyEvents;
}
void QEventDispatcherSymbian::flush()
{
}
bool QEventDispatcherSymbian::hasPendingEvents()
{
Q_D(QAbstractEventDispatcher);
return (d->threadData->symbian_thread_handle.RequestCount() != 0
|| !d->threadData->canWait || !m_deferredSocketEvents.isEmpty());
}
void QEventDispatcherSymbian::registerSocketNotifier ( QSocketNotifier * notifier )
{
QSocketActiveObject *socketAO = q_check_ptr(new QSocketActiveObject(this, notifier));
m_notifiers.insert(notifier, socketAO);
selectThread().requestSocketEvents(notifier, &socketAO->iStatus);
}
void QEventDispatcherSymbian::unregisterSocketNotifier ( QSocketNotifier * notifier )
{
if (m_selectThread)
m_selectThread->cancelSocketEvents(notifier);
if (m_notifiers.contains(notifier)) {
QSocketActiveObject *sockObj = *m_notifiers.find(notifier);
m_deferredSocketEvents.removeAll(sockObj);
sockObj->deleteLater();
m_notifiers.remove(notifier);
}
}
void QEventDispatcherSymbian::reactivateSocketNotifier(QSocketNotifier *notifier)
{
selectThread().requestSocketEvents(notifier, &m_notifiers[notifier]->iStatus);
}
void QEventDispatcherSymbian::registerTimer ( int timerId, int interval, QObject * object )
{
if (interval < 0) {
qWarning("Timer interval < 0");
interval = 0;
}
SymbianTimerInfoPtr timer(new SymbianTimerInfo);
timer->timerId = timerId;
timer->interval = interval;
timer->inTimerEvent = false;
timer->receiver = object;
timer->dispatcher = this;
timer->timerAO = q_check_ptr(new QTimerActiveObject(this, timer.data()));
m_timerList.insert(timerId, timer);
timer->timerAO->Start();
}
bool QEventDispatcherSymbian::unregisterTimer ( int timerId )
{
if (!m_timerList.contains(timerId)) {
return false;
}
SymbianTimerInfoPtr timerInfo = m_timerList.take(timerId);
if (!QObjectPrivate::get(timerInfo->receiver)->inThreadChangeEvent)
QAbstractEventDispatcherPrivate::releaseTimerId(timerId);
return true;
}
bool QEventDispatcherSymbian::unregisterTimers ( QObject * object )
{
if (m_timerList.isEmpty())
return false;
bool unregistered = false;
for (QHash<int, SymbianTimerInfoPtr>::iterator i = m_timerList.begin(); i != m_timerList.end(); ) {
if ((*i)->receiver == object) {
i = m_timerList.erase(i);
unregistered = true;
} else {
++i;
}
}
return unregistered;
}
QList<QEventDispatcherSymbian::TimerInfo> QEventDispatcherSymbian::registeredTimers ( QObject * object ) const
{
QList<TimerInfo> list;
for (QHash<int, SymbianTimerInfoPtr>::const_iterator i = m_timerList.begin(); i != m_timerList.end(); ++i) {
if ((*i)->receiver == object) {
list.push_back(TimerInfo((*i)->timerId, (*i)->interval));
}
}
return list;
}
/*
* This active scheduler class implements a simple report and continue policy, for Symbian OS leaves
* or exceptions from Qt that fall back to the scheduler.
* It will be used in cases where there is no existing active scheduler installed.
* Apps which link to qts60main.lib will have the UI active scheduler installed in the main thread
* instead of this one. But this would be used in other threads in the UI.
* An app could replace this behaviour by installing an alternative active scheduler.
*/
void CQtActiveScheduler::Error(TInt aError) const
{
QT_TRY {
qWarning("Error from active scheduler %d", aError);
}
QT_CATCH (const std::bad_alloc&) {} // ignore alloc fails, nothing more can be done
}
QT_END_NAMESPACE
#include "moc_qeventdispatcher_symbian_p.cpp"
|