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.

370 lines
11KB

  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. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  53. return NSTerminateCancel;
  54. }
  55. return NSTerminateNow;
  56. }
  57. virtual BOOL openFile (const NSString* filename)
  58. {
  59. if (JUCEApplication::getInstance() != 0)
  60. {
  61. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  62. return YES;
  63. }
  64. return NO;
  65. }
  66. virtual void openFiles (NSArray* filenames)
  67. {
  68. StringArray files;
  69. for (unsigned int i = 0; i < [filenames count]; ++i)
  70. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  71. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  72. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  73. }
  74. virtual void focusChanged()
  75. {
  76. juce_HandleProcessFocusChange();
  77. }
  78. virtual void deliverMessage (void* message)
  79. {
  80. MessageManager::getInstance()->deliverMessage (message);
  81. }
  82. virtual void deleteSelf()
  83. {
  84. delete this;
  85. }
  86. };
  87. END_JUCE_NAMESPACE
  88. using namespace JUCE_NAMESPACE;
  89. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  90. static int numPendingMessages = 0;
  91. static bool flushingMessages = false;
  92. @interface JuceAppDelegate : NSObject
  93. {
  94. @private
  95. id oldDelegate;
  96. AppDelegateRedirector* redirector;
  97. }
  98. - (JuceAppDelegate*) init;
  99. - (void) dealloc;
  100. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  101. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  102. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  103. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  104. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  105. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  106. - (void) customEvent: (id) data;
  107. - (void) performCallback: (id) info;
  108. - (void) dummyMethod;
  109. @end
  110. @implementation JuceAppDelegate
  111. - (JuceAppDelegate*) init
  112. {
  113. [super init];
  114. redirector = new AppDelegateRedirector();
  115. numPendingMessages = 0;
  116. flushingMessages = false;
  117. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  118. if (JUCEApplication::getInstance() != 0)
  119. {
  120. oldDelegate = [NSApp delegate];
  121. [NSApp setDelegate: self];
  122. }
  123. else
  124. {
  125. oldDelegate = 0;
  126. [center addObserver: self selector: @selector (applicationDidResignActive:)
  127. name: NSApplicationDidResignActiveNotification object: NSApp];
  128. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  129. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  130. [center addObserver: self selector: @selector (applicationWillUnhide:)
  131. name: NSApplicationWillUnhideNotification object: NSApp];
  132. }
  133. return self;
  134. }
  135. - (void) dealloc
  136. {
  137. if (oldDelegate != 0)
  138. [NSApp setDelegate: oldDelegate];
  139. redirector->deleteSelf();
  140. [super dealloc];
  141. }
  142. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  143. {
  144. return redirector->shouldTerminate();
  145. }
  146. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  147. {
  148. return redirector->openFile (filename);
  149. }
  150. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  151. {
  152. return redirector->openFiles (filenames);
  153. }
  154. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  155. {
  156. redirector->focusChanged();
  157. }
  158. - (void) applicationDidResignActive: (NSNotification*) aNotification
  159. {
  160. redirector->focusChanged();
  161. }
  162. - (void) applicationWillUnhide: (NSNotification*) aNotification
  163. {
  164. redirector->focusChanged();
  165. }
  166. - (void) customEvent: (id) n
  167. {
  168. atomicDecrement (numPendingMessages);
  169. NSData* data = (NSData*) n;
  170. void* message = 0;
  171. [data getBytes: &message length: sizeof (message)];
  172. if (message != 0 && ! flushingMessages)
  173. redirector->deliverMessage (message);
  174. [data release];
  175. }
  176. - (void) performCallback: (id) info
  177. {
  178. if ([info isKindOfClass: [NSData class]])
  179. {
  180. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  181. if (pl != 0)
  182. {
  183. pl->result = (*pl->function) (pl->parameter);
  184. pl->hasBeenExecuted = true;
  185. }
  186. }
  187. else
  188. {
  189. jassertfalse // should never get here!
  190. }
  191. }
  192. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  193. @end
  194. BEGIN_JUCE_NAMESPACE
  195. static JuceAppDelegate* juceAppDelegate = 0;
  196. void MessageManager::runDispatchLoop()
  197. {
  198. const ScopedAutoReleasePool pool;
  199. MessageManagerLock mml;
  200. // must only be called by the message thread!
  201. jassert (isThisTheMessageThread());
  202. [NSApp run];
  203. }
  204. void MessageManager::stopDispatchLoop()
  205. {
  206. quitMessagePosted = true;
  207. [NSApp stop: nil];
  208. }
  209. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  210. {
  211. const ScopedAutoReleasePool pool;
  212. jassert (isThisTheMessageThread()); // must only be called by the message thread
  213. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  214. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  215. while (Time::getMillisecondCounter() < endTime)
  216. {
  217. const ScopedAutoReleasePool pool;
  218. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  219. beforeDate: endDate];
  220. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  221. untilDate: endDate
  222. inMode: NSDefaultRunLoopMode
  223. dequeue: YES];
  224. [NSApp sendEvent: e];
  225. }
  226. return ! quitMessagePosted;
  227. }
  228. //==============================================================================
  229. void MessageManager::doPlatformSpecificInitialisation()
  230. {
  231. if (juceAppDelegate == 0)
  232. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234. // correctly (needed prior to 10.5)
  235. if (! [NSThread isMultiThreaded])
  236. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  237. toTarget: juceAppDelegate
  238. withObject: nil];
  239. initialiseMainMenu();
  240. }
  241. void MessageManager::doPlatformSpecificShutdown()
  242. {
  243. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  244. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  245. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  246. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  247. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  248. {
  249. flushingMessages = true;
  250. getInstance()->runDispatchLoopUntil (10);
  251. }
  252. jassert (numPendingMessages == 0); // failed to get all the pending messages cleared before quitting..
  253. [juceAppDelegate release];
  254. juceAppDelegate = 0;
  255. }
  256. bool juce_postMessageToSystemQueue (void* message)
  257. {
  258. atomicIncrement (numPendingMessages);
  259. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  260. withObject: (id) [[NSData alloc] initWithBytes: &message
  261. length: (int) sizeof (message)]
  262. waitUntilDone: NO];
  263. return true;
  264. }
  265. void MessageManager::broadcastMessage (const String& value) throw()
  266. {
  267. }
  268. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  269. void* data)
  270. {
  271. if (isThisTheMessageThread())
  272. {
  273. return (*callback) (data);
  274. }
  275. else
  276. {
  277. const ScopedAutoReleasePool pool;
  278. CallbackMessagePayload cmp;
  279. cmp.function = callback;
  280. cmp.parameter = data;
  281. cmp.result = 0;
  282. cmp.hasBeenExecuted = false;
  283. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  284. withObject: [NSData dataWithBytesNoCopy: &cmp
  285. length: sizeof (cmp)]
  286. waitUntilDone: YES];
  287. return cmp.result;
  288. }
  289. }
  290. #endif