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.

497 lines
19KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 AppDelegateClass : public ObjCClass<NSObject>
  27. {
  28. AppDelegateClass() : ObjCClass ("JUCEAppDelegate_")
  29. {
  30. addMethod (@selector (applicationWillFinishLaunching:), [] (id self, SEL, NSNotification*)
  31. {
  32. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  33. [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
  34. andSelector: @selector (getUrl:withReplyEvent:)
  35. forEventClass: kInternetEventClass
  36. andEventID: kAEGetURL];
  37. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  38. });
  39. addMethod (@selector (applicationShouldTerminate:), [] (id /*self*/, SEL, NSApplication*)
  40. {
  41. if (auto* app = JUCEApplicationBase::getInstance())
  42. {
  43. app->systemRequestedQuit();
  44. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  45. return NSTerminateCancel;
  46. }
  47. return NSTerminateNow;
  48. });
  49. addMethod (@selector (applicationWillTerminate:), [] (id /*self*/, SEL, NSNotification*)
  50. {
  51. JUCEApplicationBase::appWillTerminateByForce();
  52. });
  53. addMethod (@selector (application:openFile:), [] (id /*self*/, SEL, NSApplication*, NSString* filename)
  54. {
  55. if (auto* app = JUCEApplicationBase::getInstance())
  56. {
  57. app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  58. return YES;
  59. }
  60. return NO;
  61. });
  62. addMethod (@selector (application:openFiles:), [] (id /*self*/, SEL, NSApplication*, NSArray* filenames)
  63. {
  64. if (auto* app = JUCEApplicationBase::getInstance())
  65. {
  66. StringArray files;
  67. for (NSString* f in filenames)
  68. files.add (quotedIfContainsSpaces (f));
  69. if (files.size() > 0)
  70. app->anotherInstanceStarted (files.joinIntoString (" "));
  71. }
  72. });
  73. addMethod (@selector (applicationDidBecomeActive:), [] (id /*self*/, SEL, NSNotification*) { focusChanged(); });
  74. addMethod (@selector (applicationDidResignActive:), [] (id /*self*/, SEL, NSNotification*) { focusChanged(); });
  75. addMethod (@selector (applicationWillUnhide:), [] (id /*self*/, SEL, NSNotification*) { focusChanged(); });
  76. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  77. addMethod (@selector (getUrl:withReplyEvent:), [] (id /*self*/, SEL, NSAppleEventDescriptor* event, NSAppleEventDescriptor*)
  78. {
  79. if (auto* app = JUCEApplicationBase::getInstance())
  80. app->anotherInstanceStarted (quotedIfContainsSpaces ([[event paramDescriptorForKeyword: keyDirectObject] stringValue]));
  81. });
  82. addMethod (@selector (broadcastMessageCallback:), [] (id /*self*/, SEL, NSNotification* n)
  83. {
  84. NSDictionary* dict = (NSDictionary*) [n userInfo];
  85. auto messageString = nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]);
  86. MessageManager::getInstance()->deliverBroadcastMessage (messageString);
  87. });
  88. addMethod (@selector (mainMenuTrackingBegan:), [] (id /*self*/, SEL, NSNotification*)
  89. {
  90. if (menuTrackingChangedCallback != nullptr)
  91. menuTrackingChangedCallback (true);
  92. });
  93. addMethod (@selector (mainMenuTrackingEnded:), [] (id /*self*/, SEL, NSNotification*)
  94. {
  95. if (menuTrackingChangedCallback != nullptr)
  96. menuTrackingChangedCallback (false);
  97. });
  98. // (used as a way of running a dummy thread)
  99. addMethod (@selector (dummyMethod), [] (id /*self*/, SEL) {});
  100. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  101. #if JUCE_PUSH_NOTIFICATIONS
  102. //==============================================================================
  103. addIvar<NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>*> ("pushNotificationsDelegate");
  104. addMethod (@selector (applicationDidFinishLaunching:), [] (id self, SEL, NSNotification* notification)
  105. {
  106. if (notification.userInfo != nil)
  107. {
  108. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  109. // NSUserNotification is deprecated from macOS 11, but there doesn't seem to be a
  110. // replacement for NSApplicationLaunchUserNotificationKey returning a non-deprecated type
  111. NSUserNotification* userNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey];
  112. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  113. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullable-to-nonnull-conversion")
  114. if (userNotification != nil && userNotification.userInfo != nil)
  115. [self application: [NSApplication sharedApplication] didReceiveRemoteNotification: userNotification.userInfo];
  116. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  117. }
  118. });
  119. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  120. addMethod (@selector (setPushNotificationsDelegate:), [] (id self, SEL, NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* delegate)
  121. {
  122. object_setInstanceVariable (self, "pushNotificationsDelegate", delegate);
  123. });
  124. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  125. addMethod (@selector (application:didRegisterForRemoteNotificationsWithDeviceToken:), [] (id self, SEL, NSApplication* application, NSData* deviceToken)
  126. {
  127. auto* delegate = getPushNotificationsDelegate (self);
  128. SEL selector = @selector (application:didRegisterForRemoteNotificationsWithDeviceToken:);
  129. if (delegate != nil && [delegate respondsToSelector: selector])
  130. {
  131. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  132. [invocation setSelector: selector];
  133. [invocation setTarget: delegate];
  134. [invocation setArgument: &application atIndex:2];
  135. [invocation setArgument: &deviceToken atIndex:3];
  136. [invocation invoke];
  137. }
  138. });
  139. addMethod (@selector (application:didFailToRegisterForRemoteNotificationsWithError:), [] (id self, SEL, NSApplication* application, NSError* error)
  140. {
  141. auto* delegate = getPushNotificationsDelegate (self);
  142. SEL selector = @selector (application:didFailToRegisterForRemoteNotificationsWithError:);
  143. if (delegate != nil && [delegate respondsToSelector: selector])
  144. {
  145. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  146. [invocation setSelector: selector];
  147. [invocation setTarget: delegate];
  148. [invocation setArgument: &application atIndex:2];
  149. [invocation setArgument: &error atIndex:3];
  150. [invocation invoke];
  151. }
  152. });
  153. addMethod (@selector (application:didReceiveRemoteNotification:), [] (id self, SEL, NSApplication* application, NSDictionary* userInfo)
  154. {
  155. auto* delegate = getPushNotificationsDelegate (self);
  156. SEL selector = @selector (application:didReceiveRemoteNotification:);
  157. if (delegate != nil && [delegate respondsToSelector: selector])
  158. {
  159. NSInvocation* invocation = [NSInvocation invocationWithMethodSignature: [delegate methodSignatureForSelector: selector]];
  160. [invocation setSelector: selector];
  161. [invocation setTarget: delegate];
  162. [invocation setArgument: &application atIndex:2];
  163. [invocation setArgument: &userInfo atIndex:3];
  164. [invocation invoke];
  165. }
  166. });
  167. #endif
  168. registerClass();
  169. }
  170. private:
  171. static void focusChanged()
  172. {
  173. if (appFocusChangeCallback != nullptr)
  174. (*appFocusChangeCallback)();
  175. }
  176. static String quotedIfContainsSpaces (NSString* file)
  177. {
  178. String s (nsStringToJuce (file));
  179. s = s.unquoted().replace ("\"", "\\\"");
  180. if (s.containsChar (' '))
  181. s = s.quoted();
  182. return s;
  183. }
  184. //==============================================================================
  185. #if JUCE_PUSH_NOTIFICATIONS
  186. static NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>* getPushNotificationsDelegate (id self)
  187. {
  188. return getIvar<NSObject<NSApplicationDelegate, NSUserNotificationCenterDelegate>*> (self, "pushNotificationsDelegate");
  189. }
  190. #endif
  191. };
  192. // This is declared at file scope, so that it's guaranteed to be
  193. // constructed before and destructed after `appDelegate` (below)
  194. static AppDelegateClass appDelegateClass;
  195. //==============================================================================
  196. struct AppDelegate
  197. {
  198. public:
  199. AppDelegate()
  200. {
  201. delegate = [appDelegateClass.createInstance() init];
  202. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  203. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  204. [center addObserver: delegate selector: @selector (mainMenuTrackingBegan:)
  205. name: NSMenuDidBeginTrackingNotification object: nil];
  206. [center addObserver: delegate selector: @selector (mainMenuTrackingEnded:)
  207. name: NSMenuDidEndTrackingNotification object: nil];
  208. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  209. if (JUCEApplicationBase::isStandaloneApp())
  210. {
  211. [NSApp setDelegate: delegate];
  212. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  213. [[NSDistributedNotificationCenter defaultCenter] addObserver: delegate
  214. selector: @selector (broadcastMessageCallback:)
  215. name: getBroadcastEventName()
  216. object: nil
  217. suspensionBehavior: NSNotificationSuspensionBehaviorDeliverImmediately];
  218. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  219. }
  220. else
  221. {
  222. [center addObserver: delegate selector: @selector (applicationDidResignActive:)
  223. name: NSApplicationDidResignActiveNotification object: NSApp];
  224. [center addObserver: delegate selector: @selector (applicationDidBecomeActive:)
  225. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  226. [center addObserver: delegate selector: @selector (applicationWillUnhide:)
  227. name: NSApplicationWillUnhideNotification object: NSApp];
  228. }
  229. }
  230. ~AppDelegate()
  231. {
  232. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: delegate];
  233. [[NSNotificationCenter defaultCenter] removeObserver: delegate];
  234. if (JUCEApplicationBase::isStandaloneApp())
  235. {
  236. [NSApp setDelegate: nil];
  237. [[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate
  238. name: getBroadcastEventName()
  239. object: nil];
  240. }
  241. [delegate release];
  242. }
  243. static NSString* getBroadcastEventName()
  244. {
  245. return juceStringToNS ("juce_" + String::toHexString (File::getSpecialLocation (File::currentExecutableFile).hashCode64()));
  246. }
  247. MessageQueue messageQueue;
  248. id delegate;
  249. };
  250. //==============================================================================
  251. void MessageManager::runDispatchLoop()
  252. {
  253. if (quitMessagePosted.get() == 0) // check that the quit message wasn't already posted..
  254. {
  255. JUCE_AUTORELEASEPOOL
  256. {
  257. // must only be called by the message thread!
  258. jassert (isThisTheMessageThread());
  259. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  260. @try
  261. {
  262. [NSApp run];
  263. }
  264. @catch (NSException* e)
  265. {
  266. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  267. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  268. JUCEApplicationBase::sendUnhandledException (&ex, __FILE__, __LINE__);
  269. }
  270. @finally
  271. {
  272. }
  273. #else
  274. [NSApp run];
  275. #endif
  276. }
  277. }
  278. }
  279. static void shutdownNSApp()
  280. {
  281. [NSApp stop: nil];
  282. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  283. }
  284. void MessageManager::stopDispatchLoop()
  285. {
  286. if (isThisTheMessageThread())
  287. {
  288. quitMessagePosted = true;
  289. shutdownNSApp();
  290. }
  291. else
  292. {
  293. struct QuitCallback : public CallbackMessage
  294. {
  295. QuitCallback() {}
  296. void messageCallback() override { MessageManager::getInstance()->stopDispatchLoop(); }
  297. };
  298. (new QuitCallback())->post();
  299. }
  300. }
  301. #if JUCE_MODAL_LOOPS_PERMITTED
  302. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  303. {
  304. jassert (millisecondsToRunFor >= 0);
  305. jassert (isThisTheMessageThread()); // must only be called by the message thread
  306. auto endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  307. while (quitMessagePosted.get() == 0)
  308. {
  309. JUCE_AUTORELEASEPOOL
  310. {
  311. auto msRemaining = endTime - Time::currentTimeMillis();
  312. if (msRemaining <= 0)
  313. break;
  314. CFRunLoopRunInMode (kCFRunLoopDefaultMode, jmin (1.0, msRemaining * 0.001), true);
  315. if (NSEvent* e = [NSApp nextEventMatchingMask: NSEventMaskAny
  316. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  317. inMode: NSDefaultRunLoopMode
  318. dequeue: YES])
  319. if (isEventBlockedByModalComps == nullptr || ! (*isEventBlockedByModalComps) (e))
  320. [NSApp sendEvent: e];
  321. }
  322. }
  323. return quitMessagePosted.get() == 0;
  324. }
  325. #endif
  326. //==============================================================================
  327. void initialiseNSApplication();
  328. void initialiseNSApplication()
  329. {
  330. JUCE_AUTORELEASEPOOL
  331. {
  332. [NSApplication sharedApplication];
  333. }
  334. }
  335. static std::unique_ptr<AppDelegate> appDelegate;
  336. void MessageManager::doPlatformSpecificInitialisation()
  337. {
  338. if (appDelegate == nil)
  339. appDelegate.reset (new AppDelegate());
  340. }
  341. void MessageManager::doPlatformSpecificShutdown()
  342. {
  343. appDelegate = nullptr;
  344. }
  345. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  346. {
  347. jassert (appDelegate != nil);
  348. appDelegate->messageQueue.post (message);
  349. return true;
  350. }
  351. void MessageManager::broadcastMessage (const String& message)
  352. {
  353. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  354. forKey: nsStringLiteral ("message")];
  355. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroadcastEventName()
  356. object: nil
  357. userInfo: info];
  358. }
  359. //==============================================================================
  360. #if JUCE_MAC
  361. struct MountedVolumeListChangeDetector::Pimpl
  362. {
  363. Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
  364. {
  365. static ObserverClass cls;
  366. delegate = [cls.createInstance() init];
  367. ObserverClass::setOwner (delegate, this);
  368. NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
  369. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  370. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
  371. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
  372. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  373. }
  374. ~Pimpl()
  375. {
  376. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
  377. [delegate release];
  378. }
  379. private:
  380. MountedVolumeListChangeDetector& owner;
  381. id delegate;
  382. struct ObserverClass : public ObjCClass<NSObject>
  383. {
  384. ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
  385. {
  386. addIvar<Pimpl*> ("owner");
  387. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  388. addMethod (@selector (changed:), changed);
  389. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  390. addProtocol (@protocol (NSTextInput));
  391. registerClass();
  392. }
  393. static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
  394. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  395. static void changed (id self, SEL, NSNotification*)
  396. {
  397. getOwner (self)->owner.mountedVolumeListChanged();
  398. }
  399. };
  400. };
  401. MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl.reset (new Pimpl (*this)); }
  402. MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
  403. #endif
  404. } // namespace juce