VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 (keep the newest one). */
  84. if (message->type == VLCNotification) {
  85. NSInteger last_match_msg = -1;
  86. for (NSInteger i = [[self messageQueue] count]-1; i >= 0; i-- ) {
  87. message_newer = (message_t *)[(NSData *)[self messageQueue][i] bytes];
  88. if (message_newer->type == VLCNotification &&
  89. message_newer->target == message->target &&
  90. [message_newer->u.name isEqualToString:message->u.name]) {
  91. if (last_match_msg >= 0) {
  92. message_t * msg = (message_t *)[(NSData *)[self messageQueue][last_match_msg] bytes];
  93. [msg->u.name release];
  94. [[self messageQueue] removeObjectAtIndex:last_match_msg];
  95. }
  96. last_match_msg = i;
  97. }
  98. }
  99. if (last_match_msg >= 0) {
  100. // newer notification detected, ignore current one
  101. [message->u.name release];
  102. [dataMessage release];
  103. [pool release];
  104. pthread_mutex_unlock([self queueLock]);
  105. continue;
  106. }
  107. } else if (message->type == VLCObjectMethodWithArrayArg) {
  108. NSMutableArray * newArg = nil;
  109. /* Collapse messages that takes array arg by sending one bigger array */
  110. for (NSInteger i = [[self messageQueue] count] - 1; i >= 0; i--) {
  111. message_newer = (message_t *)[(NSData *)[self messageQueue][i] bytes];
  112. if (message_newer->type == VLCObjectMethodWithArrayArg &&
  113. message_newer->target == message->target &&
  114. message_newer->sel == message->sel) {
  115. if (!newArg) {
  116. newArg = [NSMutableArray arrayWithArray:message->u.object];
  117. [message->u.object release];
  118. }
  119. [newArg addObjectsFromArray:message_newer->u.object];
  120. [message_newer->u.object release];
  121. [[self messageQueue] removeObjectAtIndex:i];
  122. }
  123. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  124. * This could be particulary problematic when the same object receive two related events
  125. * (for instance Added and Removed).
  126. * Ignore for now only if target is the same */
  127. else if (message_newer->target == message->target)
  128. break;
  129. }
  130. if (newArg)
  131. message->u.object = [newArg retain];
  132. }
  133. [self addMessageToHandleOnMainThread:dataMessage];
  134. pthread_mutex_unlock([self queueLock]);
  135. if (message->type == VLCNotification)
  136. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  137. withObject:dataMessage
  138. waitUntilDone: NO];
  139. else
  140. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  141. withObject:dataMessage
  142. waitUntilDone: YES];
  143. [pool release];
  144. }
  145. return nil;
  146. }
  147. @implementation VLCEventManager
  148. + (id)sharedManager
  149. {
  150. static dispatch_once_t onceToken;
  151. static VLCEventManager *defaultManager = nil;
  152. dispatch_once(&onceToken, ^{
  153. defaultManager = [[VLCEventManager alloc] init];
  154. });
  155. return defaultManager;
  156. }
  157. - (void)dummy
  158. {
  159. /* Put Cocoa in multithreaded mode by calling a dummy function */
  160. }
  161. - (id)init
  162. {
  163. if (self = [super init]) {
  164. if (![NSThread isMultiThreaded]) {
  165. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  166. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  167. }
  168. messageQueue = [[NSMutableArray alloc] initWithCapacity:10];
  169. pendingMessagesOnMainThread = [[NSMutableArray alloc] initWithCapacity:10];
  170. pendingMessagesLock = [[NSLock alloc] init];
  171. pthread_mutex_init(&queueLock, NULL);
  172. pthread_cond_init(&signalData, NULL);
  173. pthread_create(&dispatcherThread, NULL, EventDispatcherMainLoop, self);
  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. pthread_mutex_lock([self queueLock]);
  197. [[self messageQueue] insertObject:[NSData dataWithBytes:&message length:sizeof(message_t)] atIndex:0];
  198. pthread_cond_signal([self signalData]);
  199. pthread_mutex_unlock([self queueLock]);
  200. [pool release];
  201. }
  202. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  203. {
  204. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  205. message_t message =
  206. {
  207. aTarget,
  208. aSelector,
  209. [arg retain],
  210. [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg
  211. };
  212. pthread_mutex_lock([self queueLock]);
  213. [[self messageQueue] insertObject:[NSData dataWithBytes:&message length:sizeof(message_t)] atIndex:0];
  214. pthread_cond_signal([self signalData]);
  215. pthread_mutex_unlock([self queueLock]);
  216. [pool release];
  217. }
  218. - (void)cancelCallToObject:(id)target
  219. {
  220. // Remove all queued message
  221. pthread_mutex_lock([self queueLock]);
  222. [pendingMessagesLock lock];
  223. NSMutableArray *queue = [self messageQueue];
  224. for (int i = [queue count] - 1; i >= 0; i--) {
  225. NSData *data = queue[i];
  226. message_t *message = (message_t *)[data bytes];
  227. if (message->target == target)
  228. [queue removeObjectAtIndex:i];
  229. }
  230. // Remove all pending messages
  231. NSMutableArray *messages = pendingMessagesOnMainThread;
  232. for (int i = [messages count] - 1; i >= 0; i--) {
  233. NSData *data = messages[i];
  234. message_t *message = (message_t *)[data bytes];
  235. if (message->target == target)
  236. [messages removeObjectAtIndex:i];
  237. }
  238. [pendingMessagesLock unlock];
  239. pthread_mutex_unlock([self queueLock]);
  240. }
  241. @end
  242. @implementation VLCEventManager (Private)
  243. - (void)addMessageToHandleOnMainThread:(NSData *)messageAsData
  244. {
  245. [pendingMessagesLock lock];
  246. [pendingMessagesOnMainThread addObject:messageAsData];
  247. [pendingMessagesLock unlock];
  248. }
  249. - (BOOL)markMessageHandledOnMainThreadIfExists:(NSData *)messageAsData
  250. {
  251. [pendingMessagesLock lock];
  252. BOOL cancelled = ![pendingMessagesOnMainThread containsObject:messageAsData];
  253. if (!cancelled)
  254. [pendingMessagesOnMainThread removeObject:messageAsData];
  255. [pendingMessagesLock unlock];
  256. return !cancelled;
  257. }
  258. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(NSData*)data
  259. {
  260. message_t * message = (message_t *)[data bytes];
  261. // Check that we were not cancelled, ie, target was released
  262. if ([self markMessageHandledOnMainThreadIfExists:data])
  263. [self callDelegateOfObject:message->target withDelegateMethod:message->sel withNotificationName:message->u.name];
  264. [message->u.name release];
  265. [data release];
  266. }
  267. - (void)callObjectMethodWithArgs:(NSData*)data
  268. {
  269. message_t * message = (message_t *)[data bytes];
  270. // Check that we were not cancelled
  271. if ([self markMessageHandledOnMainThreadIfExists:data]) {
  272. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message->target methodForSelector: message->sel];
  273. method(message->target, message->sel, message->u.object);
  274. }
  275. [message->u.object release];
  276. [data release];
  277. }
  278. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  279. {
  280. [[NSNotificationCenter defaultCenter] postNotification: [NSNotification notificationWithName:aNotificationName object:aTarget]];
  281. id delegate = [aTarget delegate];
  282. if (!delegate || ![delegate respondsToSelector:aSelector])
  283. return;
  284. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[[aTarget delegate] methodForSelector: aSelector];
  285. method([aTarget delegate], aSelector, [NSNotification notificationWithName:aNotificationName object:aTarget]);
  286. }
  287. - (NSMutableArray *)messageQueue
  288. {
  289. return messageQueue;
  290. }
  291. - (NSMutableArray *)pendingMessagesOnMainThread
  292. {
  293. return pendingMessagesOnMainThread;
  294. }
  295. - (NSLock *)pendingMessagesLock
  296. {
  297. return pendingMessagesLock;
  298. }
  299. - (pthread_cond_t *)signalData
  300. {
  301. return &signalData;
  302. }
  303. - (pthread_mutex_t *)queueLock
  304. {
  305. return &queueLock;
  306. }
  307. @end