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
9 // application; a well-behaved XUL app should have some kind of handling for all
13 // http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html
16 #include <AppKit/AppKit.h>
17 #import <Cocoa/Cocoa.h>
18 #include "NativeMenuMac.h"
19 #import <Carbon/Carbon.h>
21 #include "CustomCocoaEvents.h"
22 #include "gfxPlatform.h"
24 #include "nsINativeAppSupport.h"
25 #include "nsAppRunner.h"
26 #include "nsAppShell.h"
27 #include "nsComponentManagerUtils.h"
28 #include "nsServiceManagerUtils.h"
29 #include "nsIAppStartup.h"
30 #include "nsIObserverService.h"
31 #include "nsISupportsPrimitives.h"
32 #include "nsObjCExceptions.h"
34 #include "nsDirectoryServiceDefs.h"
35 #include "nsCommandLine.h"
36 #include "nsIMacDockSupport.h"
37 #include "nsIStandaloneNativeMenu.h"
38 #include "nsILocalFileMac.h"
40 #include "nsCommandLineServiceMac.h"
41 #include "nsCommandLine.h"
42 #include "nsStandaloneNativeMenu.h"
43 #include "nsCocoaUtils.h"
44 #include "nsMenuBarX.h"
45 #include "mozilla/NeverDestroyed.h"
47 class AutoAutoreleasePool {
49 AutoAutoreleasePool() { mLocalPool = [[NSAutoreleasePool alloc] init]; }
50 ~AutoAutoreleasePool() { [mLocalPool release]; }
53 NSAutoreleasePool* mLocalPool;
56 @interface MacApplicationDelegate : NSObject <NSApplicationDelegate> {
59 // This is used as a workaround for bug 1478347 in order to make OS-provided
60 // menu items such as the emoji picker available in the Edit menu, especially
61 // in multi-language environments.
62 - (IBAction)copy:(id)aSender;
66 enum class LaunchStatus {
73 static LaunchStatus sLaunchStatus = LaunchStatus::Initial;
75 static nsTArray<nsCString>& StartupURLs() {
76 static mozilla::NeverDestroyed<nsTArray<nsCString>> sStartupURLs;
80 // Methods that can be called from non-Objective-C code.
82 // This is needed, on relaunch, to force the OS to use the "Cocoa Dock API"
83 // instead of the "Carbon Dock API". For more info see bmo bug 377166.
84 void EnsureUseCocoaDockAPI() {
85 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
87 [GeckoNSApplication sharedApplication];
89 NS_OBJC_END_TRY_IGNORE_BLOCK;
92 void DisableAppNap() {
93 // Prevent the parent process from entering App Nap. macOS does not put our
94 // child processes into App Nap and, as a result, when the parent is in
95 // App Nap, child processes continue to run normally generating IPC messages
96 // for the parent which can end up being queued. This can cause the browser
97 // to be unresponsive for a period of time after the App Nap until the parent
98 // process "catches up." NSAppSleepDisabled has to be set early during
99 // startup before the OS reads the value for the process.
100 [[NSUserDefaults standardUserDefaults] registerDefaults:@{
101 @"NSAppSleepDisabled" : @YES,
105 void SetupMacApplicationDelegate(bool* gRestartedByOS) {
106 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
108 // this is called during startup, outside an event loop, and therefore
109 // needs an autorelease pool to avoid cocoa object leakage (bug 559075)
110 AutoAutoreleasePool pool;
112 // Ensure that InitializeMacApp() doesn't regress bug 377166.
113 [GeckoNSApplication sharedApplication];
115 // This call makes it so that application:openFile: doesn't get bogus calls
116 // from Cocoa doing its own parsing of the argument string. And yes, we need
117 // to use a string with a boolean value in it. That's just how it works.
118 [[NSUserDefaults standardUserDefaults]
120 forKey:@"NSTreatUnknownArgumentsAsOpen"];
122 // Create the delegate. This should be around for the lifetime of the app.
123 id<NSApplicationDelegate> delegate = [[MacApplicationDelegate alloc] init];
124 [[GeckoNSApplication sharedApplication] setDelegate:delegate];
126 *gRestartedByOS = !!nsCocoaUtils::ShouldRestoreStateDueToLaunchAtLogin();
129 sLaunchStatus == LaunchStatus::Initial,
130 "Launch status should be in intial state when setting up delegate");
131 sLaunchStatus = LaunchStatus::DelegateIsSetup;
133 NS_OBJC_END_TRY_IGNORE_BLOCK;
136 // Run the mac app and stop it immediately after launch. This allows us to
137 // (a) Initialize accessibility early enough for modals that appear before
138 // the main app and nest their own event loop to be accessible.
139 // (b) Collect URLs that were provided to the app at open time.
140 void InitializeMacApp() {
141 if (sLaunchStatus != LaunchStatus::DelegateIsSetup) {
142 // Delegate has not been set up or NSApp has been launched already.
146 sLaunchStatus = LaunchStatus::CollectingURLs;
147 if (!gfxPlatform::IsHeadless()) {
150 sLaunchStatus = LaunchStatus::CollectedURLs;
153 nsTArray<nsCString> TakeStartupURLs() { return std::move(StartupURLs()); }
155 @implementation MacApplicationDelegate
157 - (IBAction)copy:(id)aSender {
158 [nsMenuBarX::sNativeEventTarget menuItemHit:aSender];
162 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
164 if ((self = [super init])) {
165 if (![NSApp windowsMenu]) {
166 // If the application has a windows menu, it will keep it up to date and
167 // prepend the window list to the Dock menu automatically.
168 NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
169 [NSApp setWindowsMenu:windowsMenu];
170 [windowsMenu release];
175 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
178 // The method that NSApplication calls upon a request to reopen, such as when
179 // the Dock icon is clicked and no windows are open. A "visible" window may be
180 // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'.
181 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp
182 hasVisibleWindows:(BOOL)flag {
183 nsCOMPtr<nsINativeAppSupport> nas = NS_GetNativeAppSupport();
184 NS_ENSURE_TRUE(nas, NO);
186 // Go to the common Carbon/Cocoa reopen method.
187 nsresult rv = nas->ReOpen();
188 NS_ENSURE_SUCCESS(rv, NO);
190 // NO says we don't want NSApplication to do anything else for us.
194 // The method that NSApplication calls when documents are requested to be
195 // printed from the Finder (under the "File" menu). It will be called once for
196 // each selected document.
197 - (BOOL)application:(NSApplication*)theApplication
198 printFile:(NSString*)filename {
202 // The method that NSApplication calls for using secure state restoration.
203 - (BOOL)applicationSupportsSecureRestorableState:(NSApplication*)app {
207 // Create the menu that shows up in the Dock.
208 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
209 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
211 // Create the NSMenu that will contain the dock menu items.
212 NSMenu* menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
213 [menu setAutoenablesItems:NO];
215 // Add application-specific dock menu items. On error, do not insert the
218 nsCOMPtr<nsIMacDockSupport> dockSupport =
219 do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
220 if (NS_FAILED(rv) || !dockSupport) return menu;
222 nsCOMPtr<nsIStandaloneNativeMenu> dockMenuInterface;
223 rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenuInterface));
224 if (NS_FAILED(rv) || !dockMenuInterface) return menu;
226 RefPtr<mozilla::widget::NativeMenuMac> dockMenu =
227 static_cast<nsStandaloneNativeMenu*>(dockMenuInterface.get())
230 // Give the menu the opportunity to update itself before display.
231 dockMenu->MenuWillOpen();
233 // Obtain a copy of the native menu.
234 NSMenu* nativeDockMenu = dockMenu->NativeNSMenu();
235 if (!nativeDockMenu) {
239 // Loop through the application-specific dock menu and insert its
240 // contents into the dock menu that we are building for Cocoa.
241 int numDockMenuItems = [nativeDockMenu numberOfItems];
242 if (numDockMenuItems > 0) {
243 if ([menu numberOfItems] > 0) [menu addItem:[NSMenuItem separatorItem]];
245 for (int i = 0; i < numDockMenuItems; i++) {
246 NSMenuItem* itemCopy = [[nativeDockMenu itemAtIndex:i] copy];
247 [menu addItem:itemCopy];
254 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
257 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
258 // We provide our own full screen menu item, so we don't want the OS providing
260 [[NSUserDefaults standardUserDefaults]
262 forKey:@"NSFullScreenMenuItemEverywhere"];
265 - (void)applicationDidFinishLaunching:(NSNotification*)notification {
266 if (sLaunchStatus == LaunchStatus::CollectingURLs) {
267 // We are in an inner `run` loop that we are spinning in order to get
268 // URLs that were requested while launching. `application:openURLs:` will
269 // have been called by this point and we will have finished reconstructing
270 // the command line. We now stop the app loop for the rest of startup to be
271 // processed and will call `run` again when the main event loop should
275 // Send a bogus event so that the internal "app stopped" flag is processed.
276 // Since we aren't calling this from a responder, we need to post an event
277 // to have the loop iterate and respond to the stopped flag.
278 [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
279 location:NSMakePoint(0, 0)
284 subtype:kEventSubtypeNone
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:
294 (NSApplication*)sender {
295 nsCOMPtr<nsIObserverService> obsServ =
296 do_GetService("@mozilla.org/observer-service;1");
297 if (!obsServ) return NSTerminateNow;
299 nsCOMPtr<nsISupportsPRBool> cancelQuit =
300 do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
301 if (!cancelQuit) return NSTerminateNow;
303 cancelQuit->SetData(false);
304 obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nullptr);
307 cancelQuit->GetData(&abortQuit);
308 if (abortQuit) return NSTerminateCancel;
310 nsCOMPtr<nsIAppStartup> appService =
311 do_GetService("@mozilla.org/toolkit/app-startup;1");
313 bool userAllowedQuit = true;
314 appService->Quit(nsIAppStartup::eForceQuit, 0, &userAllowedQuit);
315 if (!userAllowedQuit) {
316 return NSTerminateCancel;
320 return NSTerminateNow;
323 - (void)application:(NSApplication*)application
324 openURLs:(NSArray<NSURL*>*)urls {
325 [self openURLs:urls];
328 - (BOOL)application:(NSApplication*)application
329 willContinueUserActivityWithType:(NSString*)userActivityType {
330 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
333 - (BOOL)application:(NSApplication*)application
334 continueUserActivity:(NSUserActivity*)userActivity
336 (void (^)(NSArray<id<NSUserActivityRestoring>>*))restorationHandler {
337 if (![userActivity.activityType
338 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
342 return [self openURLs:@[ userActivity.webpageURL ]];
345 - (void)application:(NSApplication*)application
346 didFailToContinueUserActivityWithType:(NSString*)userActivityType
347 error:(NSError*)error {
348 NSLog(@"Failed to continue user activity %@: %@", userActivityType, error);
351 - (BOOL)openURLs:(NSArray<NSURL*>*)urls {
352 nsTArray<const char*> args([urls count] * 2 + 2);
353 // Placeholder for unused program name.
354 args.AppendElement(nullptr);
356 for (NSURL* url in urls) {
357 if (!url || !url.scheme ||
358 [url.scheme caseInsensitiveCompare:@"chrome"] == NSOrderedSame) {
362 const char* const urlString = [[url absoluteString] UTF8String];
363 if (sLaunchStatus == LaunchStatus::CollectingURLs) {
364 StartupURLs().AppendElement(urlString);
368 args.AppendElement("-url");
369 args.AppendElement(urlString);
372 if (args.Length() <= 1) {
373 // No URLs were added to the command line.
377 nsCOMPtr<nsICommandLineRunner> cmdLine(new nsCommandLine());
378 nsCOMPtr<nsIFile> workingDir;
379 nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR,
380 getter_AddRefs(workingDir));
382 // Couldn't find a working dir. Uh oh. Good job cmdline::Init can cope.
383 workingDir = nullptr;
386 rv = cmdLine->Init(args.Length(), args.Elements(), workingDir,
387 nsICommandLine::STATE_REMOTE_EXPLICIT);