1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 // NSApplication delegate for Mac OS X Cocoa API.
8 // As of 10.4 Tiger, the system can send six kinds of Apple Events to an application;
9 // a well-behaved XUL app should have some kind of handling for all of them.
12 // http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html
15 #import <Cocoa/Cocoa.h>
16 #include "NativeMenuMac.h"
17 #import <Carbon/Carbon.h>
20 #include "nsINativeAppSupport.h"
21 #include "nsAppRunner.h"
22 #include "nsAppShell.h"
23 #include "nsComponentManagerUtils.h"
24 #include "nsServiceManagerUtils.h"
25 #include "nsIAppStartup.h"
26 #include "nsIObserverService.h"
27 #include "nsISupportsPrimitives.h"
28 #include "nsObjCExceptions.h"
30 #include "nsDirectoryServiceDefs.h"
31 #include "nsCommandLine.h"
32 #include "nsIMacDockSupport.h"
33 #include "nsIStandaloneNativeMenu.h"
34 #include "nsILocalFileMac.h"
36 #include "nsCommandLineServiceMac.h"
37 #include "nsCommandLine.h"
38 #include "nsStandaloneNativeMenu.h"
40 class AutoAutoreleasePool {
42 AutoAutoreleasePool() { mLocalPool = [[NSAutoreleasePool alloc] init]; }
43 ~AutoAutoreleasePool() { [mLocalPool release]; }
46 NSAutoreleasePool* mLocalPool;
49 @interface MacApplicationDelegate : NSObject <NSApplicationDelegate> {
54 static bool sProcessedGetURLEvent = false;
56 // Methods that can be called from non-Objective-C code.
58 // This is needed, on relaunch, to force the OS to use the "Cocoa Dock API"
59 // instead of the "Carbon Dock API". For more info see bmo bug 377166.
60 void EnsureUseCocoaDockAPI() {
61 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
63 [GeckoNSApplication sharedApplication];
65 NS_OBJC_END_TRY_IGNORE_BLOCK;
68 void DisableAppNap() {
69 // Prevent the parent process from entering App Nap. macOS does not put our
70 // child processes into App Nap and, as a result, when the parent is in
71 // App Nap, child processes continue to run normally generating IPC messages
72 // for the parent which can end up being queued. This can cause the browser
73 // to be unresponsive for a period of time after the App Nap until the parent
74 // process "catches up." NSAppSleepDisabled has to be set early during
75 // startup before the OS reads the value for the process.
76 [[NSUserDefaults standardUserDefaults] registerDefaults:@{
77 @"NSAppSleepDisabled" : @YES,
81 void SetupMacApplicationDelegate() {
82 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
84 // this is called during startup, outside an event loop, and therefore
85 // needs an autorelease pool to avoid cocoa object leakage (bug 559075)
86 AutoAutoreleasePool pool;
88 // Ensure that ProcessPendingGetURLAppleEvents() doesn't regress bug 377166.
89 [GeckoNSApplication sharedApplication];
91 // This call makes it so that application:openFile: doesn't get bogus calls
92 // from Cocoa doing its own parsing of the argument string. And yes, we need
93 // to use a string with a boolean value in it. That's just how it works.
94 [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"];
96 // Create the delegate. This should be around for the lifetime of the app.
97 id<NSApplicationDelegate> delegate = [[MacApplicationDelegate alloc] init];
98 [[GeckoNSApplication sharedApplication] setDelegate:delegate];
100 NS_OBJC_END_TRY_IGNORE_BLOCK;
103 // Indirectly make the OS process any pending GetURL Apple events. This is
104 // done via _DPSNextEvent() (an undocumented AppKit function called from
105 // [NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]). Apple
106 // events are only processed if 'dequeue' is 'YES' -- so we need to call
107 // [NSApplication sendEvent:] on any event that gets returned. 'event' will
108 // never itself be an Apple event, and it may be 'nil' even when Apple events
110 void ProcessPendingGetURLAppleEvents() {
111 AutoAutoreleasePool pool;
112 bool keepSpinning = true;
113 while (keepSpinning) {
114 sProcessedGetURLEvent = false;
115 NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
117 inMode:NSDefaultRunLoopMode
119 if (event) [NSApp sendEvent:event];
120 keepSpinning = sProcessedGetURLEvent;
124 @implementation MacApplicationDelegate
127 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
129 if ((self = [super init])) {
130 NSAppleEventManager* aeMgr = [NSAppleEventManager sharedAppleEventManager];
132 [aeMgr setEventHandler:self
133 andSelector:@selector(handleAppleEvent:withReplyEvent:)
134 forEventClass:kInternetEventClass
135 andEventID:kAEGetURL];
137 [aeMgr setEventHandler:self
138 andSelector:@selector(handleAppleEvent:withReplyEvent:)
142 [aeMgr setEventHandler:self
143 andSelector:@selector(handleAppleEvent:withReplyEvent:)
144 forEventClass:kCoreEventClass
145 andEventID:kAEOpenDocuments];
147 if (![NSApp windowsMenu]) {
148 // If the application has a windows menu, it will keep it up to date and
149 // prepend the window list to the Dock menu automatically.
150 NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
151 [NSApp setWindowsMenu:windowsMenu];
152 [windowsMenu release];
157 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
161 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
163 NSAppleEventManager* aeMgr = [NSAppleEventManager sharedAppleEventManager];
164 [aeMgr removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
165 [aeMgr removeEventHandlerForEventClass:'WWW!' andEventID:'OURL'];
166 [aeMgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
169 NS_OBJC_END_TRY_IGNORE_BLOCK;
172 // The method that NSApplication calls upon a request to reopen, such as when
173 // the Dock icon is clicked and no windows are open. A "visible" window may be
174 // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'.
175 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp hasVisibleWindows:(BOOL)flag {
176 nsCOMPtr<nsINativeAppSupport> nas = NS_GetNativeAppSupport();
177 NS_ENSURE_TRUE(nas, NO);
179 // Go to the common Carbon/Cocoa reopen method.
180 nsresult rv = nas->ReOpen();
181 NS_ENSURE_SUCCESS(rv, NO);
183 // NO says we don't want NSApplication to do anything else for us.
187 // The method that NSApplication calls when documents are requested to be opened.
188 // It will be called once for each selected document.
189 - (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename {
190 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
192 NSURL* url = [NSURL fileURLWithPath:filename];
195 NSString* urlString = [url absoluteString];
196 if (!urlString) return NO;
198 // Add the URL to any command line we're currently setting up.
199 if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String])) return YES;
201 nsCOMPtr<nsILocalFileMac> inFile;
202 nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile));
203 if (NS_FAILED(rv)) return NO;
205 nsCOMPtr<nsICommandLineRunner> cmdLine(new nsCommandLine());
208 rv = inFile->GetNativePath(filePath);
209 if (NS_FAILED(rv)) return NO;
211 nsCOMPtr<nsIFile> workingDir;
212 rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
214 // Couldn't find a working dir. Uh oh. Good job cmdline::Init can cope.
215 workingDir = nullptr;
218 const char* argv[3] = {nullptr, "-file", filePath.get()};
219 rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
220 if (NS_FAILED(rv)) return NO;
222 if (NS_SUCCEEDED(cmdLine->Run())) return YES;
226 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
229 // The method that NSApplication calls when documents are requested to be printed
230 // from the Finder (under the "File" menu).
231 // It will be called once for each selected document.
232 - (BOOL)application:(NSApplication*)theApplication printFile:(NSString*)filename {
236 // Create the menu that shows up in the Dock.
237 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
238 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
240 // Create the NSMenu that will contain the dock menu items.
241 NSMenu* menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
242 [menu setAutoenablesItems:NO];
244 // Add application-specific dock menu items. On error, do not insert the
247 nsCOMPtr<nsIMacDockSupport> dockSupport =
248 do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
249 if (NS_FAILED(rv) || !dockSupport) return menu;
251 nsCOMPtr<nsIStandaloneNativeMenu> dockMenuInterface;
252 rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenuInterface));
253 if (NS_FAILED(rv) || !dockMenuInterface) return menu;
255 RefPtr<mozilla::widget::NativeMenuMac> dockMenu =
256 static_cast<nsStandaloneNativeMenu*>(dockMenuInterface.get())->GetNativeMenu();
258 // Give the menu the opportunity to update itself before display.
259 dockMenu->MenuWillOpen();
261 // Obtain a copy of the native menu.
262 NSMenu* nativeDockMenu = dockMenu->NativeNSMenu();
263 if (!nativeDockMenu) {
267 // Loop through the application-specific dock menu and insert its
268 // contents into the dock menu that we are building for Cocoa.
269 int numDockMenuItems = [nativeDockMenu numberOfItems];
270 if (numDockMenuItems > 0) {
271 if ([menu numberOfItems] > 0) [menu addItem:[NSMenuItem separatorItem]];
273 for (int i = 0; i < numDockMenuItems; i++) {
274 NSMenuItem* itemCopy = [[nativeDockMenu itemAtIndex:i] copy];
275 [menu addItem:itemCopy];
282 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
285 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
286 // We provide our own full screen menu item, so we don't want the OS providing
288 [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"NSFullScreenMenuItemEverywhere"];
291 // If we don't handle applicationShouldTerminate:, a call to [NSApp terminate:]
292 // (from the browser or from the OS) can result in an unclean shutdown.
293 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender {
294 nsCOMPtr<nsIObserverService> obsServ = do_GetService("@mozilla.org/observer-service;1");
295 if (!obsServ) return NSTerminateNow;
297 nsCOMPtr<nsISupportsPRBool> cancelQuit = do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
298 if (!cancelQuit) return NSTerminateNow;
300 cancelQuit->SetData(false);
301 obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nullptr);
304 cancelQuit->GetData(&abortQuit);
305 if (abortQuit) return NSTerminateCancel;
307 nsCOMPtr<nsIAppStartup> appService = do_GetService("@mozilla.org/toolkit/app-startup;1");
309 bool userAllowedQuit = true;
310 appService->Quit(nsIAppStartup::eForceQuit, 0, &userAllowedQuit);
311 if (!userAllowedQuit) {
312 return NSTerminateCancel;
316 return NSTerminateNow;
319 - (void)handleAppleEvent:(NSAppleEventDescriptor*)event
320 withReplyEvent:(NSAppleEventDescriptor*)replyEvent {
323 AutoAutoreleasePool pool;
325 bool isGetURLEvent = ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL);
326 if (isGetURLEvent) sProcessedGetURLEvent = true;
328 if (isGetURLEvent || ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) {
329 NSString* urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
330 NSURL* url = [NSURL URLWithString:urlString];
333 } else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) {
334 NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject];
335 if (!fileListDescriptor) return;
337 // Descriptor list indexing is one-based...
338 NSInteger numberOfFiles = [fileListDescriptor numberOfItems];
339 for (NSInteger i = 1; i <= numberOfFiles; i++) {
340 NSString* urlString = [[fileListDescriptor descriptorAtIndex:i] stringValue];
341 if (!urlString) continue;
343 // We need a path, not a URL
344 NSURL* url = [NSURL URLWithString:urlString];
347 [self application:NSApp openFile:[url path]];
352 - (BOOL)application:(NSApplication*)application
353 willContinueUserActivityWithType:(NSString*)userActivityType {
354 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
357 - (BOOL)application:(NSApplication*)application
358 continueUserActivity:(NSUserActivity*)userActivity
359 #if defined(MAC_OS_X_VERSION_10_14) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_14
360 restorationHandler:(void (^)(NSArray<id<NSUserActivityRestoring>>*))restorationHandler {
362 restorationHandler:(void (^)(NSArray*))restorationHandler {
364 if (![userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
368 return [self openURL:userActivity.webpageURL];
371 - (void)application:(NSApplication*)application
372 didFailToContinueUserActivityWithType:(NSString*)userActivityType
373 error:(NSError*)error {
374 NSLog(@"Failed to continue user activity %@: %@", userActivityType, error);
377 - (BOOL)openURL:(NSURL*)url {
378 if (!url || !url.scheme || [url.scheme caseInsensitiveCompare:@"chrome"] == NSOrderedSame) {
382 const char* const urlString = [[url absoluteString] UTF8String];
383 // Add the URL to any command line we're currently setting up.
384 if (CommandLineServiceMac::AddURLToCurrentCommandLine(urlString)) {
388 nsCOMPtr<nsICommandLineRunner> cmdLine(new nsCommandLine());
389 nsCOMPtr<nsIFile> workingDir;
390 nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
392 // Couldn't find a working dir. Uh oh. Good job cmdline::Init can cope.
393 workingDir = nullptr;
396 const char* argv[3] = {nullptr, "-url", urlString};
397 rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);