VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*****************************************************************************
  2. * VLCEventManager.m: VLCKit.framework VLCEventManager implementation
  3. *****************************************************************************
  4. * Copyright (C) 2007 Pierre d'Herbemont
  5. * Copyright (C) 2007 VLC authors and VideoLAN
  6. * $Id$
  7. *
  8. * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
  9. *
  10. * This program is free software; you can redistribute it and/or modify it
  11. * under the terms of the GNU Lesser General Public License as published by
  12. * the Free Software Foundation; either version 2.1 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public License
  21. * along with this program; if not, write to the Free Software Foundation,
  22. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  23. *****************************************************************************/
  24. #import "VLCEventManager.h"
  25. #import <pthread.h>
  26. /**
  27. * Defines the type of interthread message on the queue.
  28. */
  29. typedef enum
  30. {
  31. VLCNotification, //< Standard NSNotification.
  32. VLCObjectMethodWithObjectArg, //< Method with an object argument.
  33. VLCObjectMethodWithArrayArg //< Method with an array argument.
  34. } message_type_t;
  35. /**
  36. * Data structured used to enqueue messages onto the queue.
  37. */
  38. typedef struct {
  39. id target; //< Target object that should receive the message (retained until method is called).
  40. SEL sel; //< A selector that identifies the message to be sent to the target.
  41. union u //< Object could either be a VLCNotification or other.
  42. {
  43. NSString * name; //< Name to be used for NSNotification
  44. id object; //< Object argument to pass to the target via the selector.
  45. } u;
  46. message_type_t type; //< Type of queued message.
  47. } message_t;
  48. @interface VLCEventManager (Private)
  49. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(NSData*)data;
  50. - (void)callObjectMethodWithArgs:(NSData*)data;
  51. - (void)callDelegateOfObject:(id) aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName;
  52. - (pthread_cond_t *)signalData;
  53. - (pthread_mutex_t *)queueLock;
  54. - (NSMutableArray *)messageQueue;
  55. - (NSMutableArray *)pendingMessagesOnMainThread;
  56. - (NSLock *)pendingMessagesLock;
  57. - (void)addMessageToHandleOnMainThread:(NSData *)messageAsData;
  58. @end
  59. /**
  60. * Provides a function for the main entry point for the dispatch thread. It dispatches any messages that is queued.
  61. * \param user_data Pointer to the VLCEventManager instance that instiated this thread.
  62. */
  63. static void * EventDispatcherMainLoop(void * user_data)
  64. {
  65. VLCEventManager * self = user_data;
  66. for(;;)
  67. {
  68. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  69. message_t * message, * message_newer = NULL;
  70. NSData * dataMessage;
  71. NSInteger i;
  72. /* Sleep a bit not to flood the interface */
  73. usleep(300);
  74. /* Wait for some data */
  75. pthread_mutex_lock([self queueLock]);
  76. /* Wait until we have something on the queue */
  77. while( [[self messageQueue] count] <= 0)
  78. {
  79. pthread_cond_wait([self signalData], [self queueLock]);
  80. }
  81. //if( [[self messageQueue] count] % 100 == 0 || [[self messageQueue] count] < 100 )
  82. // NSLog(@"[EVENT_MANAGER] On the stack we have %d elements", [[self messageQueue] count]);
  83. /* Get the first object off the queue. */
  84. dataMessage = [[[self messageQueue] lastObject] retain]; // Released in 'call'
  85. [[self messageQueue] removeLastObject];
  86. message = (message_t *)[dataMessage bytes];
  87. /* Remove duplicate notifications. */
  88. if( message->type == VLCNotification )
  89. {
  90. for( i = [[self messageQueue] count]-1; i >= 0; i-- )
  91. {
  92. message_newer = (message_t *)[(NSData *)[[self messageQueue] objectAtIndex:i] bytes];
  93. if( message_newer->type == VLCNotification &&
  94. message_newer->target == message->target &&
  95. [message_newer->u.name isEqualToString:message->u.name] )
  96. {
  97. [message_newer->u.name release];
  98. [[self messageQueue] removeObjectAtIndex:i];
  99. }
  100. }
  101. }
  102. else if( message->type == VLCObjectMethodWithArrayArg )
  103. {
  104. NSMutableArray * newArg = nil;
  105. /* Collapse messages that takes array arg by sending one bigger array */
  106. for(i = [[self messageQueue] count] - 1; i >= 0; i--)
  107. {
  108. message_newer = (message_t *)[(NSData *)[[self messageQueue] objectAtIndex: i] bytes];
  109. if (message_newer->type == VLCObjectMethodWithArrayArg &&
  110. message_newer->target == message->target &&
  111. message_newer->sel == message->sel)
  112. {
  113. if (!newArg)
  114. {
  115. newArg = [NSMutableArray arrayWithArray:message->u.object];
  116. [message->u.object release];
  117. }
  118. [newArg addObjectsFromArray:message_newer->u.object];
  119. [message_newer->u.object release];
  120. [[self messageQueue] removeObjectAtIndex:i];
  121. }
  122. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  123. * This could be particulary problematic when the same object receive two related events
  124. * (for instance Added and Removed).
  125. * Ignore for now only if target is the same */
  126. else if( message_newer->target == message->target )
  127. break;
  128. }
  129. if (newArg)
  130. message->u.object = [newArg retain];
  131. }
  132. [self addMessageToHandleOnMainThread:dataMessage];
  133. pthread_mutex_unlock([self queueLock]);
  134. if( message->type == VLCNotification )
  135. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  136. withObject:dataMessage
  137. waitUntilDone: NO];
  138. else
  139. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  140. withObject:dataMessage
  141. waitUntilDone: YES];
  142. [pool drain];
  143. }
  144. return nil;
  145. }
  146. @implementation VLCEventManager
  147. + (id)sharedManager
  148. {
  149. static VLCEventManager *defaultManager = NULL;
  150. /* We do want a lock here to avoid leaks */
  151. if (!defaultManager)
  152. defaultManager = [[VLCEventManager alloc] init];
  153. return defaultManager;
  154. }
  155. - (void)dummy
  156. {
  157. /* Put Cocoa in multithreaded mode by calling a dummy function */
  158. }
  159. - (id)init
  160. {
  161. if(self = [super init])
  162. {
  163. if(![NSThread isMultiThreaded])
  164. {
  165. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  166. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  167. }
  168. pthread_mutex_init(&queueLock, NULL);
  169. pthread_cond_init(&signalData, NULL);
  170. pthread_create(&dispatcherThread, NULL, EventDispatcherMainLoop, self);
  171. messageQueue = [[NSMutableArray alloc] initWithCapacity:10];
  172. pendingMessagesOnMainThread = [[NSMutableArray alloc] initWithCapacity:10];
  173. pendingMessagesLock = [[NSLock alloc] init];
  174. }
  175. return self;
  176. }
  177. - (void)dealloc
  178. {
  179. pthread_kill(dispatcherThread, SIGKILL);
  180. pthread_join(dispatcherThread, NULL);
  181. [messageQueue release];
  182. [pendingMessagesOnMainThread release];
  183. [super dealloc];
  184. }
  185. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  186. {
  187. /* Don't send on main thread before this gets sorted out */
  188. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  189. message_t message =
  190. {
  191. aTarget,
  192. aSelector,
  193. [aNotificationName retain],
  194. VLCNotification
  195. };
  196. if( [NSThread isMainThread] )
  197. {
  198. NSData *nsd_message = [NSData dataWithBytes:&message length:sizeof(message_t)];
  199. [self addMessageToHandleOnMainThread:nsd_message];
  200. [self callDelegateOfObjectAndSendNotificationWithArgs:[nsd_message retain] /* released in the call */];
  201. [nsd_message autorelease];
  202. }
  203. else
  204. {
  205. pthread_mutex_lock([self queueLock]);
  206. [[self messageQueue] insertObject:[NSData dataWithBytes:&message length:sizeof(message_t)] atIndex:0];
  207. pthread_cond_signal([self signalData]);
  208. pthread_mutex_unlock([self queueLock]);
  209. }
  210. [pool drain];
  211. }
  212. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  213. {
  214. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  215. message_t message =
  216. {
  217. aTarget,
  218. aSelector,
  219. [arg retain],
  220. [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg
  221. };
  222. pthread_mutex_lock([self queueLock]);
  223. [[self messageQueue] insertObject:[NSData dataWithBytes:&message length:sizeof(message_t)] atIndex:0];
  224. pthread_cond_signal([self signalData]);
  225. pthread_mutex_unlock([self queueLock]);
  226. [pool drain];
  227. }
  228. - (void)cancelCallToObject:(id)target
  229. {
  230. // Remove all queued message
  231. pthread_mutex_lock([self queueLock]);
  232. [pendingMessagesLock lock];
  233. NSMutableArray *queue = [self messageQueue];
  234. for (int i = [queue count] - 1; i >= 0; i--) {
  235. NSData *data = [queue objectAtIndex:i];
  236. message_t *message = (message_t *)[data bytes];
  237. if (message->target == target) {
  238. [queue removeObjectAtIndex:i];
  239. }
  240. }
  241. // Remove all pending messages
  242. NSMutableArray *messages = pendingMessagesOnMainThread;
  243. for (int i = [messages count] - 1; i >= 0; i--) {
  244. NSData *data = [messages objectAtIndex:i];
  245. message_t *message = (message_t *)[data bytes];
  246. if (message->target == target) {
  247. [messages removeObjectAtIndex:i];
  248. }
  249. }
  250. [pendingMessagesLock unlock];
  251. pthread_mutex_unlock([self queueLock]);
  252. }
  253. @end
  254. @implementation VLCEventManager (Private)
  255. - (void)addMessageToHandleOnMainThread:(NSData *)messageAsData
  256. {
  257. [pendingMessagesLock lock];
  258. [pendingMessagesOnMainThread addObject:messageAsData];
  259. [pendingMessagesLock unlock];
  260. }
  261. - (BOOL)markMessageHandledOnMainThreadIfExists:(NSData *)messageAsData
  262. {
  263. [pendingMessagesLock lock];
  264. BOOL cancelled = ![pendingMessagesOnMainThread containsObject:messageAsData];
  265. if (!cancelled)
  266. [pendingMessagesOnMainThread removeObject:messageAsData];
  267. [pendingMessagesLock unlock];
  268. return !cancelled;
  269. }
  270. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(NSData*)data
  271. {
  272. message_t * message = (message_t *)[data bytes];
  273. // Check that we were not cancelled, ie, target was released
  274. if ([self markMessageHandledOnMainThreadIfExists:data]) {
  275. [self callDelegateOfObject:message->target withDelegateMethod:message->sel withNotificationName:message->u.name];
  276. }
  277. [message->u.name release];
  278. [data release];
  279. }
  280. - (void)callObjectMethodWithArgs:(NSData*)data
  281. {
  282. message_t * message = (message_t *)[data bytes];
  283. // Check that we were not cancelled
  284. if ([self markMessageHandledOnMainThreadIfExists:data]) {
  285. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message->target methodForSelector: message->sel];
  286. method(message->target, message->sel, message->u.object);
  287. }
  288. [message->u.object release];
  289. [data release];
  290. }
  291. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  292. {
  293. [[NSNotificationCenter defaultCenter] postNotification: [NSNotification notificationWithName:aNotificationName object:aTarget]];
  294. id delegate = [aTarget delegate];
  295. if (!delegate || ![delegate respondsToSelector:aSelector])
  296. return;
  297. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[[aTarget delegate] methodForSelector: aSelector];
  298. method([aTarget delegate], aSelector, [NSNotification notificationWithName:aNotificationName object:aTarget]);
  299. }
  300. - (NSMutableArray *)messageQueue
  301. {
  302. return messageQueue;
  303. }
  304. - (NSMutableArray *)pendingMessagesOnMainThread
  305. {
  306. return pendingMessagesOnMainThread;
  307. }
  308. - (NSLock *)pendingMessagesLock
  309. {
  310. return pendingMessagesLock;
  311. }
  312. - (pthread_cond_t *)signalData
  313. {
  314. return &signalData;
  315. }
  316. - (pthread_mutex_t *)queueLock
  317. {
  318. return &queueLock;
  319. }
  320. @end