2 // XPCNotificationDispatcher.m
5 // Created by Mitch Adler on 11/1/16.
9 #import "XPCNotificationDispatcher.h"
10 #include <dispatch/dispatch.h>
12 #include <utilities/debugging.h>
17 // PointerArray helpers
19 @interface NSPointerArray (Removal)
20 - (void) removePointer: (nullable void *)pointer;
23 @implementation NSPointerArray (Removal)
24 - (void) removePointer: (nullable void *)pointer {
26 while(pos < [self count]) {
27 if (pointer == [self pointerAtIndex:pos]) {
28 [self removePointerAtIndex:pos];
39 static const char *kXPCNotificationStreamName = "com.apple.notifyd.matching";
40 static const char *kXPCNotificationNameKey = "Notification";
42 @interface XPCNotificationDispatcher ()
43 @property dispatch_queue_t queue;
44 @property NSPointerArray* listeners;
46 - (void) notification: (const char *) value;
51 @implementation XPCNotificationDispatcher
53 + (instancetype) dispatcher {
54 static dispatch_once_t onceToken;
55 static XPCNotificationDispatcher* sDispactcher;
56 dispatch_once(&onceToken, ^{
57 sDispactcher = [[XPCNotificationDispatcher alloc] init];
63 - (instancetype) init {
67 self.queue = dispatch_queue_create("XPC Notification Dispatch", DISPATCH_QUEUE_SERIAL);
68 self.listeners = [NSPointerArray weakObjectsPointerArray];
70 xpc_set_event_stream_handler(kXPCNotificationStreamName, self.queue, ^(xpc_object_t event){
71 const char *notificationName = xpc_dictionary_get_string(event, kXPCNotificationNameKey);
72 if (notificationName) {
73 [self notification:notificationName];
81 - (void) notification:(const char *)name {
82 [self.listeners compact];
83 [[self.listeners allObjects] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
84 [obj handleNotification: name];
89 - (void) addListener: (NSObject<XPCNotificationListener>*) newHandler {
90 dispatch_sync(self.queue, ^{
91 [self.listeners compact];
92 [self.listeners addPointer:(__bridge void * _Nullable)(newHandler)];
96 - (void) removeListener: (NSObject<XPCNotificationListener>*) existingHandler {
97 dispatch_sync(self.queue, ^{
98 [self.listeners removePointer:(__bridge void * _Nullable)existingHandler];