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.

379 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. const ScopedAutoReleasePool pool;
  203. // must only be called by the message thread!
  204. jassert (isThisTheMessageThread());
  205. [NSApp run];
  206. }
  207. void MessageManager::stopDispatchLoop()
  208. {
  209. quitMessagePosted = true;
  210. [NSApp stop: nil];
  211. }
  212. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  213. {
  214. const ScopedAutoReleasePool pool;
  215. jassert (isThisTheMessageThread()); // must only be called by the message thread
  216. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  217. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  218. while (Time::getMillisecondCounter() < endTime)
  219. {
  220. const ScopedAutoReleasePool pool;
  221. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  222. beforeDate: endDate];
  223. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  224. untilDate: endDate
  225. inMode: NSDefaultRunLoopMode
  226. dequeue: YES];
  227. [NSApp sendEvent: e];
  228. }
  229. return ! quitMessagePosted;
  230. }
  231. //==============================================================================
  232. void MessageManager::doPlatformSpecificInitialisation()
  233. {
  234. if (juceAppDelegate == 0)
  235. juceAppDelegate = [[JuceAppDelegate alloc] init];
  236. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  237. // correctly (needed prior to 10.5)
  238. if (! [NSThread isMultiThreaded])
  239. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  240. toTarget: juceAppDelegate
  241. withObject: nil];
  242. initialiseMainMenu();
  243. }
  244. void MessageManager::doPlatformSpecificShutdown()
  245. {
  246. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  247. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  248. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  249. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  250. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  251. {
  252. flushingMessages = true;
  253. getInstance()->runDispatchLoopUntil (10);
  254. }
  255. jassert (numPendingMessages == 0); // failed to get all the pending messages cleared before quitting..
  256. [juceAppDelegate release];
  257. juceAppDelegate = 0;
  258. }
  259. bool juce_postMessageToSystemQueue (void* message)
  260. {
  261. atomicIncrement (numPendingMessages);
  262. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  263. withObject: (id) [[NSData alloc] initWithBytes: &message
  264. length: (int) sizeof (message)]
  265. waitUntilDone: NO];
  266. return true;
  267. }
  268. void MessageManager::broadcastMessage (const String& value) throw()
  269. {
  270. }
  271. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  272. void* data)
  273. {
  274. if (isThisTheMessageThread())
  275. {
  276. return (*callback) (data);
  277. }
  278. else
  279. {
  280. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  281. // deadlock because the message manager is blocked from running, so can never
  282. // call your function..
  283. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  284. const ScopedAutoReleasePool pool;
  285. CallbackMessagePayload cmp;
  286. cmp.function = callback;
  287. cmp.parameter = data;
  288. cmp.result = 0;
  289. cmp.hasBeenExecuted = false;
  290. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  291. withObject: [NSData dataWithBytesNoCopy: &cmp
  292. length: sizeof (cmp)
  293. freeWhenDone: NO]
  294. waitUntilDone: YES];
  295. return cmp.result;
  296. }
  297. }
  298. #endif