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.

462 lines
14KB

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