VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  68. message_t * message, * message_newer = NULL;
  69. NSData * dataMessage;
  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. pthread_cond_wait([self signalData], [self queueLock]);
  77. //if ([[self messageQueue] count] % 100 == 0 || [[self messageQueue] count] < 100)
  78. // VKLog(@"[EVENT_MANAGER] On the stack we have %d elements", [[self messageQueue] count]);
  79. /* Get the first object off the queue. */
  80. dataMessage = [[[self messageQueue] lastObject] retain]; // Released in 'call'
  81. [[self messageQueue] removeLastObject];
  82. message = (message_t *)[dataMessage bytes];
  83. /* Remove duplicate notifications. */
  84. if (message->type == VLCNotification) {
  85. for (NSInteger i = [[self messageQueue] count]-1; i >= 0; i-- ) {
  86. message_newer = (message_t *)[(NSData *)[[self messageQueue] objectAtIndex:i] bytes];
  87. if (message_newer->type == VLCNotification &&
  88. message_newer->target == message->target &&
  89. [message_newer->u.name isEqualToString:message->u.name]) {
  90. [message_newer->u.name release];
  91. [[self messageQueue] removeObjectAtIndex:i];
  92. }
  93. }
  94. } else if (message->type == VLCObjectMethodWithArrayArg) {
  95. NSMutableArray * newArg = nil;
  96. /* Collapse messages that takes array arg by sending one bigger array */
  97. for (NSInteger i = [[self messageQueue] count] - 1; i >= 0; i--) {
  98. message_newer = (message_t *)[(NSData *)[[self messageQueue] objectAtIndex: i] bytes];
  99. if (message_newer->type == VLCObjectMethodWithArrayArg &&
  100. message_newer->target == message->target &&
  101. message_newer->sel == message->sel) {
  102. if (!newArg) {
  103. newArg = [NSMutableArray arrayWithArray:message->u.object];
  104. [message->u.object release];
  105. }
  106. [newArg addObjectsFromArray:message_newer->u.object];
  107. [message_newer->u.object release];
  108. [[self messageQueue] removeObjectAtIndex:i];
  109. }
  110. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  111. * This could be particulary problematic when the same object receive two related events
  112. * (for instance Added and Removed).
  113. * Ignore for now only if target is the same */
  114. else if (message_newer->target == message->target)
  115. break;
  116. }
  117. if (newArg)
  118. message->u.object = [newArg retain];
  119. }
  120. [self addMessageToHandleOnMainThread:dataMessage];
  121. pthread_mutex_unlock([self queueLock]);
  122. if (message->type == VLCNotification)
  123. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  124. withObject:dataMessage
  125. waitUntilDone: NO];
  126. else
  127. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  128. withObject:dataMessage
  129. waitUntilDone: YES];
  130. [pool drain];
  131. }
  132. return nil;
  133. }
  134. @implementation VLCEventManager
  135. + (id)sharedManager
  136. {
  137. static VLCEventManager *defaultManager = NULL;
  138. /* We do want a lock here to avoid leaks */
  139. if (!defaultManager)
  140. defaultManager = [[VLCEventManager alloc] init];
  141. return defaultManager;
  142. }
  143. - (void)dummy
  144. {
  145. /* Put Cocoa in multithreaded mode by calling a dummy function */
  146. }
  147. - (id)init
  148. {
  149. if (self = [super init]) {
  150. if (![NSThread isMultiThreaded]) {
  151. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  152. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  153. }
  154. pthread_mutex_init(&queueLock, NULL);
  155. pthread_cond_init(&signalData, NULL);
  156. pthread_create(&dispatcherThread, NULL, EventDispatcherMainLoop, self);
  157. messageQueue = [[NSMutableArray alloc] initWithCapacity:10];
  158. pendingMessagesOnMainThread = [[NSMutableArray alloc] initWithCapacity:10];
  159. pendingMessagesLock = [[NSLock alloc] init];
  160. }
  161. return self;
  162. }
  163. - (void)dealloc
  164. {
  165. pthread_kill(dispatcherThread, SIGKILL);
  166. pthread_join(dispatcherThread, NULL);
  167. [messageQueue release];
  168. [pendingMessagesOnMainThread release];
  169. [super dealloc];
  170. }
  171. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  172. {
  173. /* Don't send on main thread before this gets sorted out */
  174. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  175. message_t message =
  176. {
  177. aTarget,
  178. aSelector,
  179. [aNotificationName retain],
  180. VLCNotification
  181. };
  182. if ([NSThread isMainThread]) {
  183. NSData *nsd_message = [NSData dataWithBytes:&message length:sizeof(message_t)];
  184. [self addMessageToHandleOnMainThread:nsd_message];
  185. [self callDelegateOfObjectAndSendNotificationWithArgs:[nsd_message retain] /* released in the call */];
  186. [nsd_message autorelease];
  187. } else {
  188. pthread_mutex_lock([self queueLock]);
  189. [[self messageQueue] insertObject:[NSData dataWithBytes:&message length:sizeof(message_t)] atIndex:0];
  190. pthread_cond_signal([self signalData]);
  191. pthread_mutex_unlock([self queueLock]);
  192. }
  193. [pool drain];
  194. }
  195. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  196. {
  197. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  198. message_t message =
  199. {
  200. aTarget,
  201. aSelector,
  202. [arg retain],
  203. [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg
  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. [pool drain];
  210. }
  211. - (void)cancelCallToObject:(id)target
  212. {
  213. // Remove all queued message
  214. pthread_mutex_lock([self queueLock]);
  215. [pendingMessagesLock lock];
  216. NSMutableArray *queue = [self messageQueue];
  217. for (int i = [queue count] - 1; i >= 0; i--) {
  218. NSData *data = [queue objectAtIndex:i];
  219. message_t *message = (message_t *)[data bytes];
  220. if (message->target == target)
  221. [queue removeObjectAtIndex:i];
  222. }
  223. // Remove all pending messages
  224. NSMutableArray *messages = pendingMessagesOnMainThread;
  225. for (int i = [messages count] - 1; i >= 0; i--) {
  226. NSData *data = [messages objectAtIndex:i];
  227. message_t *message = (message_t *)[data bytes];
  228. if (message->target == target)
  229. [messages removeObjectAtIndex:i];
  230. }
  231. [pendingMessagesLock unlock];
  232. pthread_mutex_unlock([self queueLock]);
  233. }
  234. @end
  235. @implementation VLCEventManager (Private)
  236. - (void)addMessageToHandleOnMainThread:(NSData *)messageAsData
  237. {
  238. [pendingMessagesLock lock];
  239. [pendingMessagesOnMainThread addObject:messageAsData];
  240. [pendingMessagesLock unlock];
  241. }
  242. - (BOOL)markMessageHandledOnMainThreadIfExists:(NSData *)messageAsData
  243. {
  244. [pendingMessagesLock lock];
  245. BOOL cancelled = ![pendingMessagesOnMainThread containsObject:messageAsData];
  246. if (!cancelled)
  247. [pendingMessagesOnMainThread removeObject:messageAsData];
  248. [pendingMessagesLock unlock];
  249. return !cancelled;
  250. }
  251. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(NSData*)data
  252. {
  253. message_t * message = (message_t *)[data bytes];
  254. // Check that we were not cancelled, ie, target was released
  255. if ([self markMessageHandledOnMainThreadIfExists:data])
  256. [self callDelegateOfObject:message->target withDelegateMethod:message->sel withNotificationName:message->u.name];
  257. [message->u.name release];
  258. [data release];
  259. }
  260. - (void)callObjectMethodWithArgs:(NSData*)data
  261. {
  262. message_t * message = (message_t *)[data bytes];
  263. // Check that we were not cancelled
  264. if ([self markMessageHandledOnMainThreadIfExists:data]) {
  265. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message->target methodForSelector: message->sel];
  266. method(message->target, message->sel, message->u.object);
  267. }
  268. [message->u.object release];
  269. [data release];
  270. }
  271. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  272. {
  273. [[NSNotificationCenter defaultCenter] postNotification: [NSNotification notificationWithName:aNotificationName object:aTarget]];
  274. id delegate = [aTarget delegate];
  275. if (!delegate || ![delegate respondsToSelector:aSelector])
  276. return;
  277. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[[aTarget delegate] methodForSelector: aSelector];
  278. method([aTarget delegate], aSelector, [NSNotification notificationWithName:aNotificationName object:aTarget]);
  279. }
  280. - (NSMutableArray *)messageQueue
  281. {
  282. return messageQueue;
  283. }
  284. - (NSMutableArray *)pendingMessagesOnMainThread
  285. {
  286. return pendingMessagesOnMainThread;
  287. }
  288. - (NSLock *)pendingMessagesLock
  289. {
  290. return pendingMessagesLock;
  291. }
  292. - (pthread_cond_t *)signalData
  293. {
  294. return &signalData;
  295. }
  296. - (pthread_mutex_t *)queueLock
  297. {
  298. return &queueLock;
  299. }
  300. @end