/toolkit/xre/MacApplicationDelegate.mm

http://github.com/zpao/v8monkey · Objective C++ · 431 lines · 269 code · 74 blank · 88 comment · 52 complexity · a7ab8828b1963124420d9459f38fde40 MD5 · raw file

  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 ***** */
  39. // NSApplication delegate for Mac OS X Cocoa API.
  40. // As of 10.4 Tiger, the system can send six kinds of Apple Events to an application;
  41. // a well-behaved XUL app should have some kind of handling for all of them.
  42. //
  43. // See http://developer.apple.com/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/chapter_11_section_3.html for details.
  44. #import <Cocoa/Cocoa.h>
  45. #import <Carbon/Carbon.h>
  46. #include "nsCOMPtr.h"
  47. #include "nsINativeAppSupport.h"
  48. #include "nsAppRunner.h"
  49. #include "nsComponentManagerUtils.h"
  50. #include "nsIServiceManager.h"
  51. #include "nsServiceManagerUtils.h"
  52. #include "nsIAppStartup.h"
  53. #include "nsIObserverService.h"
  54. #include "nsISupportsPrimitives.h"
  55. #include "nsObjCExceptions.h"
  56. #include "nsIFile.h"
  57. #include "nsDirectoryServiceDefs.h"
  58. #include "nsICommandLineRunner.h"
  59. #include "nsIMacDockSupport.h"
  60. #include "nsIStandaloneNativeMenu.h"
  61. #include "nsILocalFileMac.h"
  62. #include "nsString.h"
  63. #include "nsCommandLineServiceMac.h"
  64. class AutoAutoreleasePool {
  65. public:
  66. AutoAutoreleasePool()
  67. {
  68. mLocalPool = [[NSAutoreleasePool alloc] init];
  69. }
  70. ~AutoAutoreleasePool()
  71. {
  72. [mLocalPool release];
  73. }
  74. private:
  75. NSAutoreleasePool *mLocalPool;
  76. };
  77. @interface MacApplicationDelegate : NSObject
  78. {
  79. }
  80. @end
  81. static bool sProcessedGetURLEvent = false;
  82. @class GeckoNSApplication;
  83. // Methods that can be called from non-Objective-C code.
  84. // This is needed, on relaunch, to force the OS to use the "Cocoa Dock API"
  85. // instead of the "Carbon Dock API". For more info see bmo bug 377166.
  86. void
  87. EnsureUseCocoaDockAPI()
  88. {
  89. NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
  90. [GeckoNSApplication sharedApplication];
  91. NS_OBJC_END_TRY_ABORT_BLOCK;
  92. }
  93. void
  94. SetupMacApplicationDelegate()
  95. {
  96. NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
  97. // this is called during startup, outside an event loop, and therefore
  98. // needs an autorelease pool to avoid cocoa object leakage (bug 559075)
  99. AutoAutoreleasePool pool;
  100. // Ensure that ProcessPendingGetURLAppleEvents() doesn't regress bug 377166.
  101. [GeckoNSApplication sharedApplication];
  102. // This call makes it so that application:openFile: doesn't get bogus calls
  103. // from Cocoa doing its own parsing of the argument string. And yes, we need
  104. // to use a string with a boolean value in it. That's just how it works.
  105. [[NSUserDefaults standardUserDefaults] setObject:@"NO"
  106. forKey:@"NSTreatUnknownArgumentsAsOpen"];
  107. // Create the delegate. This should be around for the lifetime of the app.
  108. MacApplicationDelegate *delegate = [[MacApplicationDelegate alloc] init];
  109. [NSApp setDelegate:delegate];
  110. NS_OBJC_END_TRY_ABORT_BLOCK;
  111. }
  112. // Indirectly make the OS process any pending GetURL Apple events. This is
  113. // done via _DPSNextEvent() (an undocumented AppKit function called from
  114. // [NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]). Apple
  115. // events are only processed if 'dequeue' is 'YES' -- so we need to call
  116. // [NSApplication sendEvent:] on any event that gets returned. 'event' will
  117. // never itself be an Apple event, and it may be 'nil' even when Apple events
  118. // are processed.
  119. void
  120. ProcessPendingGetURLAppleEvents()
  121. {
  122. AutoAutoreleasePool pool;
  123. bool keepSpinning = true;
  124. while (keepSpinning) {
  125. sProcessedGetURLEvent = false;
  126. NSEvent *event = [NSApp nextEventMatchingMask:NSAnyEventMask
  127. untilDate:nil
  128. inMode:NSDefaultRunLoopMode
  129. dequeue:YES];
  130. if (event)
  131. [NSApp sendEvent:event];
  132. keepSpinning = sProcessedGetURLEvent;
  133. }
  134. }
  135. @implementation MacApplicationDelegate
  136. - (id)init
  137. {
  138. NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
  139. if ((self = [super init])) {
  140. NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
  141. [aeMgr setEventHandler:self
  142. andSelector:@selector(handleAppleEvent:withReplyEvent:)
  143. forEventClass:kInternetEventClass
  144. andEventID:kAEGetURL];
  145. [aeMgr setEventHandler:self
  146. andSelector:@selector(handleAppleEvent:withReplyEvent:)
  147. forEventClass:'WWW!'
  148. andEventID:'OURL'];
  149. [aeMgr setEventHandler:self
  150. andSelector:@selector(handleAppleEvent:withReplyEvent:)
  151. forEventClass:kCoreEventClass
  152. andEventID:kAEOpenDocuments];
  153. if (![NSApp windowsMenu]) {
  154. // If the application has a windows menu, it will keep it up to date and
  155. // prepend the window list to the Dock menu automatically.
  156. NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
  157. [NSApp setWindowsMenu:windowsMenu];
  158. [windowsMenu release];
  159. }
  160. }
  161. return self;
  162. NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(nil);
  163. }
  164. - (void)dealloc
  165. {
  166. NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
  167. NSAppleEventManager *aeMgr = [NSAppleEventManager sharedAppleEventManager];
  168. [aeMgr removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL];
  169. [aeMgr removeEventHandlerForEventClass:'WWW!' andEventID:'OURL'];
  170. [aeMgr removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEOpenDocuments];
  171. [super dealloc];
  172. NS_OBJC_END_TRY_ABORT_BLOCK;
  173. }
  174. // The method that NSApplication calls upon a request to reopen, such as when
  175. // the Dock icon is clicked and no windows are open. A "visible" window may be
  176. // miniaturized, so we can't skip nsCocoaNativeReOpen() if 'flag' is 'true'.
  177. - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApp hasVisibleWindows:(BOOL)flag
  178. {
  179. nsCOMPtr<nsINativeAppSupport> nas = do_CreateInstance(NS_NATIVEAPPSUPPORT_CONTRACTID);
  180. NS_ENSURE_TRUE(nas, NO);
  181. // Go to the common Carbon/Cocoa reopen method.
  182. nsresult rv = nas->ReOpen();
  183. NS_ENSURE_SUCCESS(rv, NO);
  184. // NO says we don't want NSApplication to do anything else for us.
  185. return NO;
  186. }
  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. {
  191. NS_OBJC_BEGIN_TRY_ABORT_BLOCK_RETURN;
  192. NSURL *url = [NSURL fileURLWithPath:filename];
  193. if (!url)
  194. return NO;
  195. NSString *urlString = [url absoluteString];
  196. if (!urlString)
  197. return NO;
  198. // Add the URL to any command line we're currently setting up.
  199. if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
  200. return YES;
  201. nsCOMPtr<nsILocalFileMac> inFile;
  202. nsresult rv = NS_NewLocalFileWithCFURL((CFURLRef)url, true, getter_AddRefs(inFile));
  203. if (NS_FAILED(rv))
  204. return NO;
  205. nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
  206. if (!cmdLine) {
  207. NS_ERROR("Couldn't create command line!");
  208. return NO;
  209. }
  210. nsCString filePath;
  211. rv = inFile->GetNativePath(filePath);
  212. if (NS_FAILED(rv))
  213. return NO;
  214. nsCOMPtr<nsIFile> workingDir;
  215. rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
  216. if (NS_FAILED(rv))
  217. return NO;
  218. const char *argv[3] = {nsnull, "-file", filePath.get()};
  219. rv = cmdLine->Init(3, const_cast<char**>(argv), workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
  220. if (NS_FAILED(rv))
  221. return NO;
  222. if (NS_SUCCEEDED(cmdLine->Run()))
  223. return YES;
  224. return NO;
  225. NS_OBJC_END_TRY_ABORT_BLOCK_RETURN(NO);
  226. }
  227. // The method that NSApplication calls when documents are requested to be printed
  228. // from the Finder (under the "File" menu).
  229. // It will be called once for each selected document.
  230. - (BOOL)application:(NSApplication*)theApplication printFile:(NSString*)filename
  231. {
  232. return NO;
  233. }
  234. // Create the menu that shows up in the Dock.
  235. - (NSMenu*)applicationDockMenu:(NSApplication*)sender
  236. {
  237. NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NIL;
  238. // Create the NSMenu that will contain the dock menu items.
  239. NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
  240. [menu setAutoenablesItems:NO];
  241. // Add application-specific dock menu items. On error, do not insert the
  242. // dock menu items.
  243. nsresult rv;
  244. nsCOMPtr<nsIMacDockSupport> dockSupport = do_GetService("@mozilla.org/widget/macdocksupport;1", &rv);
  245. if (NS_FAILED(rv) || !dockSupport)
  246. return menu;
  247. nsCOMPtr<nsIStandaloneNativeMenu> dockMenu;
  248. rv = dockSupport->GetDockMenu(getter_AddRefs(dockMenu));
  249. if (NS_FAILED(rv) || !dockMenu)
  250. return menu;
  251. // Determine if the dock menu items should be displayed. This also gives
  252. // the menu the opportunity to update itself before display.
  253. bool shouldShowItems;
  254. rv = dockMenu->MenuWillOpen(&shouldShowItems);
  255. if (NS_FAILED(rv) || !shouldShowItems)
  256. return menu;
  257. // Obtain a copy of the native menu.
  258. NSMenu * nativeDockMenu;
  259. rv = dockMenu->GetNativeMenu(reinterpret_cast<void **>(&nativeDockMenu));
  260. if (NS_FAILED(rv) || !nativeDockMenu)
  261. return menu;
  262. // Loop through the application-specific dock menu and insert its
  263. // contents into the dock menu that we are building for Cocoa.
  264. int numDockMenuItems = [nativeDockMenu numberOfItems];
  265. if (numDockMenuItems > 0) {
  266. if ([menu numberOfItems] > 0)
  267. [menu addItem:[NSMenuItem separatorItem]];
  268. for (int i = 0; i < numDockMenuItems; i++) {
  269. NSMenuItem * itemCopy = [[nativeDockMenu itemAtIndex:i] copy];
  270. [menu addItem:itemCopy];
  271. [itemCopy release];
  272. }
  273. }
  274. return menu;
  275. NS_OBJC_END_TRY_ABORT_BLOCK_NIL;
  276. }
  277. // If we don't handle applicationShouldTerminate:, a call to [NSApp terminate:]
  278. // (from the browser or from the OS) can result in an unclean shutdown.
  279. - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
  280. {
  281. nsCOMPtr<nsIObserverService> obsServ =
  282. do_GetService("@mozilla.org/observer-service;1");
  283. if (!obsServ)
  284. return NSTerminateNow;
  285. nsCOMPtr<nsISupportsPRBool> cancelQuit =
  286. do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
  287. if (!cancelQuit)
  288. return NSTerminateNow;
  289. cancelQuit->SetData(false);
  290. obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nsnull);
  291. bool abortQuit;
  292. cancelQuit->GetData(&abortQuit);
  293. if (abortQuit)
  294. return NSTerminateCancel;
  295. nsCOMPtr<nsIAppStartup> appService =
  296. do_GetService("@mozilla.org/toolkit/app-startup;1");
  297. if (appService)
  298. appService->Quit(nsIAppStartup::eForceQuit);
  299. return NSTerminateNow;
  300. }
  301. - (void)handleAppleEvent:(NSAppleEventDescriptor*)event withReplyEvent:(NSAppleEventDescriptor*)replyEvent
  302. {
  303. if (!event)
  304. return;
  305. AutoAutoreleasePool pool;
  306. bool isGetURLEvent =
  307. ([event eventClass] == kInternetEventClass && [event eventID] == kAEGetURL);
  308. if (isGetURLEvent)
  309. sProcessedGetURLEvent = true;
  310. if (isGetURLEvent ||
  311. ([event eventClass] == 'WWW!' && [event eventID] == 'OURL')) {
  312. NSString* urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
  313. // don't open chrome URLs
  314. NSString* schemeString = [[NSURL URLWithString:urlString] scheme];
  315. if (!schemeString ||
  316. [schemeString compare:@"chrome"
  317. options:NSCaseInsensitiveSearch
  318. range:NSMakeRange(0, [schemeString length])] == NSOrderedSame) {
  319. return;
  320. }
  321. // Add the URL to any command line we're currently setting up.
  322. if (CommandLineServiceMac::AddURLToCurrentCommandLine([urlString UTF8String]))
  323. return;
  324. nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1"));
  325. if (!cmdLine) {
  326. NS_ERROR("Couldn't create command line!");
  327. return;
  328. }
  329. nsCOMPtr<nsIFile> workingDir;
  330. nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir));
  331. if (NS_FAILED(rv))
  332. return;
  333. const char *argv[3] = {nsnull, "-url", [urlString UTF8String]};
  334. rv = cmdLine->Init(3, const_cast<char**>(argv), workingDir, nsICommandLine::STATE_REMOTE_EXPLICIT);
  335. if (NS_FAILED(rv))
  336. return;
  337. rv = cmdLine->Run();
  338. }
  339. else if ([event eventClass] == kCoreEventClass && [event eventID] == kAEOpenDocuments) {
  340. NSAppleEventDescriptor* fileListDescriptor = [event paramDescriptorForKeyword:keyDirectObject];
  341. if (!fileListDescriptor)
  342. return;
  343. // Descriptor list indexing is one-based...
  344. NSInteger numberOfFiles = [fileListDescriptor numberOfItems];
  345. for (NSInteger i = 1; i <= numberOfFiles; i++) {
  346. NSString* urlString = [[fileListDescriptor descriptorAtIndex:i] stringValue];
  347. if (!urlString)
  348. continue;
  349. // We need a path, not a URL
  350. NSURL* url = [NSURL URLWithString:urlString];
  351. if (!url)
  352. continue;
  353. [self application:NSApp openFile:[url path]];
  354. }
  355. }
  356. }
  357. @end