bug 313956: expand installer .exe contents to make complete mar. r=ted.
[gecko.git] / toolkit / xre / MacApplicationDelegate.mm
blobea495d89f00c0ac4d300afdb49d09df55f0a0cd3
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4  *
5  * The contents of this file are subject to the Mozilla Public License Version
6  * 1.1 (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  * http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the
13  * License.
14  *
15  * The Original Code is the Mozilla XUL Toolkit.
16  *
17  * The Initial Developer of the Original Code is
18  * Mozilla Corporation.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * the Initial Developer. All Rights Reserved.
21  *
22  * Contributor(s):
23  *   Stan Shebs <shebs@mozilla.com>
24  *   Thomas K. Dyas <tom.dyas@gmail.com>
25  *
26  * Alternatively, the contents of this file may be used under the terms of
27  * either the GNU General Public License Version 2 or later (the "GPL"), or
28  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
29  * in which case the provisions of the GPL or the LGPL are applicable instead
30  * of those above. If you wish to allow use of your version of this file only
31  * under the terms of either the GPL or the LGPL, and not to allow others to
32  * use your version of this file under the terms of the MPL, indicate your
33  * decision by deleting the provisions above and replace them with the notice
34  * and other provisions required by the GPL or the LGPL. If you do not delete
35  * the provisions above, a recipient may use your version of this file under
36  * the terms of any one of the MPL, the GPL or the LGPL.
37  *
38  * ***** END LICENSE BLOCK ***** */
40 // NSApplication delegate for Mac OS X Cocoa API.
42 // As of 10.4 Tiger, the system can send six kinds of Apple Events to an application;
43 // a well-behaved XUL app should have some kind of handling for all of them.
45 // See http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html for details.
47 #import <Cocoa/Cocoa.h>
48 #import <Carbon/Carbon.h>
50 #include "nsCOMPtr.h"
51 #include "nsINativeAppSupport.h"
52 #include "nsAppRunner.h"
53 #include "nsComponentManagerUtils.h"
54 #include "nsIServiceManager.h"
55 #include "nsServiceManagerUtils.h"
56 #include "nsIAppStartup.h"
57 #include "nsIObserverService.h"
58 #include "nsISupportsPrimitives.h"
59 #include "nsObjCExceptions.h"
60 #include "nsIFile.h"
61 #include "nsDirectoryServiceDefs.h"
62 #include "nsICommandLineRunner.h"
63 #include "nsIMacDockSupport.h"
64 #include "nsIStandaloneNativeMenu.h"
65 #include "nsILocalFileMac.h"
66 #include "nsString.h"
67 #include "nsCommandLineServiceMac.h"
69 class AutoAutoreleasePool {
70 public:
71   AutoAutoreleasePool()
72   {
73     mLocalPool = [[NSAutoreleasePool alloc] init];
74   }
75   ~AutoAutoreleasePool()
76   {
77     [mLocalPool release];
78   }
79 private:
80   NSAutoreleasePool *mLocalPool;
83 @interface MacApplicationDelegate : NSObject
87 @end
89 static PRBool sProcessedGetURLEvent = PR_FALSE;
91 // Methods that can be called from non-Objective-C code.
93 // This is needed, on relaunch, to force the OS to use the "Cocoa Dock API"
94 // instead of the "Carbon Dock API".  For more info see bmo bug 377166.
95 void
96 EnsureUseCocoaDockAPI()
98   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
100   [NSApplication sharedApplication];
102   NS_OBJC_END_TRY_ABORT_BLOCK;
105 void
106 SetupMacApplicationDelegate()
108   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
110   // this is called during startup, outside an event loop, and therefore
111   // needs an autorelease pool to avoid cocoa object leakage (bug 559075)
112   AutoAutoreleasePool pool;
114   // Ensure that ProcessPendingGetURLAppleEvents() doesn't regress bug 377166.
115   [NSApplication sharedApplication];
117   // This call makes it so that application:openFile: doesn't get bogus calls
118   // from Cocoa doing its own parsing of the argument string. And yes, we need
119   // to use a string with a boolean value in it. That's just how it works.
120   [[NSUserDefaults standardUserDefaults] setObject:@"NO"
121                                             forKey:@"NSTreatUnknownArgumentsAsOpen"];
123   // Create the delegate. This should be around for the lifetime of the app.
124   MacApplicationDelegate *delegate = [[MacApplicationDelegate alloc] init];
125   [NSApp setDelegate:delegate];
127   NS_OBJC_END_TRY_ABORT_BLOCK;
130 // Indirectly make the OS process any pending GetURL Apple events.  This is
131 // done via _DPSNextEvent() (an undocumented AppKit function called from
132 // [NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]).  Apple
133 // events are only processed if 'dequeue' is 'YES' -- so we need to call
134 // [NSApplication sendEvent:] on any event that gets returned.  'event' will
135 // never itself be an Apple event, and it may be 'nil' even when Apple events
136 // are processed.
137 void
138 ProcessPendingGetURLAppleEvents()
140   AutoAutoreleasePool pool;
141   PRBool keepSpinning = PR_TRUE;
142   while (keepSpinning) {
143     sProcessedGetURLEvent = PR_FALSE;
144     NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask
145                                         untilDate:nil
146                                            inMode:NSDefaultRunLoopMode
147                                           dequeue:YES];
148     if (event)
149       [NSApp sendEvent:event];
150     keepSpinning = sProcessedGetURLEvent;
151   }
154 @implementation MacApplicationDelegate
156 - (id)init
158   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
160   if ((self = [super init])) {
161     NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
163     [aeMgr setEventHandler:self
164                andSelector:@selector(handleAppleEvent:withReplyEvent:)
165              forEventClass:kInternetEventClass
166                 andEventID:kAEGetURL];
168     [aeMgr setEventHandler:self
169                andSelector:@selector(handleAppleEvent:withReplyEvent:)
170              forEventClass:'WWW!'
171                 andEventID:'OURL'];
173     [aeMgr setEventHandler:self
174                andSelector:@selector(handleAppleEvent:withReplyEvent:)
175              forEventClass:kCoreEventClass
176                 andEventID:kAEOpenDocuments];
178     if (![NSApp windowsMenu]) {
179       // If the application has a windows menu, it will keep it up to date and
180       // prepend the window list to the Dock menu automatically.
181       NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
182       [NSApp setWindowsMenu:windowsMenu];
183       [windowsMenu release];
184     }
185   }
186   return self;
188   NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(nil);
191 - (void)dealloc
193   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
195   NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
196   [aeMgr removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
197   [aeMgr removeEventHandlerForEventClass:'WWW!' andEventID:'OURL'];
198   [aeMgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
199   [super dealloc];
201   NS_OBJC_END_TRY_ABORT_BLOCK;
204 // The method that NSApplication calls upon a request to reopen, such as when
205 // the Dock icon is clicked and no windows are open. A "visible" window may be
206 // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'.
207 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp hasVisibleWindows:(BOOL)flag
209   nsCOMPtr<nsINativeAppSupport> nas = do_CreateInstance(NS_NATIVEAPPSUPPORT_CONTRACTID);
210   NS_ENSURE_TRUE(nas, NO);
212   // Go to the common Carbon/Cocoa reopen method.
213   nsresult rv = nas->ReOpen();
214   NS_ENSURE_SUCCESS(rv, NO);
216   // NO says we don't want NSApplication to do anything else for us.
217   return NO;
220 // The method that NSApplication calls when documents are requested to be opened.
221 // It will be called once for each selected document.
222 - (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename
224   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
226   NSURL *url = [NSURL fileURLWithPath:filename];
227   if (!url)
228     return NO;
230   NSString *urlString = [url absoluteString];
231   if (!urlString)
232     return NO;
234   // Add the URL to any command line we're currently setting up.
235   if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
236     return YES;
238   nsCOMPtr<nsILocalFileMac> inFile;
239   nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, PR_TRUE, getter_AddRefs(inFile));
240   if (NS_FAILED(rv))
241     return NO;
243   nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
244   if (!cmdLine) {
245     NS_ERROR("Couldn't create command line!");
246     return NO;
247   }
249   nsCString filePath;
250   rv = inFile->GetNativePath(filePath);
251   if (NS_FAILED(rv))
252     return NO;
254   nsCOMPtr<nsIFile> workingDir;
255   rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
256   if (NS_FAILED(rv))
257     return NO;
259   const char *argv[3] = {nsnull, "-file", filePath.get()};
260   rv = cmdLine->Init(3, const_cast<char**>(argv), workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
261   if (NS_FAILED(rv))
262     return NO;
264   if (NS_SUCCEEDED(cmdLine->Run()))
265     return YES;
267   return NO;
269   NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(NO);
272 // The method that NSApplication calls when documents are requested to be printed
273 // from the Finder (under the "File" menu).
274 // It will be called once for each selected document.
275 - (BOOL)application:(NSApplication*)theApplication printFile:(NSString*)filename
277   return NO;
280 // Create the menu that shows up in the Dock.
281 - (NSMenu*)applicationDockMenu:(NSApplication*)sender
283   NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
285   // Create the NSMenu that will contain the dock menu items.
286   NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
287   [menu setAutoenablesItems:NO];
289   // Add application-specific dock menu items. On error, do not insert the
290   // dock menu items.
291   nsresult rv;
292   nsCOMPtr<nsIMacDockSupport> dockSupport = do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
293   if (NS_FAILED(rv) || !dockSupport)
294     return menu;
296   nsCOMPtr<nsIStandaloneNativeMenu> dockMenu;
297   rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenu));
298   if (NS_FAILED(rv) || !dockMenu)
299     return menu;
301   // Determine if the dock menu items should be displayed. This also gives
302   // the menu the opportunity to update itself before display.
303   PRBool shouldShowItems;
304   rv = dockMenu->MenuWillOpen(&shouldShowItems);
305   if (NS_FAILED(rv) || !shouldShowItems)
306     return menu;
308   // Obtain a copy of the native menu.
309   NSMenu * nativeDockMenu;
310   rv = dockMenu->GetNativeMenu(reinterpret_cast<void **>(&nativeDockMenu));
311   if (NS_FAILED(rv) || !nativeDockMenu)
312     return menu;
314   // Loop through the application-specific dock menu and insert its
315   // contents into the dock menu that we are building for Cocoa.
316   int numDockMenuItems = [nativeDockMenu numberOfItems];
317   if (numDockMenuItems > 0) {
318     if ([menu numberOfItems] > 0)
319       [menu addItem:[NSMenuItem separatorItem]];
321     for (int i = 0; i < numDockMenuItems; i++) {
322       NSMenuItem * itemCopy = [[nativeDockMenu itemAtIndex:i] copy];
323       [menu addItem:itemCopy];
324       [itemCopy release];
325     }
326   }
328   return menu;
330   NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
333 // If we don't handle applicationShouldTerminate:, a call to [NSApp terminate:]
334 // (from the browser or from the OS) can result in an unclean shutdown.
335 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
337   nsCOMPtr<nsIObserverService> obsServ =
338            do_GetService("@mozilla.org/observer-service;1");
339   if (!obsServ)
340     return NSTerminateNow;
342   nsCOMPtr<nsISupportsPRBool> cancelQuit =
343            do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
344   if (!cancelQuit)
345     return NSTerminateNow;
347   cancelQuit->SetData(PR_FALSE);
348   obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nsnull);
350   PRBool abortQuit;
351   cancelQuit->GetData(&abortQuit);
352   if (abortQuit)
353     return NSTerminateCancel;
355   nsCOMPtr<nsIAppStartup> appService =
356            do_GetService("@mozilla.org/toolkit/app-startup;1");
357   if (appService)
358     appService->Quit(nsIAppStartup::eForceQuit);
360   return NSTerminateNow;
363 - (void)handleAppleEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
365   if (!event)
366     return;
368   AutoAutoreleasePool pool;
370   PRBool isGetURLEvent =
371     ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL);
372   if (isGetURLEvent)
373     sProcessedGetURLEvent = PR_TRUE;
375   if (isGetURLEvent ||
376       ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) {
377     NSString* urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
379     // don't open chrome URLs
380     NSString* schemeString = [[NSURL URLWithString:urlString] scheme];
381     if (!schemeString ||
382         [schemeString compare:@"chrome"
383                       options:NSCaseInsensitiveSearch
384                         range:NSMakeRange(0, [schemeString length])] == NSOrderedSame) {
385       return;
386     }
388     // Add the URL to any command line we're currently setting up.
389     if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
390       return;
392     nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
393     if (!cmdLine) {
394       NS_ERROR("Couldn't create command line!");
395       return;
396     }
397     nsCOMPtr<nsIFile> workingDir;
398     nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
399     if (NS_FAILED(rv))
400       return;
401     const char *argv[3] = {nsnull, "-url", [urlString UTF8String]};
402     rv = cmdLine->Init(3, const_cast<char**>(argv), workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
403     if (NS_FAILED(rv))
404       return;
405     rv = cmdLine->Run();
406   }
407   else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) {
408     NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject];
409     if (!fileListDescriptor)
410       return;
412     // Descriptor list indexing is one-based...
413     NSInteger numberOfFiles = [fileListDescriptor numberOfItems];
414     for (NSInteger i = 1; i <= numberOfFiles; i++) {
415       NSString* urlString = [[fileListDescriptor descriptorAtIndex:i] stringValue];
416       if (!urlString)
417         continue;
419       // We need a path, not a URL
420       NSURL* url = [NSURL URLWithString:urlString];
421       if (!url)
422         continue;
424       [self application:NSApp openFile:[url path]];
425     }
426   }
429 @end