VLCEventManager.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. @interface message_t : NSObject
  39. @property (nonatomic) id target; //< Target object that should receive the message (retained until method is called).
  40. @property (nonatomic) SEL sel; //< A selector that identifies the message to be sent to the target.
  41. @property (nonatomic, copy) NSString * name; //< Name to be used for NSNotification
  42. @property (nonatomic) id object; //< Object argument to pass to the target via the selector.
  43. @property (nonatomic) message_type_t type; //< Type of queued message.
  44. @end
  45. @implementation message_t
  46. - (BOOL)isEqual:(id)object
  47. {
  48. if (![object isKindOfClass:[message_t class]]) return NO;
  49. message_t *otherObject = object;
  50. BOOL notificatonMatches =
  51. (otherObject.type == VLCNotification && [otherObject.name isEqualToString:self.name]) ||
  52. (otherObject.type == VLCObjectMethodWithArrayArg && [otherObject.object isEqual:self.object]) ||
  53. (otherObject.type == VLCObjectMethodWithObjectArg && [otherObject.object isEqual:self.object]);
  54. return [otherObject.target isEqual:_target] &&
  55. otherObject.sel == self.sel &&
  56. otherObject.type == self.type &&
  57. notificatonMatches;
  58. }
  59. @end
  60. @interface VLCEventManager (Private)
  61. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message;
  62. - (void)callObjectMethodWithArgs:(message_t *)message;
  63. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName;
  64. - (pthread_cond_t *)signalData;
  65. - (pthread_mutex_t *)queueLock;
  66. - (NSMutableArray *)messageQueue;
  67. - (NSMutableArray *)pendingMessagesOnMainThread;
  68. - (NSLock *)pendingMessagesLock;
  69. - (void)addMessageToHandleOnMainThread:(message_t *)message;
  70. @end
  71. /**
  72. * Provides a function for the main entry point for the dispatch thread. It dispatches any messages that is queued.
  73. * \param user_data Pointer to the VLCEventManager instance that instiated this thread.
  74. */
  75. static void * EventDispatcherMainLoop(void * user_data)
  76. {
  77. VLCEventManager * self = (__bridge VLCEventManager *)(user_data);
  78. for (;;) {
  79. message_t * message, * message_newer = NULL;
  80. /* Sleep a bit not to flood the interface */
  81. usleep(300);
  82. /* Wait for some data */
  83. pthread_mutex_lock([self queueLock]);
  84. /* Wait until we have something on the queue */
  85. while ([[self messageQueue] count] <= 0)
  86. pthread_cond_wait([self signalData], [self queueLock]);
  87. /* Get the first object off the queue. */
  88. message = [[self messageQueue] lastObject]; // Released in 'call'
  89. [[self messageQueue] removeLastObject];
  90. /* Remove duplicate notifications (keep the newest one). */
  91. if (message.type == VLCNotification) {
  92. NSInteger last_match_msg = -1;
  93. for (NSInteger i = [[self messageQueue] count]-1; i >= 0; i--) {
  94. message_newer = [self messageQueue][i];
  95. if (message_newer.type == VLCNotification &&
  96. message_newer.target == message.target &&
  97. [message_newer.name isEqualToString:message.name]) {
  98. if (last_match_msg >= 0) {
  99. [[self messageQueue] removeObjectAtIndex:last_match_msg];
  100. }
  101. last_match_msg = i;
  102. }
  103. }
  104. if (last_match_msg >= 0) {
  105. // newer notification detected, ignore current one
  106. pthread_mutex_unlock([self queueLock]);
  107. continue;
  108. }
  109. } else if (message.type == VLCObjectMethodWithArrayArg) {
  110. NSMutableArray * newArg = nil;
  111. /* Collapse messages that takes array arg by sending one bigger array */
  112. for (NSInteger i = [[self messageQueue] count] - 1; i >= 0; i--) {
  113. message_newer = [self messageQueue][i];
  114. if (message_newer.type == VLCObjectMethodWithArrayArg &&
  115. message_newer.target == message.target &&
  116. message_newer.sel == message.sel) {
  117. if (!newArg) {
  118. newArg = [NSMutableArray arrayWithArray:message.object];
  119. }
  120. [newArg addObjectsFromArray:message_newer.object];
  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.object = newArg;
  132. }
  133. [self addMessageToHandleOnMainThread:message];
  134. pthread_mutex_unlock([self queueLock]);
  135. if (message.type == VLCNotification)
  136. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  137. withObject:message
  138. waitUntilDone: NO];
  139. else
  140. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  141. withObject:message
  142. waitUntilDone: YES];
  143. }
  144. return nil;
  145. }
  146. @implementation VLCEventManager
  147. + (id)sharedManager
  148. {
  149. static dispatch_once_t onceToken;
  150. static VLCEventManager *defaultManager = nil;
  151. dispatch_once(&onceToken, ^{
  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. if (![NSThread isMultiThreaded]) {
  164. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  165. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  166. }
  167. messageQueue = [NSMutableArray new];
  168. pendingMessagesOnMainThread = [NSMutableArray new];
  169. pendingMessagesLock = [[NSLock alloc] init];
  170. pthread_mutex_init(&queueLock, NULL);
  171. pthread_cond_init(&signalData, NULL);
  172. pthread_create(&dispatcherThread, NULL, EventDispatcherMainLoop, (__bridge void *)(self));
  173. }
  174. return self;
  175. }
  176. - (void)dealloc
  177. {
  178. pthread_kill(dispatcherThread, SIGKILL);
  179. pthread_join(dispatcherThread, NULL);
  180. }
  181. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  182. {
  183. /* Don't send on main thread before this gets sorted out */
  184. @autoreleasepool {
  185. message_t *message = [message_t new];
  186. message.sel = aSelector;
  187. message.target = aTarget;
  188. message.name = aNotificationName;
  189. message.type = VLCNotification;
  190. pthread_mutex_lock([self queueLock]);
  191. [[self messageQueue] insertObject:message atIndex:0];
  192. pthread_cond_signal([self signalData]);
  193. pthread_mutex_unlock([self queueLock]);
  194. }
  195. }
  196. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  197. {
  198. @autoreleasepool {
  199. message_t *message = [message_t new];
  200. message.sel = aSelector;
  201. message.target = aTarget;
  202. message.object = arg;
  203. message.type = [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg;
  204. pthread_mutex_lock([self queueLock]);
  205. [[self messageQueue] insertObject:message atIndex:0];
  206. pthread_cond_signal([self signalData]);
  207. pthread_mutex_unlock([self queueLock]);
  208. }
  209. }
  210. - (void)cancelCallToObject:(id)target
  211. {
  212. // Remove all queued message
  213. pthread_mutex_lock([self queueLock]);
  214. [pendingMessagesLock lock];
  215. NSMutableArray *queue = [self messageQueue];
  216. for (NSInteger i = [queue count] - 1; i >= 0; i--) {
  217. message_t *message = (message_t *)queue[i];
  218. if (message.target == target)
  219. [queue removeObjectAtIndex:i];
  220. }
  221. // Remove all pending messages
  222. NSMutableArray *messages = pendingMessagesOnMainThread;
  223. // need to interate in reverse since we are removing objects
  224. for (NSInteger i = [messages count] - 1; i >= 0; i--) {
  225. message_t *message = messages[i];
  226. if (message.target == target)
  227. [messages removeObjectAtIndex:i];
  228. }
  229. [pendingMessagesLock unlock];
  230. pthread_mutex_unlock([self queueLock]);
  231. }
  232. @end
  233. @implementation VLCEventManager (Private)
  234. - (void)addMessageToHandleOnMainThread:(message_t *)message
  235. {
  236. [pendingMessagesLock lock];
  237. [pendingMessagesOnMainThread addObject:message];
  238. [pendingMessagesLock unlock];
  239. }
  240. - (BOOL)markMessageHandledOnMainThreadIfExists:(message_t *)message
  241. {
  242. [pendingMessagesLock lock];
  243. BOOL cancelled = ![pendingMessagesOnMainThread containsObject:message];
  244. if (!cancelled) {
  245. [pendingMessagesOnMainThread removeObject:message];
  246. }
  247. [pendingMessagesLock unlock];
  248. return !cancelled;
  249. }
  250. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message
  251. {
  252. // Check that we were not cancelled, ie, target was released
  253. if ([self markMessageHandledOnMainThreadIfExists:message])
  254. [self callDelegateOfObject:message.target withDelegateMethod:message.sel withNotificationName:message.name];
  255. }
  256. - (void)callObjectMethodWithArgs:(message_t *)message
  257. {
  258. // Check that we were not cancelled
  259. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  260. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message.target methodForSelector: message.sel];
  261. method(message.target, message.sel, message.object);
  262. }
  263. }
  264. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  265. {
  266. [[NSNotificationCenter defaultCenter] postNotification: [NSNotification notificationWithName:aNotificationName object:aTarget]];
  267. id delegate = [aTarget delegate];
  268. if (!delegate || ![delegate respondsToSelector:aSelector])
  269. return;
  270. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[delegate methodForSelector: aSelector];
  271. method(delegate, aSelector, [NSNotification notificationWithName:aNotificationName object:aTarget]);
  272. }
  273. - (NSMutableArray *)messageQueue
  274. {
  275. return messageQueue;
  276. }
  277. - (NSMutableArray *)pendingMessagesOnMainThread
  278. {
  279. return pendingMessagesOnMainThread;
  280. }
  281. - (NSLock *)pendingMessagesLock
  282. {
  283. return pendingMessagesLock;
  284. }
  285. - (pthread_cond_t *)signalData
  286. {
  287. return &signalData;
  288. }
  289. - (pthread_mutex_t *)queueLock
  290. {
  291. return &queueLock;
  292. }
  293. @end