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.

325 lines
12KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 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. typedef void (*AppFocusChangeCallback)();
  19. AppFocusChangeCallback appFocusChangeCallback = nullptr;
  20. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  21. CheckEventBlockedByModalComps isEventBlockedByModalComps = nullptr;
  22. typedef void (*MenuTrackingBeganCallback)();
  23. MenuTrackingBeganCallback menuTrackingBeganCallback = nullptr;
  24. //==============================================================================
  25. struct AppDelegate
  26. {
  27. public:
  28. AppDelegate()
  29. {
  30. static AppDelegateClass cls;
  31. delegate = [cls.createInstance() init];
  32. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  33. [center addObserver: delegate selector: @selector (mainMenuTrackingBegan:)
  34. name: NSMenuDidBeginTrackingNotification object: nil];
  35. if (JUCEApplicationBase::isStandaloneApp())
  36. {
  37. [NSApp setDelegate: delegate];
  38. [[NSDistributedNotificationCenter defaultCenter] addObserver: delegate
  39. selector: @selector (broadcastMessageCallback:)
  40. name: getBroacastEventName()
  41. object: nil];
  42. }
  43. else
  44. {
  45. [center addObserver: delegate selector: @selector (applicationDidResignActive:)
  46. name: NSApplicationDidResignActiveNotification object: NSApp];
  47. [center addObserver: delegate selector: @selector (applicationDidBecomeActive:)
  48. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  49. [center addObserver: delegate selector: @selector (applicationWillUnhide:)
  50. name: NSApplicationWillUnhideNotification object: NSApp];
  51. }
  52. }
  53. ~AppDelegate()
  54. {
  55. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: delegate];
  56. [[NSNotificationCenter defaultCenter] removeObserver: delegate];
  57. if (JUCEApplicationBase::isStandaloneApp())
  58. {
  59. [NSApp setDelegate: nil];
  60. [[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate
  61. name: getBroacastEventName()
  62. object: nil];
  63. }
  64. [delegate release];
  65. }
  66. static NSString* getBroacastEventName()
  67. {
  68. return juceStringToNS ("juce_" + String::toHexString (File::getSpecialLocation (File::currentExecutableFile).hashCode64()));
  69. }
  70. MessageQueue messageQueue;
  71. id delegate;
  72. private:
  73. CFRunLoopRef runLoop;
  74. CFRunLoopSourceRef runLoopSource;
  75. //==============================================================================
  76. struct AppDelegateClass : public ObjCClass <NSObject>
  77. {
  78. AppDelegateClass() : ObjCClass <NSObject> ("JUCEAppDelegate_")
  79. {
  80. addMethod (@selector (applicationShouldTerminate:), applicationShouldTerminate, "I@:@");
  81. addMethod (@selector (applicationWillTerminate:), applicationWillTerminate, "v@:@");
  82. addMethod (@selector (application:openFile:), application_openFile, "c@:@@");
  83. addMethod (@selector (application:openFiles:), application_openFiles, "v@:@@");
  84. addMethod (@selector (applicationDidBecomeActive:), applicationDidBecomeActive, "v@:@");
  85. addMethod (@selector (applicationDidResignActive:), applicationDidResignActive, "v@:@");
  86. addMethod (@selector (applicationWillUnhide:), applicationWillUnhide, "v@:@");
  87. addMethod (@selector (broadcastMessageCallback:), broadcastMessageCallback, "v@:@");
  88. addMethod (@selector (mainMenuTrackingBegan:), mainMenuTrackingBegan, "v@:@");
  89. addMethod (@selector (dummyMethod), dummyMethod, "v@:");
  90. registerClass();
  91. }
  92. private:
  93. static NSApplicationTerminateReply applicationShouldTerminate (id /*self*/, SEL, NSApplication*)
  94. {
  95. JUCEApplicationBase* const app = JUCEApplicationBase::getInstance();
  96. if (app != nullptr)
  97. {
  98. app->systemRequestedQuit();
  99. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  100. return NSTerminateCancel;
  101. }
  102. return NSTerminateNow;
  103. }
  104. static void applicationWillTerminate (id /*self*/, SEL, NSNotification*)
  105. {
  106. JUCEApplicationBase::appWillTerminateByForce();
  107. }
  108. static BOOL application_openFile (id /*self*/, SEL, NSApplication*, NSString* filename)
  109. {
  110. JUCEApplicationBase* const app = JUCEApplicationBase::getInstance();
  111. if (app != nullptr)
  112. {
  113. app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  114. return YES;
  115. }
  116. return NO;
  117. }
  118. static void application_openFiles (id /*self*/, SEL, NSApplication*, NSArray* filenames)
  119. {
  120. JUCEApplicationBase* const app = JUCEApplicationBase::getInstance();
  121. if (app != nullptr)
  122. {
  123. StringArray files;
  124. for (unsigned int i = 0; i < [filenames count]; ++i)
  125. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  126. if (files.size() > 0)
  127. app->anotherInstanceStarted (files.joinIntoString (" "));
  128. }
  129. }
  130. static void applicationDidBecomeActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  131. static void applicationDidResignActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  132. static void applicationWillUnhide (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  133. static void broadcastMessageCallback (id /*self*/, SEL, NSNotification* n)
  134. {
  135. NSDictionary* dict = (NSDictionary*) [n userInfo];
  136. const String messageString (nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]));
  137. MessageManager::getInstance()->deliverBroadcastMessage (messageString);
  138. }
  139. static void mainMenuTrackingBegan (id /*self*/, SEL, NSNotification*)
  140. {
  141. if (menuTrackingBeganCallback != nullptr)
  142. (*menuTrackingBeganCallback)();
  143. }
  144. static void dummyMethod (id /*self*/, SEL) {} // (used as a way of running a dummy thread)
  145. private:
  146. static void focusChanged()
  147. {
  148. if (appFocusChangeCallback != nullptr)
  149. (*appFocusChangeCallback)();
  150. }
  151. static String quotedIfContainsSpaces (NSString* file)
  152. {
  153. String s (nsStringToJuce (file));
  154. if (s.containsChar (' '))
  155. s = s.quoted ('"');
  156. return s;
  157. }
  158. };
  159. };
  160. //==============================================================================
  161. void MessageManager::runDispatchLoop()
  162. {
  163. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  164. {
  165. JUCE_AUTORELEASEPOOL
  166. // must only be called by the message thread!
  167. jassert (isThisTheMessageThread());
  168. #if JUCE_PROJUCER_LIVE_BUILD
  169. runDispatchLoopUntil (std::numeric_limits<int>::max());
  170. #else
  171. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  172. @try
  173. {
  174. [NSApp run];
  175. }
  176. @catch (NSException* e)
  177. {
  178. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  179. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  180. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  181. }
  182. @finally
  183. {
  184. }
  185. #else
  186. [NSApp run];
  187. #endif
  188. #endif
  189. }
  190. }
  191. void MessageManager::stopDispatchLoop()
  192. {
  193. quitMessagePosted = true;
  194. #if ! JUCE_PROJUCER_LIVE_BUILD
  195. [NSApp stop: nil];
  196. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  197. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  198. #endif
  199. }
  200. #if JUCE_MODAL_LOOPS_PERMITTED
  201. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  202. {
  203. jassert (millisecondsToRunFor >= 0);
  204. jassert (isThisTheMessageThread()); // must only be called by the message thread
  205. uint32 endTime = Time::getMillisecondCounter() + (uint32) millisecondsToRunFor;
  206. while (! quitMessagePosted)
  207. {
  208. JUCE_AUTORELEASEPOOL
  209. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  210. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  211. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  212. inMode: NSDefaultRunLoopMode
  213. dequeue: YES];
  214. if (e != nil && (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e)))
  215. [NSApp sendEvent: e];
  216. if (Time::getMillisecondCounter() >= endTime)
  217. break;
  218. }
  219. return ! quitMessagePosted;
  220. }
  221. #endif
  222. //==============================================================================
  223. void initialiseNSApplication();
  224. void initialiseNSApplication()
  225. {
  226. JUCE_AUTORELEASEPOOL
  227. [NSApplication sharedApplication];
  228. }
  229. static AppDelegate* appDelegate = nullptr;
  230. void MessageManager::doPlatformSpecificInitialisation()
  231. {
  232. if (appDelegate == nil)
  233. appDelegate = new AppDelegate();
  234. #if ! (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  235. // This launches a dummy thread, which forces Cocoa to initialise NSThreads correctly (needed prior to 10.5)
  236. if (! [NSThread isMultiThreaded])
  237. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  238. toTarget: appDelegate->delegate
  239. withObject: nil];
  240. #endif
  241. }
  242. void MessageManager::doPlatformSpecificShutdown()
  243. {
  244. delete appDelegate;
  245. appDelegate = nullptr;
  246. }
  247. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  248. {
  249. jassert (appDelegate != nil);
  250. appDelegate->messageQueue.post (message);
  251. return true;
  252. }
  253. void MessageManager::broadcastMessage (const String& message)
  254. {
  255. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  256. forKey: nsStringLiteral ("message")];
  257. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroacastEventName()
  258. object: nil
  259. userInfo: info];
  260. }