The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

382 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  24. // compiled on its own).
  25. #ifdef JUCE_INCLUDED_FILE
  26. struct CallbackMessagePayload
  27. {
  28. MessageCallbackFunction* function;
  29. void* parameter;
  30. void* volatile result;
  31. bool volatile hasBeenExecuted;
  32. };
  33. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  34. for example having more than one juce plugin loaded into a host, then when a
  35. method is called, the actual code that runs might actually be in a different module
  36. than the one you expect... So any calls to library functions or statics that are
  37. made inside obj-c methods will probably end up getting executed in a different DLL's
  38. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  39. To work around this insanity, I'm only allowing obj-c methods to make calls to
  40. virtual methods of an object that's known to live inside the right module's space.
  41. */
  42. class AppDelegateRedirector
  43. {
  44. public:
  45. AppDelegateRedirector() {}
  46. virtual ~AppDelegateRedirector() {}
  47. virtual NSApplicationTerminateReply shouldTerminate()
  48. {
  49. if (JUCEApplication::getInstance() != 0)
  50. {
  51. JUCEApplication::getInstance()->systemRequestedQuit();
  52. return NSTerminateCancel;
  53. }
  54. return NSTerminateNow;
  55. }
  56. virtual BOOL openFile (const NSString* filename)
  57. {
  58. if (JUCEApplication::getInstance() != 0)
  59. {
  60. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  61. return YES;
  62. }
  63. return NO;
  64. }
  65. virtual void openFiles (NSArray* filenames)
  66. {
  67. StringArray files;
  68. for (unsigned int i = 0; i < [filenames count]; ++i)
  69. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  70. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  71. {
  72. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  73. }
  74. }
  75. virtual void focusChanged()
  76. {
  77. juce_HandleProcessFocusChange();
  78. }
  79. virtual void deliverMessage (void* message)
  80. {
  81. // no need for an mm lock here - deliverMessage locks it
  82. MessageManager::getInstance()->deliverMessage (message);
  83. }
  84. virtual void performCallback (CallbackMessagePayload* pl)
  85. {
  86. pl->result = (*pl->function) (pl->parameter);
  87. pl->hasBeenExecuted = true;
  88. }
  89. virtual void deleteSelf()
  90. {
  91. delete this;
  92. }
  93. };
  94. END_JUCE_NAMESPACE
  95. using namespace JUCE_NAMESPACE;
  96. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  97. static int numPendingMessages = 0;
  98. static bool flushingMessages = false;
  99. @interface JuceAppDelegate : NSObject
  100. {
  101. @private
  102. id oldDelegate;
  103. AppDelegateRedirector* redirector;
  104. }
  105. - (JuceAppDelegate*) init;
  106. - (void) dealloc;
  107. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  108. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  109. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  110. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  111. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  112. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  113. - (void) customEvent: (id) data;
  114. - (void) performCallback: (id) info;
  115. - (void) dummyMethod;
  116. @end
  117. @implementation JuceAppDelegate
  118. - (JuceAppDelegate*) init
  119. {
  120. [super init];
  121. redirector = new AppDelegateRedirector();
  122. numPendingMessages = 0;
  123. flushingMessages = false;
  124. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  125. if (JUCEApplication::getInstance() != 0)
  126. {
  127. oldDelegate = [NSApp delegate];
  128. [NSApp setDelegate: self];
  129. }
  130. else
  131. {
  132. oldDelegate = 0;
  133. [center addObserver: self selector: @selector (applicationDidResignActive:)
  134. name: NSApplicationDidResignActiveNotification object: NSApp];
  135. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  136. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  137. [center addObserver: self selector: @selector (applicationWillUnhide:)
  138. name: NSApplicationWillUnhideNotification object: NSApp];
  139. }
  140. return self;
  141. }
  142. - (void) dealloc
  143. {
  144. if (oldDelegate != 0)
  145. [NSApp setDelegate: oldDelegate];
  146. redirector->deleteSelf();
  147. [super dealloc];
  148. }
  149. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  150. {
  151. return redirector->shouldTerminate();
  152. }
  153. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  154. {
  155. return redirector->openFile (filename);
  156. }
  157. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  158. {
  159. return redirector->openFiles (filenames);
  160. }
  161. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  162. {
  163. redirector->focusChanged();
  164. }
  165. - (void) applicationDidResignActive: (NSNotification*) aNotification
  166. {
  167. redirector->focusChanged();
  168. }
  169. - (void) applicationWillUnhide: (NSNotification*) aNotification
  170. {
  171. redirector->focusChanged();
  172. }
  173. - (void) customEvent: (id) n
  174. {
  175. atomicDecrement (numPendingMessages);
  176. NSData* data = (NSData*) n;
  177. void* message = 0;
  178. [data getBytes: &message length: sizeof (message)];
  179. if (message != 0 && ! flushingMessages)
  180. redirector->deliverMessage (message);
  181. [data release];
  182. }
  183. - (void) performCallback: (id) info
  184. {
  185. if ([info isKindOfClass: [NSData class]])
  186. {
  187. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  188. if (pl != 0)
  189. redirector->performCallback (pl);
  190. }
  191. else
  192. {
  193. jassertfalse // should never get here!
  194. }
  195. }
  196. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  197. @end
  198. BEGIN_JUCE_NAMESPACE
  199. static JuceAppDelegate* juceAppDelegate = 0;
  200. void MessageManager::runDispatchLoop()
  201. {
  202. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  203. {
  204. const ScopedAutoReleasePool pool;
  205. // must only be called by the message thread!
  206. jassert (isThisTheMessageThread());
  207. [NSApp run];
  208. }
  209. }
  210. void MessageManager::stopDispatchLoop()
  211. {
  212. quitMessagePosted = true;
  213. [NSApp stop: nil];
  214. }
  215. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  216. {
  217. const ScopedAutoReleasePool pool;
  218. jassert (isThisTheMessageThread()); // must only be called by the message thread
  219. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  220. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  221. while (Time::getMillisecondCounter() < endTime)
  222. {
  223. const ScopedAutoReleasePool pool;
  224. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  225. beforeDate: endDate];
  226. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  227. untilDate: endDate
  228. inMode: NSDefaultRunLoopMode
  229. dequeue: YES];
  230. [NSApp sendEvent: e];
  231. }
  232. return ! quitMessagePosted;
  233. }
  234. //==============================================================================
  235. void MessageManager::doPlatformSpecificInitialisation()
  236. {
  237. if (juceAppDelegate == 0)
  238. juceAppDelegate = [[JuceAppDelegate alloc] init];
  239. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  240. // correctly (needed prior to 10.5)
  241. if (! [NSThread isMultiThreaded])
  242. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  243. toTarget: juceAppDelegate
  244. withObject: nil];
  245. initialiseMainMenu();
  246. }
  247. void MessageManager::doPlatformSpecificShutdown()
  248. {
  249. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  250. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  251. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  252. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  253. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  254. {
  255. flushingMessages = true;
  256. getInstance()->runDispatchLoopUntil (10);
  257. }
  258. jassert (numPendingMessages == 0); // failed to get all the pending messages cleared before quitting..
  259. [juceAppDelegate release];
  260. juceAppDelegate = 0;
  261. }
  262. bool juce_postMessageToSystemQueue (void* message)
  263. {
  264. atomicIncrement (numPendingMessages);
  265. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  266. withObject: (id) [[NSData alloc] initWithBytes: &message
  267. length: (int) sizeof (message)]
  268. waitUntilDone: NO];
  269. return true;
  270. }
  271. void MessageManager::broadcastMessage (const String& value) throw()
  272. {
  273. }
  274. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  275. void* data)
  276. {
  277. if (isThisTheMessageThread())
  278. {
  279. return (*callback) (data);
  280. }
  281. else
  282. {
  283. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  284. // deadlock because the message manager is blocked from running, so can never
  285. // call your function..
  286. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  287. const ScopedAutoReleasePool pool;
  288. CallbackMessagePayload cmp;
  289. cmp.function = callback;
  290. cmp.parameter = data;
  291. cmp.result = 0;
  292. cmp.hasBeenExecuted = false;
  293. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  294. withObject: [NSData dataWithBytesNoCopy: &cmp
  295. length: sizeof (cmp)
  296. freeWhenDone: NO]
  297. waitUntilDone: YES];
  298. return cmp.result;
  299. }
  300. }
  301. #endif