juce_mac_MessageManager.mm 21 KB

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