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.

434 lines
16KB

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