VLCEventManager.m 13 KB

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