Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / app_controller_mac.mm
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #import "chrome/browser/app_controller_mac.h"
6
7 #include "apps/app_shim/app_shim_mac.h"
8 #include "apps/app_shim/extension_app_shim_handler_mac.h"
9 #include "apps/app_window_registry.h"
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/file_path.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/mac_util.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/sys_string_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "chrome/app/chrome_command_ids.h"
22 #include "chrome/browser/background/background_application_list_model.h"
23 #include "chrome/browser/background/background_mode_manager.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/browser_shutdown.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/command_updater.h"
28 #include "chrome/browser/download/download_service.h"
29 #include "chrome/browser/download/download_service_factory.h"
30 #include "chrome/browser/extensions/extension_service.h"
31 #include "chrome/browser/first_run/first_run.h"
32 #include "chrome/browser/lifetime/application_lifetime.h"
33 #include "chrome/browser/printing/print_dialog_cloud.h"
34 #include "chrome/browser/profiles/profile_info_cache_observer.h"
35 #include "chrome/browser/profiles/profile_manager.h"
36 #include "chrome/browser/profiles/profiles_state.h"
37 #include "chrome/browser/service_process/service_process_control.h"
38 #include "chrome/browser/sessions/session_restore.h"
39 #include "chrome/browser/sessions/session_service.h"
40 #include "chrome/browser/sessions/session_service_factory.h"
41 #include "chrome/browser/sessions/tab_restore_service.h"
42 #include "chrome/browser/sessions/tab_restore_service_factory.h"
43 #include "chrome/browser/signin/signin_manager.h"
44 #include "chrome/browser/signin/signin_manager_factory.h"
45 #include "chrome/browser/signin/signin_promo.h"
46 #include "chrome/browser/sync/profile_sync_service.h"
47 #include "chrome/browser/sync/sync_ui_util.h"
48 #include "chrome/browser/ui/browser.h"
49 #include "chrome/browser/ui/browser_command_controller.h"
50 #include "chrome/browser/ui/browser_commands.h"
51 #include "chrome/browser/ui/browser_dialogs.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_iterator.h"
54 #include "chrome/browser/ui/browser_mac.h"
55 #include "chrome/browser/ui/browser_window.h"
56 #include "chrome/browser/ui/chrome_pages.h"
57 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
58 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
59 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
60 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
61 #import "chrome/browser/ui/cocoa/confirm_quit.h"
62 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
63 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
64 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
65 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
66 #import "chrome/browser/ui/cocoa/profile_menu_controller.h"
67 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
68 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
69 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
70 #include "chrome/browser/ui/extensions/application_launch.h"
71 #include "chrome/browser/ui/host_desktop.h"
72 #include "chrome/browser/ui/startup/startup_browser_creator.h"
73 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
74 #include "chrome/common/chrome_paths_internal.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
77 #include "chrome/common/extensions/extension_constants.h"
78 #include "chrome/common/mac/app_mode_common.h"
79 #include "chrome/common/pref_names.h"
80 #include "chrome/common/profile_management_switches.h"
81 #include "chrome/common/service_messages.h"
82 #include "chrome/common/url_constants.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "content/public/browser/download_manager.h"
85 #include "content/public/browser/notification_service.h"
86 #include "content/public/browser/notification_types.h"
87 #include "content/public/browser/plugin_service.h"
88 #include "content/public/browser/user_metrics.h"
89 #include "extensions/browser/extension_system.h"
90 #include "grit/chromium_strings.h"
91 #include "grit/generated_resources.h"
92 #include "net/base/net_util.h"
93 #include "ui/base/cocoa/focus_window_set.h"
94 #include "ui/base/l10n/l10n_util.h"
95 #include "ui/base/l10n/l10n_util_mac.h"
96
97 using base::UserMetricsAction;
98 using content::BrowserContext;
99 using content::BrowserThread;
100 using content::DownloadManager;
101
102 namespace {
103
104 // Declare notification names from the 10.7 SDK.
105 #if !defined(MAC_OS_X_VERSION_10_7) || \
106     MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
107 NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
108 NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
109 #endif
110
111 // How long we allow a workspace change notification to wait to be
112 // associated with a dock activation. The animation lasts 250ms. See
113 // applicationShouldHandleReopen:hasVisibleWindows:.
114 static const int kWorkspaceChangeTimeoutMs = 500;
115
116 // True while AppController is calling chrome::NewEmptyWindow(). We need a
117 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
118 // because otherwise the SessionService will try to restore sessions when we
119 // make a new window while there are no other active windows.
120 bool g_is_opening_new_window = false;
121
122 // Activates a browser window having the given profile (the last one active) if
123 // possible and returns a pointer to the activate |Browser| or NULL if this was
124 // not possible. If the last active browser is minimized (in particular, if
125 // there are only minimized windows), it will unminimize it.
126 Browser* ActivateBrowser(Profile* profile) {
127   Browser* browser = chrome::FindLastActiveWithProfile(profile,
128       chrome::HOST_DESKTOP_TYPE_NATIVE);
129   if (browser)
130     browser->window()->Activate();
131   return browser;
132 }
133
134 // Creates an empty browser window with the given profile and returns a pointer
135 // to the new |Browser|.
136 Browser* CreateBrowser(Profile* profile) {
137   {
138     base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
139     chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
140   }
141
142   Browser* browser = chrome::GetLastActiveBrowser();
143   CHECK(browser);
144   return browser;
145 }
146
147 // Activates a browser window having the given profile (the last one active) if
148 // possible or creates an empty one if necessary. Returns a pointer to the
149 // activated/new |Browser|.
150 Browser* ActivateOrCreateBrowser(Profile* profile) {
151   if (Browser* browser = ActivateBrowser(profile))
152     return browser;
153   return CreateBrowser(profile);
154 }
155
156 CFStringRef BaseBundleID_CFString() {
157   NSString* base_bundle_id =
158       [NSString stringWithUTF8String:base::mac::BaseBundleID()];
159   return base::mac::NSToCFCast(base_bundle_id);
160 }
161
162 // This callback synchronizes preferences (under "org.chromium.Chromium" or
163 // "com.google.Chrome"), in particular, writes them out to disk.
164 void PrefsSyncCallback() {
165   if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
166     LOG(WARNING) << "Error recording application bundle path.";
167 }
168
169 // Record the location of the application bundle (containing the main framework)
170 // from which Chromium was loaded. This is used by app mode shims to find
171 // Chromium.
172 void RecordLastRunAppBundlePath() {
173   // Going up three levels from |chrome::GetVersionedDirectory()| gives the
174   // real, user-visible app bundle directory. (The alternatives give either the
175   // framework's path or the initial app's path, which may be an app mode shim
176   // or a unit test.)
177   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
178
179   base::FilePath app_bundle_path =
180       chrome::GetVersionedDirectory().DirName().DirName().DirName();
181   base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
182       base::SysUTF8ToCFStringRef(app_bundle_path.value()));
183   CFPreferencesSetAppValue(
184       base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
185       app_bundle_path_cfstring, BaseBundleID_CFString());
186
187   // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
188   BrowserThread::PostDelayedTask(
189       BrowserThread::FILE, FROM_HERE,
190       base::Bind(&PrefsSyncCallback),
191       base::TimeDelta::FromMilliseconds(1500));
192 }
193
194 bool IsProfileSignedOut(Profile* profile) {
195   // The signed out status only makes sense at the moment in the context of the
196   // --new-profile-management flag.
197   if (!switches::IsNewProfileManagement())
198     return false;
199   ProfileInfoCache& cache =
200       g_browser_process->profile_manager()->GetProfileInfoCache();
201   size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
202   if (profile_index == std::string::npos)
203     return false;
204   return cache.ProfileIsSigninRequiredAtIndex(profile_index);
205 }
206
207 }  // anonymous namespace
208
209 @interface AppController (Private)
210 - (void)initMenuState;
211 - (void)initProfileMenu;
212 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
213 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
214 - (void)openUrls:(const std::vector<GURL>&)urls;
215 - (void)getUrl:(NSAppleEventDescriptor*)event
216      withReply:(NSAppleEventDescriptor*)reply;
217 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
218 - (void)windowLayeringDidChange:(NSNotification*)inNotification;
219 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
220 - (void)windowChangedToProfile:(Profile*)profile;
221 - (void)checkForAnyKeyWindows;
222 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
223 - (BOOL)shouldQuitWithInProgressDownloads;
224 - (void)executeApplication:(id)sender;
225 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
226 @end
227
228 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
229  public:
230   AppControllerProfileObserver(
231       ProfileManager* profile_manager, AppController* app_controller)
232       : profile_manager_(profile_manager),
233         app_controller_(app_controller) {
234     DCHECK(profile_manager_);
235     DCHECK(app_controller_);
236     profile_manager_->GetProfileInfoCache().AddObserver(this);
237   }
238
239   virtual ~AppControllerProfileObserver() {
240     DCHECK(profile_manager_);
241     profile_manager_->GetProfileInfoCache().RemoveObserver(this);
242   }
243
244  private:
245   // ProfileInfoCacheObserver implementation:
246
247   virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
248   }
249
250   virtual void OnProfileWasRemoved(
251       const base::FilePath& profile_path,
252       const base::string16& profile_name) OVERRIDE {
253     // When a profile is deleted we need to notify the AppController,
254     // so it can correctly update its pointer to the last used profile.
255     [app_controller_ profileWasRemoved:profile_path];
256   }
257
258   virtual void OnProfileWillBeRemoved(
259       const base::FilePath& profile_path) OVERRIDE {
260   }
261
262   virtual void OnProfileNameChanged(
263       const base::FilePath& profile_path,
264       const base::string16& old_profile_name) OVERRIDE {
265   }
266
267   virtual void OnProfileAvatarChanged(
268       const base::FilePath& profile_path) OVERRIDE {
269   }
270
271   ProfileManager* profile_manager_;
272
273   AppController* app_controller_;  // Weak; owns us.
274
275   DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
276 };
277
278 @implementation AppController
279
280 @synthesize startupComplete = startupComplete_;
281
282 // This method is called very early in application startup (ie, before
283 // the profile is loaded or any preferences have been registered). Defer any
284 // user-data initialization until -applicationDidFinishLaunching:.
285 - (void)awakeFromNib {
286   // We need to register the handlers early to catch events fired on launch.
287   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
288   [em setEventHandler:self
289           andSelector:@selector(getUrl:withReply:)
290         forEventClass:kInternetEventClass
291            andEventID:kAEGetURL];
292   [em setEventHandler:self
293           andSelector:@selector(submitCloudPrintJob:)
294         forEventClass:cloud_print::kAECloudPrintClass
295            andEventID:cloud_print::kAECloudPrintClass];
296   [em setEventHandler:self
297           andSelector:@selector(getUrl:withReply:)
298         forEventClass:'WWW!'    // A particularly ancient AppleEvent that dates
299            andEventID:'OURL'];  // back to the Spyglass days.
300
301   // Register for various window layering changes. We use these to update
302   // various UI elements (command-key equivalents, etc) when the frontmost
303   // window changes.
304   NSNotificationCenter* notificationCenter =
305       [NSNotificationCenter defaultCenter];
306   [notificationCenter
307       addObserver:self
308          selector:@selector(windowLayeringDidChange:)
309              name:NSWindowDidBecomeKeyNotification
310            object:nil];
311   [notificationCenter
312       addObserver:self
313          selector:@selector(windowLayeringDidChange:)
314              name:NSWindowDidResignKeyNotification
315            object:nil];
316   [notificationCenter
317       addObserver:self
318          selector:@selector(windowLayeringDidChange:)
319              name:NSWindowDidBecomeMainNotification
320            object:nil];
321   [notificationCenter
322       addObserver:self
323          selector:@selector(windowLayeringDidChange:)
324              name:NSWindowDidResignMainNotification
325            object:nil];
326
327   if (base::mac::IsOSLionOrLater()) {
328     [notificationCenter
329         addObserver:self
330            selector:@selector(popoverDidShow:)
331                name:NSPopoverDidShowNotification
332              object:nil];
333     [notificationCenter
334         addObserver:self
335            selector:@selector(popoverDidClose:)
336                name:NSPopoverDidCloseNotification
337              object:nil];
338   }
339
340   // Register for space change notifications.
341   [[[NSWorkspace sharedWorkspace] notificationCenter]
342     addObserver:self
343        selector:@selector(activeSpaceDidChange:)
344            name:NSWorkspaceActiveSpaceDidChangeNotification
345          object:nil];
346
347   // Set up the command updater for when there are no windows open
348   [self initMenuState];
349
350   // Initialize the Profile menu.
351   [self initProfileMenu];
352 }
353
354 - (void)unregisterEventHandlers {
355   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
356   [em removeEventHandlerForEventClass:kInternetEventClass
357                            andEventID:kAEGetURL];
358   [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
359                            andEventID:cloud_print::kAECloudPrintClass];
360   [em removeEventHandlerForEventClass:'WWW!'
361                            andEventID:'OURL'];
362   [[NSNotificationCenter defaultCenter] removeObserver:self];
363   [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
364 }
365
366 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
367 // the default handlers.
368 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
369   // Nothing here right now.
370 }
371
372 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
373   // Check for in-process downloads, and prompt the user if they really want
374   // to quit (and thus cancel downloads). Only check if we're not already
375   // shutting down, else the user might be prompted multiple times if the
376   // download isn't stopped before terminate is called again.
377   if (!browser_shutdown::IsTryingToQuit() &&
378       ![self shouldQuitWithInProgressDownloads])
379     return NO;
380
381   // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
382   // them in, but I'm not sure about UX; we'd also want to disable other things
383   // though.) http://crbug.com/40861
384
385   // Check if the user really wants to quit by employing the confirm-to-quit
386   // mechanism.
387   if (!browser_shutdown::IsTryingToQuit() &&
388       [self applicationShouldTerminate:app] != NSTerminateNow)
389     return NO;
390
391   size_t num_browsers = chrome::GetTotalBrowserCount();
392
393   // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
394   // already shutting down.
395   if (!browser_shutdown::IsTryingToQuit()) {
396     content::NotificationService::current()->Notify(
397         chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
398         content::NotificationService::AllSources(),
399         content::NotificationService::NoDetails());
400     chrome::CloseAllBrowsersAndQuit();
401   }
402
403   return num_browsers == 0 ? YES : NO;
404 }
405
406 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
407   if (browser_shutdown::IsTryingToQuit()) {
408     // Reset the "trying to quit" state, so that closing all browser windows
409     // will no longer lead to termination.
410     browser_shutdown::SetTryingToQuit(false);
411
412     // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
413     // would have to reinstall them here. http://crbug.com/40861
414   }
415 }
416
417 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
418   // If there are no windows, quit immediately.
419   if (chrome::BrowserIterator().done() &&
420       !apps::AppWindowRegistry::IsAppWindowRegisteredInAnyProfile(0)) {
421     return NSTerminateNow;
422   }
423
424   // Check if the preference is turned on.
425   const PrefService* prefs = g_browser_process->local_state();
426   if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
427     confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
428     return NSTerminateNow;
429   }
430
431   // If the application is going to terminate as the result of a Cmd+Q
432   // invocation, use the special sauce to prevent accidental quitting.
433   // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
434
435   // This logic is only for keyboard-initiated quits.
436   if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
437     return NSTerminateNow;
438
439   return [[ConfirmQuitPanelController sharedController]
440       runModalLoopForApplication:app];
441 }
442
443 // Called when the app is shutting down. Clean-up as appropriate.
444 - (void)applicationWillTerminate:(NSNotification*)aNotification {
445   // There better be no browser windows left at this point.
446   CHECK_EQ(0u, chrome::GetTotalBrowserCount());
447
448   // Tell BrowserList not to keep the browser process alive. Once all the
449   // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
450   chrome::EndKeepAlive();
451
452   // Reset all pref watching, as this object outlives the prefs system.
453   profilePrefRegistrar_.reset();
454   localPrefRegistrar_.RemoveAll();
455
456   [self unregisterEventHandlers];
457
458   appShimMenuController_.reset();
459 }
460
461 - (void)didEndMainMessageLoop {
462   DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
463                                         chrome::HOST_DESKTOP_TYPE_NATIVE));
464   if (!chrome::GetBrowserCount([self lastProfile],
465                                chrome::HOST_DESKTOP_TYPE_NATIVE)) {
466     // As we're shutting down, we need to nuke the TabRestoreService, which
467     // will start the shutdown of the NavigationControllers and allow for
468     // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
469     // and may end up crashing when some thread tries to use the IO thread (or
470     // another thread) that is no longer valid.
471     TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
472   }
473 }
474
475 // If the window has a tab controller, make "close window" be cmd-shift-w,
476 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
477 // affects whether the shift modifier is used.
478 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
479   [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
480                                                                    @"w")];
481   [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
482 }
483
484 // If the window has a tab controller, make "close tab" take over cmd-w,
485 // otherwise it shouldn't have any key-equivalent because it should be disabled.
486 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
487   if (enableCloseTabShortcut) {
488     [closeTabMenuItem_ setKeyEquivalent:@"w"];
489     [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
490   } else {
491     [closeTabMenuItem_ setKeyEquivalent:@""];
492     [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
493   }
494 }
495
496 // Explicitly remove any command-key equivalents from the close tab/window
497 // menus so that nothing can go haywire if we get a user action during pending
498 // updates.
499 - (void)clearCloseMenuItemKeyEquivalents {
500   [closeTabMenuItem_ setKeyEquivalent:@""];
501   [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
502   [closeWindowMenuItem_ setKeyEquivalent:@""];
503   [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
504 }
505
506 // See if the focused window window has tabs, and adjust the key equivalents for
507 // Close Tab/Close Window accordingly.
508 - (void)fixCloseMenuItemKeyEquivalents {
509   fileMenuUpdatePending_ = NO;
510
511   NSWindow* window = [NSApp keyWindow];
512   NSWindow* mainWindow = [NSApp mainWindow];
513   if (!window || ([window parentWindow] == mainWindow)) {
514     // If the key window is a child of the main window (e.g. a bubble), the main
515     // window should be the one that handles the close menu item action.
516     // Also, there might be a small amount of time where there is no key window;
517     // in that case as well, just use our main browser window if there is one.
518     // You might think that we should just always use the main window, but the
519     // "About Chrome" window serves as a counterexample.
520     window = mainWindow;
521   }
522
523   BOOL hasTabs =
524       [[window windowController] isKindOfClass:[TabWindowController class]];
525   BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
526   [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
527   [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
528 }
529
530 // Fix up the "close tab/close window" command-key equivalents. We do this
531 // after a delay to ensure that window layer state has been set by the time
532 // we do the enabling. This should only be called on the main thread, code that
533 // calls this (even as a side-effect) from other threads needs to be fixed.
534 - (void)delayedFixCloseMenuItemKeyEquivalents {
535   DCHECK([NSThread isMainThread]);
536   if (!fileMenuUpdatePending_) {
537     // The OS prefers keypresses to timers, so it's possible that a cmd-w
538     // can sneak in before this timer fires. In order to prevent that from
539     // having any bad consequences, just clear the keys combos altogether. They
540     // will be reset when the timer eventually fires.
541     if ([NSThread isMainThread]) {
542       fileMenuUpdatePending_ = YES;
543       [self clearCloseMenuItemKeyEquivalents];
544       [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
545                  withObject:nil
546                  afterDelay:0];
547     } else {
548       // This shouldn't be happening, but if it does, force it to the main
549       // thread to avoid dropping the update. Don't mess with
550       // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
551       // there could be a race between the selector finishing and setting the
552       // flag.
553       [self
554           performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
555                            withObject:nil
556                         waitUntilDone:NO];
557     }
558   }
559 }
560
561 // Called when we get a notification about the window layering changing to
562 // update the UI based on the new main window.
563 - (void)windowLayeringDidChange:(NSNotification*)notify {
564   [self delayedFixCloseMenuItemKeyEquivalents];
565
566   if ([notify name] == NSWindowDidResignKeyNotification) {
567     // If a window is closed, this notification is fired but |[NSApp keyWindow]|
568     // returns nil regardless of whether any suitable candidates for the key
569     // window remain. It seems that the new key window for the app is not set
570     // until after this notification is fired, so a check is performed after the
571     // run loop is allowed to spin.
572     [self performSelector:@selector(checkForAnyKeyWindows)
573                withObject:nil
574                afterDelay:0.0];
575   }
576
577   // If the window changed to a new BrowserWindowController, update the profile.
578   id windowController = [[notify object] windowController];
579   if (![windowController isKindOfClass:[BrowserWindowController class]])
580     return;
581
582   if ([notify name] == NSWindowDidBecomeMainNotification) {
583     // If the profile is incognito, use the original profile.
584     Profile* newProfile = [windowController profile]->GetOriginalProfile();
585     [self windowChangedToProfile:newProfile];
586   } else if (chrome::GetTotalBrowserCount() == 0) {
587     [self windowChangedToProfile:
588         g_browser_process->profile_manager()->GetLastUsedProfile()];
589   }
590 }
591
592 - (void)activeSpaceDidChange:(NSNotification*)notify {
593   if (reopenTime_.is_null() ||
594       ![NSApp isActive] ||
595       (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
596       kWorkspaceChangeTimeoutMs) {
597     return;
598   }
599
600   // The last applicationShouldHandleReopen:hasVisibleWindows: call
601   // happened during a space change. Now that the change has
602   // completed, raise browser windows.
603   reopenTime_ = base::TimeTicks();
604   std::set<NSWindow*> browserWindows;
605   for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
606     Browser* browser = *iter;
607     browserWindows.insert(browser->window()->GetNativeWindow());
608   }
609   if (!browserWindows.empty()) {
610     ui::FocusWindowSet(browserWindows, false);
611   }
612 }
613
614 // Called on Lion and later when a popover (e.g. dictionary) is shown.
615 - (void)popoverDidShow:(NSNotification*)notify {
616   hasPopover_ = YES;
617   [self fixCloseMenuItemKeyEquivalents];
618 }
619
620 // Called on Lion and later when a popover (e.g. dictionary) is closed.
621 - (void)popoverDidClose:(NSNotification*)notify {
622   hasPopover_ = NO;
623   [self fixCloseMenuItemKeyEquivalents];
624 }
625
626 // Called when the user has changed browser windows, meaning the backing profile
627 // may have changed. This can cause a rebuild of the user-data menus. This is a
628 // no-op if the new profile is the same as the current one. This will always be
629 // the original profile and never incognito.
630 - (void)windowChangedToProfile:(Profile*)profile {
631   if (lastProfile_ == profile)
632     return;
633
634   // Before tearing down the menu controller bridges, return the Cocoa menus to
635   // their initial state.
636   if (bookmarkMenuBridge_.get())
637     bookmarkMenuBridge_->ResetMenu();
638   if (historyMenuBridge_.get())
639     historyMenuBridge_->ResetMenu();
640
641   // Rebuild the menus with the new profile.
642   lastProfile_ = profile;
643
644   bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
645       [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
646   // No need to |BuildMenu| here.  It is done lazily upon menu access.
647
648   historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
649   historyMenuBridge_->BuildMenu();
650
651   chrome::BrowserCommandController::
652       UpdateSharedCommandsForIncognitoAvailability(
653           menuState_.get(), lastProfile_);
654   profilePrefRegistrar_.reset(new PrefChangeRegistrar());
655   profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
656   profilePrefRegistrar_->Add(
657       prefs::kIncognitoModeAvailability,
658       base::Bind(&chrome::BrowserCommandController::
659                      UpdateSharedCommandsForIncognitoAvailability,
660                  menuState_.get(),
661                  lastProfile_));
662 }
663
664 - (void)checkForAnyKeyWindows {
665   if ([NSApp keyWindow])
666     return;
667
668   content::NotificationService::current()->Notify(
669       chrome::NOTIFICATION_NO_KEY_WINDOW,
670       content::NotificationService::AllSources(),
671       content::NotificationService::NoDetails());
672 }
673
674 // If the auto-update interval is not set, make it 5 hours.
675 // Placed here for 2 reasons:
676 // 1) Same spot as other Pref stuff
677 // 2) Try and be friendly by keeping this after app launch
678 - (void)setUpdateCheckInterval {
679 #if defined(GOOGLE_CHROME_BUILD)
680   CFStringRef app = CFSTR("com.google.Keystone.Agent");
681   CFStringRef checkInterval = CFSTR("checkInterval");
682   CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
683   if (!plist) {
684     const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
685     NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
686     CFPreferencesSetAppValue(checkInterval, value, app);
687     CFPreferencesAppSynchronize(app);
688   }
689 #endif
690 }
691
692 // This is called after profiles have been loaded and preferences registered.
693 // It is safe to access the default profile here.
694 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
695   // Notify BrowserList to keep the application running so it doesn't go away
696   // when all the browser windows get closed.
697   chrome::StartKeepAlive();
698
699   [self setUpdateCheckInterval];
700
701   // Start managing the menu for app windows. This needs to be done here because
702   // main menu item titles are not yet initialized in awakeFromNib.
703   [self initAppShimMenuController];
704
705   // Build up the encoding menu, the order of the items differs based on the
706   // current locale (see http://crbug.com/7647 for details).
707   // We need a valid g_browser_process to get the profile which is why we can't
708   // call this from awakeFromNib.
709   NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
710   NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
711   NSMenu* encodingMenu = [encodingMenuItem submenu];
712   EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
713                                                     encodingMenu);
714
715   // Instantiate the ProfileInfoCache observer so that we can get
716   // notified when a profile is deleted.
717   profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
718       g_browser_process->profile_manager(), self));
719
720   // Since Chrome is localized to more languages than the OS, tell Cocoa which
721   // menu is the Help so it can add the search item to it.
722   [NSApp setHelpMenu:helpMenu_];
723
724   // Record the path to the (browser) app bundle; this is used by the app mode
725   // shim.  It has to be done in FILE thread because getting the path requires
726   // I/O.
727   BrowserThread::PostTask(
728       BrowserThread::FILE, FROM_HERE,
729       base::Bind(&RecordLastRunAppBundlePath));
730
731   // Makes "Services" menu items available.
732   [self registerServicesMenuTypesTo:[notify object]];
733
734   startupComplete_ = YES;
735
736   // TODO(viettrungluu): This is very temporary, since this should be done "in"
737   // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
738   // (probably-empty) list of URLs from the command line.
739   if (startupUrls_.size()) {
740     [self openUrls:startupUrls_];
741     [self clearStartupUrls];
742   }
743
744   PrefService* localState = g_browser_process->local_state();
745   if (localState) {
746     localPrefRegistrar_.Init(localState);
747     localPrefRegistrar_.Add(
748         prefs::kAllowFileSelectionDialogs,
749         base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
750                    menuState_.get()));
751   }
752 }
753
754 // This is called after profiles have been loaded and preferences registered.
755 // It is safe to access the default profile here.
756 - (void)applicationDidBecomeActive:(NSNotification*)notify {
757   content::PluginService::GetInstance()->AppActivated();
758 }
759
760 // Helper function for populating and displaying the in progress downloads at
761 // exit alert panel.
762 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
763   NSString* titleText = nil;
764   NSString* explanationText = nil;
765   NSString* waitTitle = nil;
766   NSString* exitTitle = nil;
767
768   // Set the dialog text based on whether or not there are multiple downloads.
769   if (downloadCount == 1) {
770     // Dialog text: warning and explanation.
771     titleText = l10n_util::GetNSString(
772         IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
773     explanationText = l10n_util::GetNSString(
774         IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
775   } else {
776     // Dialog text: warning and explanation.
777     titleText = l10n_util::GetNSStringF(
778         IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
779         base::IntToString16(downloadCount));
780     explanationText = l10n_util::GetNSString(
781         IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
782   }
783   // Cancel download and exit button text.
784   exitTitle = l10n_util::GetNSString(
785       IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
786
787   // Wait for download button text.
788   waitTitle = l10n_util::GetNSString(
789       IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
790
791   // 'waitButton' is the default choice.
792   int choice = NSRunAlertPanel(titleText, @"%@",
793                                waitTitle, exitTitle, nil, explanationText);
794   return choice == NSAlertDefaultReturn ? YES : NO;
795 }
796
797 // Check all profiles for in progress downloads, and if we find any, prompt the
798 // user to see if we should continue to exit (and thus cancel the downloads), or
799 // if we should wait.
800 - (BOOL)shouldQuitWithInProgressDownloads {
801   ProfileManager* profile_manager = g_browser_process->profile_manager();
802   if (!profile_manager)
803     return YES;
804
805   std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
806   for (size_t i = 0; i < profiles.size(); ++i) {
807     DownloadService* download_service =
808       DownloadServiceFactory::GetForBrowserContext(profiles[i]);
809     DownloadManager* download_manager =
810         (download_service->HasCreatedDownloadManager() ?
811          BrowserContext::GetDownloadManager(profiles[i]) : NULL);
812     if (download_manager &&
813         download_manager->NonMaliciousInProgressCount() > 0) {
814       int downloadCount = download_manager->NonMaliciousInProgressCount();
815       if ([self userWillWaitForInProgressDownloads:downloadCount]) {
816         // Create a new browser window (if necessary) and navigate to the
817         // downloads page if the user chooses to wait.
818         Browser* browser = chrome::FindBrowserWithProfile(
819             profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
820         if (!browser) {
821           browser = new Browser(Browser::CreateParams(
822               profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
823           browser->window()->Show();
824         }
825         DCHECK(browser);
826         chrome::ShowDownloads(browser);
827         return NO;
828       }
829
830       // User wants to exit.
831       return YES;
832     }
833   }
834
835   // No profiles or active downloads found, okay to exit.
836   return YES;
837 }
838
839 // Called to determine if we should enable the "restore tab" menu item.
840 // Checks with the TabRestoreService to see if there's anything there to
841 // restore and returns YES if so.
842 - (BOOL)canRestoreTab {
843   TabRestoreService* service =
844       TabRestoreServiceFactory::GetForProfile([self lastProfile]);
845   return service && !service->entries().empty();
846 }
847
848 // Called from the AppControllerProfileObserver every time a profile is deleted.
849 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
850   Profile* lastProfile = [self lastProfile];
851
852   // If the lastProfile has been deleted, the profile manager has
853   // already loaded a new one, so the pointer needs to be updated;
854   // otherwise we will try to start up a browser window with a pointer
855   // to the old profile.
856   if (profilePath == lastProfile->GetPath())
857     lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
858 }
859
860 // Returns true if there is a modal window (either window- or application-
861 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
862 // sheets) will not count as blocking the browser. But things like open/save
863 // dialogs that are window modal will block the browser.
864 - (BOOL)keyWindowIsModal {
865   if ([NSApp modalWindow])
866     return YES;
867
868   Browser* browser = chrome::GetLastActiveBrowser();
869   return browser &&
870          [[browser->window()->GetNativeWindow() attachedSheet]
871              isKindOfClass:[NSWindow class]];
872 }
873
874 // Called to validate menu items when there are no key windows. All the
875 // items we care about have been set with the |commandDispatch:| action and
876 // a target of FirstResponder in IB. If it's not one of those, let it
877 // continue up the responder chain to be handled elsewhere. We pull out the
878 // tag as the cross-platform constant to differentiate and dispatch the
879 // various commands.
880 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
881   SEL action = [item action];
882   BOOL enable = NO;
883   if (action == @selector(commandDispatch:) ||
884       action == @selector(commandFromDock:)) {
885     NSInteger tag = [item tag];
886     if (menuState_ &&  // NULL in tests.
887         menuState_->SupportsCommand(tag)) {
888       switch (tag) {
889         // The File Menu commands are not automatically disabled by Cocoa when a
890         // dialog sheet obscures the browser window, so we disable several of
891         // them here.  We don't need to include IDC_CLOSE_WINDOW, because
892         // app_controller is only activated when there are no key windows (see
893         // function comment).
894         case IDC_RESTORE_TAB:
895           enable = ![self keyWindowIsModal] && [self canRestoreTab];
896           break;
897         // Browser-level items that open in new tabs should not open if there's
898         // a window- or app-modal dialog.
899         case IDC_OPEN_FILE:
900         case IDC_NEW_TAB:
901         case IDC_SHOW_HISTORY:
902         case IDC_SHOW_BOOKMARK_MANAGER:
903           enable = ![self keyWindowIsModal];
904           break;
905         // Browser-level items that open in new windows.
906         case IDC_TASK_MANAGER:
907           // Allow the user to open a new window if there's a window-modal
908           // dialog.
909           enable = ![self keyWindowIsModal];
910           break;
911         case IDC_SHOW_SYNC_SETUP: {
912           Profile* lastProfile = [self lastProfile];
913           // The profile may be NULL during shutdown -- see
914           // http://code.google.com/p/chromium/issues/detail?id=43048 .
915           //
916           // TODO(akalin,viettrungluu): Figure out whether this method
917           // can be prevented from being called if lastProfile is
918           // NULL.
919           if (!lastProfile) {
920             LOG(WARNING)
921                 << "NULL lastProfile detected -- not doing anything";
922             break;
923           }
924           SigninManager* signin = SigninManagerFactory::GetForProfile(
925               lastProfile->GetOriginalProfile());
926           enable = signin->IsSigninAllowed() &&
927               ![self keyWindowIsModal];
928           [BrowserWindowController updateSigninItem:item
929                                          shouldShow:enable
930                                      currentProfile:lastProfile];
931           break;
932         }
933 #if defined(GOOGLE_CHROME_BUILD)
934         case IDC_FEEDBACK:
935           enable = NO;
936           break;
937 #endif
938         default:
939           enable = menuState_->IsCommandEnabled(tag) ?
940                    ![self keyWindowIsModal] : NO;
941       }
942     }
943   } else if (action == @selector(terminate:)) {
944     enable = YES;
945   } else if (action == @selector(showPreferences:)) {
946     enable = YES;
947   } else if (action == @selector(orderFrontStandardAboutPanel:)) {
948     enable = YES;
949   } else if (action == @selector(commandFromDock:)) {
950     enable = YES;
951   } else if (action == @selector(toggleConfirmToQuit:)) {
952     [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
953     enable = YES;
954   } else if (action == @selector(executeApplication:)) {
955     enable = YES;
956   }
957   return enable;
958 }
959
960 // Called when the user picks a menu item when there are no key windows, or when
961 // there is no foreground browser window. Calls through to the browser object to
962 // execute the command. This assumes that the command is supported and doesn't
963 // check, otherwise it should have been disabled in the UI in
964 // |-validateUserInterfaceItem:|.
965 - (void)commandDispatch:(id)sender {
966   Profile* lastProfile = [self lastProfile];
967
968   // Handle the case where we're dispatching a command from a sender that's in a
969   // browser window. This means that the command came from a background window
970   // and is getting here because the foreground window is not a browser window.
971   if ([sender respondsToSelector:@selector(window)]) {
972     id delegate = [[sender window] windowController];
973     if ([delegate isKindOfClass:[BrowserWindowController class]]) {
974       [delegate commandDispatch:sender];
975       return;
976     }
977   }
978
979   // Ignore commands during session restore's browser creation.  It uses a
980   // nested message loop and commands dispatched during this operation cause
981   // havoc.
982   if (SessionRestore::IsRestoring(lastProfile) &&
983       base::MessageLoop::current()->IsNested())
984     return;
985
986   NSInteger tag = [sender tag];
987
988   // If there are no browser windows, and we are trying to open a browser
989   // for a locked profile, we have to show the User Manager instead as the
990   // locked profile needs authentication.
991   if (IsProfileSignedOut(lastProfile)) {
992     chrome::ShowUserManager(lastProfile->GetPath());
993     return;
994   }
995
996   switch (tag) {
997     case IDC_NEW_TAB:
998       // Create a new tab in an existing browser window (which we activate) if
999       // possible.
1000       if (Browser* browser = ActivateBrowser(lastProfile)) {
1001         chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1002         break;
1003       }
1004       // Else fall through to create new window.
1005     case IDC_NEW_WINDOW:
1006       CreateBrowser(lastProfile);
1007       break;
1008     case IDC_FOCUS_LOCATION:
1009       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1010                              IDC_FOCUS_LOCATION);
1011       break;
1012     case IDC_FOCUS_SEARCH:
1013       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1014                              IDC_FOCUS_SEARCH);
1015       break;
1016     case IDC_NEW_INCOGNITO_WINDOW:
1017       CreateBrowser(lastProfile->GetOffTheRecordProfile());
1018       break;
1019     case IDC_RESTORE_TAB:
1020       // There is only the native desktop on Mac.
1021       chrome::OpenWindowWithRestoredTabs(lastProfile,
1022                                          chrome::HOST_DESKTOP_TYPE_NATIVE);
1023       break;
1024     case IDC_OPEN_FILE:
1025       chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1026       break;
1027     case IDC_CLEAR_BROWSING_DATA: {
1028       // There may not be a browser open, so use the default profile.
1029       if (Browser* browser = ActivateBrowser(lastProfile)) {
1030         chrome::ShowClearBrowsingDataDialog(browser);
1031       } else {
1032         chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1033       }
1034       break;
1035     }
1036     case IDC_IMPORT_SETTINGS: {
1037       if (Browser* browser = ActivateBrowser(lastProfile)) {
1038         chrome::ShowImportDialog(browser);
1039       } else {
1040         chrome::OpenImportSettingsDialogWindow(lastProfile);
1041       }
1042       break;
1043     }
1044     case IDC_SHOW_BOOKMARK_MANAGER:
1045       content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1046       if (Browser* browser = ActivateBrowser(lastProfile)) {
1047         chrome::ShowBookmarkManager(browser);
1048       } else {
1049         // No browser window, so create one for the bookmark manager tab.
1050         chrome::OpenBookmarkManagerWindow(lastProfile);
1051       }
1052       break;
1053     case IDC_SHOW_HISTORY:
1054       if (Browser* browser = ActivateBrowser(lastProfile))
1055         chrome::ShowHistory(browser);
1056       else
1057         chrome::OpenHistoryWindow(lastProfile);
1058       break;
1059     case IDC_SHOW_DOWNLOADS:
1060       if (Browser* browser = ActivateBrowser(lastProfile))
1061         chrome::ShowDownloads(browser);
1062       else
1063         chrome::OpenDownloadsWindow(lastProfile);
1064       break;
1065     case IDC_MANAGE_EXTENSIONS:
1066       if (Browser* browser = ActivateBrowser(lastProfile))
1067         chrome::ShowExtensions(browser, std::string());
1068       else
1069         chrome::OpenExtensionsWindow(lastProfile);
1070       break;
1071     case IDC_HELP_PAGE_VIA_MENU:
1072       if (Browser* browser = ActivateBrowser(lastProfile))
1073         chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1074       else
1075         chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1076       break;
1077     case IDC_SHOW_SYNC_SETUP:
1078       if (Browser* browser = ActivateBrowser(lastProfile)) {
1079         chrome::ShowBrowserSignin(browser, signin::SOURCE_MENU);
1080       } else {
1081         chrome::OpenSyncSetupWindow(lastProfile, signin::SOURCE_MENU);
1082       }
1083       break;
1084     case IDC_TASK_MANAGER:
1085       content::RecordAction(UserMetricsAction("TaskManager"));
1086       TaskManagerMac::Show();
1087       break;
1088     case IDC_OPTIONS:
1089       [self showPreferences:sender];
1090       break;
1091   }
1092 }
1093
1094 // Run a (background) application in a new tab.
1095 - (void)executeApplication:(id)sender {
1096   NSInteger tag = [sender tag];
1097   Profile* profile = [self lastProfile];
1098   DCHECK(profile);
1099   BackgroundApplicationListModel applications(profile);
1100   DCHECK(tag >= 0 &&
1101          tag < static_cast<int>(applications.size()));
1102   const extensions::Extension* extension = applications.GetExtension(tag);
1103   BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1104 }
1105
1106 // Same as |-commandDispatch:|, but executes commands using a disposition
1107 // determined by the key flags. This will get called in the case where the
1108 // frontmost window is not a browser window, and the user has command-clicked
1109 // a button in a background browser window whose action is
1110 // |-commandDispatchUsingKeyModifiers:|
1111 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1112   DCHECK(sender);
1113   if ([sender respondsToSelector:@selector(window)]) {
1114     id delegate = [[sender window] windowController];
1115     if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1116       [delegate commandDispatchUsingKeyModifiers:sender];
1117     }
1118   }
1119 }
1120
1121 // NSApplication delegate method called when someone clicks on the dock icon.
1122 // To match standard mac behavior, we should open a new window if there are no
1123 // browser windows.
1124 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1125                     hasVisibleWindows:(BOOL)hasVisibleWindows {
1126   // If the browser is currently trying to quit, don't do anything and return NO
1127   // to prevent AppKit from doing anything.
1128   // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1129   if (browser_shutdown::IsTryingToQuit())
1130     return NO;
1131
1132   // Bring all browser windows to the front. Specifically, this brings them in
1133   // front of any app windows. FocusWindowSet will also unminimize the most
1134   // recently minimized window if no windows in the set are visible.
1135   // If there are any, return here. Otherwise, the windows are panels or
1136   // notifications so we still need to open a new window.
1137   if (hasVisibleWindows) {
1138     std::set<NSWindow*> browserWindows;
1139     for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1140       Browser* browser = *iter;
1141       browserWindows.insert(browser->window()->GetNativeWindow());
1142     }
1143     if (!browserWindows.empty()) {
1144       NSWindow* keyWindow = [NSApp keyWindow];
1145       if (keyWindow && ![keyWindow isOnActiveSpace]) {
1146         // The key window is not on the active space. We must be mid-animation
1147         // for a space transition triggered by the dock. Delay the call to
1148         // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1149         // wrong space's windows get raised, resulting in an off-screen key
1150         // window. It does not work to |ui::FocusWindowSet| twice, once here
1151         // and once in |activeSpaceDidChange:|, as that appears to break when
1152         // the omnibox is focused.
1153         //
1154         // This check relies on OS X setting the key window to a window on the
1155         // target space before calling this method.
1156         //
1157         // See http://crbug.com/309656.
1158         reopenTime_ = base::TimeTicks::Now();
1159       } else {
1160         ui::FocusWindowSet(browserWindows, false);
1161       }
1162       // Return NO; we've done (or soon will do) the deminiaturize, so
1163       // AppKit shouldn't do anything.
1164       return NO;
1165     }
1166   }
1167
1168   // If launched as a hidden login item (due to installation of a persistent app
1169   // or by the user, for example in System Preferences->Accounts->Login Items),
1170   // allow session to be restored first time the user clicks on a Dock icon.
1171   // Normally, it'd just open a new empty page.
1172   {
1173     static BOOL doneOnce = NO;
1174     if (!doneOnce) {
1175       doneOnce = YES;
1176       if (base::mac::WasLaunchedAsHiddenLoginItem()) {
1177         SessionService* sessionService =
1178             SessionServiceFactory::GetForProfileForSessionRestore(
1179                 [self lastProfile]);
1180         if (sessionService &&
1181             sessionService->RestoreIfNecessary(std::vector<GURL>()))
1182           return NO;
1183       }
1184     }
1185   }
1186
1187   // Platform apps don't use browser windows so don't do anything if there are
1188   // visible windows, otherwise, launch the browser with the same command line
1189   // which should launch the app again.
1190   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1191   if (command_line.HasSwitch(switches::kAppId)) {
1192     if (hasVisibleWindows)
1193       return YES;
1194
1195     {
1196       base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1197       int return_code;
1198       StartupBrowserCreator browser_creator;
1199       browser_creator.LaunchBrowser(
1200           command_line, [self lastProfile], base::FilePath(),
1201           chrome::startup::IS_NOT_PROCESS_STARTUP,
1202           chrome::startup::IS_NOT_FIRST_RUN, &return_code);
1203     }
1204     return NO;
1205   }
1206
1207   // Otherwise open a new window.
1208   // If the last profile was locked, we have to open the User Manager, as the
1209   // profile requires authentication. Similarly, because guest mode is
1210   // implemented as forced incognito, we can't open a new guest browser either,
1211   // so we have to show the User Manager as well.
1212   Profile* lastProfile = [self lastProfile];
1213   if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile))
1214     chrome::ShowUserManager(lastProfile->GetPath());
1215   else
1216     CreateBrowser(lastProfile);
1217
1218   // We've handled the reopen event, so return NO to tell AppKit not
1219   // to do anything.
1220   return NO;
1221 }
1222
1223 - (void)initMenuState {
1224   menuState_.reset(new CommandUpdater(NULL));
1225   menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1226   menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1227   menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1228   menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1229   menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1230   menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1231   menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1232   menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1233   menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1234   menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1235   menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1236   menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1237   menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1238   menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1239 #if defined(GOOGLE_CHROME_BUILD)
1240   menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1241 #endif
1242   menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1243   menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1244 }
1245
1246 // Conditionally adds the Profile menu to the main menu bar.
1247 - (void)initProfileMenu {
1248   NSMenu* mainMenu = [NSApp mainMenu];
1249   NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1250
1251   if (!profiles::IsMultipleProfilesEnabled()) {
1252     [mainMenu removeItem:profileMenu];
1253     return;
1254   }
1255
1256   // The controller will unhide the menu if necessary.
1257   [profileMenu setHidden:YES];
1258
1259   profileMenuController_.reset(
1260       [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1261 }
1262
1263 // The Confirm to Quit preference is atypical in that the preference lives in
1264 // the app menu right above the Quit menu item. This method will refresh the
1265 // display of that item depending on the preference state.
1266 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1267   // Format the string so that the correct key equivalent is displayed.
1268   NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1269   NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1270       base::SysNSStringToUTF16(acceleratorString));
1271   [item setTitle:title];
1272
1273   const PrefService* prefService = g_browser_process->local_state();
1274   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1275   [item setState:enabled ? NSOnState : NSOffState];
1276 }
1277
1278 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1279   // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1280   // handles requests from services.
1281   NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1282   [app registerServicesMenuSendTypes:types returnTypes:types];
1283 }
1284
1285 - (Profile*)lastProfile {
1286   // Return the profile of the last-used BrowserWindowController, if available.
1287   if (lastProfile_)
1288     return lastProfile_;
1289
1290   // On first launch, use the logic that ChromeBrowserMain uses to determine
1291   // the initial profile.
1292   ProfileManager* profile_manager = g_browser_process->profile_manager();
1293   if (!profile_manager)
1294     return NULL;
1295
1296   return profile_manager->GetProfile(GetStartupProfilePath(
1297       profile_manager->user_data_dir(),
1298       *CommandLine::ForCurrentProcess()));
1299 }
1300
1301 // Various methods to open URLs that we get in a native fashion. We use
1302 // StartupBrowserCreator here because on the other platforms, URLs to open come
1303 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1304 // to bottleneck the openings through that for uniform handling.
1305
1306 - (void)openUrls:(const std::vector<GURL>&)urls {
1307   // If the browser hasn't started yet, just queue up the URLs.
1308   if (!startupComplete_) {
1309     startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1310     return;
1311   }
1312
1313   Browser* browser = chrome::GetLastActiveBrowser();
1314   // if no browser window exists then create one with no tabs to be filled in
1315   if (!browser) {
1316     browser = new Browser(Browser::CreateParams(
1317         [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1318     browser->window()->Show();
1319   }
1320
1321   CommandLine dummy(CommandLine::NO_PROGRAM);
1322   chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1323       chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1324   StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1325   launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1326 }
1327
1328 - (void)getUrl:(NSAppleEventDescriptor*)event
1329      withReply:(NSAppleEventDescriptor*)reply {
1330   NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1331                       stringValue];
1332
1333   GURL gurl(base::SysNSStringToUTF8(urlStr));
1334   std::vector<GURL> gurlVector;
1335   gurlVector.push_back(gurl);
1336
1337   [self openUrls:gurlVector];
1338 }
1339
1340 // Apple Event handler that receives print event from service
1341 // process, gets the required data and launches Print dialog.
1342 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1343   // Pull parameter list out of Apple Event.
1344   NSAppleEventDescriptor* paramList =
1345       [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
1346
1347   if (paramList != nil) {
1348     // Pull required fields out of parameter list.
1349     NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1350     NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1351     NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
1352     NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
1353     // Convert the title to UTF 16 as required.
1354     base::string16 title16 = base::SysNSStringToUTF16(printTitle);
1355     base::string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
1356     print_dialog_cloud::CreatePrintDialogForFile(
1357         ProfileManager::GetActiveUserProfile(), NULL,
1358         base::FilePath([inputPath fileSystemRepresentation]), title16,
1359         printTicket16, [mime UTF8String], /*delete_on_close=*/false);
1360   }
1361 }
1362
1363 - (void)application:(NSApplication*)sender
1364           openFiles:(NSArray*)filenames {
1365   std::vector<GURL> gurlVector;
1366   for (NSString* file in filenames) {
1367     GURL gurl =
1368         net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1369     gurlVector.push_back(gurl);
1370   }
1371   if (!gurlVector.empty())
1372     [self openUrls:gurlVector];
1373   else
1374     NOTREACHED() << "Nothing to open!";
1375
1376   [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1377 }
1378
1379 // Show the preferences window, or bring it to the front if it's already
1380 // visible.
1381 - (IBAction)showPreferences:(id)sender {
1382   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1383     // Show options tab in the active browser window.
1384     chrome::ShowSettings(browser);
1385   } else {
1386     // No browser window, so create one for the options tab.
1387     chrome::OpenOptionsWindow([self lastProfile]);
1388   }
1389 }
1390
1391 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1392   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1393     chrome::ShowAboutChrome(browser);
1394   } else {
1395     // No browser window, so create one for the about tab.
1396     chrome::OpenAboutWindow([self lastProfile]);
1397   }
1398 }
1399
1400 - (IBAction)toggleConfirmToQuit:(id)sender {
1401   PrefService* prefService = g_browser_process->local_state();
1402   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1403   prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1404 }
1405
1406 // Explicitly bring to the foreground when creating new windows from the dock.
1407 - (void)commandFromDock:(id)sender {
1408   [NSApp activateIgnoringOtherApps:YES];
1409   [self commandDispatch:sender];
1410 }
1411
1412 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1413   NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1414   Profile* profile = [self lastProfile];
1415
1416   BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1417                                                           atOffset:0
1418                                                           fromDock:YES];
1419   if (profilesAdded)
1420     [dockMenu addItem:[NSMenuItem separatorItem]];
1421
1422   NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1423   base::scoped_nsobject<NSMenuItem> item(
1424       [[NSMenuItem alloc] initWithTitle:titleStr
1425                                  action:@selector(commandFromDock:)
1426                           keyEquivalent:@""]);
1427   [item setTarget:self];
1428   [item setTag:IDC_NEW_WINDOW];
1429   [item setEnabled:[self validateUserInterfaceItem:item]];
1430   [dockMenu addItem:item];
1431
1432   // |profile| can be NULL during unit tests.
1433   if (!profile || !profile->IsManaged()) {
1434     titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1435     item.reset(
1436         [[NSMenuItem alloc] initWithTitle:titleStr
1437                                    action:@selector(commandFromDock:)
1438                             keyEquivalent:@""]);
1439     [item setTarget:self];
1440     [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1441     [item setEnabled:[self validateUserInterfaceItem:item]];
1442     [dockMenu addItem:item];
1443   }
1444
1445   // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1446   // tests which use the mock in place of the profile-initialized model.
1447
1448   // Avoid breaking unit tests which have no profile.
1449   if (profile) {
1450     BackgroundApplicationListModel applications(profile);
1451     if (applications.size()) {
1452       int position = 0;
1453       NSString* menuStr =
1454           l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1455       base::scoped_nsobject<NSMenu> appMenu(
1456           [[NSMenu alloc] initWithTitle:menuStr]);
1457       for (extensions::ExtensionList::const_iterator cursor =
1458                applications.begin();
1459            cursor != applications.end();
1460            ++cursor, ++position) {
1461         DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1462         NSString* itemStr =
1463             base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1464         base::scoped_nsobject<NSMenuItem> appItem(
1465             [[NSMenuItem alloc] initWithTitle:itemStr
1466                                        action:@selector(executeApplication:)
1467                                 keyEquivalent:@""]);
1468         [appItem setTarget:self];
1469         [appItem setTag:position];
1470         [appMenu addItem:appItem];
1471       }
1472     }
1473   }
1474
1475   return dockMenu;
1476 }
1477
1478 - (const std::vector<GURL>&)startupUrls {
1479   return startupUrls_;
1480 }
1481
1482 - (void)clearStartupUrls {
1483   startupUrls_.clear();
1484 }
1485
1486 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1487   return bookmarkMenuBridge_.get();
1488 }
1489
1490 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1491   workAreaChangeObservers_.AddObserver(observer);
1492 }
1493
1494 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1495   workAreaChangeObservers_.RemoveObserver(observer);
1496 }
1497
1498 - (void)initAppShimMenuController {
1499   if (!appShimMenuController_)
1500     appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1501 }
1502
1503 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1504   // During this callback the working area is not always already updated. Defer.
1505   [self performSelector:@selector(delayedScreenParametersUpdate)
1506              withObject:nil
1507              afterDelay:0];
1508 }
1509
1510 - (void)delayedScreenParametersUpdate {
1511   FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1512       WorkAreaChanged());
1513 }
1514
1515 @end  // @implementation AppController
1516
1517 //---------------------------------------------------------------------------
1518
1519 namespace app_controller_mac {
1520
1521 bool IsOpeningNewWindow() {
1522   return g_is_opening_new_window;
1523 }
1524
1525 }  // namespace app_controller_mac