VLCEventManager.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 ()
  61. {
  62. NSMutableArray *_messageQueue; //< Holds a queue of messages.
  63. NSMutableArray *_pendingMessagesOnMainThread; //< Holds the message that are being posted on main thread.
  64. NSLock *_pendingMessagesLock;
  65. pthread_t _dispatcherThread; //< Thread responsible for dispatching messages.
  66. pthread_mutex_t _queueLock; //< Queue lock.
  67. pthread_cond_t _signalData; //< Data lock.
  68. }
  69. - (void)startEventLoop;
  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. [self startEventLoop];
  79. return NULL;
  80. }
  81. @implementation VLCEventManager
  82. + (id)sharedManager
  83. {
  84. static dispatch_once_t onceToken;
  85. static VLCEventManager *defaultManager = nil;
  86. dispatch_once(&onceToken, ^{
  87. defaultManager = [[VLCEventManager alloc] init];
  88. });
  89. return defaultManager;
  90. }
  91. - (void)dummy
  92. {
  93. /* Put Cocoa in multithreaded mode by calling a dummy function */
  94. }
  95. - (id)init
  96. {
  97. if (self = [super init]) {
  98. if (![NSThread isMultiThreaded]) {
  99. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  100. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  101. }
  102. _messageQueue = [NSMutableArray new];
  103. _pendingMessagesOnMainThread = [NSMutableArray new];
  104. _pendingMessagesLock = [[NSLock alloc] init];
  105. pthread_mutex_init(&_queueLock, NULL);
  106. pthread_cond_init(&_signalData, NULL);
  107. pthread_create(&_dispatcherThread, NULL, EventDispatcherMainLoop, (__bridge void *)(self));
  108. }
  109. return self;
  110. }
  111. - (void)dealloc
  112. {
  113. pthread_kill(_dispatcherThread, SIGKILL);
  114. pthread_join(_dispatcherThread, NULL);
  115. }
  116. #pragma mark -
  117. - (void)startEventLoop {
  118. for (;;) {
  119. @autoreleasepool {
  120. message_t * message, * message_newer = NULL;
  121. /* Sleep a bit not to flood the interface */
  122. usleep(300);
  123. /* Wait for some data */
  124. pthread_mutex_lock([self queueLock]);
  125. /* Wait until we have something on the queue */
  126. while (_messageQueue.count <= 0)
  127. pthread_cond_wait([self signalData], [self queueLock]);
  128. /* Get the first object off the queue. */
  129. message = [_messageQueue lastObject]; // Released in 'call'
  130. [_messageQueue removeLastObject];
  131. /* Remove duplicate notifications (keep the newest one). */
  132. if (message.type == VLCNotification) {
  133. NSInteger last_match_msg = -1;
  134. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  135. message_newer = _messageQueue[i];
  136. if (message_newer.type == VLCNotification &&
  137. message_newer.target == message.target &&
  138. [message_newer.name isEqualToString:message.name]) {
  139. if (last_match_msg >= 0) {
  140. [_messageQueue removeObjectAtIndex:last_match_msg];
  141. }
  142. last_match_msg = i;
  143. }
  144. }
  145. if (last_match_msg >= 0) {
  146. // newer notification detected, ignore current one
  147. pthread_mutex_unlock([self queueLock]);
  148. continue;
  149. }
  150. } else if (message.type == VLCObjectMethodWithArrayArg) {
  151. NSMutableArray * newArg = nil;
  152. /* Collapse messages that takes array arg by sending one bigger array */
  153. for (NSInteger i = [_messageQueue count] - 1; i >= 0; i--) {
  154. message_newer = _messageQueue[i];
  155. if (message_newer.type == VLCObjectMethodWithArrayArg &&
  156. message_newer.target == message.target &&
  157. message_newer.sel == message.sel) {
  158. if (!newArg) {
  159. newArg = [NSMutableArray arrayWithArray:message.object];
  160. }
  161. [newArg addObjectsFromArray:message_newer.object];
  162. [_messageQueue removeObjectAtIndex:i];
  163. }
  164. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  165. * This could be particulary problematic when the same object receive two related events
  166. * (for instance Added and Removed).
  167. * Ignore for now only if target is the same */
  168. else if (message_newer.target == message.target)
  169. break;
  170. }
  171. if (newArg)
  172. message.object = newArg;
  173. }
  174. [self addMessageToHandleOnMainThread:message];
  175. pthread_mutex_unlock([self queueLock]);
  176. if (message.type == VLCNotification)
  177. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  178. withObject:message
  179. waitUntilDone: NO];
  180. else
  181. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  182. withObject:message
  183. waitUntilDone: YES];
  184. }
  185. }
  186. }
  187. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  188. {
  189. /* Don't send on main thread before this gets sorted out */
  190. @autoreleasepool {
  191. message_t *message = [message_t new];
  192. message.sel = aSelector;
  193. message.target = aTarget;
  194. message.name = aNotificationName;
  195. message.type = VLCNotification;
  196. pthread_mutex_lock([self queueLock]);
  197. [_messageQueue insertObject:message atIndex:0];
  198. pthread_cond_signal([self signalData]);
  199. pthread_mutex_unlock([self queueLock]);
  200. }
  201. }
  202. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  203. {
  204. @autoreleasepool {
  205. message_t *message = [message_t new];
  206. message.sel = aSelector;
  207. message.target = aTarget;
  208. message.object = arg;
  209. message.type = [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg;
  210. pthread_mutex_lock([self queueLock]);
  211. [_messageQueue insertObject:message atIndex:0];
  212. pthread_cond_signal([self signalData]);
  213. pthread_mutex_unlock([self queueLock]);
  214. }
  215. }
  216. - (void)cancelCallToObject:(id)target
  217. {
  218. // Remove all queued message
  219. pthread_mutex_lock([self queueLock]);
  220. [_pendingMessagesLock lock];
  221. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  222. message_t *message = _messageQueue[i];
  223. if (message.target == target)
  224. [_messageQueue removeObjectAtIndex:i];
  225. }
  226. // Remove all pending messages
  227. NSMutableArray *messages = _pendingMessagesOnMainThread;
  228. // need to interate in reverse since we are removing objects
  229. for (NSInteger i = [messages count] - 1; i >= 0; i--) {
  230. message_t *message = messages[i];
  231. if (message.target == target)
  232. [messages removeObjectAtIndex:i];
  233. }
  234. [_pendingMessagesLock unlock];
  235. pthread_mutex_unlock([self queueLock]);
  236. }
  237. - (void)addMessageToHandleOnMainThread:(message_t *)message
  238. {
  239. [_pendingMessagesLock lock];
  240. [_pendingMessagesOnMainThread addObject:message];
  241. [_pendingMessagesLock unlock];
  242. }
  243. - (BOOL)markMessageHandledOnMainThreadIfExists:(message_t *)message
  244. {
  245. [_pendingMessagesLock lock];
  246. BOOL cancelled = ![_pendingMessagesOnMainThread containsObject:message];
  247. if (!cancelled) {
  248. [_pendingMessagesOnMainThread removeObject:message];
  249. }
  250. [_pendingMessagesLock unlock];
  251. return !cancelled;
  252. }
  253. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message
  254. {
  255. // Check that we were not cancelled, ie, target was released
  256. if ([self markMessageHandledOnMainThreadIfExists:message])
  257. [self callDelegateOfObject:message.target withDelegateMethod:message.sel withNotificationName:message.name];
  258. }
  259. - (void)callObjectMethodWithArgs:(message_t *)message
  260. {
  261. // Check that we were not cancelled
  262. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  263. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message.target methodForSelector: message.sel];
  264. method(message.target, message.sel, message.object);
  265. }
  266. }
  267. - (void)callDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  268. {
  269. [[NSNotificationCenter defaultCenter] postNotification: [NSNotification notificationWithName:aNotificationName object:aTarget]];
  270. id delegate = [aTarget delegate];
  271. if (!delegate || ![delegate respondsToSelector:aSelector])
  272. return;
  273. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[delegate methodForSelector: aSelector];
  274. method(delegate, aSelector, [NSNotification notificationWithName:aNotificationName object:aTarget]);
  275. }
  276. - (pthread_cond_t *)signalData
  277. {
  278. return &_signalData;
  279. }
  280. - (pthread_mutex_t *)queueLock
  281. {
  282. return &_queueLock;
  283. }
  284. @end