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