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.
11 // See http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html for details.
13 #import <Cocoa/Cocoa.h>
14 #import <Carbon/Carbon.h>
17 #include "nsINativeAppSupport.h"
18 #include "nsAppRunner.h"
19 #include "nsAppShell.h"
20 #include "nsComponentManagerUtils.h"
21 #include "nsIServiceManager.h"
22 #include "nsServiceManagerUtils.h"
23 #include "nsIAppStartup.h"
24 #include "nsIObserverService.h"
25 #include "nsISupportsPrimitives.h"
26 #include "nsObjCExceptions.h"
28 #include "nsDirectoryServiceDefs.h"
29 #include "nsICommandLineRunner.h"
30 #include "nsIMacDockSupport.h"
31 #include "nsIStandaloneNativeMenu.h"
32 #include "nsILocalFileMac.h"
34 #include "nsCommandLineServiceMac.h"
36 class AutoAutoreleasePool {
40 mLocalPool = [[NSAutoreleasePool alloc] init];
42 ~AutoAutoreleasePool()
47 NSAutoreleasePool *mLocalPool;
50 @interface MacApplicationDelegate : NSObject<NSApplicationDelegate>
56 static bool sProcessedGetURLEvent = false;
58 // Methods that can be called from non-Objective-C code.
60 // This is needed, on relaunch, to force the OS to use the "Cocoa Dock API"
61 // instead of the "Carbon Dock API". For more info see bmo bug 377166.
63 EnsureUseCocoaDockAPI()
65 NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
67 [GoannaNSApplication sharedApplication];
69 NS_OBJC_END_TRY_ABORT_BLOCK;
73 SetupMacApplicationDelegate()
75 NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
77 // this is called during startup, outside an event loop, and therefore
78 // needs an autorelease pool to avoid cocoa object leakage (bug 559075)
79 AutoAutoreleasePool pool;
81 // Ensure that ProcessPendingGetURLAppleEvents() doesn't regress bug 377166.
82 [GoannaNSApplication sharedApplication];
84 // This call makes it so that application:openFile: doesn't get bogus calls
85 // from Cocoa doing its own parsing of the argument string. And yes, we need
86 // to use a string with a boolean value in it. That's just how it works.
87 [[NSUserDefaults standardUserDefaults] setObject:@"NO"
88 forKey:@"NSTreatUnknownArgumentsAsOpen"];
90 // Create the delegate. This should be around for the lifetime of the app.
91 id<NSApplicationDelegate> delegate = [[MacApplicationDelegate alloc] init];
92 [[GoannaNSApplication sharedApplication] setDelegate:delegate];
94 NS_OBJC_END_TRY_ABORT_BLOCK;
97 // Indirectly make the OS process any pending GetURL Apple events. This is
98 // done via _DPSNextEvent() (an undocumented AppKit function called from
99 // [NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]). Apple
100 // events are only processed if 'dequeue' is 'YES' -- so we need to call
101 // [NSApplication sendEvent:] on any event that gets returned. 'event' will
102 // never itself be an Apple event, and it may be 'nil' even when Apple events
105 ProcessPendingGetURLAppleEvents()
107 AutoAutoreleasePool pool;
108 bool keepSpinning = true;
109 while (keepSpinning) {
110 sProcessedGetURLEvent = false;
111 NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask
113 inMode:NSDefaultRunLoopMode
116 [NSApp sendEvent:event];
117 keepSpinning = sProcessedGetURLEvent;
121 @implementation MacApplicationDelegate
125 NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
127 if ((self = [super init])) {
128 NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
130 [aeMgr setEventHandler:self
131 andSelector:@selector(handleAppleEvent:withReplyEvent:)
132 forEventClass:kInternetEventClass
133 andEventID:kAEGetURL];
135 [aeMgr setEventHandler:self
136 andSelector:@selector(handleAppleEvent:withReplyEvent:)
140 [aeMgr setEventHandler:self
141 andSelector:@selector(handleAppleEvent:withReplyEvent:)
142 forEventClass:kCoreEventClass
143 andEventID:kAEOpenDocuments];
145 if (![NSApp windowsMenu]) {
146 // If the application has a windows menu, it will keep it up to date and
147 // prepend the window list to the Dock menu automatically.
148 NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
149 [NSApp setWindowsMenu:windowsMenu];
150 [windowsMenu release];
155 NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(nil);
160 NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
162 NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
163 [aeMgr removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
164 [aeMgr removeEventHandlerForEventClass:'WWW!' andEventID:'OURL'];
165 [aeMgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
168 NS_OBJC_END_TRY_ABORT_BLOCK;
171 // The method that NSApplication calls upon a request to reopen, such as when
172 // the Dock icon is clicked and no windows are open. A "visible" window may be
173 // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'.
174 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp hasVisibleWindows:(BOOL)flag
176 nsCOMPtr<nsINativeAppSupport> nas = do_CreateInstance(NS_NATIVEAPPSUPPORT_CONTRACTID);
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
191 NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
193 NSURL *url = [NSURL fileURLWithPath:filename];
197 NSString *urlString = [url absoluteString];
201 // Add the URL to any command line we're currently setting up.
202 if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
205 nsCOMPtr<nsILocalFileMac> inFile;
206 nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile));
210 nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
212 NS_ERROR("Couldn't create command line!");
217 rv = inFile->GetNativePath(filePath);
221 nsCOMPtr<nsIFile> workingDir;
222 rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
226 const char *argv[3] = {nullptr, "-file", filePath.get()};
227 rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
231 if (NS_SUCCEEDED(cmdLine->Run()))
236 NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(NO);
239 // The method that NSApplication calls when documents are requested to be printed
240 // from the Finder (under the "File" menu).
241 // It will be called once for each selected document.
242 - (BOOL)application:(NSApplication*)theApplication printFile:(NSString*)filename
247 // Create the menu that shows up in the Dock.
248 - (NSMenu*)applicationDockMenu:(NSApplication*)sender
250 NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
252 // Create the NSMenu that will contain the dock menu items.
253 NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
254 [menu setAutoenablesItems:NO];
256 // Add application-specific dock menu items. On error, do not insert the
259 nsCOMPtr<nsIMacDockSupport> dockSupport = do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
260 if (NS_FAILED(rv) || !dockSupport)
263 nsCOMPtr<nsIStandaloneNativeMenu> dockMenu;
264 rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenu));
265 if (NS_FAILED(rv) || !dockMenu)
268 // Determine if the dock menu items should be displayed. This also gives
269 // the menu the opportunity to update itself before display.
270 bool shouldShowItems;
271 rv = dockMenu->MenuWillOpen(&shouldShowItems);
272 if (NS_FAILED(rv) || !shouldShowItems)
275 // Obtain a copy of the native menu.
276 NSMenu * nativeDockMenu;
277 rv = dockMenu->GetNativeMenu(reinterpret_cast<void **>(&nativeDockMenu));
278 if (NS_FAILED(rv) || !nativeDockMenu)
281 // Loop through the application-specific dock menu and insert its
282 // contents into the dock menu that we are building for Cocoa.
283 int numDockMenuItems = [nativeDockMenu numberOfItems];
284 if (numDockMenuItems > 0) {
285 if ([menu numberOfItems] > 0)
286 [menu addItem:[NSMenuItem separatorItem]];
288 for (int i = 0; i < numDockMenuItems; i++) {
289 NSMenuItem * itemCopy = [[nativeDockMenu itemAtIndex:i] copy];
290 [menu addItem:itemCopy];
297 NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
300 // If we don't handle applicationShouldTerminate:, a call to [NSApp terminate:]
301 // (from the browser or from the OS) can result in an unclean shutdown.
302 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
304 nsCOMPtr<nsIObserverService> obsServ =
305 do_GetService("@mozilla.org/observer-service;1");
307 return NSTerminateNow;
309 nsCOMPtr<nsISupportsPRBool> cancelQuit =
310 do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
312 return NSTerminateNow;
314 cancelQuit->SetData(false);
315 obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nullptr);
318 cancelQuit->GetData(&abortQuit);
320 return NSTerminateCancel;
322 nsCOMPtr<nsIAppStartup> appService =
323 do_GetService("@mozilla.org/toolkit/app-startup;1");
325 appService->Quit(nsIAppStartup::eForceQuit);
327 return NSTerminateNow;
330 - (void)handleAppleEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
335 AutoAutoreleasePool pool;
338 ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL);
340 sProcessedGetURLEvent = true;
343 ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) {
344 NSString* urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
346 // don't open chrome URLs
347 NSString* schemeString = [[NSURL URLWithString:urlString] scheme];
349 [schemeString compare:@"chrome"
350 options:NSCaseInsensitiveSearch
351 range:NSMakeRange(0, [schemeString length])] == NSOrderedSame) {
355 // Add the URL to any command line we're currently setting up.
356 if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
359 nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
361 NS_ERROR("Couldn't create command line!");
364 nsCOMPtr<nsIFile> workingDir;
365 nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
368 const char *argv[3] = {nullptr, "-url", [urlString UTF8String]};
369 rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
374 else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) {
375 NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject];
376 if (!fileListDescriptor)
379 // Descriptor list indexing is one-based...
380 NSInteger numberOfFiles = [fileListDescriptor numberOfItems];
381 for (NSInteger i = 1; i <= numberOfFiles; i++) {
382 NSString* urlString = [[fileListDescriptor descriptorAtIndex:i] stringValue];
386 // We need a path, not a URL
387 NSURL* url = [NSURL URLWithString:urlString];
391 [self application:NSApp openFile:[url path]];