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.

522 lines
21KB

  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. if (s.containsChar (' '))
  193. s = s.quoted ('"');
  194. return s;
  195. }
  196. #if JUCE_PUSH_NOTIFICATIONS
  197. //==============================================================================
  198. static void setPushNotificationsDelegate (id self, SEL, NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* delegate)
  199. {
  200. object_setInstanceVariable (self, "pushNotificationsDelegate", delegate);
  201. }
  202. static NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* getPushNotificationsDelegate (id self)
  203. {
  204. return getIvar<NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>*> (self, "pushNotificationsDelegate");
  205. }
  206. static void registeredForRemoteNotifications (id self, SEL, NSApplication* application, NSData* deviceToken)
  207. {
  208. auto* delegate = getPushNotificationsDelegate (self);
  209. SEL selector = NSSelectorFromString (@"application:didRegisterForRemoteNotificationsWithDeviceToken:");
  210. if (delegate != nil && [delegate respondsToSelector: selector])
  211. {
  212. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  213. [invocation setSelector: selector];
  214. [invocation setTarget: delegate];
  215. [invocation setArgument: &application atIndex:2];
  216. [invocation setArgument: &deviceToken atIndex:3];
  217. [invocation invoke];
  218. }
  219. }
  220. static void failedToRegisterForRemoteNotifications (id self, SEL, NSApplication* application, NSError* error)
  221. {
  222. auto* delegate = getPushNotificationsDelegate (self);
  223. SEL selector = NSSelectorFromString (@"application:didFailToRegisterForRemoteNotificationsWithError:");
  224. if (delegate != nil && [delegate respondsToSelector: selector])
  225. {
  226. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  227. [invocation setSelector: selector];
  228. [invocation setTarget: delegate];
  229. [invocation setArgument: &application atIndex:2];
  230. [invocation setArgument: &error atIndex:3];
  231. [invocation invoke];
  232. }
  233. }
  234. static void didReceiveRemoteNotification (id self, SEL, NSApplication* application, NSDictionary* userInfo)
  235. {
  236. auto* delegate = getPushNotificationsDelegate (self);
  237. SEL selector = NSSelectorFromString (@"application:didReceiveRemoteNotification:");
  238. if (delegate != nil && [delegate respondsToSelector: selector])
  239. {
  240. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  241. [invocation setSelector: selector];
  242. [invocation setTarget: delegate];
  243. [invocation setArgument: &application atIndex:2];
  244. [invocation setArgument: &userInfo atIndex:3];
  245. [invocation invoke];
  246. }
  247. }
  248. #endif
  249. };
  250. };
  251. //==============================================================================
  252. void MessageManager::runDispatchLoop()
  253. {
  254. if (quitMessagePosted.get() == 0) // check that the quit message wasn't already posted..
  255. {
  256. JUCE_AUTORELEASEPOOL
  257. {
  258. // must only be called by the message thread!
  259. jassert (isThisTheMessageThread());
  260. #if JUCE_PROJUCER_LIVE_BUILD
  261. runDispatchLoopUntil (std::numeric_limits<int>::max());
  262. #else
  263. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  264. @try
  265. {
  266. [NSApp run];
  267. }
  268. @catch (NSException* e)
  269. {
  270. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  271. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  272. JUCEApplicationBase::sendUnhandledException (&ex, __FILE__, __LINE__);
  273. }
  274. @finally
  275. {
  276. }
  277. #else
  278. [NSApp run];
  279. #endif
  280. #endif
  281. }
  282. }
  283. }
  284. static void shutdownNSApp()
  285. {
  286. [NSApp stop: nil];
  287. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  288. }
  289. void MessageManager::stopDispatchLoop()
  290. {
  291. #if JUCE_PROJUCER_LIVE_BUILD
  292. quitMessagePosted = true;
  293. #else
  294. if (isThisTheMessageThread())
  295. {
  296. quitMessagePosted = true;
  297. shutdownNSApp();
  298. }
  299. else
  300. {
  301. struct QuitCallback : public CallbackMessage
  302. {
  303. QuitCallback() {}
  304. void messageCallback() override { MessageManager::getInstance()->stopDispatchLoop(); }
  305. };
  306. (new QuitCallback())->post();
  307. }
  308. #endif
  309. }
  310. #if JUCE_MODAL_LOOPS_PERMITTED
  311. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  312. {
  313. jassert (millisecondsToRunFor >= 0);
  314. jassert (isThisTheMessageThread()); // must only be called by the message thread
  315. uint32 endTime = Time::getMillisecondCounter() + (uint32) millisecondsToRunFor;
  316. while (quitMessagePosted.get() == 0)
  317. {
  318. JUCE_AUTORELEASEPOOL
  319. {
  320. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  321. NSEvent* e = [NSApp nextEventMatchingMask: NSEventMaskAny
  322. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  323. inMode: NSDefaultRunLoopMode
  324. dequeue: YES];
  325. if (e != nil && (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e)))
  326. [NSApp sendEvent: e];
  327. if (Time::getMillisecondCounter() >= endTime)
  328. break;
  329. }
  330. }
  331. return quitMessagePosted.get() == 0;
  332. }
  333. #endif
  334. //==============================================================================
  335. void initialiseNSApplication();
  336. void initialiseNSApplication()
  337. {
  338. JUCE_AUTORELEASEPOOL
  339. {
  340. [NSApplication sharedApplication];
  341. }
  342. }
  343. static AppDelegate* appDelegate = nullptr;
  344. void MessageManager::doPlatformSpecificInitialisation()
  345. {
  346. if (appDelegate == nil)
  347. appDelegate = new AppDelegate();
  348. }
  349. void MessageManager::doPlatformSpecificShutdown()
  350. {
  351. delete appDelegate;
  352. appDelegate = nullptr;
  353. }
  354. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  355. {
  356. jassert (appDelegate != nil);
  357. appDelegate->messageQueue.post (message);
  358. return true;
  359. }
  360. void MessageManager::broadcastMessage (const String& message)
  361. {
  362. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  363. forKey: nsStringLiteral ("message")];
  364. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroadcastEventName()
  365. object: nil
  366. userInfo: info];
  367. }
  368. // Special function used by some plugin classes to re-post carbon events
  369. void __attribute__ ((visibility("default"))) repostCurrentNSEvent();
  370. void __attribute__ ((visibility("default"))) repostCurrentNSEvent()
  371. {
  372. struct EventReposter : public CallbackMessage
  373. {
  374. EventReposter() : e ([[NSApp currentEvent] retain]) {}
  375. ~EventReposter() { [e release]; }
  376. void messageCallback() override
  377. {
  378. [NSApp postEvent: e atStart: YES];
  379. }
  380. NSEvent* e;
  381. };
  382. (new EventReposter())->post();
  383. }
  384. //==============================================================================
  385. #if JUCE_MAC
  386. struct MountedVolumeListChangeDetector::Pimpl
  387. {
  388. Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
  389. {
  390. static ObserverClass cls;
  391. delegate = [cls.createInstance() init];
  392. ObserverClass::setOwner (delegate, this);
  393. NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
  394. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
  395. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
  396. }
  397. ~Pimpl()
  398. {
  399. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
  400. [delegate release];
  401. }
  402. private:
  403. MountedVolumeListChangeDetector& owner;
  404. id delegate;
  405. struct ObserverClass : public ObjCClass<NSObject>
  406. {
  407. ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
  408. {
  409. addIvar<Pimpl*> ("owner");
  410. addMethod (@selector (changed:), changed, "v@:@");
  411. addProtocol (@protocol (NSTextInput));
  412. registerClass();
  413. }
  414. static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
  415. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  416. static void changed (id self, SEL, NSNotification*)
  417. {
  418. getOwner (self)->owner.mountedVolumeListChanged();
  419. }
  420. };
  421. };
  422. MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl.reset (new Pimpl (*this)); }
  423. MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
  424. #endif
  425. } // namespace juce