VLCEventManager.m 11 KB

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