-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSRunLoop.m
More file actions
1585 lines (1395 loc) · 40 KB
/
NSRunLoop.m
File metadata and controls
1585 lines (1395 loc) · 40 KB
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
/** Implementation of object for waiting on several input sources
NSRunLoop.m
Copyright (C) 1996-1999 Free Software Foundation, Inc.
Original by: Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
Created: March 1996
OPENSTEP version by: Richard Frith-Macdonald <richard@brainstorm.co.uk>
Created: August 1997
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSRunLoop class reference</title>
$Date$ $Revision$
*/
#import "common.h"
#define EXPOSE_NSRunLoop_IVARS 1
#define EXPOSE_NSTimer_IVARS 1
#import "Foundation/NSMapTable.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSPort.h"
#import "Foundation/NSTimer.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSNotificationQueue.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSStream.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSInvocation.h"
#import "GSRunLoopCtxt.h"
#import "GSRunLoopWatcher.h"
#import "GSStream.h"
#import "GSPrivate.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_POLL_F
#include <poll.h>
#endif
#include <math.h>
#include <time.h>
#if GS_USE_LIBDISPATCH_RUNLOOP
# define RL_INTEGRATE_DISPATCH 1
# ifdef HAVE_DISPATCH_H
# include <dispatch.h>
# elif HAVE_DISPATCH_PRIVATE_H
# include <dispatch/private.h>
# elif HAVE_DISPATCH_DISPATCH_H
# include <dispatch/dispatch.h>
# endif
#endif
NSRunLoopMode const NSDefaultRunLoopMode = @"NSDefaultRunLoopMode";
NSRunLoopMode const NSRunLoopCommonModes = @"NSRunLoopCommonModes";
static NSDate *theFuture = nil;
@interface NSObject (OptionalPortRunLoop)
- (void) getFds: (NSInteger*)fds count: (NSInteger*)count;
@end
/*
* The GSRunLoopPerformer class is used to hold information about
* messages which are due to be sent to objects once each runloop
* iteration has passed.
*/
@interface GSRunLoopPerformer: NSObject
{
@public
SEL selector;
id target;
id argument;
unsigned order;
}
- (void) fire;
- (id) initWithSelector: (SEL)aSelector
target: (id)target
argument: (id)argument
order: (NSUInteger)order;
@end
@implementation GSRunLoopPerformer
- (void) dealloc
{
RELEASE(target);
RELEASE(argument);
[super dealloc];
}
- (void) fire
{
NS_DURING
{
[target performSelector: selector withObject: argument];
}
NS_HANDLER
{
NSLog(@"*** NSRunLoop ignoring exception '%@' (reason '%@') "
@"raised during performSelector... with target %s(%s) "
@"and selector '%s'",
[localException name], [localException reason],
GSClassNameFromObject(target),
GSObjCIsInstance(target) ? "instance" : "class",
sel_getName(selector));
}
NS_ENDHANDLER
}
- (id) initWithSelector: (SEL)aSelector
target: (id)aTarget
argument: (id)anArgument
order: (NSUInteger)theOrder
{
self = [super init];
if (self)
{
selector = aSelector;
target = RETAIN(aTarget);
argument = RETAIN(anArgument);
order = theOrder;
}
return self;
}
@end
@interface NSRunLoop (TimedPerformers)
- (NSMutableArray*) _timedPerformers;
@end
@implementation NSRunLoop (TimedPerformers)
- (NSMutableArray*) _timedPerformers
{
return _timedPerformers;
}
@end
/*
* The GSTimedPerformer class is used to hold information about
* messages which are due to be sent to objects at a particular time.
*/
@interface GSTimedPerformer: NSObject
{
@public
SEL selector;
id target;
id argument;
NSTimer *timer;
}
- (void) fire;
- (id) initWithSelector: (SEL)aSelector
target: (id)target
argument: (id)argument
delay: (NSTimeInterval)delay;
- (void) invalidate;
@end
@implementation GSTimedPerformer
- (void) dealloc
{
[self finalize];
TEST_RELEASE(timer);
RELEASE(target);
RELEASE(argument);
[super dealloc];
}
- (void) fire
{
DESTROY(timer);
[target performSelector: selector withObject: argument];
[[[NSRunLoop currentRunLoop] _timedPerformers]
removeObjectIdenticalTo: self];
}
- (void) finalize
{
[self invalidate];
}
- (id) initWithSelector: (SEL)aSelector
target: (id)aTarget
argument: (id)anArgument
delay: (NSTimeInterval)delay
{
self = [super init];
if (self != nil)
{
selector = aSelector;
target = RETAIN(aTarget);
argument = RETAIN(anArgument);
timer = [[NSTimer allocWithZone: NSDefaultMallocZone()]
initWithFireDate: nil
interval: delay
target: self
selector: @selector(fire)
userInfo: nil
repeats: NO];
}
return self;
}
- (void) invalidate
{
if (timer != nil)
{
[timer invalidate];
DESTROY(timer);
}
}
@end
/*
* Setup for inline operation of arrays.
*/
#ifndef GSI_ARRAY_TYPES
#define GSI_ARRAY_TYPES GSUNION_OBJ
#define GSI_ARRAY_RELEASE(A, X) [(X).obj release]
#define GSI_ARRAY_RETAIN(A, X) [(X).obj retain]
#include "GNUstepBase/GSIArray.h"
#endif
static inline NSDate *timerDate(NSTimer *t)
{
return t->_date;
}
static inline BOOL timerInvalidated(NSTimer *t)
{
return t->_invalidated;
}
@implementation NSObject (TimedPerformers)
/*
* Cancels any perform operations set up for the specified target
* in the current run loop.
*/
+ (void) cancelPreviousPerformRequestsWithTarget: (id)target
{
NSMutableArray *perf = [[NSRunLoop currentRunLoop] _timedPerformers];
unsigned count = [perf count];
if (count > 0)
{
GSTimedPerformer *array[count];
IF_NO_GC(RETAIN(target));
[perf getObjects: array];
while (count-- > 0)
{
GSTimedPerformer *p = array[count];
if (p->target == target)
{
[p invalidate];
[perf removeObjectAtIndex: count];
}
}
RELEASE(target);
}
}
/*
* Cancels any perform operations set up for the specified target
* in the current loop, but only if the value of aSelector and argument
* with which the performs were set up match those supplied.<br />
* Matching of the argument may be either by pointer equality or by
* use of the [NSObject-isEqual:] method.
*/
+ (void) cancelPreviousPerformRequestsWithTarget: (id)target
selector: (SEL)aSelector
object: (id)arg
{
NSMutableArray *perf = [[NSRunLoop currentRunLoop] _timedPerformers];
unsigned count = [perf count];
if (count > 0)
{
GSTimedPerformer *array[count];
IF_NO_GC(RETAIN(target));
IF_NO_GC(RETAIN(arg));
[perf getObjects: array];
while (count-- > 0)
{
GSTimedPerformer *p = array[count];
if (p->target == target && sel_isEqual(p->selector, aSelector)
&& (p->argument == arg || [p->argument isEqual: arg]))
{
[p invalidate];
[perf removeObjectAtIndex: count];
}
}
RELEASE(arg);
RELEASE(target);
}
}
- (void) performSelector: (SEL)aSelector
withObject: (id)argument
afterDelay: (NSTimeInterval)seconds
{
NSRunLoop *loop = [NSRunLoop currentRunLoop];
GSTimedPerformer *item;
item = [[GSTimedPerformer alloc] initWithSelector: aSelector
target: self
argument: argument
delay: seconds];
[[loop _timedPerformers] addObject: item];
RELEASE(item);
[loop addTimer: item->timer forMode: NSDefaultRunLoopMode];
}
- (void) performSelector: (SEL)aSelector
withObject: (id)argument
afterDelay: (NSTimeInterval)seconds
inModes: (NSArray*)modes
{
unsigned count = [modes count];
if (count > 0)
{
NSRunLoop *loop = [NSRunLoop currentRunLoop];
NSString *marray[count];
GSTimedPerformer *item;
unsigned i;
item = [[GSTimedPerformer alloc] initWithSelector: aSelector
target: self
argument: argument
delay: seconds];
[[loop _timedPerformers] addObject: item];
RELEASE(item);
if ([modes isProxy])
{
for (i = 0; i < count; i++)
{
marray[i] = [modes objectAtIndex: i];
}
}
else
{
[modes getObjects: marray];
}
for (i = 0; i < count; i++)
{
[loop addTimer: item->timer forMode: marray[i]];
}
}
}
@end
#ifdef RL_INTEGRATE_DISPATCH
#pragma clang diagnostic push
/* We have no declarations for libdispatch private functions, so we ignore
* warnings here, knowing that we are using an undocumented feature which
* may go away in later releases (in which case we will use another library)
*/
#pragma clang diagnostic ignored "-Wimplicit-function-declaration"
@interface GSMainQueueDrainer : NSObject <RunLoopEvents>
+ (void*) mainQueueFileDescriptor;
@end
@implementation GSMainQueueDrainer
+ (void*) mainQueueFileDescriptor
{
#if HAVE_DISPATCH_GET_MAIN_QUEUE_HANDLE_NP
return (void*)(uintptr_t)dispatch_get_main_queue_handle_np();
#elif HAVE__DISPATCH_GET_MAIN_QUEUE_HANDLE_4CF
return (void*)(uintptr_t)_dispatch_get_main_queue_handle_4CF();
#else
#error libdispatch missing main queue handle function
#endif
}
- (void) receivedEvent: (void*)data
type: (RunLoopEventType)type
extra: (void*)extra
forMode: (NSString*)mode
{
#if HAVE_DISPATCH_MAIN_QUEUE_DRAIN_NP
dispatch_main_queue_drain_np();
#elif HAVE__DISPATCH_MAIN_QUEUE_CALLBACK_4CF
_dispatch_main_queue_callback_4CF(NULL);
#else
#error libdispatch missing main queue callback function
#endif
}
@end
#pragma clang diagnostic pop
#endif
@interface NSRunLoop (Private)
- (void) _addWatcher: (GSRunLoopWatcher*)item
forMode: (NSString*)mode;
- (BOOL) _checkPerformers: (GSRunLoopCtxt*)context;
- (GSRunLoopWatcher*) _getWatcher: (void*)data
type: (RunLoopEventType)type
forMode: (NSString*)mode;
- (id) _init;
- (void) _removeWatcher: (void*)data
type: (RunLoopEventType)type
forMode: (NSString*)mode;
@end
@implementation NSRunLoop (Private)
/* Add a watcher to the list for the specified mode. Keep the list in
limit-date order. */
- (void) _addWatcher: (GSRunLoopWatcher*) item forMode: (NSString*)mode
{
GSRunLoopCtxt *context;
GSIArray watchers;
unsigned i;
context = NSMapGet(_contextMap, mode);
if (context == nil)
{
context = [[GSRunLoopCtxt alloc] initWithMode: mode extra: _extra];
NSMapInsert(_contextMap, context->mode, context);
RELEASE(context);
}
watchers = context->watchers;
GSIArrayAddItem(watchers, (GSIArrayItem)((id)item));
i = GSIArrayCount(watchers);
if (i % 1000 == 0 && i > context->maxWatchers)
{
context->maxWatchers = i;
NSLog(@"WARNING ... there are %u watchers scheduled in mode %@ of %@",
i, mode, self);
}
}
- (BOOL) _checkPerformers: (GSRunLoopCtxt*)context
{
BOOL found = NO;
if (context != nil)
{
GSIArray performers = context->performers;
unsigned count = GSIArrayCount(performers);
if (count > 0)
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
GSRunLoopPerformer *array[count];
NSMapEnumerator enumerator;
GSRunLoopCtxt *original;
void *mode;
unsigned i;
found = YES;
/* We have to remove the performers before firing, so we copy
* the pointers without releasing the objects, and then set
* the performers to be empty. The copied objects in 'array'
* will be released later.
*/
for (i = 0; i < count; i++)
{
array[i] = GSIArrayItemAtIndex(performers, i).obj;
}
performers->count = 0;
/* Remove the requests that we are about to fire from all modes.
*/
original = context;
enumerator = NSEnumerateMapTable(_contextMap);
while (NSNextMapEnumeratorPair(&enumerator, &mode, (void**)&context))
{
if (context != nil && context != original)
{
GSIArray performers = context->performers;
unsigned tmpCount = GSIArrayCount(performers);
while (tmpCount--)
{
GSRunLoopPerformer *p;
p = GSIArrayItemAtIndex(performers, tmpCount).obj;
for (i = 0; i < count; i++)
{
if (p == array[i])
{
GSIArrayRemoveItemAtIndex(performers, tmpCount);
}
}
}
}
}
NSEndMapTableEnumeration(&enumerator);
/* Finally, fire the requests and release them.
*/
for (i = 0; i < count; i++)
{
[array[i] fire];
RELEASE(array[i]);
IF_NO_GC([arp emptyPool];)
}
[arp drain];
}
}
return found;
}
/**
* Locates a runloop watcher matching the specified data and type in this
* runloop. If the mode is nil, either the currentMode is used (if the
* loop is running) or NSDefaultRunLoopMode is used.
*/
- (GSRunLoopWatcher*) _getWatcher: (void*)data
type: (RunLoopEventType)type
forMode: (NSString*)mode
{
GSRunLoopCtxt *context;
if (mode == nil)
{
mode = [self currentMode];
if (mode == nil)
{
mode = NSDefaultRunLoopMode;
}
}
context = NSMapGet(_contextMap, mode);
if (context != nil)
{
GSIArray watchers = context->watchers;
unsigned i = GSIArrayCount(watchers);
while (i-- > 0)
{
GSRunLoopWatcher *info;
info = GSIArrayItemAtIndex(watchers, i).obj;
if (info->type == type && info->data == data)
{
return info;
}
}
}
return nil;
}
- (id) _init
{
self = [super init];
if (self != nil)
{
_contextStack = [NSMutableArray new];
_contextMap = NSCreateMapTable (NSNonRetainedObjectMapKeyCallBacks,
NSObjectMapValueCallBacks, 0);
_timedPerformers = [[NSMutableArray alloc] initWithCapacity: 8];
#ifdef HAVE_POLL_F
_extra = NSZoneMalloc(NSDefaultMallocZone(), sizeof(pollextra));
memset(_extra, '\0', sizeof(pollextra));
#endif
}
return self;
}
/**
* Removes a runloop watcher matching the specified data and type in this
* runloop. If the mode is nil, either the currentMode is used (if the
* loop is running) or NSDefaultRunLoopMode is used.
*/
- (void) _removeWatcher: (void*)data
type: (RunLoopEventType)type
forMode: (NSString*)mode
{
GSRunLoopCtxt *context;
if (mode == nil)
{
mode = [self currentMode];
if (mode == nil)
{
mode = NSDefaultRunLoopMode;
}
}
context = NSMapGet(_contextMap, mode);
if (context != nil)
{
GSIArray watchers = context->watchers;
unsigned i = GSIArrayCount(watchers);
while (i-- > 0)
{
GSRunLoopWatcher *info;
info = GSIArrayItemAtIndex(watchers, i).obj;
if (info->type == type && info->data == data)
{
info->_invalidated = YES;
GSIArrayRemoveItemAtIndex(watchers, i);
}
}
}
}
@end
@implementation NSRunLoop(GNUstepExtensions)
- (void) addEvent: (void*)data
type: (RunLoopEventType)type
watcher: (id<RunLoopEvents>)watcher
forMode: (NSString*)mode
{
GSRunLoopWatcher *info;
if (mode == nil)
{
mode = [self currentMode];
if (mode == nil)
{
mode = NSDefaultRunLoopMode;
}
}
info = [self _getWatcher: data type: type forMode: mode];
if (info != nil && (id)info->receiver == (id)watcher)
{
/* Increment usage count for this watcher. */
info->count++;
}
else
{
/* Remove any existing handler for another watcher. */
[self _removeWatcher: data type: type forMode: mode];
/* Create new object to hold information. */
info = [[GSRunLoopWatcher alloc] initWithType: type
receiver: watcher
data: data];
/* Add the object to the array for the mode. */
[self _addWatcher: info forMode: mode];
RELEASE(info); /* Now held in array. */
}
}
- (void) removeEvent: (void*)data
type: (RunLoopEventType)type
forMode: (NSString*)mode
all: (BOOL)removeAll
{
if (mode == nil)
{
mode = [self currentMode];
if (mode == nil)
{
mode = NSDefaultRunLoopMode;
}
}
if (removeAll)
{
[self _removeWatcher: data type: type forMode: mode];
}
else
{
GSRunLoopWatcher *info;
info = [self _getWatcher: data type: type forMode: mode];
if (info)
{
if (info->count == 0)
{
[self _removeWatcher: data type: type forMode: mode];
}
else
{
info->count--;
}
}
}
}
@end
/**
* <p><code>NSRunLoop</code> instances handle various utility tasks that must
* be performed repetitively in an application, such as processing input
* events, listening for distributed objects communications, firing
* [NSTimer]s, and sending notifications and other messages
* asynchronously.</p>
*
* <p>There is one run loop per thread in an application, which
* may always be obtained through the <code>+currentRunLoop</code> method
* (you cannot use -init or +new),
* however unless you are using the AppKit and the [NSApplication] class, the
* run loop will not be started unless you explicitly send it a
* <code>-run</code> message.</p>
*
* <p>At any given point, a run loop operates in a single <em>mode</em>, usually
* <code>NSDefaultRunLoopMode</code>. Other options include
* <code>NSConnectionReplyMode</code>, and certain modes used by the AppKit.</p>
*/
@implementation NSRunLoop
+ (void) initialize
{
if (self == [NSRunLoop class])
{
[self currentRunLoop];
theFuture = RETAIN([NSDate distantFuture]);
RELEASE([NSObject leakAt: &theFuture]);
}
}
+ (NSRunLoop*) _runLoopForThread: (NSThread*) aThread
{
GSRunLoopThreadInfo *info = GSRunLoopInfoForThread(aThread);
NSRunLoop *current = info->loop;
if (nil == current)
{
current = info->loop = [[self alloc] _init];
/* If this is the main thread, set up a housekeeping timer.
*/
if (nil != current && [GSCurrentThread() isMainThread] == YES)
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSNotificationCenter *ctr;
NSNotification *not;
NSInvocation *inv;
NSTimer *timer;
SEL sel;
ctr = [NSNotificationCenter defaultCenter];
not = [NSNotification notificationWithName: @"GSHousekeeping"
object: nil
userInfo: nil];
sel = @selector(postNotification:);
inv = [NSInvocation invocationWithMethodSignature:
[ctr methodSignatureForSelector: sel]];
[inv setTarget: ctr];
[inv setSelector: sel];
[inv setArgument: ¬ atIndex: 2];
[inv retainArguments];
timer = [[NSTimer alloc] initWithFireDate: nil
interval: 30.0
target: inv
selector: NULL
userInfo: nil
repeats: YES];
[current addTimer: timer forMode: NSDefaultRunLoopMode];
#ifdef RL_INTEGRATE_DISPATCH
// We leak the queue drainer, because it's integral part of RL
// operations
GSMainQueueDrainer *drain =
[NSObject leak: [[GSMainQueueDrainer new] autorelease]];
[current addEvent: [GSMainQueueDrainer mainQueueFileDescriptor]
#ifdef _WIN32
type: ET_HANDLE
#else
type: ET_RDESC
#endif
watcher: drain
forMode: NSDefaultRunLoopMode];
#endif
[arp drain];
}
}
return current;
}
+ (NSRunLoop*) currentRunLoop
{
return [self _runLoopForThread: nil];
}
+ (NSRunLoop*) mainRunLoop
{
return [self _runLoopForThread: [NSThread mainThread]];
}
- (id) init
{
DESTROY(self);
return nil;
}
- (void) dealloc
{
#ifdef HAVE_POLL_F
if (_extra != 0)
{
pollextra *e = (pollextra*)_extra;
if (e->index != 0)
NSZoneFree(NSDefaultMallocZone(), e->index);
NSZoneFree(NSDefaultMallocZone(), e);
}
#endif
RELEASE(_contextStack);
if (_contextMap != 0)
{
NSFreeMapTable(_contextMap);
}
RELEASE(_timedPerformers);
[super dealloc];
}
/**
* Returns the current mode of this runloop. If the runloop is not running
* then this method returns nil.
*/
- (NSString*) currentMode
{
return _currentMode;
}
/**
* Adds a timer to the loop in the specified mode.<br />
* Timers are removed automatically when they are invalid.<br />
*/
- (void) addTimer: (NSTimer*)timer
forMode: (NSString*)mode
{
GSRunLoopCtxt *context;
GSIArray timers;
unsigned i;
if ([timer isKindOfClass: [NSTimer class]] == NO
|| [timer isProxy] == YES)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] not a valid timer",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
if ([mode isKindOfClass: [NSString class]] == NO)
{
[NSException raise: NSInvalidArgumentException
format: @"[%@-%@] not a valid mode",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
}
NSDebugMLLog(@"NSRunLoop", @"add timer for %f in %@",
[[timer fireDate] timeIntervalSinceReferenceDate], mode);
context = NSMapGet(_contextMap, mode);
if (context == nil)
{
context = [[GSRunLoopCtxt alloc] initWithMode: mode extra: _extra];
NSMapInsert(_contextMap, context->mode, context);
RELEASE(context);
}
timers = context->timers;
i = GSIArrayCount(timers);
while (i-- > 0)
{
if (timer == GSIArrayItemAtIndex(timers, i).obj)
{
return; /* Timer already present */
}
}
/*
* NB. A previous version of the timer code maintained an ordered
* array on the theory that we could improve performance by only
* checking the first few timers (up to the first one whose fire
* date is in the future) each time -limitDateForMode: is called.
* The problem with this was that it's possible for one timer to
* be added in multiple modes (or to different run loops) and for
* a repeated timer this could mean that the firing of the timer
* in one mode/loop adjusts its date ... without changing the
* ordering of the timers in the other modes/loops which contain
* the timer. When the ordering of timers in an array was broken
* we could get delays in processing timeouts, so we reverted to
* simply having timers in an unordered array and checking them
* all each time -limitDateForMode: is called.
*/
GSIArrayAddItem(timers, (GSIArrayItem)((id)timer));
i = GSIArrayCount(timers);
if (i % 1000 == 0 && i > context->maxTimers)
{
context->maxTimers = i;
NSLog(@"WARNING ... there are %u timers scheduled in mode %@ of %@",
i, mode, self);
}
}
/* Ensure that the fire date has been updated either by the timeout handler
* updating it or by incrementing it ourselves.<br />
* Return YES if it was updated, NO if it was invalidated.
*/
static BOOL
updateTimer(NSTimer *t, NSDate *d, NSTimeInterval now)
{
if (timerInvalidated(t) == YES)
{
return NO;
}
if (timerDate(t) == d)
{
NSTimeInterval ti = [d timeIntervalSinceReferenceDate];
NSTimeInterval increment = [t timeInterval];
if (increment <= 0.0)
{
/* Should never get here ... unless a subclass is returning
* a bad interval ... we return NO so that the timer gets
* removed from the loop.
*/
NSLog(@"WARNING timer %@ had bad interval ... removed", t);
return NO;
}
ti += increment; // Hopefully a single increment will do.
if (ti < now)
{
NSTimeInterval add;
/* Just incrementing the date was insufficient to bring it to
* the current time, so we must have missed one or more fire
* opportunities, or the fire date has been set on the timer.
* If a fire date long ago has been set and the increment value
* is really small, we might need to increment very many times
* to get the new fire date. To avoid looping for ages, we
* calculate the number of increments needed and do them in one
* go.
*/
add = floor((now - ti) / increment);
ti += (increment * add);
if (ti < now)
{
ti += increment;
}
}
RELEASE(t->_date);
t->_date = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: ti];
}
return YES;
}
- (NSDate*) _limitDateForContext: (GSRunLoopCtxt *)context
{
NSDate *when = nil;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
GSIArray timers = context->timers;