GitHub Sale: sign up for any paid plan this week and pay nothing until January 1, 2009!  [ hide ]

public
Description: An iPhoto plugin to export photos to Gallery.
Homepage: http://zwily.com/iphoto
Clone URL: git://github.com/zwily/iphototogallery.git
iphototogallery / Source / InterThreadMessaging.m
100644 446 lines (345 sloc) 12.661 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
/*-*- Mode: ObjC; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-*/
/*
* InterThreadMessaging -- InterThreadMessaging.m
* Created by toby on Tue Jun 19 2001.
*
* NOTE: this is a modified InterThreadMessaging that schedules on the run loop for the modal mode along with default
*
*/
 
#import <pthread.h>
#import "InterThreadMessaging.h"
 
/* There are four types of messages that can be posted between threads: a
notification to be posted to the default notification centre and selectors
to be performed with a varying number of arguments. (I was tempted to
implement all three in terms of performSelector:withObject:withObject:
and passing in nil for the empty arguments, but then it occurred to me
that perhaps the receiver has overridden performSelector: and
performSelector:withObject:. So I think I must disambiguate between
them all.) */
 
typedef enum InterThreadMessageType InterThreadMessageType;
enum InterThreadMessageType
{
    kITMPostNotification = 1,
    kITMPerformSelector0Args,
    kITMPerformSelector1Args,
    kITMPerformSelector2Args
};
 
 
/* The message contents are carried between threads in this struct. The
struct is allocated in the sending thread and freed in the receiving thread.
It is carried between the threads in an NSPortMessage - the NSPortMessage
contains a single NSData argument, which is a wrapper around the pointer to
this struct. */
 
typedef struct InterThreadMessage InterThreadMessage;
struct InterThreadMessage
{
    InterThreadMessageType type;
    union {
        NSNotification *notification;
        struct {
            SEL selector;
            id receiver;
            id arg1;
            id arg2;
        } sel;
    } data;
};
 
 
 
/* Each thread is associated with an NSPort. This port is used to deliver
messages to the target thread. */
 
static NSMapTable *pThreadMessagePorts = NULL;
static pthread_mutex_t pGate = { 0 };
 
@interface InterThreadManager : NSObject
+ (void) threadDied:(NSNotification *)notification;
+ (void) handlePortMessage:(NSPortMessage *)msg;
@end
 
static void
createMessagePortForThread (NSThread *thread, NSRunLoop *runLoop)
{
    NSPort *port;
 
    assert(nil != thread);
    assert(nil != runLoop);
    assert(NULL != pThreadMessagePorts);
 
    pthread_mutex_lock(&pGate);
 
    port = NSMapGet(pThreadMessagePorts, thread);
    if (nil == port) {
        port = [[NSPort allocWithZone:NULL] init];
        [port setDelegate:[InterThreadManager class]];
        [port scheduleInRunLoop:runLoop forMode:NSModalPanelRunLoopMode]; // ZWw: I need this for iPhotoToGallery usage
        [port scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
        NSMapInsertKnownAbsent(pThreadMessagePorts, thread, port);
 
        /* Transfer ownership of this port to the map table. */
        [port release];
    }
 
    pthread_mutex_unlock(&pGate);
}
 
static NSPort *
messagePortForThread (NSThread *thread)
{
    NSPort *port;
 
    assert(nil != thread);
    assert(NULL != pThreadMessagePorts);
 
    pthread_mutex_lock(&pGate);
    port = NSMapGet(pThreadMessagePorts, thread);
    pthread_mutex_unlock(&pGate);
 
    if (nil == port) {
        [NSException raise:NSInvalidArgumentException
                     format:@"Thread %@ is not prepared to receive "
                            @"inter-thread messages. You must invoke "
                            @"+prepareForInterThreadMessages first.", thread];
    }
 
    return port;
}
 
static void
removeMessagePortForThread (NSThread *thread, NSRunLoop *runLoop)
{
    NSPort *port;
 
    assert(nil != thread);
    assert(NULL != pThreadMessagePorts);
 
    pthread_mutex_lock(&pGate);
    
    port = (NSPort *) NSMapGet(pThreadMessagePorts, thread);
    if (nil != port) {
        [port removeFromRunLoop:runLoop forMode:NSModalPanelRunLoopMode]; // ZWw: I added it, so I need to remove it
        [port removeFromRunLoop:runLoop forMode:NSDefaultRunLoopMode];
        NSMapRemove(pThreadMessagePorts, thread);
    }
 
    pthread_mutex_unlock(&pGate);
}
 
 
 
 
@implementation NSThread (InterThreadMessaging)
 
+ (void) prepareForInterThreadMessages
{
    /* Force the class initialization. */
    [InterThreadManager class];
 
    createMessagePortForThread([NSThread currentThread],
                               [NSRunLoop currentRunLoop]);
}
 
@end
 
 
 
 
@interface NSThread (SecretStuff)
- (NSRunLoop *) runLoop;
@end
 
@implementation InterThreadManager
 
+ (void) initialize
{
    /* Create the mutex - this should be invoked by the Objective-C runtime
(in a thread-safe manner) before any one can use this module, so I
don't think I need to worry about race conditions here. */
    if (nil == pThreadMessagePorts) {
        pthread_mutex_init(&pGate, NULL);
 
        pThreadMessagePorts =
            NSCreateMapTable(NSNonRetainedObjectMapKeyCallBacks,
                             NSObjectMapValueCallBacks, 0);
 
        [[NSNotificationCenter defaultCenter]
            addObserver:[self class]
            selector:@selector(threadDied:)
            name:NSThreadWillExitNotification
            object:nil];
    }
}
 
+ (void) threadDied:(NSNotification *)notification
{
    NSThread *thread;
    NSRunLoop *runLoop;
 
    thread = [notification object];
    runLoop = [thread runLoop];
    if (nil != runLoop) {
        removeMessagePortForThread(thread, [thread runLoop]);
    }
}
 
+ (void) handlePortMessage:(NSPortMessage *)portMessage
{
    InterThreadMessage *msg;
    NSArray *components;
    NSData *data;
 
    components = [portMessage components];
    assert(1 == [components count]);
 
    data = [components objectAtIndex:0];
    msg = *((InterThreadMessage **) [data bytes]);
    
    switch (msg->type)
    {
        case kITMPostNotification:
            [[NSNotificationCenter defaultCenter]
                postNotification:msg->data.notification];
            [msg->data.notification release];
            break;
 
        case kITMPerformSelector0Args:
            [msg->data.sel.receiver performSelector:msg->data.sel.selector];
            [msg->data.sel.receiver release];
            break;
 
        case kITMPerformSelector1Args:
            [msg->data.sel.receiver performSelector:msg->data.sel.selector
                                    withObject:msg->data.sel.arg1];
            [msg->data.sel.receiver release];
            [msg->data.sel.arg1 release];
            break;
 
        case kITMPerformSelector2Args:
            [msg->data.sel.receiver performSelector:msg->data.sel.selector
                                    withObject:msg->data.sel.arg1
                                    withObject:msg->data.sel.arg2];
            [msg->data.sel.receiver release];
            [msg->data.sel.arg1 release];
            [msg->data.sel.arg2 release];
            break;
 
        default:
            assert(0);
    }
 
    free(msg);
}
 
@end
 
 
 
 
 
static void
postMessage (InterThreadMessage *message, NSThread *thread, NSDate *limitDate)
{
    NSPortMessage *portMessage;
    NSMutableArray *components;
    NSPort *port;
    NSData *data;
    BOOL retval;
 
    if (nil == thread) { thread = [NSThread currentThread]; }
    port = messagePortForThread(thread);
    assert(nil != port);
 
    data = [[NSData alloc] initWithBytes:&message length:sizeof(void *)];
    components = [[NSMutableArray alloc] initWithObjects:&data count:1];
    portMessage = [[NSPortMessage alloc] initWithSendPort:port
                                         receivePort:nil
                                         components:components];
 
    if (nil == limitDate) { limitDate = [NSDate distantFuture]; }
    retval = [portMessage sendBeforeDate:limitDate];
    [portMessage release];
    [components release];
    [data release];
 
    if (!retval) {
        [NSException raise:NSPortTimeoutException
                     format:@"Can't send message to thread %@: timeout "
                            @"before date %@", thread, limitDate];
    }
}
 
static void
performSelector (InterThreadMessageType type, SEL selector, id receiver,
                 id object1, id object2, NSThread *thread, NSDate *limitDate)
{
    InterThreadMessage *msg;
 
    assert(NULL != selector);
    
    if (nil != receiver) {
        msg = (InterThreadMessage *) malloc(sizeof(struct InterThreadMessage));
        bzero(msg, sizeof(struct InterThreadMessage));
        msg->type = type;
        msg->data.sel.selector = selector;
        msg->data.sel.receiver = [receiver retain];
        msg->data.sel.arg1 = [object1 retain];
        msg->data.sel.arg2 = [object2 retain];
 
        postMessage(msg, thread, limitDate);
    }
}
 
static void
postNotification (NSNotification *notification, NSThread *thread,
                  NSDate *limitDate)
{
    InterThreadMessage *msg;
 
    assert(nil != notification);
    
    msg = (InterThreadMessage *) malloc(sizeof(struct InterThreadMessage));
    bzero(msg, sizeof(struct InterThreadMessage));
    msg->type = kITMPostNotification;
    msg->data.notification = [notification retain];
 
    postMessage(msg, thread, limitDate);
}
 
 
 
 
 
 
@implementation NSObject (InterThreadMessaging)
 
- (void) performSelector:(SEL)selector
         inThread:(NSThread *)thread
{
    performSelector(kITMPerformSelector0Args, selector, self, nil, nil,
                    thread, nil);
}
 
- (void) performSelector:(SEL)selector
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    performSelector(kITMPerformSelector0Args, selector, self, nil, nil,
                    thread, limitDate);
}
 
- (void) performSelector:(SEL)selector
         withObject:(id)object
         inThread:(NSThread *)thread
{
    performSelector(kITMPerformSelector1Args, selector, self, object, nil,
                    thread, nil);
}
 
- (void) performSelector:(SEL)selector
         withObject:(id)object
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    performSelector(kITMPerformSelector1Args, selector, self, object, nil,
                    thread, limitDate);
}
 
- (void) performSelector:(SEL)selector
         withObject:(id)object1
         withObject:(id)object2
         inThread:(NSThread *)thread
{
    performSelector(kITMPerformSelector2Args, selector, self, object1, object2,
                    thread, nil);
}
 
- (void) performSelector:(SEL)selector
         withObject:(id)object1
         withObject:(id)object2
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    performSelector(kITMPerformSelector2Args, selector, self, object1, object2,
                    thread, limitDate);
}
 
@end
 
 
 
@implementation NSNotificationCenter (InterThreadMessaging)
 
- (void) postNotification:(NSNotification *)notification
         inThread:(NSThread *)thread
{
    postNotification(notification, thread, nil);
}
 
- (void) postNotification:(NSNotification *)notification
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    postNotification(notification, thread, limitDate);
}
 
- (void) postNotificationName:(NSString *)name
         object:(id)object
         inThread:(NSThread *)thread
{
    NSNotification *notification;
    
    notification = [NSNotification notificationWithName:name
                                   object:object
                                   userInfo:nil];
    postNotification(notification, thread, nil);
}
 
- (void) postNotificationName:(NSString *)name
         object:(id)object
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    NSNotification *notification;
    
    notification = [NSNotification notificationWithName:name
                                   object:object
                                   userInfo:nil];
    postNotification(notification, thread, limitDate);
}
 
- (void) postNotificationName:(NSString *)name
         object:(id)object
         userInfo:(NSDictionary *)userInfo
         inThread:(NSThread *)thread
{
    NSNotification *notification;
    
    notification = [NSNotification notificationWithName:name
                                   object:object
                                   userInfo:userInfo];
    postNotification(notification, thread, nil);
}
 
- (void) postNotificationName:(NSString *)name
         object:(id)object
         userInfo:(NSDictionary *)userInfo
         inThread:(NSThread *)thread
         beforeDate:(NSDate *)limitDate
{
    NSNotification *notification;
    
    notification = [NSNotification notificationWithName:name
                                   object:object
                                   userInfo:userInfo];
    postNotification(notification, thread, limitDate);
}
 
@end