Fix typo in 9b54bd30006c008b4a951331b273613d5bac3abf
[pm.git] / toolkit / xre / MacApplicationDelegate.mm
blob85e98691e81dd8d196e62762256979aef0788ae4
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>
16 #include "nsCOMPtr.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"
27 #include "nsIFile.h"
28 #include "nsDirectoryServiceDefs.h"
29 #include "nsICommandLineRunner.h"
30 #include "nsIMacDockSupport.h"
31 #include "nsIStandaloneNativeMenu.h"
32 #include "nsILocalFileMac.h"
33 #include "nsString.h"
34 #include "nsCommandLineServiceMac.h"
36 class AutoAutoreleasePool {
37 public:
38   AutoAutoreleasePool()
39   {
40     mLocalPool = [[NSAutoreleasePool alloc] init];
41   }
42   ~AutoAutoreleasePool()
43   {
44     [mLocalPool release];
45   }
46 private:
47   NSAutoreleasePool *mLocalPool;
50 @interface MacApplicationDelegate : NSObject<NSApplicationDelegate>
54 @end
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.
62 void
63 EnsureUseCocoaDockAPI()
65   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
67   [GoannaNSApplication sharedApplication];
69   NS_OBJC_END_TRY_ABORT_BLOCK;
72 void
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
103 // are processed.
104 void
105 ProcessPendingGetURLAppleEvents()
107   AutoAutoreleasePool pool;
108   bool keepSpinning = true;
109   while (keepSpinning) {
110     sProcessedGetURLEvent = false;
111     NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask
112                                         untilDate:nil
113                                            inMode:NSDefaultRunLoopMode
114                                           dequeue:YES];
115     if (event)
116       [NSApp sendEvent:event];
117     keepSpinning = sProcessedGetURLEvent;
118   }
121 @implementation MacApplicationDelegate
123 - (id)init
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:)
137              forEventClass:'WWW!'
138                 andEventID:'OURL'];
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];
151     }
152   }
153   return self;
155   NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(nil);
158 - (void)dealloc
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];
166   [super dealloc];
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.
184   return NO;
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];
194   if (!url)
195     return NO;
197   NSString *urlString = [url absoluteString];
198   if (!urlString)
199     return NO;
201   // Add the URL to any command line we're currently setting up.
202   if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
203     return YES;
205   nsCOMPtr<nsILocalFileMac> inFile;
206   nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile));
207   if (NS_FAILED(rv))
208     return NO;
210   nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
211   if (!cmdLine) {
212     NS_ERROR("Couldn't create command line!");
213     return NO;
214   }
216   nsCString filePath;
217   rv = inFile->GetNativePath(filePath);
218   if (NS_FAILED(rv))
219     return NO;
221   nsCOMPtr<nsIFile> workingDir;
222   rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
223   if (NS_FAILED(rv))
224     return NO;
226   const char *argv[3] = {nullptr, "-file", filePath.get()};
227   rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
228   if (NS_FAILED(rv))
229     return NO;
231   if (NS_SUCCEEDED(cmdLine->Run()))
232     return YES;
234   return NO;
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
244   return NO;
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
257   // dock menu items.
258   nsresult rv;
259   nsCOMPtr<nsIMacDockSupport> dockSupport = do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
260   if (NS_FAILED(rv) || !dockSupport)
261     return menu;
263   nsCOMPtr<nsIStandaloneNativeMenu> dockMenu;
264   rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenu));
265   if (NS_FAILED(rv) || !dockMenu)
266     return menu;
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)
273     return menu;
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)
279     return menu;
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];
291       [itemCopy release];
292     }
293   }
295   return menu;
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");
306   if (!obsServ)
307     return NSTerminateNow;
309   nsCOMPtr<nsISupportsPRBool> cancelQuit =
310            do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
311   if (!cancelQuit)
312     return NSTerminateNow;
314   cancelQuit->SetData(false);
315   obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nullptr);
317   bool abortQuit;
318   cancelQuit->GetData(&abortQuit);
319   if (abortQuit)
320     return NSTerminateCancel;
322   nsCOMPtr<nsIAppStartup> appService =
323            do_GetService("@mozilla.org/toolkit/app-startup;1");
324   if (appService)
325     appService->Quit(nsIAppStartup::eForceQuit);
327   return NSTerminateNow;
330 - (void)handleAppleEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
332   if (!event)
333     return;
335   AutoAutoreleasePool pool;
337   bool isGetURLEvent =
338     ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL);
339   if (isGetURLEvent)
340     sProcessedGetURLEvent = true;
342   if (isGetURLEvent ||
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];
348     if (!schemeString ||
349         [schemeString compare:@"chrome"
350                       options:NSCaseInsensitiveSearch
351                         range:NSMakeRange(0, [schemeString length])] == NSOrderedSame) {
352       return;
353     }
355     // Add the URL to any command line we're currently setting up.
356     if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
357       return;
359     nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
360     if (!cmdLine) {
361       NS_ERROR("Couldn't create command line!");
362       return;
363     }
364     nsCOMPtr<nsIFile> workingDir;
365     nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
366     if (NS_FAILED(rv))
367       return;
368     const char *argv[3] = {nullptr, "-url", [urlString UTF8String]};
369     rv = cmdLine->Init(3, argv, workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
370     if (NS_FAILED(rv))
371       return;
372     rv = cmdLine->Run();
373   }
374   else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) {
375     NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject];
376     if (!fileListDescriptor)
377       return;
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];
383       if (!urlString)
384         continue;
386       // We need a path, not a URL
387       NSURL* url = [NSURL URLWithString:urlString];
388       if (!url)
389         continue;
391       [self application:NSApp openFile:[url path]];
392     }
393   }
396 @end