Audio plugin host https://kx.studio/carla
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.

juce_mac_MessageManager.mm 16KB

7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. typedef void (*AppFocusChangeCallback)();
  20. AppFocusChangeCallback appFocusChangeCallback = nullptr;
  21. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  22. CheckEventBlockedByModalComps isEventBlockedByModalComps = nullptr;
  23. typedef void (*MenuTrackingChangedCallback)(bool);
  24. MenuTrackingChangedCallback menuTrackingChangedCallback = nullptr;
  25. //==============================================================================
  26. struct AppDelegate
  27. {
  28. public:
  29. AppDelegate()
  30. {
  31. static AppDelegateClass cls;
  32. delegate = [cls.createInstance() init];
  33. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  34. [center addObserver: delegate selector: @selector (mainMenuTrackingBegan:)
  35. name: NSMenuDidBeginTrackingNotification object: nil];
  36. [center addObserver: delegate selector: @selector (mainMenuTrackingEnded:)
  37. name: NSMenuDidEndTrackingNotification object: nil];
  38. if (JUCEApplicationBase::isStandaloneApp())
  39. {
  40. [NSApp setDelegate: delegate];
  41. [[NSDistributedNotificationCenter defaultCenter] addObserver: delegate
  42. selector: @selector (broadcastMessageCallback:)
  43. name: getBroadcastEventName()
  44. object: nil
  45. suspensionBehavior: NSNotificationSuspensionBehaviorDeliverImmediately];
  46. }
  47. else
  48. {
  49. [center addObserver: delegate selector: @selector (applicationDidResignActive:)
  50. name: NSApplicationDidResignActiveNotification object: NSApp];
  51. [center addObserver: delegate selector: @selector (applicationDidBecomeActive:)
  52. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  53. [center addObserver: delegate selector: @selector (applicationWillUnhide:)
  54. name: NSApplicationWillUnhideNotification object: NSApp];
  55. }
  56. }
  57. ~AppDelegate()
  58. {
  59. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: delegate];
  60. [[NSNotificationCenter defaultCenter] removeObserver: delegate];
  61. if (JUCEApplicationBase::isStandaloneApp())
  62. {
  63. [NSApp setDelegate: nil];
  64. [[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate
  65. name: getBroadcastEventName()
  66. object: nil];
  67. }
  68. [delegate release];
  69. }
  70. static NSString* getBroadcastEventName()
  71. {
  72. return juceStringToNS ("juce_" + String::toHexString (File::getSpecialLocation (File::currentExecutableFile).hashCode64()));
  73. }
  74. MessageQueue messageQueue;
  75. id delegate;
  76. private:
  77. //==============================================================================
  78. struct AppDelegateClass : public ObjCClass<NSObject>
  79. {
  80. AppDelegateClass() : ObjCClass<NSObject> ("JUCEAppDelegate_")
  81. {
  82. addMethod (@selector (applicationWillFinishLaunching:), applicationWillFinishLaunching, "v@:@@");
  83. addMethod (@selector (getUrl:withReplyEvent:), getUrl_withReplyEvent, "v@:@@");
  84. addMethod (@selector (applicationShouldTerminate:), applicationShouldTerminate, "I@:@");
  85. addMethod (@selector (applicationWillTerminate:), applicationWillTerminate, "v@:@");
  86. addMethod (@selector (application:openFile:), application_openFile, "c@:@@");
  87. addMethod (@selector (application:openFiles:), application_openFiles, "v@:@@");
  88. addMethod (@selector (applicationDidBecomeActive:), applicationDidBecomeActive, "v@:@");
  89. addMethod (@selector (applicationDidResignActive:), applicationDidResignActive, "v@:@");
  90. addMethod (@selector (applicationWillUnhide:), applicationWillUnhide, "v@:@");
  91. addMethod (@selector (broadcastMessageCallback:), broadcastMessageCallback, "v@:@");
  92. addMethod (@selector (mainMenuTrackingBegan:), mainMenuTrackingBegan, "v@:@");
  93. addMethod (@selector (mainMenuTrackingEnded:), mainMenuTrackingEnded, "v@:@");
  94. addMethod (@selector (dummyMethod), dummyMethod, "v@:");
  95. registerClass();
  96. }
  97. private:
  98. static void applicationWillFinishLaunching (id self, SEL, NSApplication*, NSNotification*)
  99. {
  100. [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
  101. andSelector: @selector (getUrl:withReplyEvent:)
  102. forEventClass: kInternetEventClass
  103. andEventID: kAEGetURL];
  104. }
  105. static NSApplicationTerminateReply applicationShouldTerminate (id /*self*/, SEL, NSApplication*)
  106. {
  107. if (auto* app = JUCEApplicationBase::getInstance())
  108. {
  109. app->systemRequestedQuit();
  110. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  111. return NSTerminateCancel;
  112. }
  113. return NSTerminateNow;
  114. }
  115. static void applicationWillTerminate (id /*self*/, SEL, NSNotification*)
  116. {
  117. JUCEApplicationBase::appWillTerminateByForce();
  118. }
  119. static BOOL application_openFile (id /*self*/, SEL, NSApplication*, NSString* filename)
  120. {
  121. if (auto* app = JUCEApplicationBase::getInstance())
  122. {
  123. app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  124. return YES;
  125. }
  126. return NO;
  127. }
  128. static void application_openFiles (id /*self*/, SEL, NSApplication*, NSArray* filenames)
  129. {
  130. if (auto* app = JUCEApplicationBase::getInstance())
  131. {
  132. StringArray files;
  133. for (NSString* f in filenames)
  134. files.add (quotedIfContainsSpaces (f));
  135. if (files.size() > 0)
  136. app->anotherInstanceStarted (files.joinIntoString (" "));
  137. }
  138. }
  139. static void applicationDidBecomeActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  140. static void applicationDidResignActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  141. static void applicationWillUnhide (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  142. static void broadcastMessageCallback (id /*self*/, SEL, NSNotification* n)
  143. {
  144. NSDictionary* dict = (NSDictionary*) [n userInfo];
  145. const String messageString (nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]));
  146. MessageManager::getInstance()->deliverBroadcastMessage (messageString);
  147. }
  148. static void mainMenuTrackingBegan (id /*self*/, SEL, NSNotification*)
  149. {
  150. if (menuTrackingChangedCallback != nullptr)
  151. (*menuTrackingChangedCallback) (true);
  152. }
  153. static void mainMenuTrackingEnded (id /*self*/, SEL, NSNotification*)
  154. {
  155. if (menuTrackingChangedCallback != nullptr)
  156. (*menuTrackingChangedCallback) (false);
  157. }
  158. static void dummyMethod (id /*self*/, SEL) {} // (used as a way of running a dummy thread)
  159. static void focusChanged()
  160. {
  161. if (appFocusChangeCallback != nullptr)
  162. (*appFocusChangeCallback)();
  163. }
  164. static void getUrl_withReplyEvent (id /*self*/, SEL, NSAppleEventDescriptor* event, NSAppleEventDescriptor*)
  165. {
  166. if (auto* app = JUCEApplicationBase::getInstance())
  167. app->anotherInstanceStarted (quotedIfContainsSpaces ([[event paramDescriptorForKeyword: keyDirectObject] stringValue]));
  168. }
  169. static String quotedIfContainsSpaces (NSString* file)
  170. {
  171. String s (nsStringToJuce (file));
  172. if (s.containsChar (' '))
  173. s = s.quoted ('"');
  174. return s;
  175. }
  176. };
  177. };
  178. //==============================================================================
  179. void MessageManager::runDispatchLoop()
  180. {
  181. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  182. {
  183. JUCE_AUTORELEASEPOOL
  184. {
  185. // must only be called by the message thread!
  186. jassert (isThisTheMessageThread());
  187. #if JUCE_PROJUCER_LIVE_BUILD
  188. runDispatchLoopUntil (std::numeric_limits<int>::max());
  189. #else
  190. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  191. @try
  192. {
  193. [NSApp run];
  194. }
  195. @catch (NSException* e)
  196. {
  197. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  198. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  199. JUCEApplicationBase::sendUnhandledException (&ex, __FILE__, __LINE__);
  200. }
  201. @finally
  202. {
  203. }
  204. #else
  205. [NSApp run];
  206. #endif
  207. #endif
  208. }
  209. }
  210. }
  211. static void shutdownNSApp()
  212. {
  213. [NSApp stop: nil];
  214. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  215. }
  216. void MessageManager::stopDispatchLoop()
  217. {
  218. #if JUCE_PROJUCER_LIVE_BUILD
  219. quitMessagePosted = true;
  220. #else
  221. if (isThisTheMessageThread())
  222. {
  223. quitMessagePosted = true;
  224. shutdownNSApp();
  225. }
  226. else
  227. {
  228. struct QuitCallback : public CallbackMessage
  229. {
  230. QuitCallback() {}
  231. void messageCallback() override { MessageManager::getInstance()->stopDispatchLoop(); }
  232. };
  233. (new QuitCallback())->post();
  234. }
  235. #endif
  236. }
  237. #if JUCE_MODAL_LOOPS_PERMITTED
  238. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  239. {
  240. jassert (millisecondsToRunFor >= 0);
  241. jassert (isThisTheMessageThread()); // must only be called by the message thread
  242. uint32 endTime = Time::getMillisecondCounter() + (uint32) millisecondsToRunFor;
  243. while (! quitMessagePosted)
  244. {
  245. JUCE_AUTORELEASEPOOL
  246. {
  247. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  248. NSEvent* e = [NSApp nextEventMatchingMask: NSEventMaskAny
  249. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  250. inMode: NSDefaultRunLoopMode
  251. dequeue: YES];
  252. if (e != nil && (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e)))
  253. [NSApp sendEvent: e];
  254. if (Time::getMillisecondCounter() >= endTime)
  255. break;
  256. }
  257. }
  258. return ! quitMessagePosted;
  259. }
  260. #endif
  261. //==============================================================================
  262. void initialiseNSApplication();
  263. void initialiseNSApplication()
  264. {
  265. JUCE_AUTORELEASEPOOL
  266. {
  267. [NSApplication sharedApplication];
  268. }
  269. }
  270. static AppDelegate* appDelegate = nullptr;
  271. void MessageManager::doPlatformSpecificInitialisation()
  272. {
  273. if (appDelegate == nil)
  274. appDelegate = new AppDelegate();
  275. }
  276. void MessageManager::doPlatformSpecificShutdown()
  277. {
  278. delete appDelegate;
  279. appDelegate = nullptr;
  280. }
  281. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  282. {
  283. jassert (appDelegate != nil);
  284. appDelegate->messageQueue.post (message);
  285. return true;
  286. }
  287. void MessageManager::broadcastMessage (const String& message)
  288. {
  289. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  290. forKey: nsStringLiteral ("message")];
  291. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroadcastEventName()
  292. object: nil
  293. userInfo: info];
  294. }
  295. // Special function used by some plugin classes to re-post carbon events
  296. void __attribute__ ((visibility("default"))) repostCurrentNSEvent();
  297. void __attribute__ ((visibility("default"))) repostCurrentNSEvent()
  298. {
  299. struct EventReposter : public CallbackMessage
  300. {
  301. EventReposter() : e ([[NSApp currentEvent] retain]) {}
  302. ~EventReposter() { [e release]; }
  303. void messageCallback() override
  304. {
  305. [NSApp postEvent: e atStart: YES];
  306. }
  307. NSEvent* e;
  308. };
  309. (new EventReposter())->post();
  310. }
  311. //==============================================================================
  312. #if JUCE_MAC
  313. struct MountedVolumeListChangeDetector::Pimpl
  314. {
  315. Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
  316. {
  317. static ObserverClass cls;
  318. delegate = [cls.createInstance() init];
  319. ObserverClass::setOwner (delegate, this);
  320. NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
  321. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
  322. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
  323. }
  324. ~Pimpl()
  325. {
  326. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
  327. [delegate release];
  328. }
  329. private:
  330. MountedVolumeListChangeDetector& owner;
  331. id delegate;
  332. struct ObserverClass : public ObjCClass<NSObject>
  333. {
  334. ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
  335. {
  336. addIvar<Pimpl*> ("owner");
  337. addMethod (@selector (changed:), changed, "v@:@");
  338. addProtocol (@protocol (NSTextInput));
  339. registerClass();
  340. }
  341. static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
  342. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  343. static void changed (id self, SEL, NSNotification*)
  344. {
  345. getOwner (self)->owner.mountedVolumeListChanged();
  346. }
  347. };
  348. };
  349. MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl = new Pimpl (*this); }
  350. MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
  351. #endif
  352. } // namespace juce