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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. using AppFocusChangeCallback = void (*)();
  20. AppFocusChangeCallback appFocusChangeCallback = nullptr;
  21. using CheckEventBlockedByModalComps = bool (*)(NSEvent*);
  22. CheckEventBlockedByModalComps isEventBlockedByModalComps = nullptr;
  23. using MenuTrackingChangedCallback = void (*)(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. #if JUCE_PUSH_NOTIFICATIONS
  96. //==============================================================================
  97. addIvar<NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>*> ("pushNotificationsDelegate");
  98. addMethod (@selector (applicationDidFinishLaunching:), applicationDidFinishLaunching, "v@:@");
  99. addMethod (@selector (setPushNotificationsDelegate:), setPushNotificationsDelegate, "v@:@");
  100. addMethod (@selector (application:didRegisterForRemoteNotificationsWithDeviceToken:), registeredForRemoteNotifications, "v@:@@");
  101. addMethod (@selector (application:didFailToRegisterForRemoteNotificationsWithError:), failedToRegisterForRemoteNotifications, "v@:@@");
  102. addMethod (@selector (application:didReceiveRemoteNotification:), didReceiveRemoteNotification, "v@:@@");
  103. #endif
  104. registerClass();
  105. }
  106. private:
  107. static void applicationWillFinishLaunching (id self, SEL, NSNotification*)
  108. {
  109. [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
  110. andSelector: @selector (getUrl:withReplyEvent:)
  111. forEventClass: kInternetEventClass
  112. andEventID: kAEGetURL];
  113. }
  114. #if JUCE_PUSH_NOTIFICATIONS
  115. static void applicationDidFinishLaunching (id self, SEL, NSNotification* notification)
  116. {
  117. if (notification.userInfo != nil)
  118. {
  119. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  120. // NSUserNotification is deprecated from macOS 11, but there doesn't seem to be a
  121. // replacement for NSApplicationLaunchUserNotificationKey returning a non-deprecated type
  122. NSUserNotification* userNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey];
  123. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  124. if (userNotification != nil && userNotification.userInfo != nil)
  125. didReceiveRemoteNotification (self, nil, [NSApplication sharedApplication], userNotification.userInfo);
  126. }
  127. }
  128. #endif
  129. static NSApplicationTerminateReply applicationShouldTerminate (id /*self*/, SEL, NSApplication*)
  130. {
  131. if (auto* app = JUCEApplicationBase::getInstance())
  132. {
  133. app->systemRequestedQuit();
  134. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  135. return NSTerminateCancel;
  136. }
  137. return NSTerminateNow;
  138. }
  139. static void applicationWillTerminate (id /*self*/, SEL, NSNotification*)
  140. {
  141. JUCEApplicationBase::appWillTerminateByForce();
  142. }
  143. static BOOL application_openFile (id /*self*/, SEL, NSApplication*, NSString* filename)
  144. {
  145. if (auto* app = JUCEApplicationBase::getInstance())
  146. {
  147. app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  148. return YES;
  149. }
  150. return NO;
  151. }
  152. static void application_openFiles (id /*self*/, SEL, NSApplication*, NSArray* filenames)
  153. {
  154. if (auto* app = JUCEApplicationBase::getInstance())
  155. {
  156. StringArray files;
  157. for (NSString* f in filenames)
  158. files.add (quotedIfContainsSpaces (f));
  159. if (files.size() > 0)
  160. app->anotherInstanceStarted (files.joinIntoString (" "));
  161. }
  162. }
  163. static void applicationDidBecomeActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  164. static void applicationDidResignActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  165. static void applicationWillUnhide (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  166. static void broadcastMessageCallback (id /*self*/, SEL, NSNotification* n)
  167. {
  168. NSDictionary* dict = (NSDictionary*) [n userInfo];
  169. auto messageString = nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]);
  170. MessageManager::getInstance()->deliverBroadcastMessage (messageString);
  171. }
  172. static void mainMenuTrackingBegan (id /*self*/, SEL, NSNotification*)
  173. {
  174. if (menuTrackingChangedCallback != nullptr)
  175. (*menuTrackingChangedCallback) (true);
  176. }
  177. static void mainMenuTrackingEnded (id /*self*/, SEL, NSNotification*)
  178. {
  179. if (menuTrackingChangedCallback != nullptr)
  180. (*menuTrackingChangedCallback) (false);
  181. }
  182. static void dummyMethod (id /*self*/, SEL) {} // (used as a way of running a dummy thread)
  183. static void focusChanged()
  184. {
  185. if (appFocusChangeCallback != nullptr)
  186. (*appFocusChangeCallback)();
  187. }
  188. static void getUrl_withReplyEvent (id /*self*/, SEL, NSAppleEventDescriptor* event, NSAppleEventDescriptor*)
  189. {
  190. if (auto* app = JUCEApplicationBase::getInstance())
  191. app->anotherInstanceStarted (quotedIfContainsSpaces ([[event paramDescriptorForKeyword: keyDirectObject] stringValue]));
  192. }
  193. static String quotedIfContainsSpaces (NSString* file)
  194. {
  195. String s (nsStringToJuce (file));
  196. s = s.unquoted().replace ("\"", "\\\"");
  197. if (s.containsChar (' '))
  198. s = s.quoted();
  199. return s;
  200. }
  201. #if JUCE_PUSH_NOTIFICATIONS
  202. //==============================================================================
  203. static void setPushNotificationsDelegate (id self, SEL, NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* delegate)
  204. {
  205. object_setInstanceVariable (self, "pushNotificationsDelegate", delegate);
  206. }
  207. static NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* getPushNotificationsDelegate (id self)
  208. {
  209. return getIvar<NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>*> (self, "pushNotificationsDelegate");
  210. }
  211. static void registeredForRemoteNotifications (id self, SEL, NSApplication* application, NSData* deviceToken)
  212. {
  213. auto* delegate = getPushNotificationsDelegate (self);
  214. SEL selector = NSSelectorFromString (@"application:didRegisterForRemoteNotificationsWithDeviceToken:");
  215. if (delegate != nil && [delegate respondsToSelector: selector])
  216. {
  217. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  218. [invocation setSelector: selector];
  219. [invocation setTarget: delegate];
  220. [invocation setArgument: &application atIndex:2];
  221. [invocation setArgument: &deviceToken atIndex:3];
  222. [invocation invoke];
  223. }
  224. }
  225. static void failedToRegisterForRemoteNotifications (id self, SEL, NSApplication* application, NSError* error)
  226. {
  227. auto* delegate = getPushNotificationsDelegate (self);
  228. SEL selector = NSSelectorFromString (@"application:didFailToRegisterForRemoteNotificationsWithError:");
  229. if (delegate != nil && [delegate respondsToSelector: selector])
  230. {
  231. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  232. [invocation setSelector: selector];
  233. [invocation setTarget: delegate];
  234. [invocation setArgument: &application atIndex:2];
  235. [invocation setArgument: &error atIndex:3];
  236. [invocation invoke];
  237. }
  238. }
  239. static void didReceiveRemoteNotification (id self, SEL, NSApplication* application, NSDictionary* userInfo)
  240. {
  241. auto* delegate = getPushNotificationsDelegate (self);
  242. SEL selector = NSSelectorFromString (@"application:didReceiveRemoteNotification:");
  243. if (delegate != nil && [delegate respondsToSelector: selector])
  244. {
  245. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  246. [invocation setSelector: selector];
  247. [invocation setTarget: delegate];
  248. [invocation setArgument: &application atIndex:2];
  249. [invocation setArgument: &userInfo atIndex:3];
  250. [invocation invoke];
  251. }
  252. }
  253. #endif
  254. };
  255. };
  256. //==============================================================================
  257. void MessageManager::runDispatchLoop()
  258. {
  259. if (quitMessagePosted.get() == 0) // check that the quit message wasn't already posted..
  260. {
  261. JUCE_AUTORELEASEPOOL
  262. {
  263. // must only be called by the message thread!
  264. jassert (isThisTheMessageThread());
  265. #if JUCE_PROJUCER_LIVE_BUILD
  266. runDispatchLoopUntil (std::numeric_limits<int>::max());
  267. #else
  268. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  269. @try
  270. {
  271. [NSApp run];
  272. }
  273. @catch (NSException* e)
  274. {
  275. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  276. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  277. JUCEApplicationBase::sendUnhandledException (&ex, __FILE__, __LINE__);
  278. }
  279. @finally
  280. {
  281. }
  282. #else
  283. [NSApp run];
  284. #endif
  285. #endif
  286. }
  287. }
  288. }
  289. static void shutdownNSApp()
  290. {
  291. [NSApp stop: nil];
  292. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  293. }
  294. void MessageManager::stopDispatchLoop()
  295. {
  296. #if JUCE_PROJUCER_LIVE_BUILD
  297. quitMessagePosted = true;
  298. #else
  299. if (isThisTheMessageThread())
  300. {
  301. quitMessagePosted = true;
  302. shutdownNSApp();
  303. }
  304. else
  305. {
  306. struct QuitCallback : public CallbackMessage
  307. {
  308. QuitCallback() {}
  309. void messageCallback() override { MessageManager::getInstance()->stopDispatchLoop(); }
  310. };
  311. (new QuitCallback())->post();
  312. }
  313. #endif
  314. }
  315. #if JUCE_MODAL_LOOPS_PERMITTED
  316. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  317. {
  318. jassert (millisecondsToRunFor >= 0);
  319. jassert (isThisTheMessageThread()); // must only be called by the message thread
  320. auto endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  321. while (quitMessagePosted.get() == 0)
  322. {
  323. JUCE_AUTORELEASEPOOL
  324. {
  325. auto msRemaining = endTime - Time::currentTimeMillis();
  326. if (msRemaining <= 0)
  327. break;
  328. CFRunLoopRunInMode (kCFRunLoopDefaultMode, jmin (1.0, msRemaining * 0.001), true);
  329. if (NSEvent* e = [NSApp nextEventMatchingMask: NSEventMaskAny
  330. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  331. inMode: NSDefaultRunLoopMode
  332. dequeue: YES])
  333. if (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e))
  334. [NSApp sendEvent: e];
  335. }
  336. }
  337. return quitMessagePosted.get() == 0;
  338. }
  339. #endif
  340. //==============================================================================
  341. void initialiseNSApplication();
  342. void initialiseNSApplication()
  343. {
  344. JUCE_AUTORELEASEPOOL
  345. {
  346. [NSApplication sharedApplication];
  347. }
  348. }
  349. static AppDelegate* appDelegate = nullptr;
  350. void MessageManager::doPlatformSpecificInitialisation()
  351. {
  352. if (appDelegate == nil)
  353. appDelegate = new AppDelegate();
  354. }
  355. void MessageManager::doPlatformSpecificShutdown()
  356. {
  357. delete appDelegate;
  358. appDelegate = nullptr;
  359. }
  360. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  361. {
  362. jassert (appDelegate != nil);
  363. appDelegate->messageQueue.post (message);
  364. return true;
  365. }
  366. void MessageManager::broadcastMessage (const String& message)
  367. {
  368. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  369. forKey: nsStringLiteral ("message")];
  370. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroadcastEventName()
  371. object: nil
  372. userInfo: info];
  373. }
  374. // Special function used by some plugin classes to re-post carbon events
  375. void __attribute__ ((visibility("default"))) repostCurrentNSEvent();
  376. void __attribute__ ((visibility("default"))) repostCurrentNSEvent()
  377. {
  378. struct EventReposter : public CallbackMessage
  379. {
  380. EventReposter() : e ([[NSApp currentEvent] retain]) {}
  381. ~EventReposter() override { [e release]; }
  382. void messageCallback() override
  383. {
  384. [NSApp postEvent: e atStart: YES];
  385. }
  386. NSEvent* e;
  387. };
  388. (new EventReposter())->post();
  389. }
  390. //==============================================================================
  391. #if JUCE_MAC
  392. struct MountedVolumeListChangeDetector::Pimpl
  393. {
  394. Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
  395. {
  396. static ObserverClass cls;
  397. delegate = [cls.createInstance() init];
  398. ObserverClass::setOwner (delegate, this);
  399. NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
  400. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
  401. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
  402. }
  403. ~Pimpl()
  404. {
  405. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
  406. [delegate release];
  407. }
  408. private:
  409. MountedVolumeListChangeDetector& owner;
  410. id delegate;
  411. struct ObserverClass : public ObjCClass<NSObject>
  412. {
  413. ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
  414. {
  415. addIvar<Pimpl*> ("owner");
  416. addMethod (@selector (changed:), changed, "v@:@");
  417. addProtocol (@protocol (NSTextInput));
  418. registerClass();
  419. }
  420. static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
  421. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  422. static void changed (id self, SEL, NSNotification*)
  423. {
  424. getOwner (self)->owner.mountedVolumeListChanged();
  425. }
  426. };
  427. };
  428. MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl.reset (new Pimpl (*this)); }
  429. MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
  430. #endif
  431. } // namespace juce