Extensions: Remove the legacy GetMessages/HasMessages
[chromium-blink-merge.git] / chrome / browser / app_controller_mac.mm
blobe1f5a42245b7e9a0dace2f011e63a06e94f4ac8f
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 "base/auto_reset.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/mac/foundation_util.h"
12 #include "base/mac/mac_util.h"
13 #include "base/mac/sdk_forward_declarations.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/stl_util.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/apps/app_shim/extension_app_shim_handler_mac.h"
23 #include "chrome/browser/apps/app_window_registry_util.h"
24 #include "chrome/browser/background/background_application_list_model.h"
25 #include "chrome/browser/background/background_mode_manager.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/browser_shutdown.h"
28 #include "chrome/browser/chrome_notification_types.h"
29 #include "chrome/browser/command_updater.h"
30 #include "chrome/browser/download/download_service.h"
31 #include "chrome/browser/download/download_service_factory.h"
32 #include "chrome/browser/extensions/extension_service.h"
33 #include "chrome/browser/first_run/first_run.h"
34 #include "chrome/browser/lifetime/application_lifetime.h"
35 #include "chrome/browser/mac/mac_startup_profiler.h"
36 #include "chrome/browser/prefs/incognito_mode_prefs.h"
37 #include "chrome/browser/profiles/profile_info_cache_observer.h"
38 #include "chrome/browser/profiles/profile_manager.h"
39 #include "chrome/browser/profiles/profiles_state.h"
40 #include "chrome/browser/sessions/session_restore.h"
41 #include "chrome/browser/sessions/session_service.h"
42 #include "chrome/browser/sessions/session_service_factory.h"
43 #include "chrome/browser/sessions/tab_restore_service.h"
44 #include "chrome/browser/sessions/tab_restore_service_factory.h"
45 #include "chrome/browser/signin/signin_manager_factory.h"
46 #include "chrome/browser/signin/signin_promo.h"
47 #include "chrome/browser/sync/profile_sync_service.h"
48 #include "chrome/browser/sync/sync_ui_util.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_command_controller.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_dialogs.h"
53 #include "chrome/browser/ui/browser_finder.h"
54 #include "chrome/browser/ui/browser_iterator.h"
55 #include "chrome/browser/ui/browser_mac.h"
56 #include "chrome/browser/ui/browser_window.h"
57 #include "chrome/browser/ui/chrome_pages.h"
58 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
59 #include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
60 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.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 #include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
65 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
66 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
67 #import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.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/browser/ui/tabs/tab_strip_model.h"
73 #include "chrome/browser/ui/user_manager.h"
74 #include "chrome/browser/web_applications/web_app_mac.h"
75 #include "chrome/common/chrome_paths_internal.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
78 #include "chrome/common/extensions/extension_constants.h"
79 #include "chrome/common/mac/app_mode_common.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/grit/chromium_strings.h"
83 #include "chrome/grit/generated_resources.h"
84 #include "components/handoff/handoff_manager.h"
85 #include "components/handoff/handoff_utility.h"
86 #include "components/signin/core/browser/signin_manager.h"
87 #include "components/signin/core/common/profile_management_switches.h"
88 #include "content/public/browser/browser_thread.h"
89 #include "content/public/browser/download_manager.h"
90 #include "content/public/browser/notification_service.h"
91 #include "content/public/browser/notification_types.h"
92 #include "content/public/browser/plugin_service.h"
93 #include "content/public/browser/user_metrics.h"
94 #include "extensions/browser/extension_registry.h"
95 #include "extensions/browser/extension_system.h"
96 #include "net/base/filename_util.h"
97 #include "ui/base/cocoa/focus_window_set.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/base/l10n/l10n_util_mac.h"
101 using apps::AppShimHandler;
102 using apps::ExtensionAppShimHandler;
103 using base::UserMetricsAction;
104 using content::BrowserContext;
105 using content::BrowserThread;
106 using content::DownloadManager;
108 namespace {
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 }  // namespace
209 @interface AppController () <HandoffActiveURLObserverBridgeDelegate>
211 - (void)initMenuState;
212 - (void)initProfileMenu;
213 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
214 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
215 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
216 - (void)getUrl:(NSAppleEventDescriptor*)event
217      withReply:(NSAppleEventDescriptor*)reply;
218 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
219 - (void)checkForAnyKeyWindows;
220 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
221 - (BOOL)shouldQuitWithInProgressDownloads;
222 - (void)executeApplication:(id)sender;
223 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
225 // Opens a tab for each GURL in |urls|.
226 - (void)openUrls:(const std::vector<GURL>&)urls;
228 // This class cannot open urls until startup has finished. The urls that cannot
229 // be opened are cached in |startupUrls_|. This method must be called exactly
230 // once after startup has completed. It opens the urls in |startupUrls_|, and
231 // clears |startupUrls_|.
232 - (void)openStartupUrls;
234 // Opens a tab for each GURL in |urls|. If there is exactly one tab open before
235 // this method is called, and that tab is the NTP, then this method closes the
236 // NTP after all the |urls| have been opened.
237 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
239 // Whether instances of this class should use the Handoff feature.
240 - (BOOL)shouldUseHandoff;
242 // This method passes |handoffURL| to |handoffManager_|.
243 - (void)passURLToHandoffManager:(const GURL&)handoffURL;
245 // Lazily creates the Handoff Manager. Updates the state of the Handoff
246 // Manager. This method is idempotent. This should be called:
247 // - During initialization.
248 // - When the current tab navigates to a new URL.
249 // - When the active browser changes.
250 // - When the active browser's active tab switches.
251 // |webContents| should be the new, active WebContents.
252 - (void)updateHandoffManager:(content::WebContents*)webContents;
254 // Given |webContents|, extracts a GURL to be used for Handoff. This may return
255 // the empty GURL.
256 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
257 @end
259 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
260  public:
261   AppControllerProfileObserver(
262       ProfileManager* profile_manager, AppController* app_controller)
263       : profile_manager_(profile_manager),
264         app_controller_(app_controller) {
265     DCHECK(profile_manager_);
266     DCHECK(app_controller_);
267     profile_manager_->GetProfileInfoCache().AddObserver(this);
268   }
270   ~AppControllerProfileObserver() override {
271     DCHECK(profile_manager_);
272     profile_manager_->GetProfileInfoCache().RemoveObserver(this);
273   }
275  private:
276   // ProfileInfoCacheObserver implementation:
278   void OnProfileAdded(const base::FilePath& profile_path) override {}
280   void OnProfileWasRemoved(const base::FilePath& profile_path,
281                            const base::string16& profile_name) override {
282     // When a profile is deleted we need to notify the AppController,
283     // so it can correctly update its pointer to the last used profile.
284     [app_controller_ profileWasRemoved:profile_path];
285   }
287   void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
289   void OnProfileNameChanged(const base::FilePath& profile_path,
290                             const base::string16& old_profile_name) override {}
292   void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
294   ProfileManager* profile_manager_;
296   AppController* app_controller_;  // Weak; owns us.
298   DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
301 @implementation AppController
303 @synthesize startupComplete = startupComplete_;
305 - (void)dealloc {
306   [[closeTabMenuItem_ menu] setDelegate:nil];
307   [super dealloc];
310 // This method is called very early in application startup (ie, before
311 // the profile is loaded or any preferences have been registered). Defer any
312 // user-data initialization until -applicationDidFinishLaunching:.
313 - (void)awakeFromNib {
314   MacStartupProfiler::GetInstance()->Profile(
315       MacStartupProfiler::AWAKE_FROM_NIB);
316   // We need to register the handlers early to catch events fired on launch.
317   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
318   [em setEventHandler:self
319           andSelector:@selector(getUrl:withReply:)
320         forEventClass:kInternetEventClass
321            andEventID:kAEGetURL];
322   [em setEventHandler:self
323           andSelector:@selector(getUrl:withReply:)
324         forEventClass:'WWW!'    // A particularly ancient AppleEvent that dates
325            andEventID:'OURL'];  // back to the Spyglass days.
327   NSNotificationCenter* notificationCenter =
328       [NSNotificationCenter defaultCenter];
329   [notificationCenter
330       addObserver:self
331          selector:@selector(windowDidResignKey:)
332              name:NSWindowDidResignKeyNotification
333            object:nil];
334   [notificationCenter
335       addObserver:self
336          selector:@selector(windowDidBecomeMain:)
337              name:NSWindowDidBecomeMainNotification
338            object:nil];
339   [notificationCenter
340       addObserver:self
341          selector:@selector(windowDidResignMain:)
342              name:NSWindowDidResignMainNotification
343            object:nil];
345   // Register for space change notifications.
346   [[[NSWorkspace sharedWorkspace] notificationCenter]
347     addObserver:self
348        selector:@selector(activeSpaceDidChange:)
349            name:NSWorkspaceActiveSpaceDidChangeNotification
350          object:nil];
352   [[[NSWorkspace sharedWorkspace] notificationCenter]
353       addObserver:self
354          selector:@selector(willPowerOff:)
355              name:NSWorkspaceWillPowerOffNotification
356            object:nil];
358   // Set up the command updater for when there are no windows open
359   [self initMenuState];
361   // Initialize the Profile menu.
362   [self initProfileMenu];
365 - (void)unregisterEventHandlers {
366   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
367   [em removeEventHandlerForEventClass:kInternetEventClass
368                            andEventID:kAEGetURL];
369   [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
370                            andEventID:cloud_print::kAECloudPrintClass];
371   [em removeEventHandlerForEventClass:'WWW!'
372                            andEventID:'OURL'];
373   [[NSNotificationCenter defaultCenter] removeObserver:self];
374   [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
377 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
378 // the default handlers.
379 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
380   MacStartupProfiler::GetInstance()->Profile(
381       MacStartupProfiler::WILL_FINISH_LAUNCHING);
384 - (void)applicationWillHide:(NSNotification*)notification {
385   apps::ExtensionAppShimHandler::OnChromeWillHide();
388 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
389   // Reset this now that we've received the call to terminate.
390   BOOL isPoweringOff = isPoweringOff_;
391   isPoweringOff_ = NO;
393   // Check for in-process downloads, and prompt the user if they really want
394   // to quit (and thus cancel downloads). Only check if we're not already
395   // shutting down, else the user might be prompted multiple times if the
396   // download isn't stopped before terminate is called again.
397   if (!browser_shutdown::IsTryingToQuit() &&
398       ![self shouldQuitWithInProgressDownloads])
399     return NO;
401   // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
402   // them in, but I'm not sure about UX; we'd also want to disable other things
403   // though.) http://crbug.com/40861
405   // Check if the user really wants to quit by employing the confirm-to-quit
406   // mechanism.
407   if (!browser_shutdown::IsTryingToQuit() &&
408       [self applicationShouldTerminate:app] != NSTerminateNow)
409     return NO;
411   // Check for active apps. If quitting is prevented, only close browsers and
412   // sessions.
413   if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
414       quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
415     if (base::CommandLine::ForCurrentProcess()->HasSwitch(
416             switches::kHostedAppQuitNotification)) {
417       return NO;
418     }
420     content::NotificationService::current()->Notify(
421         chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
422         content::NotificationService::AllSources(),
423         content::NotificationService::NoDetails());
424     // This will close all browser sessions.
425     chrome::CloseAllBrowsers();
427     // At this point, the user has already chosen to cancel downloads. If we
428     // were to shut down as usual, the downloads would be cancelled in
429     // DownloadService::Shutdown().
430     DownloadService::CancelAllDownloads();
432     return NO;
433   }
435   size_t num_browsers = chrome::GetTotalBrowserCount();
437   // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
438   // already shutting down.
439   if (!browser_shutdown::IsTryingToQuit()) {
440     content::NotificationService::current()->Notify(
441         chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
442         content::NotificationService::AllSources(),
443         content::NotificationService::NoDetails());
444     chrome::CloseAllBrowsersAndQuit();
445   }
447   return num_browsers == 0 ? YES : NO;
450 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
451   if (browser_shutdown::IsTryingToQuit()) {
452     // Reset the "trying to quit" state, so that closing all browser windows
453     // will no longer lead to termination.
454     browser_shutdown::SetTryingToQuit(false);
456     // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
457     // would have to reinstall them here. http://crbug.com/40861
458   }
461 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
462   // If there are no windows, quit immediately.
463   if (chrome::BrowserIterator().done() &&
464       !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
465     return NSTerminateNow;
466   }
468   // Check if the preference is turned on.
469   const PrefService* prefs = g_browser_process->local_state();
470   if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
471     confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
472     return NSTerminateNow;
473   }
475   // If the application is going to terminate as the result of a Cmd+Q
476   // invocation, use the special sauce to prevent accidental quitting.
477   // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
479   // This logic is only for keyboard-initiated quits.
480   if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
481     return NSTerminateNow;
483   return [[ConfirmQuitPanelController sharedController]
484       runModalLoopForApplication:app];
487 // Called when the app is shutting down. Clean-up as appropriate.
488 - (void)applicationWillTerminate:(NSNotification*)aNotification {
489   // There better be no browser windows left at this point.
490   CHECK_EQ(0u, chrome::GetTotalBrowserCount());
492   // Tell BrowserList not to keep the browser process alive. Once all the
493   // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
494   chrome::DecrementKeepAliveCount();
496   // Reset all pref watching, as this object outlives the prefs system.
497   profilePrefRegistrar_.reset();
498   localPrefRegistrar_.RemoveAll();
500   [self unregisterEventHandlers];
502   appShimMenuController_.reset();
504   STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
505                                        profileBookmarkMenuBridgeMap_.end());
508 - (void)didEndMainMessageLoop {
509   DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
510                                         chrome::HOST_DESKTOP_TYPE_NATIVE));
511   if (!chrome::GetBrowserCount([self lastProfile],
512                                chrome::HOST_DESKTOP_TYPE_NATIVE)) {
513     // As we're shutting down, we need to nuke the TabRestoreService, which
514     // will start the shutdown of the NavigationControllers and allow for
515     // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
516     // and may end up crashing when some thread tries to use the IO thread (or
517     // another thread) that is no longer valid.
518     TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
519   }
522 // If the window has a tab controller, make "close window" be cmd-shift-w,
523 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
524 // affects whether the shift modifier is used.
525 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
526   [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
527                                                                    @"w")];
528   [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
531 // If the window has a tab controller, make "close tab" take over cmd-w,
532 // otherwise it shouldn't have any key-equivalent because it should be disabled.
533 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
534   if (enableCloseTabShortcut) {
535     [closeTabMenuItem_ setKeyEquivalent:@"w"];
536     [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
537   } else {
538     [closeTabMenuItem_ setKeyEquivalent:@""];
539     [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
540   }
543 // See if the focused window window has tabs, and adjust the key equivalents for
544 // Close Tab/Close Window accordingly.
545 - (void)menuNeedsUpdate:(NSMenu*)menu {
546   DCHECK(menu == [closeTabMenuItem_ menu]);
548   BOOL enableCloseTabShortcut = NO;
549   id target = [NSApp targetForAction:@selector(performClose:)];
551   // |target| is an instance of NSPopover or NSWindow.
552   // If a popover (likely the dictionary lookup popover), we want Cmd-W to
553   // close the popover so map it to "Close Window".
554   // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
555   if ([target isKindOfClass:[NSWindow class]]) {
556     NSWindow* window = target;
557     NSWindow* mainWindow = [NSApp mainWindow];
558     if (!window || ([window parentWindow] == mainWindow)) {
559       // If the target window is a child of the main window (e.g. a bubble), the
560       // main window should be the one that handles the close menu item action.
561       window = mainWindow;
562     }
563     Browser* browser = chrome::FindBrowserWithWindow(window);
564     enableCloseTabShortcut = browser && browser->is_type_tabbed();
565   }
567   [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
568   [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
571 - (void)windowDidResignKey:(NSNotification*)notify {
572   // If a window is closed, this notification is fired but |[NSApp keyWindow]|
573   // returns nil regardless of whether any suitable candidates for the key
574   // window remain. It seems that the new key window for the app is not set
575   // until after this notification is fired, so a check is performed after the
576   // run loop is allowed to spin.
577   [self performSelector:@selector(checkForAnyKeyWindows)
578              withObject:nil
579              afterDelay:0.0];
582 - (void)windowDidBecomeMain:(NSNotification*)notify {
583   Browser* browser = chrome::FindBrowserWithWindow([notify object]);
584   if (browser)
585     [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
588 - (void)windowDidResignMain:(NSNotification*)notify {
589   if (chrome::GetTotalBrowserCount() == 0) {
590     [self windowChangedToProfile:
591         g_browser_process->profile_manager()->GetLastUsedProfile()];
592   }
595 - (void)activeSpaceDidChange:(NSNotification*)notify {
596   if (reopenTime_.is_null() ||
597       ![NSApp isActive] ||
598       (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
599       kWorkspaceChangeTimeoutMs) {
600     return;
601   }
603   // The last applicationShouldHandleReopen:hasVisibleWindows: call
604   // happened during a space change. Now that the change has
605   // completed, raise browser windows.
606   reopenTime_ = base::TimeTicks();
607   std::set<NSWindow*> browserWindows;
608   for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
609     Browser* browser = *iter;
610     browserWindows.insert(browser->window()->GetNativeWindow());
611   }
612   if (!browserWindows.empty()) {
613     ui::FocusWindowSetOnCurrentSpace(browserWindows);
614   }
617 // Called when shutting down or logging out.
618 - (void)willPowerOff:(NSNotification*)notify {
619   // Don't attempt any shutdown here. Cocoa will shortly call
620   // -[BrowserCrApplication terminate:].
621   isPoweringOff_ = YES;
624 - (void)checkForAnyKeyWindows {
625   if ([NSApp keyWindow])
626     return;
628   content::NotificationService::current()->Notify(
629       chrome::NOTIFICATION_NO_KEY_WINDOW,
630       content::NotificationService::AllSources(),
631       content::NotificationService::NoDetails());
634 // If the auto-update interval is not set, make it 5 hours.
635 // Placed here for 2 reasons:
636 // 1) Same spot as other Pref stuff
637 // 2) Try and be friendly by keeping this after app launch
638 - (void)setUpdateCheckInterval {
639 #if defined(GOOGLE_CHROME_BUILD)
640   CFStringRef app = CFSTR("com.google.Keystone.Agent");
641   CFStringRef checkInterval = CFSTR("checkInterval");
642   CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
643   if (!plist) {
644     const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
645     NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
646     CFPreferencesSetAppValue(checkInterval, value, app);
647     CFPreferencesAppSynchronize(app);
648   }
649 #endif
652 - (void)openStartupUrls {
653   DCHECK(startupComplete_);
654   [self openUrlsReplacingNTP:startupUrls_];
655   startupUrls_.clear();
658 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
659   if (urls.empty())
660     return;
662   // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
663   // NSApplication is created in MainMessageLoop, and then the shortcut urls
664   // are passed in via Apple events. At this point, the first browser is
665   // already loaded in PreMainMessageLoop. If we initialize NSApplication
666   // before PreMainMessageLoop to capture shortcut URL events, it may cause
667   // more problems because it relies on things created in PreMainMessageLoop
668   // and may break existing message loop design.
670   // If the browser hasn't started yet, just queue up the URLs.
671   if (!startupComplete_) {
672     startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
673     return;
674   }
676   // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
677   // startup urls in new tabs, because the omnibox will stay focused if we
678   // load url in NTP tab.
679   Browser* browser = chrome::GetLastActiveBrowser();
680   int startupIndex = TabStripModel::kNoTab;
681   content::WebContents* startupContent = NULL;
683   if (browser && browser->tab_strip_model()->count() == 1) {
684     startupIndex = browser->tab_strip_model()->active_index();
685     startupContent = browser->tab_strip_model()->GetActiveWebContents();
686   }
688   [self openUrls:urls];
690   if (startupIndex != TabStripModel::kNoTab &&
691       startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
692     browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
693         TabStripModel::CLOSE_NONE);
694   }
697 // This is called after profiles have been loaded and preferences registered.
698 // It is safe to access the default profile here.
699 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
700   MacStartupProfiler::GetInstance()->Profile(
701       MacStartupProfiler::DID_FINISH_LAUNCHING);
702   MacStartupProfiler::GetInstance()->RecordMetrics();
704   // Notify BrowserList to keep the application running so it doesn't go away
705   // when all the browser windows get closed.
706   chrome::IncrementKeepAliveCount();
708   [self setUpdateCheckInterval];
710   // Start managing the menu for app windows. This needs to be done here because
711   // main menu item titles are not yet initialized in awakeFromNib.
712   [self initAppShimMenuController];
714   // If enabled, keep Chrome alive when apps are open instead of quitting all
715   // apps.
716   quitWithAppsController_ = new QuitWithAppsController();
718   // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
719   [[closeTabMenuItem_ menu] setDelegate:self];
721   // Build up the encoding menu, the order of the items differs based on the
722   // current locale (see http://crbug.com/7647 for details).
723   // We need a valid g_browser_process to get the profile which is why we can't
724   // call this from awakeFromNib.
725   NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
726   NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
727   NSMenu* encodingMenu = [encodingMenuItem submenu];
728   EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
729                                                     encodingMenu);
731   // Instantiate the ProfileInfoCache observer so that we can get
732   // notified when a profile is deleted.
733   profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
734       g_browser_process->profile_manager(), self));
736   // Since Chrome is localized to more languages than the OS, tell Cocoa which
737   // menu is the Help so it can add the search item to it.
738   [NSApp setHelpMenu:helpMenu_];
740   // Record the path to the (browser) app bundle; this is used by the app mode
741   // shim.  It has to be done in FILE thread because getting the path requires
742   // I/O.
743   BrowserThread::PostTask(
744       BrowserThread::FILE, FROM_HERE,
745       base::Bind(&RecordLastRunAppBundlePath));
747   // Makes "Services" menu items available.
748   [self registerServicesMenuTypesTo:[notify object]];
750   startupComplete_ = YES;
752   Browser* browser =
753       FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
754   content::WebContents* activeWebContents = nullptr;
755   if (browser)
756     activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
757   [self updateHandoffManager:activeWebContents];
758   [self openStartupUrls];
760   PrefService* localState = g_browser_process->local_state();
761   if (localState) {
762     localPrefRegistrar_.Init(localState);
763     localPrefRegistrar_.Add(
764         prefs::kAllowFileSelectionDialogs,
765         base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
766                    menuState_.get()));
767   }
769   handoff_active_url_observer_bridge_.reset(
770       new HandoffActiveURLObserverBridge(self));
773 // This is called after profiles have been loaded and preferences registered.
774 // It is safe to access the default profile here.
775 - (void)applicationDidBecomeActive:(NSNotification*)notify {
776   content::PluginService::GetInstance()->AppActivated();
779 // Helper function for populating and displaying the in progress downloads at
780 // exit alert panel.
781 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
782   NSString* titleText = nil;
783   NSString* explanationText = nil;
784   NSString* waitTitle = nil;
785   NSString* exitTitle = nil;
787   // Set the dialog text based on whether or not there are multiple downloads.
788   // Dialog text: warning and explanation.
789   titleText = l10n_util::GetPluralNSStringF(
790       IDS_DOWNLOAD_REMOVE_CONFIRM_TITLE, downloadCount);
791   explanationText = l10n_util::GetPluralNSStringF(
792       IDS_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, downloadCount);
793   // Cancel download and exit button text.
794   exitTitle = l10n_util::GetPluralNSStringF(
795       IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL, downloadCount);
797   // Wait for download button text.
798   waitTitle = l10n_util::GetPluralNSStringF(
799       IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL, downloadCount);
801   // 'waitButton' is the default choice.
802   int choice = NSRunAlertPanel(titleText, @"%@",
803                                waitTitle, exitTitle, nil, explanationText);
804   return choice == NSAlertDefaultReturn ? YES : NO;
807 // Check all profiles for in progress downloads, and if we find any, prompt the
808 // user to see if we should continue to exit (and thus cancel the downloads), or
809 // if we should wait.
810 - (BOOL)shouldQuitWithInProgressDownloads {
811   ProfileManager* profile_manager = g_browser_process->profile_manager();
812   if (!profile_manager)
813     return YES;
815   std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
816   for (size_t i = 0; i < profiles.size(); ++i) {
817     DownloadService* download_service =
818       DownloadServiceFactory::GetForBrowserContext(profiles[i]);
819     DownloadManager* download_manager =
820         (download_service->HasCreatedDownloadManager() ?
821          BrowserContext::GetDownloadManager(profiles[i]) : NULL);
822     if (download_manager &&
823         download_manager->NonMaliciousInProgressCount() > 0) {
824       int downloadCount = download_manager->NonMaliciousInProgressCount();
825       if ([self userWillWaitForInProgressDownloads:downloadCount]) {
826         // Create a new browser window (if necessary) and navigate to the
827         // downloads page if the user chooses to wait.
828         Browser* browser = chrome::FindBrowserWithProfile(
829             profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
830         if (!browser) {
831           browser = new Browser(Browser::CreateParams(
832               profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
833           browser->window()->Show();
834         }
835         DCHECK(browser);
836         chrome::ShowDownloads(browser);
837         return NO;
838       }
840       // User wants to exit.
841       return YES;
842     }
843   }
845   // No profiles or active downloads found, okay to exit.
846   return YES;
849 // Called to determine if we should enable the "restore tab" menu item.
850 // Checks with the TabRestoreService to see if there's anything there to
851 // restore and returns YES if so.
852 - (BOOL)canRestoreTab {
853   TabRestoreService* service =
854       TabRestoreServiceFactory::GetForProfile([self lastProfile]);
855   return service && !service->entries().empty();
858 // Called from the AppControllerProfileObserver every time a profile is deleted.
859 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
860   // If the lastProfile has been deleted, the profile manager has
861   // already loaded a new one, so the pointer needs to be updated;
862   // otherwise we will try to start up a browser window with a pointer
863   // to the old profile.
864   // In a browser test, the application is not brought to the front, so
865   // |lastProfile_| might be null.
866   if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
867     // Force windowChangedToProfile: to set the lastProfile_ and also update the
868     // relevant menuBridge objects.
869     lastProfile_ = nullptr;
870     [self windowChangedToProfile:g_browser_process->profile_manager()->
871         GetLastUsedProfile()];
872   }
874   auto it = profileBookmarkMenuBridgeMap_.find(profilePath);
875   if (it != profileBookmarkMenuBridgeMap_.end()) {
876     delete it->second;
877     profileBookmarkMenuBridgeMap_.erase(it);
878   }
881 // Returns true if there is a modal window (either window- or application-
882 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
883 // sheets) will not count as blocking the browser. But things like open/save
884 // dialogs that are window modal will block the browser.
885 - (BOOL)keyWindowIsModal {
886   if ([NSApp modalWindow])
887     return YES;
889   Browser* browser = chrome::GetLastActiveBrowser();
890   return browser &&
891          [[browser->window()->GetNativeWindow() attachedSheet]
892              isKindOfClass:[NSWindow class]];
895 // Called to validate menu items when there are no key windows. All the
896 // items we care about have been set with the |commandDispatch:| action and
897 // a target of FirstResponder in IB. If it's not one of those, let it
898 // continue up the responder chain to be handled elsewhere. We pull out the
899 // tag as the cross-platform constant to differentiate and dispatch the
900 // various commands.
901 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
902   SEL action = [item action];
903   BOOL enable = NO;
904   if (action == @selector(commandDispatch:) ||
905       action == @selector(commandFromDock:)) {
906     NSInteger tag = [item tag];
907     if (menuState_ &&  // NULL in tests.
908         menuState_->SupportsCommand(tag)) {
909       switch (tag) {
910         // The File Menu commands are not automatically disabled by Cocoa when a
911         // dialog sheet obscures the browser window, so we disable several of
912         // them here.  We don't need to include IDC_CLOSE_WINDOW, because
913         // app_controller is only activated when there are no key windows (see
914         // function comment).
915         case IDC_RESTORE_TAB:
916           enable = ![self keyWindowIsModal] && [self canRestoreTab];
917           break;
918         // Browser-level items that open in new tabs should not open if there's
919         // a window- or app-modal dialog.
920         case IDC_OPEN_FILE:
921         case IDC_NEW_TAB:
922         case IDC_SHOW_HISTORY:
923         case IDC_SHOW_BOOKMARK_MANAGER:
924           enable = ![self keyWindowIsModal];
925           break;
926         // Browser-level items that open in new windows.
927         case IDC_TASK_MANAGER:
928           // Allow the user to open a new window if there's a window-modal
929           // dialog.
930           enable = ![self keyWindowIsModal];
931           break;
932 #if defined(GOOGLE_CHROME_BUILD)
933         case IDC_FEEDBACK:
934           enable = NO;
935           break;
936 #endif
937         default:
938           enable = menuState_->IsCommandEnabled(tag) ?
939                    ![self keyWindowIsModal] : NO;
940       }
941     }
942   } else if (action == @selector(terminate:)) {
943     enable = YES;
944   } else if (action == @selector(showPreferences:)) {
945     enable = YES;
946   } else if (action == @selector(orderFrontStandardAboutPanel:)) {
947     enable = YES;
948   } else if (action == @selector(commandFromDock:)) {
949     enable = YES;
950   } else if (action == @selector(toggleConfirmToQuit:)) {
951     [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
952     enable = YES;
953   } else if (action == @selector(toggleDisplayMessageCenter:)) {
954     NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
955     [self updateDisplayMessageCenterPrefMenuItem:menuItem];
956     enable = YES;
957   } else if (action == @selector(executeApplication:)) {
958     enable = YES;
959   }
960   return enable;
963 // Called when the user picks a menu item when there are no key windows, or when
964 // there is no foreground browser window. Calls through to the browser object to
965 // execute the command. This assumes that the command is supported and doesn't
966 // check, otherwise it should have been disabled in the UI in
967 // |-validateUserInterfaceItem:|.
968 - (void)commandDispatch:(id)sender {
969   Profile* lastProfile = [self safeLastProfileForNewWindows];
971   // Handle the case where we're dispatching a command from a sender that's in a
972   // browser window. This means that the command came from a background window
973   // and is getting here because the foreground window is not a browser window.
974   if ([sender respondsToSelector:@selector(window)]) {
975     id delegate = [[sender window] windowController];
976     if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
977       [delegate commandDispatch:sender];
978       return;
979     }
980   }
982   // Ignore commands during session restore's browser creation.  It uses a
983   // nested message loop and commands dispatched during this operation cause
984   // havoc.
985   if (SessionRestore::IsRestoring(lastProfile) &&
986       base::MessageLoop::current()->IsNested())
987     return;
989   NSInteger tag = [sender tag];
991   // If there are no browser windows, and we are trying to open a browser
992   // for a locked profile or the system profile, we have to show the User
993   // Manager instead as the locked profile needs authentication and the system
994   // profile cannot have a browser.
995   if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile()) {
996     UserManager::Show(base::FilePath(),
997                       profiles::USER_MANAGER_NO_TUTORIAL,
998                       profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
999     return;
1000   }
1002   switch (tag) {
1003     case IDC_NEW_TAB:
1004       // Create a new tab in an existing browser window (which we activate) if
1005       // possible.
1006       if (Browser* browser = ActivateBrowser(lastProfile)) {
1007         chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1008         break;
1009       }
1010       // Else fall through to create new window.
1011     case IDC_NEW_WINDOW:
1012       CreateBrowser(lastProfile);
1013       break;
1014     case IDC_FOCUS_LOCATION:
1015       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1016                              IDC_FOCUS_LOCATION);
1017       break;
1018     case IDC_FOCUS_SEARCH:
1019       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1020                              IDC_FOCUS_SEARCH);
1021       break;
1022     case IDC_NEW_INCOGNITO_WINDOW:
1023       CreateBrowser(lastProfile->GetOffTheRecordProfile());
1024       break;
1025     case IDC_RESTORE_TAB:
1026       // There is only the native desktop on Mac.
1027       chrome::OpenWindowWithRestoredTabs(lastProfile,
1028                                          chrome::HOST_DESKTOP_TYPE_NATIVE);
1029       break;
1030     case IDC_OPEN_FILE:
1031       chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1032       break;
1033     case IDC_CLEAR_BROWSING_DATA: {
1034       // There may not be a browser open, so use the default profile.
1035       if (Browser* browser = ActivateBrowser(lastProfile)) {
1036         chrome::ShowClearBrowsingDataDialog(browser);
1037       } else {
1038         chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1039       }
1040       break;
1041     }
1042     case IDC_IMPORT_SETTINGS: {
1043       if (Browser* browser = ActivateBrowser(lastProfile)) {
1044         chrome::ShowImportDialog(browser);
1045       } else {
1046         chrome::OpenImportSettingsDialogWindow(lastProfile);
1047       }
1048       break;
1049     }
1050     case IDC_SHOW_BOOKMARK_MANAGER:
1051       content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1052       if (Browser* browser = ActivateBrowser(lastProfile)) {
1053         chrome::ShowBookmarkManager(browser);
1054       } else {
1055         // No browser window, so create one for the bookmark manager tab.
1056         chrome::OpenBookmarkManagerWindow(lastProfile);
1057       }
1058       break;
1059     case IDC_SHOW_HISTORY:
1060       if (Browser* browser = ActivateBrowser(lastProfile))
1061         chrome::ShowHistory(browser);
1062       else
1063         chrome::OpenHistoryWindow(lastProfile);
1064       break;
1065     case IDC_SHOW_DOWNLOADS:
1066       if (Browser* browser = ActivateBrowser(lastProfile))
1067         chrome::ShowDownloads(browser);
1068       else
1069         chrome::OpenDownloadsWindow(lastProfile);
1070       break;
1071     case IDC_MANAGE_EXTENSIONS:
1072       if (Browser* browser = ActivateBrowser(lastProfile))
1073         chrome::ShowExtensions(browser, std::string());
1074       else
1075         chrome::OpenExtensionsWindow(lastProfile);
1076       break;
1077     case IDC_HELP_PAGE_VIA_MENU:
1078       if (Browser* browser = ActivateBrowser(lastProfile))
1079         chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1080       else
1081         chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1082       break;
1083     case IDC_TASK_MANAGER:
1084       chrome::OpenTaskManager(NULL);
1085       break;
1086     case IDC_OPTIONS:
1087       [self showPreferences:sender];
1088       break;
1089   }
1092 // Run a (background) application in a new tab.
1093 - (void)executeApplication:(id)sender {
1094   NSInteger tag = [sender tag];
1095   Profile* profile = [self lastProfile];
1096   DCHECK(profile);
1097   BackgroundApplicationListModel applications(profile);
1098   DCHECK(tag >= 0 &&
1099          tag < static_cast<int>(applications.size()));
1100   const extensions::Extension* extension = applications.GetExtension(tag);
1101   BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1104 // Same as |-commandDispatch:|, but executes commands using a disposition
1105 // determined by the key flags. This will get called in the case where the
1106 // frontmost window is not a browser window, and the user has command-clicked
1107 // a button in a background browser window whose action is
1108 // |-commandDispatchUsingKeyModifiers:|
1109 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1110   DCHECK(sender);
1111   if ([sender respondsToSelector:@selector(window)]) {
1112     id delegate = [[sender window] windowController];
1113     if ([delegate respondsToSelector:
1114             @selector(commandDispatchUsingKeyModifiers:)]) {
1115       [delegate commandDispatchUsingKeyModifiers:sender];
1116     }
1117   }
1120 // NSApplication delegate method called when someone clicks on the dock icon.
1121 // To match standard mac behavior, we should open a new window if there are no
1122 // browser windows.
1123 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1124                     hasVisibleWindows:(BOOL)hasVisibleWindows {
1125   // If the browser is currently trying to quit, don't do anything and return NO
1126   // to prevent AppKit from doing anything.
1127   // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1128   if (browser_shutdown::IsTryingToQuit())
1129     return NO;
1131   // Bring all browser windows to the front. Specifically, this brings them in
1132   // front of any app windows. FocusWindowSet will also unminimize the most
1133   // recently minimized window if no windows in the set are visible.
1134   // If there are any, return here. Otherwise, the windows are panels or
1135   // notifications so we still need to open a new window.
1136   if (hasVisibleWindows) {
1137     std::set<NSWindow*> browserWindows;
1138     for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1139       Browser* browser = *iter;
1140       // When focusing Chrome, don't focus any browser windows associated with
1141       // a currently running app shim, so ignore them.
1142       if (browser && browser->is_app()) {
1143         extensions::ExtensionRegistry* registry =
1144             extensions::ExtensionRegistry::Get(browser->profile());
1145         const extensions::Extension* extension = registry->GetExtensionById(
1146             web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1147             extensions::ExtensionRegistry::ENABLED);
1148         if (extension && extension->is_hosted_app())
1149           continue;
1150       }
1151       browserWindows.insert(browser->window()->GetNativeWindow());
1152     }
1153     if (!browserWindows.empty()) {
1154       NSWindow* keyWindow = [NSApp keyWindow];
1155       if (keyWindow && ![keyWindow isOnActiveSpace]) {
1156         // The key window is not on the active space. We must be mid-animation
1157         // for a space transition triggered by the dock. Delay the call to
1158         // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1159         // wrong space's windows get raised, resulting in an off-screen key
1160         // window. It does not work to |ui::FocusWindowSet| twice, once here
1161         // and once in |activeSpaceDidChange:|, as that appears to break when
1162         // the omnibox is focused.
1163         //
1164         // This check relies on OS X setting the key window to a window on the
1165         // target space before calling this method.
1166         //
1167         // See http://crbug.com/309656.
1168         reopenTime_ = base::TimeTicks::Now();
1169       } else {
1170         ui::FocusWindowSetOnCurrentSpace(browserWindows);
1171       }
1172       // Return NO; we've done (or soon will do) the deminiaturize, so
1173       // AppKit shouldn't do anything.
1174       return NO;
1175     }
1176   }
1178   // If launched as a hidden login item (due to installation of a persistent app
1179   // or by the user, for example in System Preferences->Accounts->Login Items),
1180   // allow session to be restored first time the user clicks on a Dock icon.
1181   // Normally, it'd just open a new empty page.
1182   {
1183     static BOOL doneOnce = NO;
1184     BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1185         (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1186     doneOnce = YES;
1187     if (attemptRestore) {
1188       SessionService* sessionService =
1189           SessionServiceFactory::GetForProfileForSessionRestore(
1190               [self lastProfile]);
1191       if (sessionService &&
1192           sessionService->RestoreIfNecessary(std::vector<GURL>()))
1193         return NO;
1194     }
1195   }
1197   // Otherwise open a new window.
1198   // If the last profile was locked, we have to open the User Manager, as the
1199   // profile requires authentication. Similarly, because guest mode and system
1200   // profile are implemented as forced incognito, we can't open a new guest
1201   // browser either, so we have to show the User Manager as well.
1202   Profile* lastProfile = [self lastProfile];
1203   if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1204       lastProfile->IsSystemProfile()) {
1205     UserManager::Show(base::FilePath(),
1206                       profiles::USER_MANAGER_NO_TUTORIAL,
1207                       profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1208   } else {
1209     CreateBrowser(lastProfile);
1210   }
1212   // We've handled the reopen event, so return NO to tell AppKit not
1213   // to do anything.
1214   return NO;
1217 - (void)initMenuState {
1218   menuState_.reset(new CommandUpdater(NULL));
1219   menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1220   menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1221   menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1222   menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1223   menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1224   menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1225   menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1226   menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1227   menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1228   menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1229   menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1230   menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1231   menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1232   menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1233 #if defined(GOOGLE_CHROME_BUILD)
1234   menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1235 #endif
1236   menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1239 // Conditionally adds the Profile menu to the main menu bar.
1240 - (void)initProfileMenu {
1241   NSMenu* mainMenu = [NSApp mainMenu];
1242   NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1244   if (!profiles::IsMultipleProfilesEnabled()) {
1245     [mainMenu removeItem:profileMenu];
1246     return;
1247   }
1249   // The controller will unhide the menu if necessary.
1250   [profileMenu setHidden:YES];
1252   profileMenuController_.reset(
1253       [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1256 // The Confirm to Quit preference is atypical in that the preference lives in
1257 // the app menu right above the Quit menu item. This method will refresh the
1258 // display of that item depending on the preference state.
1259 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1260   // Format the string so that the correct key equivalent is displayed.
1261   NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1262   NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1263       base::SysNSStringToUTF16(acceleratorString));
1264   [item setTitle:title];
1266   const PrefService* prefService = g_browser_process->local_state();
1267   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1268   [item setState:enabled ? NSOnState : NSOffState];
1271 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
1272   const PrefService* prefService = g_browser_process->local_state();
1273   bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1274   // The item should be checked if "show icon" is false, since the text reads
1275   // "Hide notification center icon."
1276   [item setState:enabled ? NSOffState : NSOnState];
1279 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1280   // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1281   // handles requests from services.
1282   NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1283   [app registerServicesMenuSendTypes:types returnTypes:types];
1286 - (Profile*)lastProfile {
1287   // Return the profile of the last-used Browser, if available.
1288   if (lastProfile_)
1289     return lastProfile_;
1291   // On first launch, use the logic that ChromeBrowserMain uses to determine
1292   // the initial profile.
1293   ProfileManager* profile_manager = g_browser_process->profile_manager();
1294   if (!profile_manager)
1295     return NULL;
1297   return profile_manager->GetProfile(
1298       GetStartupProfilePath(profile_manager->user_data_dir(),
1299                             *base::CommandLine::ForCurrentProcess()));
1302 - (Profile*)safeLastProfileForNewWindows {
1303   Profile* profile = [self lastProfile];
1305   // Guest sessions must always be OffTheRecord. Use that when opening windows.
1306   if (profile->IsGuestSession())
1307     return profile->GetOffTheRecordProfile();
1309   return profile;
1312 // Returns true if a browser window may be opened for the last active profile.
1313 - (bool)canOpenNewBrowser {
1314   Profile* profile = [self safeLastProfileForNewWindows];
1316   const PrefService* prefs = g_browser_process->local_state();
1317   return !profile->IsGuestSession() ||
1318          prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1321 // Various methods to open URLs that we get in a native fashion. We use
1322 // StartupBrowserCreator here because on the other platforms, URLs to open come
1323 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1324 // to bottleneck the openings through that for uniform handling.
1325 - (void)openUrls:(const std::vector<GURL>&)urls {
1326   if (!startupComplete_) {
1327     startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1328     return;
1329   }
1331   Browser* browser = chrome::GetLastActiveBrowser();
1332   // if no browser window exists then create one with no tabs to be filled in
1333   if (!browser) {
1334     browser = new Browser(Browser::CreateParams(
1335         [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1336     browser->window()->Show();
1337   }
1339   base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1340   chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1341       chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1342   StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1343   launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1346 - (void)getUrl:(NSAppleEventDescriptor*)event
1347      withReply:(NSAppleEventDescriptor*)reply {
1348   NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1349                       stringValue];
1351   GURL gurl(base::SysNSStringToUTF8(urlStr));
1352   std::vector<GURL> gurlVector;
1353   gurlVector.push_back(gurl);
1355   [self openUrlsReplacingNTP:gurlVector];
1358 - (void)application:(NSApplication*)sender
1359           openFiles:(NSArray*)filenames {
1360   std::vector<GURL> gurlVector;
1361   for (NSString* file in filenames) {
1362     GURL gurl =
1363         net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1364     gurlVector.push_back(gurl);
1365   }
1366   if (!gurlVector.empty())
1367     [self openUrlsReplacingNTP:gurlVector];
1368   else
1369     NOTREACHED() << "Nothing to open!";
1371   [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1374 // Show the preferences window, or bring it to the front if it's already
1375 // visible.
1376 - (IBAction)showPreferences:(id)sender {
1377   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1378     // Show options tab in the active browser window.
1379     chrome::ShowSettings(browser);
1380   } else if ([self canOpenNewBrowser]) {
1381     // No browser window, so create one for the options tab.
1382     chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
1383   } else {
1384     // No way to create a browser, default to the User Manager.
1385     UserManager::Show(base::FilePath(),
1386                       profiles::USER_MANAGER_NO_TUTORIAL,
1387                       profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
1388   }
1391 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1392   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1393     chrome::ShowAboutChrome(browser);
1394   } else if ([self canOpenNewBrowser]) {
1395     // No browser window, so create one for the options tab.
1396     chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
1397   } else {
1398     // No way to create a browser, default to the User Manager.
1399     UserManager::Show(base::FilePath(),
1400                       profiles::USER_MANAGER_NO_TUTORIAL,
1401                       profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
1402   }
1405 - (IBAction)toggleConfirmToQuit:(id)sender {
1406   PrefService* prefService = g_browser_process->local_state();
1407   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1408   prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1411 - (IBAction)toggleDisplayMessageCenter:(id)sender {
1412   PrefService* prefService = g_browser_process->local_state();
1413   bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1414   prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
1417 // Explicitly bring to the foreground when creating new windows from the dock.
1418 - (void)commandFromDock:(id)sender {
1419   [NSApp activateIgnoringOtherApps:YES];
1420   [self commandDispatch:sender];
1423 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1424   NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1425   Profile* profile = [self lastProfile];
1427   BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1428                                                           atOffset:0
1429                                                           fromDock:YES];
1430   if (profilesAdded)
1431     [dockMenu addItem:[NSMenuItem separatorItem]];
1433   NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1434   base::scoped_nsobject<NSMenuItem> item(
1435       [[NSMenuItem alloc] initWithTitle:titleStr
1436                                  action:@selector(commandFromDock:)
1437                           keyEquivalent:@""]);
1438   [item setTarget:self];
1439   [item setTag:IDC_NEW_WINDOW];
1440   [item setEnabled:[self validateUserInterfaceItem:item]];
1441   [dockMenu addItem:item];
1443   // |profile| can be NULL during unit tests.
1444   if (!profile ||
1445       IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1446           IncognitoModePrefs::DISABLED) {
1447     titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1448     item.reset(
1449         [[NSMenuItem alloc] initWithTitle:titleStr
1450                                    action:@selector(commandFromDock:)
1451                             keyEquivalent:@""]);
1452     [item setTarget:self];
1453     [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1454     [item setEnabled:[self validateUserInterfaceItem:item]];
1455     [dockMenu addItem:item];
1456   }
1458   // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1459   // tests which use the mock in place of the profile-initialized model.
1461   // Avoid breaking unit tests which have no profile.
1462   if (profile) {
1463     BackgroundApplicationListModel applications(profile);
1464     if (applications.size()) {
1465       int position = 0;
1466       NSString* menuStr =
1467           l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1468       base::scoped_nsobject<NSMenu> appMenu(
1469           [[NSMenu alloc] initWithTitle:menuStr]);
1470       for (extensions::ExtensionList::const_iterator cursor =
1471                applications.begin();
1472            cursor != applications.end();
1473            ++cursor, ++position) {
1474         DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1475         NSString* itemStr =
1476             base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1477         base::scoped_nsobject<NSMenuItem> appItem(
1478             [[NSMenuItem alloc] initWithTitle:itemStr
1479                                        action:@selector(executeApplication:)
1480                                 keyEquivalent:@""]);
1481         [appItem setTarget:self];
1482         [appItem setTag:position];
1483         [appMenu addItem:appItem];
1484       }
1485     }
1486   }
1488   return dockMenu;
1491 - (const std::vector<GURL>&)startupUrls {
1492   return startupUrls_;
1495 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1496   return bookmarkMenuBridge_;
1499 - (HistoryMenuBridge*)historyMenuBridge {
1500   return historyMenuBridge_.get();
1503 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1504   workAreaChangeObservers_.AddObserver(observer);
1507 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1508   workAreaChangeObservers_.RemoveObserver(observer);
1511 - (void)initAppShimMenuController {
1512   if (!appShimMenuController_)
1513     appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1516 - (void)windowChangedToProfile:(Profile*)profile {
1517   if (lastProfile_ == profile)
1518     return;
1520   // Before tearing down the menu controller bridges, return the history menu to
1521   // its initial state.
1522   if (historyMenuBridge_)
1523     historyMenuBridge_->ResetMenu();
1525   // Rebuild the menus with the new profile.
1526   lastProfile_ = profile;
1528   auto it = profileBookmarkMenuBridgeMap_.find(profile->GetPath());
1529   if (it == profileBookmarkMenuBridgeMap_.end()) {
1530     base::scoped_nsobject<NSMenu> submenu(
1531         [[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu] copy]);
1532     bookmarkMenuBridge_ = new BookmarkMenuBridge(profile, submenu);
1533     profileBookmarkMenuBridgeMap_[profile->GetPath()] = bookmarkMenuBridge_;
1534   } else {
1535     bookmarkMenuBridge_ = it->second;
1536   }
1538   [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] setSubmenu:
1539       bookmarkMenuBridge_->BookmarkMenu()];
1540   // No need to |BuildMenu| here.  It is done lazily upon menu access.
1542   historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1543   historyMenuBridge_->BuildMenu();
1545   chrome::BrowserCommandController::
1546       UpdateSharedCommandsForIncognitoAvailability(
1547           menuState_.get(), lastProfile_);
1548   profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1549   profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1550   profilePrefRegistrar_->Add(
1551       prefs::kIncognitoModeAvailability,
1552       base::Bind(&chrome::BrowserCommandController::
1553                      UpdateSharedCommandsForIncognitoAvailability,
1554                  menuState_.get(),
1555                  lastProfile_));
1558 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1559   // During this callback the working area is not always already updated. Defer.
1560   [self performSelector:@selector(delayedScreenParametersUpdate)
1561              withObject:nil
1562              afterDelay:0];
1565 - (void)delayedScreenParametersUpdate {
1566   FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1567       WorkAreaChanged());
1570 - (BOOL)application:(NSApplication*)application
1571     willContinueUserActivityWithType:(NSString*)userActivityType {
1572   return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1575 - (BOOL)application:(NSApplication*)application
1576     continueUserActivity:(NSUserActivity*)userActivity
1577       restorationHandler:(void (^)(NSArray*))restorationHandler {
1578   if (![userActivity.activityType
1579           isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1580     return NO;
1581   }
1583   NSString* originString = base::mac::ObjCCast<NSString>(
1584       [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1585   handoff::Origin origin = handoff::OriginFromString(originString);
1586   UMA_HISTOGRAM_ENUMERATION(
1587       "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1589   NSURL* url = userActivity.webpageURL;
1590   if (!url)
1591     return NO;
1593   GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1594   std::vector<GURL> gurlVector;
1595   gurlVector.push_back(gurl);
1597   [self openUrlsReplacingNTP:gurlVector];
1598   return YES;
1601 - (void)application:(NSApplication*)application
1602     didFailToContinueUserActivityWithType:(NSString*)userActivityType
1603                                     error:(NSError*)error {
1606 #pragma mark - Handoff Manager
1608 - (BOOL)shouldUseHandoff {
1609   return base::mac::IsOSYosemiteOrLater();
1612 - (void)passURLToHandoffManager:(const GURL&)handoffURL {
1613   [handoffManager_ updateActiveURL:handoffURL];
1616 - (void)updateHandoffManager:(content::WebContents*)webContents {
1617   if (![self shouldUseHandoff])
1618     return;
1620   if (!handoffManager_)
1621     handoffManager_.reset([[HandoffManager alloc] init]);
1623   GURL handoffURL = [self handoffURLFromWebContents:webContents];
1624   [self passURLToHandoffManager:handoffURL];
1627 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1628   if (!webContents)
1629     return GURL();
1631   Profile* profile =
1632       Profile::FromBrowserContext(webContents->GetBrowserContext());
1633   if (!profile)
1634     return GURL();
1636   // Handoff is not allowed from an incognito profile. To err on the safe side,
1637   // also disallow Handoff from a guest profile.
1638   if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1639     return GURL();
1641   if (!webContents)
1642     return GURL();
1644   return webContents->GetVisibleURL();
1647 #pragma mark - HandoffActiveURLObserverBridgeDelegate
1649 - (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1650   [self updateHandoffManager:webContents];
1653 @end  // @implementation AppController
1655 //---------------------------------------------------------------------------
1657 namespace app_controller_mac {
1659 bool IsOpeningNewWindow() {
1660   return g_is_opening_new_window;
1663 }  // namespace app_controller_mac