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.

421 lines
13KB

  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. static bool isEventBlockedByModalComps (NSEvent* e)
  216. {
  217. if (Component::getNumCurrentlyModalComponents() == 0)
  218. return false;
  219. [[NSApp mainMenu] update];
  220. NSWindow* const w = [e window];
  221. if (w == 0 || [w worksWhenModal])
  222. return false;
  223. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  224. {
  225. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  226. NSView* const compView = (NSView*) peer->getNativeHandle();
  227. if ([compView window] == w
  228. && (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  229. [compView bounds])
  230. || peer->getComponent()->isMouseButtonDown()))
  231. {
  232. return false;
  233. }
  234. }
  235. if ([e type] == NSLeftMouseDown
  236. || [e type] == NSRightMouseDown
  237. || [e type] == NSOtherMouseDown)
  238. {
  239. if (! [NSApp isActive])
  240. [NSApp activateIgnoringOtherApps: YES];
  241. Component* const modal = Component::getCurrentlyModalComponent (0);
  242. if (modal != 0)
  243. modal->inputAttemptWhenModal();
  244. }
  245. return true;
  246. }
  247. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  248. {
  249. const ScopedAutoReleasePool pool;
  250. jassert (isThisTheMessageThread()); // must only be called by the message thread
  251. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  252. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  253. while (Time::getMillisecondCounter() < endTime && ! quitMessagePosted)
  254. {
  255. const ScopedAutoReleasePool pool;
  256. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  257. beforeDate: endDate];
  258. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  259. untilDate: endDate
  260. inMode: NSDefaultRunLoopMode
  261. dequeue: YES];
  262. if (! isEventBlockedByModalComps (e))
  263. [NSApp sendEvent: e];
  264. }
  265. return ! quitMessagePosted;
  266. }
  267. //==============================================================================
  268. void MessageManager::doPlatformSpecificInitialisation()
  269. {
  270. if (juceAppDelegate == 0)
  271. juceAppDelegate = [[JuceAppDelegate alloc] init];
  272. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  273. // correctly (needed prior to 10.5)
  274. if (! [NSThread isMultiThreaded])
  275. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  276. toTarget: juceAppDelegate
  277. withObject: nil];
  278. initialiseMainMenu();
  279. }
  280. void MessageManager::doPlatformSpecificShutdown()
  281. {
  282. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  283. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  284. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  285. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  286. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  287. {
  288. flushingMessages = true;
  289. getInstance()->runDispatchLoopUntil (10);
  290. }
  291. [juceAppDelegate release];
  292. juceAppDelegate = 0;
  293. }
  294. bool juce_postMessageToSystemQueue (void* message)
  295. {
  296. atomicIncrement (numPendingMessages);
  297. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  298. withObject: (id) [[NSData alloc] initWithBytes: &message
  299. length: (int) sizeof (message)]
  300. waitUntilDone: NO];
  301. return true;
  302. }
  303. void MessageManager::broadcastMessage (const String& value) throw()
  304. {
  305. }
  306. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  307. void* data)
  308. {
  309. if (isThisTheMessageThread())
  310. {
  311. return (*callback) (data);
  312. }
  313. else
  314. {
  315. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  316. // deadlock because the message manager is blocked from running, so can never
  317. // call your function..
  318. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  319. const ScopedAutoReleasePool pool;
  320. CallbackMessagePayload cmp;
  321. cmp.function = callback;
  322. cmp.parameter = data;
  323. cmp.result = 0;
  324. cmp.hasBeenExecuted = false;
  325. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  326. withObject: [NSData dataWithBytesNoCopy: &cmp
  327. length: sizeof (cmp)
  328. freeWhenDone: NO]
  329. waitUntilDone: YES];
  330. return cmp.result;
  331. }
  332. }
  333. #endif