-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCFNotificationCenter.c
1312 lines (1083 loc) · 41.8 KB
/
CFNotificationCenter.c
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
/*
* Copyright (c) 2009 Stuart Crook. All rights reserved.
*
* Created by Stuart Crook on 23/02/2009.
* This source code is a reverse-engineered implementation of the notification center from
* Apple's core foundation library.
*
* The PureFoundation code base consists of a combination of original code provided by contributors
* and open-source code drawn from a nuber of other projects -- chiefly Cocotron (www.coctron.org)
* and GNUStep (www.gnustep.org). Under the principal that the least-liberal licence trumps the others,
* the PureFoundation project as a whole is released under the GNU Lesser General Public License (LGPL).
* Where code has been included from other projects, that project's licence, along with a note of the
* exact source (eg. file name) is included inline in the source.
*
* Since PureFoundation is a dynamically-loaded shared library, it is my interpretation of the LGPL
* that any application linking to it is not automatically bound by its terms.
*
* See the text of the LGPL (from http://www.gnu.org/licenses/lgpl-3.0.txt, accessed 26/2/09):
*
*/
#include "CFNotificationCenter.h"
#include <CoreFoundation/CFPropertyList.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFMessagePort.h>
#include <CoreFoundation/CFStream.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFRuntime.h>
#include "CFPriv.h"
#include <CoreFoundation/CoreFoundation_Prefix.h>
#include "CFInternal.h"
#include <stdlib.h>
#include <stdio.h>
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX
#include <unistd.h>
#endif
#define CF_LOCAL_CENTER 0
#define CF_DIST_CENTER 1
#define CF_DARWIN_CENTER 2
#define CF_OBS_SIZE 32
typedef struct __CFObserver {
//CFStringRef name; // can be NULL
CFHashCode hash; // hashed string, for speed. can be NULL
const void *object; // can be NULL
const void *observer; // may be NULL
CFNotificationCallback callback;
CFNotificationSuspensionBehavior sb;
} __CFObserver;
struct __CFNotificationCenter {
CFRuntimeBase _base;
CFIndex type;
CFIndex suspended; // <- move into base bits?
CFIndex observers;
CFIndex capacity;
__CFObserver *obs;
CFSpinLock_t lock;
};
// STRUCTURES FOR DISTRIBUTED CENTER HERE
// message ids recognised by ddistnoted
#define NOTIFICATION 0
#define REGISTER_PORT 1
#define UNREGISTER_PORT 2
#define REGISTER_NOTIFICATION 3
#define UNREGISTER_NOTIFICATION 4
#define CF_DIST_SIZE 32
#define CF_QUEUE_SIZE 32
typedef struct __CFDistNotification {
CFHashCode hash;
CFHashCode object;
CFIndex count;
} __CFDistNotification;
typedef struct __CFQueueRecord {
CFStringRef name;
const void *object; // will be a CFStringRef...
const void *observer;
CFDictionaryRef userInfo;
CFNotificationCallback callback;
} __CFQueueRecord;
typedef struct __CFDistributedCenterInfo {
CFMessagePortRef local;
CFMessagePortRef remote;
long session;
CFHashCode uid;
CFRunLoopSourceRef rls;
CFIndex count;
CFIndex capacity;
__CFDistNotification *nots;
CFIndex queueCount;
CFIndex queueCapacity;
__CFQueueRecord *queue;
} __CFDistributedCenterInfo;
static __CFDistributedCenterInfo __CFDistInfo = { NULL, NULL, 0, 0, NULL, 0, 0, NULL, 0, 0, NULL };
// these structures come from the ddistnoted project -- beter keep their definitions synced
typedef struct dndNotReg {
CFHashCode uid;
CFHashCode name;
CFHashCode object;
} dndNotReg;
typedef struct dndNotHeader {
long session;
CFHashCode name;
CFHashCode object;
CFIndex flags;
} dndNotHeader;
#if DEPLOYMENT_TARGET_MACOSX
#include <notify.h>
#include <CoreFoundation/CFMachPort.h>
#endif
/*
* Darwin notifications
*
* There are two ways we could organise recieving notify messages via Mach ports. The
* method we are using here is to use a single port for all messages, with an int token
* in the message header used to identify the notification name.
*
* The alternative, which we may have to consider if the number of notifications in
* general use swamps a single port's message queue, is to allocate one Mach port per
* notification name.
*/
#define CF_DARWIN_SIZE 32
typedef struct __CFDarwinNotifications {
//CFStringRef name;
CFHashCode hash;
int token;
CFIndex count;
} __CFDarwinNotifications;
typedef struct __CFDarwinCenterInfo {
#if defined(__MACH__)
CFMachPortRef port;
#endif
CFRunLoopSourceRef rls;
CFIndex count;
CFIndex capacity;
__CFDarwinNotifications *nots;
} __CFDarwinCenterInfo;
#if defined(__MACH__)
static __CFDarwinCenterInfo __CFDarwinInfo = { NULL, NULL, 0, 0, NULL };
#else
static __CFDarwinCenterInfo __CFDarwinInfo = { NULL, 0, 0, NULL };
#endif
// the task's singleton centres
static CFNotificationCenterRef __CFLocalCenter = NULL;
static CFNotificationCenterRef __CFDistributedCenter = NULL;
static CFNotificationCenterRef __CFDarwinCenter = NULL;
static CFMutableDictionaryRef __CFHashStore = NULL;
// these control access to the Get functions. access to individual structure are
// embeded within those structures
static CFSpinLock_t __CFLocalCenterLock = CFSpinLockInit;
static CFSpinLock_t __CFDistributedCenterLock = CFSpinLockInit;
static CFSpinLock_t __CFDarwinCenterLock = CFSpinLockInit;
static CFSpinLock_t __CFHashStoreLock = CFSpinLockInit;
// store for our typeID
static CFTypeID __kCFNotificationCenterTypeID = _kCFRuntimeNotATypeID;
// life-cycle stuff can wait for now
static const CFRuntimeClass __CFNotificationCenterClass = {
0,
"CFNotificationCenter",
NULL, // init
NULL, // copy
NULL, //__CFDataDeallocate,
NULL, //__CFDataEqual,
NULL, //__CFDataHash,
NULL, //
NULL, //__CFDataCopyDescription
};
__private_extern__ void __CFNotificationCenterInitialize(void)
{
__kCFNotificationCenterTypeID = _CFRuntimeRegisterClass(&__CFNotificationCenterClass);
__CFHashStore = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, NULL, NULL );
}
CFTypeID CFNotificationCenterGetTypeID(void) { return __kCFNotificationCenterTypeID; }
/*
* The __CFAdd and Remove functions take an optional callback of this type which is called once
* for each observer added or removed. It runs under the current spinlock and gets over the
* problem of returning a list of notification to remove from the RemoveEvery function
*/
typedef void (*__CFAdderCallBack)( CFStringRef name, CFHashCode hash, CFHashCode object );
typedef void (*__CFRemoverCallBack)( CFHashCode name, CFHashCode object );
/*
* Declaration of functions internal to this file
*/
CFNotificationCenterRef __CFCreateCenter( CFIndex type );
void __CFAddObserver( CFNotificationCenterRef center, const void *observer, CFNotificationCallback callBack, CFStringRef name, const void *object, CFNotificationSuspensionBehavior suspensionBehavior, __CFAdderCallBack cb );
void __CFRemoveObserver( CFNotificationCenterRef center, const void *observer, CFHashCode name, const void *object, __CFRemoverCallBack cb );
void __CFRemoveEveryObserver( CFNotificationCenterRef center, const void *observer, __CFRemoverCallBack cb );
void __CFInvokeCallBacks( CFNotificationCenterRef center, CFHashCode name, CFStringRef nameReturn, const void *object, const void *objectReturn, CFDictionaryRef userInfo, Boolean deliverNow );
//void __PFPostLocalNotification( PFNotificationCenterRef center, CFStringRef name, const void *object, CFDictionaryRef userInfo );
void __CFPostDistributedNotification( CFNotificationCenterRef center, CFStringRef name, CFStringRef object, CFDictionaryRef userInfom, CFOptionFlags options );
void __CFPostDarwinNotification( CFNotificationCenterRef center, CFStringRef name );
void __CFAddQueue( CFStringRef name, const void *object, const void *observer, CFDictionaryRef userInfo, CFNotificationCallback callback, Boolean coalesce );
void __CFDeliverQueue( void );
Boolean _CFNotificationCenterIsSuspended( CFNotificationCenterRef center );
void _CFNotificationCenterSetSuspended( CFNotificationCenterRef center, Boolean suspended );
#if DEPLOYMENT_TARGET_MACOSX
void __CFDarwinCallBack(CFMachPortRef port, void *msg, CFIndex size, void *info);
#endif
/*
* Manage the message queue, which is used to store distributed notifications
* when delivery has been suspended.
*/
void __CFAddQueue( CFStringRef name, const void *object, const void *observer, CFDictionaryRef userInfo, CFNotificationCallback callback, Boolean coalesce )
{
CFRetain(userInfo);
__CFQueueRecord *queue = __CFDistInfo.queue;
CFIndex count = __CFDistInfo.queueCount;
if( coalesce ) // do we check for this notification in the queue?
{
while( count-- )
{
// we're looking for exactl matches on name, object, observer and callback
if( (queue->name == name) && (queue->object == object)
&& (queue->observer == observer) && (queue->callback == callback) )
{
CFRelease(queue->userInfo);
queue->userInfo = userInfo;
break;
}
queue++;
}
}
// either we're not coalescing or this notification wasn't already enqueued
if( __CFDistInfo.count == __CFDistInfo.capacity )
{
__CFDistInfo.capacity += CF_QUEUE_SIZE;
__CFDistInfo.queue = (__CFQueueRecord*)realloc( __CFDistInfo.queue, (CF_QUEUE_SIZE * sizeof(__CFQueueRecord)) );
if( __CFDistInfo.queue == NULL ) return;
}
queue = __CFDistInfo.queue + __CFDistInfo.queueCount;
queue->name = name;
queue->object = object;
queue->observer = observer;
queue->callback = callback;
queue->userInfo = userInfo;
__CFDistInfo.queueCount++;
}
void __CFDeliverQueue( void )
{
CFIndex count = __CFDistInfo.queueCount;
__CFQueueRecord *queue = __CFDistInfo.queue;
while( count-- )
{
queue->callback( (CFNotificationCenterRef)__CFDistributedCenter, (void*)queue->observer, queue->name, queue->object, queue->userInfo );
CFRelease(queue->userInfo);
queue->name = NULL;
queue->object = NULL;
queue->observer = NULL;
queue->callback = NULL;
queue->userInfo = NULL;
}
__CFDistInfo.queueCount = 0;
}
/*
* Set the suspended condition of the distributed notification centre (only). At the
* moment these will be left as no-ops, to be activated when we write the
* NSDitributedNotificationCenter class (which provides -setSuspended: and -suspended
* methods).
*
* The docs suggested that these functions existed, and running nm over CoreFoundation
* revealed their names. I'm just guessing their prototypes at the moment, and hoping
* that nothing tries to call them directly.
*/
Boolean _CFNotificationCenterIsSuspended( CFNotificationCenterRef center ) { return center->suspended; }
void _CFNotificationCenterSetSuspended( CFNotificationCenterRef center, Boolean suspended )
{
if( center->type == CF_DIST_CENTER ) // only suspendable type
{
__CFSpinLock(¢er->lock);
if( center->suspended != suspended ) // changing state?
{
center->suspended = suspended;
// have we just un-suspended and are there notifications to deliver?
if( !suspended && (__CFDistInfo.queueCount != 0) )
__CFDeliverQueue();
}
__CFSpinUnlock(¢er->lock);
}
}
/*
* Strings (names for all notifications, and objects from distributed observers) are
* stored as hashes in the look-up tables, with strings stored in the __CFHashStore
* dictionary
*
* Strings are copied into the dictionary. At present, they are never removed.
*/
CFHashCode __CFNCHash( CFStringRef string );
CFStringRef __CFNCUnhash( CFHashCode hash );
// this should maybe be called "hashAndStore" - use CFHash() for just the hash
CFHashCode __CFNCHash( CFStringRef string )
{
if( string == NULL ) return 0;
CFHashCode hash = CFHash(string);
__CFSpinLock(&__CFHashStoreLock);
if( !CFDictionaryContainsKey(__CFHashStore, (const void *)hash) )
CFDictionaryAddValue( __CFHashStore, (const void *)hash, CFStringCreateCopy( kCFAllocatorDefault, string) );
__CFSpinUnlock(&__CFHashStoreLock);
return hash;
}
CFStringRef __CFNCUnhash( CFHashCode hash )
{
CFStringRef string;
__CFSpinLock(&__CFHashStoreLock);
if( hash == 0 )
string = NULL;
else
string = (CFStringRef)CFDictionaryGetValue(__CFHashStore, (const void *)hash);
__CFSpinUnlock(&__CFHashStoreLock);
return string;
}
/*
* Basic diagnostic functions
*/
#include <stdio.h>
void __CFCenterDiag( CFNotificationCenterRef c );
void __CFObserverDiag( __CFObserver o );
void __CFCenterDiag( CFNotificationCenterRef c )
{
//printf("centre: type = %d, observers = %d, capacity = %d, obs at 0x%X\n", c->type, c->observers, c->capacity, c->obs);
}
void __CFObserverDiag( __CFObserver o )
{
//printf("observer: hash = %u, object = 0x%X, observer = 0x%X, callback to 0x%X, sb = %d\n", o.hash, o.object, o.observer, o.callback, o.sb);
}
// END DIAGNOSTIC FUNCTIONS
/*
* Add or remove a notification from the table of distributed notifications we are
* monitoring. When the first notification with a unique signature is added (or the
* last is removed) we make a call to the ddistnoted daemon to register (or unregister)
* for that notification.
*
* When the first monitored notification is added (or the last is removed) we add the
* message port source to (or remove it from) the main runloop.
*/
#if DEPLOYMENT_TARGET_MACOSX
CFDataRef __CFDistRecieve( CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info );
#endif
void __CFDistAddNotification( CFStringRef name, CFHashCode hash, CFHashCode object );
void __CFDistRemoveNotification( CFHashCode hash, CFHashCode object );
#if DEPLOYMENT_TARGET_MACOSX
/*
* recieves messages from the ddistnoted daemon
*
* In a later version we're going to have to take note of the centre's suspended
* state, queuing and coalescing messages as needed
*/
CFDataRef __CFDistRecieve( CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info )
{
//printf("local port done got a message.\n");
// center hasn't been created at the time the callback's set, so just as easier to pull in the global
CFNotificationCenterRef center = __CFDistributedCenter;
CFIndex length = CFDataGetLength(data);
if( length < sizeof(dndNotHeader) ) return NULL;
CFReadStreamRef rs = CFReadStreamCreateWithBytesNoCopy( kCFAllocatorDefault, CFDataGetBytePtr(data), length, NULL );
CFReadStreamOpen(rs);
dndNotHeader header;
CFReadStreamRead( rs, (UInt8 *)&header, sizeof(dndNotHeader) );
//printf("\tmessage name = %u, object = %u, flags = %u\n", header.name, header.object, header.flags);
// the rest of the data contains an array: [name, object, userInfo] with kCFBooleanFalse representing
// a missing object or userInfo
CFPropertyListRef array = NULL;
CFIndex format = kCFPropertyListBinaryFormat_v1_0;
array = CFPropertyListCreateFromStream( kCFAllocatorDefault, rs, 0, kCFPropertyListImmutable, &format, NULL );
if( (array == NULL) || (CFGetTypeID(array) != CFArrayGetTypeID()) ) return NULL;
// now recover and set up the arguments to invoke callbacks. If either name or object hasn't been
// encountered (and hashed) before, add it to the hash store now, so that coalescing based on
// pointers will work later. If it ever needs to.
CFStringRef name;
if( (name = __CFNCUnhash(header.name)) == NULL ) // we haven't met this name before
{
__CFNCHash( CFArrayGetValueAtIndex(array, 0) );
name = __CFNCUnhash(header.name);
}
CFStringRef object;
if( header.object == 0 )
object = NULL;
else
if( (object = __CFNCUnhash(header.object)) == NULL )
{
__CFNCHash( CFArrayGetValueAtIndex(array, 1) );
object = __CFNCUnhash(header.object);
}
CFPropertyListRef userInfo = CFArrayGetValueAtIndex(array, 2);
if( CFGetTypeID(userInfo) != CFDictionaryGetTypeID() ) userInfo = NULL;
// we deliver now if the centre isn't suspended or the messages header says we should
Boolean deliverNow = header.flags | kCFNotificationDeliverImmediately;
__CFInvokeCallBacks(center, header.name, name, (const void *)header.object, (const void *)object, userInfo, deliverNow);
if( userInfo != NULL ) CFRelease(userInfo);
return NULL;
}
#endif
/*
* Add a notification to the table of registered notifications, optionally registering it with
* the ddistnoted daemon and adding the local message port's source to the main runloop
*
* We can ignore name.
*/
void __CFDistAddNotification( CFStringRef name, CFHashCode hash, CFHashCode object )
{
//fprintf(stderr, "register distributed notification %8X, %8X\n", hash, object);
CFIndex count = __CFDistInfo.count;
__CFDistNotification *nots = __CFDistInfo.nots;
while( count-- )
{
while( nots->count == 0 ) nots++; // count == 0 is the empty record marker
if( (nots->hash == hash) && (nots->object == object) )
{
nots->count++;
return;
}
nots++;
}
// we need to register for this notification
dndNotReg info = { __CFDistInfo.uid, hash, object };
CFDataRef data = CFDataCreate( kCFAllocatorDefault, (const UInt8 *)&info, sizeof(dndNotReg) );
#if DEPLOYMENT_TARGET_MACOSX
SInt32 result = CFMessagePortSendRequest( __CFDistInfo.remote, REGISTER_NOTIFICATION, data, 1.0, 0.0, NULL, NULL );
#else
SInt32 result = 0;
#endif
CFRelease(data);
if(result != kCFMessagePortSuccess) return;
if( __CFDistInfo.count == __CFDistInfo.capacity )
{
fprintf(stderr, "Increasing capacity of dist notification list\n");
__CFDistInfo.capacity += CF_DIST_SIZE;
__CFDistInfo.nots = (__CFDistNotification*)realloc( __CFDistInfo.nots, (__CFDistInfo.capacity * sizeof(__CFDistNotification)) );
if( __CFDistInfo.nots == NULL ) return;
// because I'm unsure if realloc zeroes the new memory...
nots = __CFDistInfo.nots + __CFDistInfo.count;
for( int i = 0; i < CF_DIST_SIZE; i++ ) (nots++)->count = 0;
nots = __CFDistInfo.nots + __CFDistInfo.count;
}
else
{
nots = __CFDistInfo.nots;
while( nots->count != 0 ) nots++;
}
nots->hash = hash;
nots->object = object;
nots->count = 1;
if( 0 == __CFDistInfo.count++ )
CFRunLoopAddSource( CFRunLoopGetMain(), __CFDistInfo.rls, kCFRunLoopCommonModes );
//fprintf(stderr, "added notification (no.%d) and leaving\n", __CFDistInfo.count);
}
void __CFDistRemoveNotification( CFHashCode hash, CFHashCode object )
{
//fprintf(stderr, "dist remove notification\n");
CFIndex count = __CFDistInfo.count;
__CFDistNotification *nots = __CFDistInfo.nots;
while( count-- )
{
while( nots->count == 0 ) nots++; // count == 0 is the empty record marker
if( (nots->hash == hash) && (nots->object == object) )
{
if( 0 == --nots->count )
{
dndNotReg info = { __CFDistInfo.uid, hash, object };
CFDataRef data = CFDataCreate( kCFAllocatorDefault, (const UInt8 *)&info, sizeof(dndNotReg) );
if( data != NULL )
{
#if DEPLOYMENT_TARGET_MACOSX
CFMessagePortSendRequest(__CFDistInfo.remote, UNREGISTER_NOTIFICATION, data, 1.0, 1.0, NULL, NULL);
#endif
CFRelease(data);
}
nots->hash = 0;
nots->object = 0;
if( 0 == --__CFDistInfo.count )
CFRunLoopRemoveSource( CFRunLoopGetMain(), __CFDistInfo.rls, kCFRunLoopCommonModes );
}
return;
}
nots++;
}
//fprintf(stderr, "dist remove notification done\n");
}
/*
* Functions used to add and remove notifications to the list we are monitoring and register
* with notifyd to recieve them. We track how many times each is added and removed, so we can
* unregister for notifications when they're no-longer needed. As above, assumes the structure
* is spinlocked.
*/
void __CFDarwinAddNotification( CFStringRef name, CFHashCode hash, CFHashCode ignored );
void __CFDarwinRemoveNotification( CFHashCode hash, CFHashCode ignored );
void __CFDarwinAddNotification( CFStringRef name, CFHashCode hash, CFHashCode ignored )
{
//CFHashCode hash = CFHash(name);
CFIndex count = __CFDarwinInfo.count;
__CFDarwinNotifications *nots = __CFDarwinInfo.nots;
while( count-- )
{
while( nots->hash == 0 ) nots++;
if( nots->hash == hash ) // already registered for this notification
{
nots->count++;
return;
}
nots++;
}
// haven't registered for this notification yet
CFIndex length = CFStringGetLength(name);
STACK_BUFFER_DECL(char, buffer, ++length);
CFStringGetCString(name, buffer, length, kCFStringEncodingASCII);
int token = 0;
#if DEPLOYMENT_TARGET_MACOSX
mach_port_t port = CFMachPortGetPort(__CFDarwinInfo.port);
if( 0 != notify_register_mach_port(buffer, &port, NOTIFY_REUSE, &token) ) return;
#endif
if( __CFDarwinInfo.count == __CFDarwinInfo.capacity )
{
__CFDarwinInfo.capacity += CF_DARWIN_SIZE;
__CFDarwinInfo.nots = (__CFDarwinNotifications*)realloc( __CFDarwinInfo.nots, ( __CFDarwinInfo.capacity * sizeof(__CFDarwinNotifications)));
if( __CFDarwinInfo.nots == NULL ) return;
// because I'm unsure if realloc zeroes the new memory...
nots = __CFDarwinInfo.nots + __CFDarwinInfo.count;
for( int i = 0; i < CF_DARWIN_SIZE; i++ ) (nots++)->hash = 0;
nots = __CFDarwinInfo.nots + __CFDarwinInfo.count;
}
else
{
nots = __CFDarwinInfo.nots;
while( nots->hash != 0 ) nots++;
}
nots->hash = hash;
//nots->name = name;
nots->token = token;
nots->count = 1;
if( 0 == __CFDarwinInfo.count++ )
CFRunLoopAddSource( CFRunLoopGetMain(), __CFDarwinInfo.rls, kCFRunLoopCommonModes );
}
void __CFDarwinRemoveNotification( CFHashCode hash, CFHashCode ignored )
{
//CFHashCode hash = CFHash(name);
CFIndex count = __CFDarwinInfo.count;
__CFDarwinNotifications *nots = __CFDarwinInfo.nots;
while( count-- )
{
while( nots->hash == 0 ) nots++;
if( nots->hash == hash )
{
if( nots->count-- > 1 ) return; // still want to recieve the notification
#if defined(__MACH__)
notify_cancel(nots->token);
#endif
nots->hash = 0;
//nots->name = NULL;
nots->token = 0;
nots->count = 0;
if( --__CFDarwinInfo.count == 0 )
CFRunLoopRemoveSource( CFRunLoopGetMain(), __CFDarwinInfo.rls, kCFRunLoopCommonModes );
return;
}
nots++;
}
}
/*
* Add the observer info into the table of observers for the notification center, growing the
* table if need be. Duplicate observers with identical signatures are allowed.
*/
void __CFAddObserver( CFNotificationCenterRef center, const void *observer, CFNotificationCallback callBack, CFStringRef name, const void *object, CFNotificationSuspensionBehavior suspensionBehavior, __CFAdderCallBack cb )
{
__CFObserver *obs;
__CFSpinLock(¢er->lock);
if( center->observers == center->capacity )
{
//fprintf(stderr, "increasing size of observer records for center type %d\n", center->type);
center->capacity += CF_OBS_SIZE;
center->obs = (__CFObserver*)realloc(center->obs, (center->capacity * sizeof(__CFObserver)));
if( center->obs == NULL )
{
fprintf(stderr, "Couldn't realloc observer records for notification center type %d\n", center->type);
__CFSpinUnlock(¢er->lock);
return;
}
obs = center->obs + center->observers;
// because I'm unsure if realloc zeroes the new memory...
for( int i = 0; i < CF_OBS_SIZE; i++ ) (obs++)->callback = NULL;
obs = center->obs + center->observers;
}
else
{
obs = center->obs;
while( obs->callback != NULL ) obs++;
}
// hash and store the name
CFHashCode hash = __CFNCHash(name);
//obs->name = name;
obs->hash = hash;
obs->object = object;
obs->observer = observer;
obs->callback = callBack;
obs->sb = suspensionBehavior;
center->observers++;
if( cb != NULL ) cb(name, hash, (CFHashCode)object);
__CFSpinUnlock(¢er->lock);
}
/*
* Remove the observer with the given signature from the notification center's table.
*/
void __CFRemoveObserver( CFNotificationCenterRef center, const void *observer, CFHashCode name, const void *object, __CFRemoverCallBack cb )
{
__CFSpinLock(¢er->lock);
//CFHashCode hash = (name == NULL) ? 0 : CFHash(name);
CFIndex count = center->observers;
__CFObserver *obs = center->obs;
while( count-- )
{
while( obs->callback == NULL ) obs++;
if( (obs->observer == observer)
&& /* match name hash */ ((name == 0) || (name == obs->hash))
&& /* match object */((object == NULL) || (object == obs->object)) )
{
//obs->name = NULL;
obs->hash = 0;
obs->object = NULL;
obs->observer = NULL;
obs->callback = NULL;
obs->sb = 0;
center->observers--;
if( cb != NULL ) cb(name, (CFHashCode)object);
}
obs++;
}
__CFSpinUnlock(¢er->lock);
}
/*
* Remove every instance of the observer from the notification centre's table.
*/
void __CFRemoveEveryObserver( CFNotificationCenterRef center, const void *observer, __CFRemoverCallBack cb )
{
__CFSpinLock(¢er->lock);
CFIndex count = center->observers;
__CFObserver *obs = center->obs;
while( count-- )
{
while( obs->callback == NULL ) obs++;
if( obs->observer == observer )
{
if( cb != NULL ) cb(obs->hash, (CFHashCode)obs->object);
//obs->name = NULL;
obs->hash = 0;
obs->object = NULL;
obs->observer = NULL;
obs->callback = NULL;
obs->sb = 0;
center->observers--;
}
obs++;
}
__CFSpinUnlock(¢er->lock);
}
/*
* Invoke the callback functions for the observers whose signature match the arguments.
*
* This is a general routine which handles the special suspension behaviour of the
* distributed centre at the cost of extra un-needed checks while processing local
* and Darwin centre notifications.
*
* I'm not entirely sure whether notifications sent with kCFNotificationDeliverImmediately
* should behave like notifications delivered to suspended observers with the deliver
* immediately behaviour and flush the notification queue... so at the moment it just
* jumps the queue and is delivered on its own.
*
* The name and object arguments are used to find matching observers, while the nameReturn
* and objectReturn are passed to the observer's callbacks or queued.
* Local: object == objectReturn
* Distributed: object == hash, objectReturn == CFStringRef
* Darwin: object == objectReturn == NULL
*/
void __CFInvokeCallBacks( CFNotificationCenterRef center, CFHashCode name, CFStringRef nameReturn, const void *object, const void *objectReturn, CFDictionaryRef userInfo, Boolean deliverNow )
{
__CFSpinLock(¢er->lock);
CFIndex count = center->observers;
__CFObserver *obs = center->obs;
//printf("A\n");
//__CFCenterDiag(center);
// process each observer in the table
while( count-- )
{
//printf("B\n");
// find a record with a non-NULL callback field
while( obs->callback == NULL ) obs++;
//printf("C\n");
//__CFObserverDiag( *obs );
//printf("observer: 0x%X\n");
// for an observer to qualify to recieve a notification, it need to match
// both name and object, taking into account the NULL-case "match any name
// or object"
if( /* match name hash */ ((obs->hash == 0) || (obs->hash == name))
/* match object */ && ((obs->object == NULL) || (obs->object == object)) )
{
// found a match, now do we deliver the notification?
if( deliverNow /* non-dist short-circuit */ || !center->suspended )
{
// CFMachPort source suggested unlocking before invoking callbacks
__CFSpinUnlock(¢er->lock);
obs->callback((CFNotificationCenterRef)center, (void*)obs->observer, nameReturn, objectReturn, userInfo);
__CFSpinLock(¢er->lock);
}
else switch(obs->sb)
{
case CFNotificationSuspensionBehaviorDrop: break;
case CFNotificationSuspensionBehaviorCoalesce:
__CFAddQueue( nameReturn, objectReturn, obs->observer, userInfo, obs->callback, TRUE );
break;
case CFNotificationSuspensionBehaviorHold:
__CFAddQueue( nameReturn, objectReturn, obs->observer, userInfo, obs->callback, FALSE );
break;
case CFNotificationSuspensionBehaviorDeliverImmediately:
if( __CFDistInfo.queueCount != 0 ) __CFDeliverQueue();
obs->callback( (CFNotificationCenterRef)center, (void*)obs->observer, nameReturn, objectReturn, userInfo );
break;
}
}
obs++;
}
__CFSpinUnlock(¢er->lock);
}
#if defined(__MACH__)
/*
* The CFMachPortCallBack invoked when a message arrives at the runloop from notifyd. The
* Darwin notification centre is passed in as the info... just because.
*/
void __CFDarwinCallBack(CFMachPortRef port, void *msg, CFIndex size, void *info)
{
//printf("Got a message from a darwin port!\n");
// first we retrieve the token associated with the notification
int token = ((mach_msg_header_t *)msg)->msgh_id;
// then we look for the matching record
CFIndex count = __CFDarwinInfo.count;
__CFDarwinNotifications *nots = __CFDarwinInfo.nots;
while( count-- )
{
while( nots->hash == 0 ) nots++;
if( nots->token == token ) // found it
{
count = -1;
break;
}
nots++;
}
if( count != -1 ) return; // couldn't find the matching notification
// then we send the notification to all the matching observers
__CFInvokeCallBacks(__CFDarwinCenter, nots->hash, __CFNCUnhash(nots->hash), NULL, NULL, NULL, TRUE);
}
#endif
// shared creation method
CFNotificationCenterRef __CFCreateCenter( CFIndex type )
{
// allocate the memory
CFIndex size = sizeof(struct __CFNotificationCenter) - sizeof(CFRuntimeBase);
struct __CFNotificationCenter *memory = (CFNotificationCenterRef)_CFRuntimeCreateInstance( kCFAllocatorDefault, __kCFNotificationCenterTypeID, size, NULL);
if (NULL == memory) return NULL;
memory->suspended = FALSE;
memory->type = type;
CF_SPINLOCK_INIT_FOR_STRUCTS(memory->lock);
// allocate storage and set counters
memory->observers = 0;
memory->capacity = CF_OBS_SIZE;
// IMPORTANT: after calloc, we assume memory is zeroed
memory->obs = (__CFObserver*)calloc(CF_OBS_SIZE, sizeof(__CFObserver));
if( memory->obs == NULL )
{
CFAllocatorDeallocate( kCFAllocatorDefault, memory );
memory = NULL;
}
return memory;
}
/*
* The local notification center is used for synchronous intra-task communication and
* can always be created.
*/
CFNotificationCenterRef CFNotificationCenterGetLocalCenter(void)
{
__CFSpinLock(&__CFLocalCenterLock);
if( __CFLocalCenter == NULL )
__CFLocalCenter = __CFCreateCenter(CF_LOCAL_CENTER);
__CFSpinUnlock(&__CFLocalCenterLock);
return __CFLocalCenter;
}
/*
* The distributed center relies on the presence of a daemon (our ddistnoted on
* Darwin) to deliver inter-task notifications. This implementation tries to contact
* it via CFMessagePort, and fails if a connection cannot be made.
*/
CFNotificationCenterRef CFNotificationCenterGetDistributedCenter(void)
{
//fprintf(stderr, "Entering CFNotificationCenterGetDistributedCenter()\n");
__CFSpinLock(&__CFDistributedCenterLock);
if( __CFDistributedCenter == NULL )
{
// generate a 'unique' port name for the current task
char uname[128];
//sprintf(uname, "ddistnoted-%s-%u", getprogname(), getpid());
//printf("unique string is '%s'\n", uname);
CFStringRef name = CFStringCreateWithCString( kCFAllocatorDefault, uname, kCFStringEncodingASCII );
// create the local port now, because the daemon will look for it
CFMessagePortContext context = { 0, NULL, NULL, NULL, NULL };
#if defined(__MACH__)
CFMessagePortRef local = CFMessagePortCreateLocal( kCFAllocatorDefault, name, __CFDistRecieve, &context, NULL );
if( local == NULL )
{
fprintf(stderr, "CFNC: Couldn't create a local message port.\n");
__CFSpinUnlock(&__CFDistributedCenterLock);
return NULL;
}
#else
CFMessagePortRef local = 0;
#endif
//CFRunLoopSourceRef rls =
//CFRunLoopAddSource( CFRunLoopGetMain(), rls, kCFRunLoopCommonModes );
#if defined(DEPLOYMENT_TARGET_MACOSX)
// create the remote port
CFMessagePortRef remote = CFMessagePortCreateRemote( kCFAllocatorDefault, CFSTR("org.puredarwin.ddistnoted") );
if( remote == NULL )
{
fprintf(stderr, "CFNC: Couldn't connect to message port.\n");
__CFSpinUnlock(&__CFDistributedCenterLock);
return NULL;
}
#else
CFMessagePortRef remote = 0;
#endif
// squeeze our unique name, as ASCII, into a data object...
CFIndex length = CFStringGetLength(name);
STACK_BUFFER_DECL(UInt8, data, (++length + sizeof(long)));
/* Security sessions come via one of the security components, although
I'm not sure which. Once we get everything working we may be able to
actually get this working properly. */
// if this isn't set -- and on other platforms -- we could maybe use userIds
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_LINUX
long session = getuid();