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.

436 lines
16KB

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