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.

426 lines
16KB

  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. 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. suspensionBehavior: NSNotificationSuspensionBehaviorDeliverImmediately];
  44. }
  45. else
  46. {
  47. [center addObserver: delegate selector: @selector (applicationDidResignActive:)
  48. name: NSApplicationDidResignActiveNotification object: NSApp];
  49. [center addObserver: delegate selector: @selector (applicationDidBecomeActive:)
  50. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  51. [center addObserver: delegate selector: @selector (applicationWillUnhide:)
  52. name: NSApplicationWillUnhideNotification object: NSApp];
  53. }
  54. }
  55. ~AppDelegate()
  56. {
  57. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: delegate];
  58. [[NSNotificationCenter defaultCenter] removeObserver: delegate];
  59. if (JUCEApplicationBase::isStandaloneApp())
  60. {
  61. [NSApp setDelegate: nil];
  62. [[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate
  63. name: getBroadcastEventName()
  64. object: nil];
  65. }
  66. [delegate release];
  67. }
  68. static NSString* getBroadcastEventName()
  69. {
  70. return juceStringToNS ("juce_" + String::toHexString (File::getSpecialLocation (File::currentExecutableFile).hashCode64()));
  71. }
  72. MessageQueue messageQueue;
  73. id delegate;
  74. private:
  75. //==============================================================================
  76. struct AppDelegateClass : public ObjCClass<NSObject>
  77. {
  78. AppDelegateClass() : ObjCClass<NSObject> ("JUCEAppDelegate_")
  79. {
  80. addMethod (@selector (applicationWillFinishLaunching:), applicationWillFinishLaunching, "v@:@@");
  81. addMethod (@selector (getUrl:withReplyEvent:), getUrl_withReplyEvent, "v@:@@");
  82. addMethod (@selector (applicationShouldTerminate:), applicationShouldTerminate, "I@:@");
  83. addMethod (@selector (applicationWillTerminate:), applicationWillTerminate, "v@:@");
  84. addMethod (@selector (application:openFile:), application_openFile, "c@:@@");
  85. addMethod (@selector (application:openFiles:), application_openFiles, "v@:@@");
  86. addMethod (@selector (applicationDidBecomeActive:), applicationDidBecomeActive, "v@:@");
  87. addMethod (@selector (applicationDidResignActive:), applicationDidResignActive, "v@:@");
  88. addMethod (@selector (applicationWillUnhide:), applicationWillUnhide, "v@:@");
  89. addMethod (@selector (broadcastMessageCallback:), broadcastMessageCallback, "v@:@");
  90. addMethod (@selector (mainMenuTrackingBegan:), mainMenuTrackingBegan, "v@:@");
  91. addMethod (@selector (mainMenuTrackingEnded:), mainMenuTrackingEnded, "v@:@");
  92. addMethod (@selector (dummyMethod), dummyMethod, "v@:");
  93. registerClass();
  94. }
  95. private:
  96. static void applicationWillFinishLaunching (id self, SEL, NSApplication*, NSNotification*)
  97. {
  98. [[NSAppleEventManager sharedAppleEventManager] setEventHandler: self
  99. andSelector: @selector (getUrl:withReplyEvent:)
  100. forEventClass: kInternetEventClass
  101. andEventID: kAEGetURL];
  102. }
  103. static NSApplicationTerminateReply applicationShouldTerminate (id /*self*/, SEL, NSApplication*)
  104. {
  105. if (auto* app = JUCEApplicationBase::getInstance())
  106. {
  107. app->systemRequestedQuit();
  108. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  109. return NSTerminateCancel;
  110. }
  111. return NSTerminateNow;
  112. }
  113. static void applicationWillTerminate (id /*self*/, SEL, NSNotification*)
  114. {
  115. JUCEApplicationBase::appWillTerminateByForce();
  116. }
  117. static BOOL application_openFile (id /*self*/, SEL, NSApplication*, NSString* filename)
  118. {
  119. if (auto* app = JUCEApplicationBase::getInstance())
  120. {
  121. app->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  122. return YES;
  123. }
  124. return NO;
  125. }
  126. static void application_openFiles (id /*self*/, SEL, NSApplication*, NSArray* filenames)
  127. {
  128. if (auto* app = JUCEApplicationBase::getInstance())
  129. {
  130. StringArray files;
  131. for (NSString* f in filenames)
  132. files.add (quotedIfContainsSpaces (f));
  133. if (files.size() > 0)
  134. app->anotherInstanceStarted (files.joinIntoString (" "));
  135. }
  136. }
  137. static void applicationDidBecomeActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  138. static void applicationDidResignActive (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  139. static void applicationWillUnhide (id /*self*/, SEL, NSNotification*) { focusChanged(); }
  140. static void broadcastMessageCallback (id /*self*/, SEL, NSNotification* n)
  141. {
  142. NSDictionary* dict = (NSDictionary*) [n userInfo];
  143. const String messageString (nsStringToJuce ((NSString*) [dict valueForKey: nsStringLiteral ("message")]));
  144. MessageManager::getInstance()->deliverBroadcastMessage (messageString);
  145. }
  146. static void mainMenuTrackingBegan (id /*self*/, SEL, NSNotification*)
  147. {
  148. if (menuTrackingChangedCallback != nullptr)
  149. (*menuTrackingChangedCallback) (true);
  150. }
  151. static void mainMenuTrackingEnded (id /*self*/, SEL, NSNotification*)
  152. {
  153. if (menuTrackingChangedCallback != nullptr)
  154. (*menuTrackingChangedCallback) (false);
  155. }
  156. static void dummyMethod (id /*self*/, SEL) {} // (used as a way of running a dummy thread)
  157. static void focusChanged()
  158. {
  159. if (appFocusChangeCallback != nullptr)
  160. (*appFocusChangeCallback)();
  161. }
  162. static void getUrl_withReplyEvent (id /*self*/, SEL, NSAppleEventDescriptor* event, NSAppleEventDescriptor*)
  163. {
  164. if (auto* app = JUCEApplicationBase::getInstance())
  165. app->anotherInstanceStarted (quotedIfContainsSpaces ([[event paramDescriptorForKeyword: keyDirectObject] stringValue]));
  166. }
  167. static String quotedIfContainsSpaces (NSString* file)
  168. {
  169. String s (nsStringToJuce (file));
  170. if (s.containsChar (' '))
  171. s = s.quoted ('"');
  172. return s;
  173. }
  174. };
  175. };
  176. //==============================================================================
  177. void MessageManager::runDispatchLoop()
  178. {
  179. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  180. {
  181. JUCE_AUTORELEASEPOOL
  182. {
  183. // must only be called by the message thread!
  184. jassert (isThisTheMessageThread());
  185. #if JUCE_PROJUCER_LIVE_BUILD
  186. runDispatchLoopUntil (std::numeric_limits<int>::max());
  187. #else
  188. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  189. @try
  190. {
  191. [NSApp run];
  192. }
  193. @catch (NSException* e)
  194. {
  195. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  196. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  197. JUCEApplicationBase::sendUnhandledException (&ex, __FILE__, __LINE__);
  198. }
  199. @finally
  200. {
  201. }
  202. #else
  203. [NSApp run];
  204. #endif
  205. #endif
  206. }
  207. }
  208. }
  209. static void shutdownNSApp()
  210. {
  211. [NSApp stop: nil];
  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: NSEventMaskAny
  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. }
  274. void MessageManager::doPlatformSpecificShutdown()
  275. {
  276. delete appDelegate;
  277. appDelegate = nullptr;
  278. }
  279. bool MessageManager::postMessageToSystemQueue (MessageBase* message)
  280. {
  281. jassert (appDelegate != nil);
  282. appDelegate->messageQueue.post (message);
  283. return true;
  284. }
  285. void MessageManager::broadcastMessage (const String& message)
  286. {
  287. NSDictionary* info = [NSDictionary dictionaryWithObject: juceStringToNS (message)
  288. forKey: nsStringLiteral ("message")];
  289. [[NSDistributedNotificationCenter defaultCenter] postNotificationName: AppDelegate::getBroadcastEventName()
  290. object: nil
  291. userInfo: info];
  292. }
  293. // Special function used by some plugin classes to re-post carbon events
  294. void __attribute__ ((visibility("default"))) repostCurrentNSEvent();
  295. void __attribute__ ((visibility("default"))) repostCurrentNSEvent()
  296. {
  297. struct EventReposter : public CallbackMessage
  298. {
  299. EventReposter() : e ([[NSApp currentEvent] retain]) {}
  300. ~EventReposter() { [e release]; }
  301. void messageCallback() override
  302. {
  303. [NSApp postEvent: e atStart: YES];
  304. }
  305. NSEvent* e;
  306. };
  307. (new EventReposter())->post();
  308. }
  309. //==============================================================================
  310. #if JUCE_MAC
  311. struct MountedVolumeListChangeDetector::Pimpl
  312. {
  313. Pimpl (MountedVolumeListChangeDetector& d) : owner (d)
  314. {
  315. static ObserverClass cls;
  316. delegate = [cls.createInstance() init];
  317. ObserverClass::setOwner (delegate, this);
  318. NSNotificationCenter* nc = [[NSWorkspace sharedWorkspace] notificationCenter];
  319. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidMountNotification object: nil];
  320. [nc addObserver: delegate selector: @selector (changed:) name: NSWorkspaceDidUnmountNotification object: nil];
  321. }
  322. ~Pimpl()
  323. {
  324. [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: delegate];
  325. [delegate release];
  326. }
  327. private:
  328. MountedVolumeListChangeDetector& owner;
  329. id delegate;
  330. struct ObserverClass : public ObjCClass<NSObject>
  331. {
  332. ObserverClass() : ObjCClass<NSObject> ("JUCEDriveObserver_")
  333. {
  334. addIvar<Pimpl*> ("owner");
  335. addMethod (@selector (changed:), changed, "v@:@");
  336. addProtocol (@protocol (NSTextInput));
  337. registerClass();
  338. }
  339. static Pimpl* getOwner (id self) { return getIvar<Pimpl*> (self, "owner"); }
  340. static void setOwner (id self, Pimpl* owner) { object_setInstanceVariable (self, "owner", owner); }
  341. static void changed (id self, SEL, NSNotification*)
  342. {
  343. getOwner (self)->owner.mountedVolumeListChanged();
  344. }
  345. };
  346. };
  347. MountedVolumeListChangeDetector::MountedVolumeListChangeDetector() { pimpl = new Pimpl (*this); }
  348. MountedVolumeListChangeDetector::~MountedVolumeListChangeDetector() {}
  349. #endif