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"
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_factory.h"
44 #include "chrome/browser/signin/signin_manager_factory.h"
45 #include "chrome/browser/signin/signin_promo.h"
46 #include "chrome/browser/signin/signin_ui_util.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/sessions/core/tab_restore_service.h"
87 #include "components/signin/core/browser/signin_manager.h"
88 #include "components/signin/core/common/profile_management_switches.h"
89 #include "content/public/browser/browser_thread.h"
90 #include "content/public/browser/download_manager.h"
91 #include "content/public/browser/notification_service.h"
92 #include "content/public/browser/notification_types.h"
93 #include "content/public/browser/plugin_service.h"
94 #include "content/public/browser/user_metrics.h"
95 #include "extensions/browser/extension_registry.h"
96 #include "extensions/browser/extension_system.h"
97 #include "net/base/filename_util.h"
98 #include "ui/base/cocoa/focus_window_set.h"
99 #include "ui/base/l10n/l10n_util.h"
100 #include "ui/base/l10n/l10n_util_mac.h"
102 using apps::AppShimHandler;
103 using apps::ExtensionAppShimHandler;
104 using base::UserMetricsAction;
105 using content::BrowserContext;
106 using content::BrowserThread;
107 using content::DownloadManager;
111 // How long we allow a workspace change notification to wait to be
112 // associated with a dock activation. The animation lasts 250ms. See
113 // applicationShouldHandleReopen:hasVisibleWindows:.
114 static const int kWorkspaceChangeTimeoutMs = 500;
116 // True while AppController is calling chrome::NewEmptyWindow(). We need a
117 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
118 // because otherwise the SessionService will try to restore sessions when we
119 // make a new window while there are no other active windows.
120 bool g_is_opening_new_window = false;
122 // Activates a browser window having the given profile (the last one active) if
123 // possible and returns a pointer to the activate |Browser| or NULL if this was
124 // not possible. If the last active browser is minimized (in particular, if
125 // there are only minimized windows), it will unminimize it.
126 Browser* ActivateBrowser(Profile* profile) {
127 Browser* browser = chrome::FindLastActiveWithProfile(
128 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile,
129 chrome::HOST_DESKTOP_TYPE_NATIVE);
131 browser->window()->Activate();
135 // Creates an empty browser window with the given profile and returns a pointer
136 // to the new |Browser|.
137 Browser* CreateBrowser(Profile* profile) {
139 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
140 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
143 Browser* browser = chrome::GetLastActiveBrowser();
148 // Activates a browser window having the given profile (the last one active) if
149 // possible or creates an empty one if necessary. Returns a pointer to the
150 // activated/new |Browser|.
151 Browser* ActivateOrCreateBrowser(Profile* profile) {
152 if (Browser* browser = ActivateBrowser(profile))
154 return CreateBrowser(profile);
157 CFStringRef BaseBundleID_CFString() {
158 NSString* base_bundle_id =
159 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
160 return base::mac::NSToCFCast(base_bundle_id);
163 // This callback synchronizes preferences (under "org.chromium.Chromium" or
164 // "com.google.Chrome"), in particular, writes them out to disk.
165 void PrefsSyncCallback() {
166 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
167 LOG(WARNING) << "Error recording application bundle path.";
170 // Record the location of the application bundle (containing the main framework)
171 // from which Chromium was loaded. This is used by app mode shims to find
173 void RecordLastRunAppBundlePath() {
174 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
175 // real, user-visible app bundle directory. (The alternatives give either the
176 // framework's path or the initial app's path, which may be an app mode shim
178 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
180 base::FilePath app_bundle_path =
181 chrome::GetVersionedDirectory().DirName().DirName().DirName();
182 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
183 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
184 CFPreferencesSetAppValue(
185 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
186 app_bundle_path_cfstring, BaseBundleID_CFString());
188 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
189 BrowserThread::PostDelayedTask(
190 BrowserThread::FILE, FROM_HERE,
191 base::Bind(&PrefsSyncCallback),
192 base::TimeDelta::FromMilliseconds(1500));
195 bool IsProfileSignedOut(Profile* profile) {
196 // The signed out status only makes sense at the moment in the context of the
197 // --new-profile-management flag.
198 if (!switches::IsNewProfileManagement())
200 ProfileInfoCache& cache =
201 g_browser_process->profile_manager()->GetProfileInfoCache();
202 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
203 if (profile_index == std::string::npos)
205 return cache.ProfileIsSigninRequiredAtIndex(profile_index);
210 @interface AppController () <HandoffActiveURLObserverBridgeDelegate>
212 - (void)initMenuState;
213 - (void)initProfileMenu;
214 - (void)updateConfirmToQuitPrefMenuItem:(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
256 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
259 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
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);
270 ~AppControllerProfileObserver() override {
271 DCHECK(profile_manager_);
272 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
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];
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)updateSigninItem:(id)signinItem
306 shouldShow:(BOOL)showSigninMenuItem
307 currentProfile:(Profile*)profile {
308 DCHECK([signinItem isKindOfClass:[NSMenuItem class]]);
309 NSMenuItem* signinMenuItem = static_cast<NSMenuItem*>(signinItem);
311 // Look for a separator immediately after the menu item so it can be hidden
312 // or shown appropriately along with the signin menu item.
313 NSMenuItem* followingSeparator = nil;
314 NSMenu* menu = [signinItem menu];
316 NSInteger signinItemIndex = [menu indexOfItem:signinMenuItem];
317 DCHECK_NE(signinItemIndex, -1);
318 if ((signinItemIndex + 1) < [menu numberOfItems]) {
319 NSMenuItem* menuItem = [menu itemAtIndex:(signinItemIndex + 1)];
320 if ([menuItem isSeparatorItem]) {
321 followingSeparator = menuItem;
326 base::string16 label = signin_ui_util::GetSigninMenuLabel(profile);
327 [signinMenuItem setTitle:l10n_util::FixUpWindowsStyleLabel(label)];
328 [signinMenuItem setHidden:!showSigninMenuItem];
329 [followingSeparator setHidden:!showSigninMenuItem];
333 [[closeTabMenuItem_ menu] setDelegate:nil];
337 // This method is called very early in application startup (ie, before
338 // the profile is loaded or any preferences have been registered). Defer any
339 // user-data initialization until -applicationDidFinishLaunching:.
340 - (void)awakeFromNib {
341 MacStartupProfiler::GetInstance()->Profile(
342 MacStartupProfiler::AWAKE_FROM_NIB);
343 // We need to register the handlers early to catch events fired on launch.
344 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
345 [em setEventHandler:self
346 andSelector:@selector(getUrl:withReply:)
347 forEventClass:kInternetEventClass
348 andEventID:kAEGetURL];
349 [em setEventHandler:self
350 andSelector:@selector(getUrl:withReply:)
351 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
352 andEventID:'OURL']; // back to the Spyglass days.
354 NSNotificationCenter* notificationCenter =
355 [NSNotificationCenter defaultCenter];
358 selector:@selector(windowDidResignKey:)
359 name:NSWindowDidResignKeyNotification
363 selector:@selector(windowDidBecomeMain:)
364 name:NSWindowDidBecomeMainNotification
368 selector:@selector(windowDidResignMain:)
369 name:NSWindowDidResignMainNotification
372 // Register for space change notifications.
373 [[[NSWorkspace sharedWorkspace] notificationCenter]
375 selector:@selector(activeSpaceDidChange:)
376 name:NSWorkspaceActiveSpaceDidChangeNotification
379 [[[NSWorkspace sharedWorkspace] notificationCenter]
381 selector:@selector(willPowerOff:)
382 name:NSWorkspaceWillPowerOffNotification
385 // Set up the command updater for when there are no windows open
386 [self initMenuState];
388 // Initialize the Profile menu.
389 [self initProfileMenu];
392 - (void)unregisterEventHandlers {
393 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
394 [em removeEventHandlerForEventClass:kInternetEventClass
395 andEventID:kAEGetURL];
396 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
397 andEventID:cloud_print::kAECloudPrintClass];
398 [em removeEventHandlerForEventClass:'WWW!'
400 [[NSNotificationCenter defaultCenter] removeObserver:self];
401 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
404 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
405 // the default handlers.
406 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
407 MacStartupProfiler::GetInstance()->Profile(
408 MacStartupProfiler::WILL_FINISH_LAUNCHING);
411 - (void)applicationWillHide:(NSNotification*)notification {
412 apps::ExtensionAppShimHandler::OnChromeWillHide();
415 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
416 // Reset this now that we've received the call to terminate.
417 BOOL isPoweringOff = isPoweringOff_;
420 // Check for in-process downloads, and prompt the user if they really want
421 // to quit (and thus cancel downloads). Only check if we're not already
422 // shutting down, else the user might be prompted multiple times if the
423 // download isn't stopped before terminate is called again.
424 if (!browser_shutdown::IsTryingToQuit() &&
425 ![self shouldQuitWithInProgressDownloads])
428 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
429 // them in, but I'm not sure about UX; we'd also want to disable other things
430 // though.) http://crbug.com/40861
432 // Check if the user really wants to quit by employing the confirm-to-quit
434 if (!browser_shutdown::IsTryingToQuit() &&
435 [self applicationShouldTerminate:app] != NSTerminateNow)
438 // Check for active apps. If quitting is prevented, only close browsers and
440 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
441 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
442 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
443 switches::kHostedAppQuitNotification)) {
447 content::NotificationService::current()->Notify(
448 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
449 content::NotificationService::AllSources(),
450 content::NotificationService::NoDetails());
451 // This will close all browser sessions.
452 chrome::CloseAllBrowsers();
454 // At this point, the user has already chosen to cancel downloads. If we
455 // were to shut down as usual, the downloads would be cancelled in
456 // DownloadService::Shutdown().
457 DownloadService::CancelAllDownloads();
462 size_t num_browsers = chrome::GetTotalBrowserCount();
464 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
465 // already shutting down.
466 if (!browser_shutdown::IsTryingToQuit()) {
467 content::NotificationService::current()->Notify(
468 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
469 content::NotificationService::AllSources(),
470 content::NotificationService::NoDetails());
471 chrome::CloseAllBrowsersAndQuit();
474 return num_browsers == 0 ? YES : NO;
477 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
478 if (browser_shutdown::IsTryingToQuit()) {
479 // Reset the "trying to quit" state, so that closing all browser windows
480 // will no longer lead to termination.
481 browser_shutdown::SetTryingToQuit(false);
483 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
484 // would have to reinstall them here. http://crbug.com/40861
488 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
489 // If there are no windows, quit immediately.
490 if (chrome::BrowserIterator().done() &&
491 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
492 return NSTerminateNow;
495 // Check if the preference is turned on.
496 const PrefService* prefs = g_browser_process->local_state();
497 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
498 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
499 return NSTerminateNow;
502 // If the application is going to terminate as the result of a Cmd+Q
503 // invocation, use the special sauce to prevent accidental quitting.
504 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
506 // This logic is only for keyboard-initiated quits.
507 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
508 return NSTerminateNow;
510 return [[ConfirmQuitPanelController sharedController]
511 runModalLoopForApplication:app];
514 // Called when the app is shutting down. Clean-up as appropriate.
515 - (void)applicationWillTerminate:(NSNotification*)aNotification {
516 // There better be no browser windows left at this point.
517 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
519 // Tell BrowserList not to keep the browser process alive. Once all the
520 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
521 chrome::DecrementKeepAliveCount();
523 // Reset all pref watching, as this object outlives the prefs system.
524 profilePrefRegistrar_.reset();
525 localPrefRegistrar_.RemoveAll();
527 [self unregisterEventHandlers];
529 appShimMenuController_.reset();
531 STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
532 profileBookmarkMenuBridgeMap_.end());
535 - (void)didEndMainMessageLoop {
536 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
537 chrome::HOST_DESKTOP_TYPE_NATIVE));
538 if (!chrome::GetBrowserCount([self lastProfile],
539 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
540 // As we're shutting down, we need to nuke the TabRestoreService, which
541 // will start the shutdown of the NavigationControllers and allow for
542 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
543 // and may end up crashing when some thread tries to use the IO thread (or
544 // another thread) that is no longer valid.
545 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
549 // If the window has a tab controller, make "close window" be cmd-shift-w,
550 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
551 // affects whether the shift modifier is used.
552 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
553 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
555 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
558 // If the window has a tab controller, make "close tab" take over cmd-w,
559 // otherwise it shouldn't have any key-equivalent because it should be disabled.
560 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
561 if (enableCloseTabShortcut) {
562 [closeTabMenuItem_ setKeyEquivalent:@"w"];
563 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
565 [closeTabMenuItem_ setKeyEquivalent:@""];
566 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
570 // See if the focused window window has tabs, and adjust the key equivalents for
571 // Close Tab/Close Window accordingly.
572 - (void)menuNeedsUpdate:(NSMenu*)menu {
573 DCHECK(menu == [closeTabMenuItem_ menu]);
575 BOOL enableCloseTabShortcut = NO;
576 id target = [NSApp targetForAction:@selector(performClose:)];
578 // |target| is an instance of NSPopover or NSWindow.
579 // If a popover (likely the dictionary lookup popover), we want Cmd-W to
580 // close the popover so map it to "Close Window".
581 // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
582 if ([target isKindOfClass:[NSWindow class]]) {
583 NSWindow* window = target;
584 NSWindow* mainWindow = [NSApp mainWindow];
585 if (!window || ([window parentWindow] == mainWindow)) {
586 // If the target window is a child of the main window (e.g. a bubble), the
587 // main window should be the one that handles the close menu item action.
590 Browser* browser = chrome::FindBrowserWithWindow(window);
591 enableCloseTabShortcut = browser && browser->is_type_tabbed();
594 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
595 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
598 - (void)windowDidResignKey:(NSNotification*)notify {
599 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
600 // returns nil regardless of whether any suitable candidates for the key
601 // window remain. It seems that the new key window for the app is not set
602 // until after this notification is fired, so a check is performed after the
603 // run loop is allowed to spin.
604 [self performSelector:@selector(checkForAnyKeyWindows)
609 - (void)windowDidBecomeMain:(NSNotification*)notify {
610 Browser* browser = chrome::FindBrowserWithWindow([notify object]);
612 [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
615 - (void)windowDidResignMain:(NSNotification*)notify {
616 if (chrome::GetTotalBrowserCount() == 0) {
617 [self windowChangedToProfile:
618 g_browser_process->profile_manager()->GetLastUsedProfile()];
622 - (void)activeSpaceDidChange:(NSNotification*)notify {
623 if (reopenTime_.is_null() ||
625 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
626 kWorkspaceChangeTimeoutMs) {
630 // The last applicationShouldHandleReopen:hasVisibleWindows: call
631 // happened during a space change. Now that the change has
632 // completed, raise browser windows.
633 reopenTime_ = base::TimeTicks();
634 std::set<NSWindow*> browserWindows;
635 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
636 Browser* browser = *iter;
637 browserWindows.insert(browser->window()->GetNativeWindow());
639 if (!browserWindows.empty()) {
640 ui::FocusWindowSetOnCurrentSpace(browserWindows);
644 // Called when shutting down or logging out.
645 - (void)willPowerOff:(NSNotification*)notify {
646 // Don't attempt any shutdown here. Cocoa will shortly call
647 // -[BrowserCrApplication terminate:].
648 isPoweringOff_ = YES;
651 - (void)checkForAnyKeyWindows {
652 if ([NSApp keyWindow])
655 content::NotificationService::current()->Notify(
656 chrome::NOTIFICATION_NO_KEY_WINDOW,
657 content::NotificationService::AllSources(),
658 content::NotificationService::NoDetails());
661 // If the auto-update interval is not set, make it 5 hours.
662 // Placed here for 2 reasons:
663 // 1) Same spot as other Pref stuff
664 // 2) Try and be friendly by keeping this after app launch
665 - (void)setUpdateCheckInterval {
666 #if defined(GOOGLE_CHROME_BUILD)
667 CFStringRef app = CFSTR("com.google.Keystone.Agent");
668 CFStringRef checkInterval = CFSTR("checkInterval");
669 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
671 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
672 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
673 CFPreferencesSetAppValue(checkInterval, value, app);
674 CFPreferencesAppSynchronize(app);
679 - (void)openStartupUrls {
680 DCHECK(startupComplete_);
681 [self openUrlsReplacingNTP:startupUrls_];
682 startupUrls_.clear();
685 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
689 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
690 // NSApplication is created in MainMessageLoop, and then the shortcut urls
691 // are passed in via Apple events. At this point, the first browser is
692 // already loaded in PreMainMessageLoop. If we initialize NSApplication
693 // before PreMainMessageLoop to capture shortcut URL events, it may cause
694 // more problems because it relies on things created in PreMainMessageLoop
695 // and may break existing message loop design.
697 // If the browser hasn't started yet, just queue up the URLs.
698 if (!startupComplete_) {
699 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
703 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
704 // startup urls in new tabs, because the omnibox will stay focused if we
705 // load url in NTP tab.
706 Browser* browser = chrome::GetLastActiveBrowser();
707 int startupIndex = TabStripModel::kNoTab;
708 content::WebContents* startupContent = NULL;
710 if (browser && browser->tab_strip_model()->count() == 1) {
711 startupIndex = browser->tab_strip_model()->active_index();
712 startupContent = browser->tab_strip_model()->GetActiveWebContents();
715 [self openUrls:urls];
717 if (startupIndex != TabStripModel::kNoTab &&
718 startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
719 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
720 TabStripModel::CLOSE_NONE);
724 // This is called after profiles have been loaded and preferences registered.
725 // It is safe to access the default profile here.
726 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
727 MacStartupProfiler::GetInstance()->Profile(
728 MacStartupProfiler::DID_FINISH_LAUNCHING);
729 MacStartupProfiler::GetInstance()->RecordMetrics();
731 // Notify BrowserList to keep the application running so it doesn't go away
732 // when all the browser windows get closed.
733 chrome::IncrementKeepAliveCount();
735 [self setUpdateCheckInterval];
737 // Start managing the menu for app windows. This needs to be done here because
738 // main menu item titles are not yet initialized in awakeFromNib.
739 [self initAppShimMenuController];
741 // If enabled, keep Chrome alive when apps are open instead of quitting all
743 quitWithAppsController_ = new QuitWithAppsController();
745 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
746 [[closeTabMenuItem_ menu] setDelegate:self];
748 // Build up the encoding menu, the order of the items differs based on the
749 // current locale (see http://crbug.com/7647 for details).
750 // We need a valid g_browser_process to get the profile which is why we can't
751 // call this from awakeFromNib.
752 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
753 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
754 NSMenu* encodingMenu = [encodingMenuItem submenu];
755 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
758 // Instantiate the ProfileInfoCache observer so that we can get
759 // notified when a profile is deleted.
760 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
761 g_browser_process->profile_manager(), self));
763 // Since Chrome is localized to more languages than the OS, tell Cocoa which
764 // menu is the Help so it can add the search item to it.
765 [NSApp setHelpMenu:helpMenu_];
767 // Record the path to the (browser) app bundle; this is used by the app mode
768 // shim. It has to be done in FILE thread because getting the path requires
770 BrowserThread::PostTask(
771 BrowserThread::FILE, FROM_HERE,
772 base::Bind(&RecordLastRunAppBundlePath));
774 // Makes "Services" menu items available.
775 [self registerServicesMenuTypesTo:[notify object]];
777 startupComplete_ = YES;
780 FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
781 content::WebContents* activeWebContents = nullptr;
783 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
784 [self updateHandoffManager:activeWebContents];
785 [self openStartupUrls];
787 PrefService* localState = g_browser_process->local_state();
789 localPrefRegistrar_.Init(localState);
790 localPrefRegistrar_.Add(
791 prefs::kAllowFileSelectionDialogs,
792 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
796 handoff_active_url_observer_bridge_.reset(
797 new HandoffActiveURLObserverBridge(self));
800 // This is called after profiles have been loaded and preferences registered.
801 // It is safe to access the default profile here.
802 - (void)applicationDidBecomeActive:(NSNotification*)notify {
803 content::PluginService::GetInstance()->AppActivated();
806 // Helper function for populating and displaying the in progress downloads at
808 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
809 NSString* titleText = nil;
810 NSString* explanationText = nil;
811 NSString* waitTitle = nil;
812 NSString* exitTitle = nil;
814 // Set the dialog text based on whether or not there are multiple downloads.
815 // Dialog text: warning and explanation.
816 titleText = l10n_util::GetPluralNSStringF(
817 IDS_DOWNLOAD_REMOVE_CONFIRM_TITLE, downloadCount);
818 explanationText = l10n_util::GetPluralNSStringF(
819 IDS_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, downloadCount);
820 // Cancel download and exit button text.
821 exitTitle = l10n_util::GetPluralNSStringF(
822 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL, downloadCount);
824 // Wait for download button text.
825 waitTitle = l10n_util::GetPluralNSStringF(
826 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL, downloadCount);
828 // 'waitButton' is the default choice.
829 int choice = NSRunAlertPanel(titleText, @"%@",
830 waitTitle, exitTitle, nil, explanationText);
831 return choice == NSAlertDefaultReturn ? YES : NO;
834 // Check all profiles for in progress downloads, and if we find any, prompt the
835 // user to see if we should continue to exit (and thus cancel the downloads), or
836 // if we should wait.
837 - (BOOL)shouldQuitWithInProgressDownloads {
838 ProfileManager* profile_manager = g_browser_process->profile_manager();
839 if (!profile_manager)
842 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
843 for (size_t i = 0; i < profiles.size(); ++i) {
844 DownloadService* download_service =
845 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
846 DownloadManager* download_manager =
847 (download_service->HasCreatedDownloadManager() ?
848 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
849 if (download_manager &&
850 download_manager->NonMaliciousInProgressCount() > 0) {
851 int downloadCount = download_manager->NonMaliciousInProgressCount();
852 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
853 // Create a new browser window (if necessary) and navigate to the
854 // downloads page if the user chooses to wait.
855 Browser* browser = chrome::FindBrowserWithProfile(
856 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
858 browser = new Browser(Browser::CreateParams(
859 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
860 browser->window()->Show();
863 chrome::ShowDownloads(browser);
867 // User wants to exit.
872 // No profiles or active downloads found, okay to exit.
876 // Called to determine if we should enable the "restore tab" menu item.
877 // Checks with the TabRestoreService to see if there's anything there to
878 // restore and returns YES if so.
879 - (BOOL)canRestoreTab {
880 sessions::TabRestoreService* service =
881 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
882 return service && !service->entries().empty();
885 // Called from the AppControllerProfileObserver every time a profile is deleted.
886 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
887 // If the lastProfile has been deleted, the profile manager has
888 // already loaded a new one, so the pointer needs to be updated;
889 // otherwise we will try to start up a browser window with a pointer
890 // to the old profile.
891 // In a browser test, the application is not brought to the front, so
892 // |lastProfile_| might be null.
893 if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
894 // Force windowChangedToProfile: to set the lastProfile_ and also update the
895 // relevant menuBridge objects.
896 lastProfile_ = nullptr;
897 [self windowChangedToProfile:g_browser_process->profile_manager()->
898 GetLastUsedProfile()];
901 auto it = profileBookmarkMenuBridgeMap_.find(profilePath);
902 if (it != profileBookmarkMenuBridgeMap_.end()) {
904 profileBookmarkMenuBridgeMap_.erase(it);
908 // Returns true if there is a modal window (either window- or application-
909 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
910 // sheets) will not count as blocking the browser. But things like open/save
911 // dialogs that are window modal will block the browser.
912 - (BOOL)keyWindowIsModal {
913 if ([NSApp modalWindow])
916 Browser* browser = chrome::GetLastActiveBrowser();
918 [[browser->window()->GetNativeWindow() attachedSheet]
919 isKindOfClass:[NSWindow class]];
922 // Called to validate menu items when there are no key windows. All the
923 // items we care about have been set with the |commandDispatch:| action and
924 // a target of FirstResponder in IB. If it's not one of those, let it
925 // continue up the responder chain to be handled elsewhere. We pull out the
926 // tag as the cross-platform constant to differentiate and dispatch the
928 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
929 SEL action = [item action];
931 if (action == @selector(commandDispatch:) ||
932 action == @selector(commandFromDock:)) {
933 NSInteger tag = [item tag];
934 if (menuState_ && // NULL in tests.
935 menuState_->SupportsCommand(tag)) {
937 // The File Menu commands are not automatically disabled by Cocoa when a
938 // dialog sheet obscures the browser window, so we disable several of
939 // them here. We don't need to include IDC_CLOSE_WINDOW, because
940 // app_controller is only activated when there are no key windows (see
941 // function comment).
942 case IDC_RESTORE_TAB:
943 enable = ![self keyWindowIsModal] && [self canRestoreTab];
945 // Browser-level items that open in new tabs should not open if there's
946 // a window- or app-modal dialog.
949 case IDC_SHOW_HISTORY:
950 case IDC_SHOW_BOOKMARK_MANAGER:
951 enable = ![self keyWindowIsModal];
953 // Browser-level items that open in new windows.
954 case IDC_TASK_MANAGER:
955 // Allow the user to open a new window if there's a window-modal
957 enable = ![self keyWindowIsModal];
959 case IDC_SHOW_SYNC_SETUP: {
960 Profile* lastProfile = [self lastProfile];
961 // The profile may be NULL during shutdown -- see
962 // http://code.google.com/p/chromium/issues/detail?id=43048 .
964 // TODO(akalin,viettrungluu): Figure out whether this method
965 // can be prevented from being called if lastProfile is
969 << "NULL lastProfile detected -- not doing anything";
972 SigninManager* signin = SigninManagerFactory::GetForProfile(
973 lastProfile->GetOriginalProfile());
974 enable = signin->IsSigninAllowed() && ![self keyWindowIsModal];
975 [AppController updateSigninItem:item
977 currentProfile:lastProfile];
980 #if defined(GOOGLE_CHROME_BUILD)
986 enable = menuState_->IsCommandEnabled(tag) ?
987 ![self keyWindowIsModal] : NO;
990 } else if (action == @selector(terminate:)) {
992 } else if (action == @selector(showPreferences:)) {
994 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
996 } else if (action == @selector(commandFromDock:)) {
998 } else if (action == @selector(toggleConfirmToQuit:)) {
999 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
1001 } else if (action == @selector(toggleDisplayMessageCenter:)) {
1002 // TODO(dewittj): Remove this (see crbug.com/530376) with a separate update
1005 } else if (action == @selector(executeApplication:)) {
1011 // Called when the user picks a menu item when there are no key windows, or when
1012 // there is no foreground browser window. Calls through to the browser object to
1013 // execute the command. This assumes that the command is supported and doesn't
1014 // check, otherwise it should have been disabled in the UI in
1015 // |-validateUserInterfaceItem:|.
1016 - (void)commandDispatch:(id)sender {
1017 Profile* lastProfile = [self safeLastProfileForNewWindows];
1019 // Handle the case where we're dispatching a command from a sender that's in a
1020 // browser window. This means that the command came from a background window
1021 // and is getting here because the foreground window is not a browser window.
1022 if ([sender respondsToSelector:@selector(window)]) {
1023 id delegate = [[sender window] windowController];
1024 if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
1025 [delegate commandDispatch:sender];
1030 // Ignore commands during session restore's browser creation. It uses a
1031 // nested message loop and commands dispatched during this operation cause
1033 if (SessionRestore::IsRestoring(lastProfile) &&
1034 base::MessageLoop::current()->IsNested())
1037 NSInteger tag = [sender tag];
1039 // If there are no browser windows, and we are trying to open a browser
1040 // for a locked profile or the system profile, we have to show the User
1041 // Manager instead as the locked profile needs authentication and the system
1042 // profile cannot have a browser.
1043 if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile()) {
1044 UserManager::Show(base::FilePath(),
1045 profiles::USER_MANAGER_NO_TUTORIAL,
1046 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1052 // Create a new tab in an existing browser window (which we activate) if
1054 if (Browser* browser = ActivateBrowser(lastProfile)) {
1055 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1058 // Else fall through to create new window.
1059 case IDC_NEW_WINDOW:
1060 CreateBrowser(lastProfile);
1062 case IDC_FOCUS_LOCATION:
1063 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1064 IDC_FOCUS_LOCATION);
1066 case IDC_FOCUS_SEARCH:
1067 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1070 case IDC_NEW_INCOGNITO_WINDOW:
1071 CreateBrowser(lastProfile->GetOffTheRecordProfile());
1073 case IDC_RESTORE_TAB:
1074 // There is only the native desktop on Mac.
1075 chrome::OpenWindowWithRestoredTabs(lastProfile,
1076 chrome::HOST_DESKTOP_TYPE_NATIVE);
1079 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1081 case IDC_CLEAR_BROWSING_DATA: {
1082 // There may not be a browser open, so use the default profile.
1083 if (Browser* browser = ActivateBrowser(lastProfile)) {
1084 chrome::ShowClearBrowsingDataDialog(browser);
1086 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1090 case IDC_IMPORT_SETTINGS: {
1091 if (Browser* browser = ActivateBrowser(lastProfile)) {
1092 chrome::ShowImportDialog(browser);
1094 chrome::OpenImportSettingsDialogWindow(lastProfile);
1098 case IDC_SHOW_BOOKMARK_MANAGER:
1099 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1100 if (Browser* browser = ActivateBrowser(lastProfile)) {
1101 chrome::ShowBookmarkManager(browser);
1103 // No browser window, so create one for the bookmark manager tab.
1104 chrome::OpenBookmarkManagerWindow(lastProfile);
1107 case IDC_SHOW_HISTORY:
1108 if (Browser* browser = ActivateBrowser(lastProfile))
1109 chrome::ShowHistory(browser);
1111 chrome::OpenHistoryWindow(lastProfile);
1113 case IDC_SHOW_DOWNLOADS:
1114 if (Browser* browser = ActivateBrowser(lastProfile))
1115 chrome::ShowDownloads(browser);
1117 chrome::OpenDownloadsWindow(lastProfile);
1119 case IDC_MANAGE_EXTENSIONS:
1120 if (Browser* browser = ActivateBrowser(lastProfile))
1121 chrome::ShowExtensions(browser, std::string());
1123 chrome::OpenExtensionsWindow(lastProfile);
1125 case IDC_HELP_PAGE_VIA_MENU:
1126 if (Browser* browser = ActivateBrowser(lastProfile))
1127 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1129 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1131 case IDC_SHOW_SYNC_SETUP:
1132 if (Browser* browser = ActivateBrowser(lastProfile)) {
1133 chrome::ShowBrowserSigninOrSettings(browser,
1134 signin_metrics::SOURCE_MENU);
1136 chrome::OpenSyncSetupWindow(lastProfile, signin_metrics::SOURCE_MENU);
1139 case IDC_TASK_MANAGER:
1140 chrome::OpenTaskManager(NULL);
1143 [self showPreferences:sender];
1148 // Run a (background) application in a new tab.
1149 - (void)executeApplication:(id)sender {
1150 NSInteger tag = [sender tag];
1151 Profile* profile = [self lastProfile];
1153 BackgroundApplicationListModel applications(profile);
1155 tag < static_cast<int>(applications.size()));
1156 const extensions::Extension* extension = applications.GetExtension(tag);
1157 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1160 // Same as |-commandDispatch:|, but executes commands using a disposition
1161 // determined by the key flags. This will get called in the case where the
1162 // frontmost window is not a browser window, and the user has command-clicked
1163 // a button in a background browser window whose action is
1164 // |-commandDispatchUsingKeyModifiers:|
1165 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1167 if ([sender respondsToSelector:@selector(window)]) {
1168 id delegate = [[sender window] windowController];
1169 if ([delegate respondsToSelector:
1170 @selector(commandDispatchUsingKeyModifiers:)]) {
1171 [delegate commandDispatchUsingKeyModifiers:sender];
1176 // NSApplication delegate method called when someone clicks on the dock icon.
1177 // To match standard mac behavior, we should open a new window if there are no
1179 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1180 hasVisibleWindows:(BOOL)hasVisibleWindows {
1181 // If the browser is currently trying to quit, don't do anything and return NO
1182 // to prevent AppKit from doing anything.
1183 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1184 if (browser_shutdown::IsTryingToQuit())
1187 // Bring all browser windows to the front. Specifically, this brings them in
1188 // front of any app windows. FocusWindowSet will also unminimize the most
1189 // recently minimized window if no windows in the set are visible.
1190 // If there are any, return here. Otherwise, the windows are panels or
1191 // notifications so we still need to open a new window.
1192 if (hasVisibleWindows) {
1193 std::set<NSWindow*> browserWindows;
1194 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1195 Browser* browser = *iter;
1196 // When focusing Chrome, don't focus any browser windows associated with
1197 // a currently running app shim, so ignore them.
1198 if (browser && browser->is_app()) {
1199 extensions::ExtensionRegistry* registry =
1200 extensions::ExtensionRegistry::Get(browser->profile());
1201 const extensions::Extension* extension = registry->GetExtensionById(
1202 web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1203 extensions::ExtensionRegistry::ENABLED);
1204 if (extension && extension->is_hosted_app())
1207 browserWindows.insert(browser->window()->GetNativeWindow());
1209 if (!browserWindows.empty()) {
1210 NSWindow* keyWindow = [NSApp keyWindow];
1211 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1212 // The key window is not on the active space. We must be mid-animation
1213 // for a space transition triggered by the dock. Delay the call to
1214 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1215 // wrong space's windows get raised, resulting in an off-screen key
1216 // window. It does not work to |ui::FocusWindowSet| twice, once here
1217 // and once in |activeSpaceDidChange:|, as that appears to break when
1218 // the omnibox is focused.
1220 // This check relies on OS X setting the key window to a window on the
1221 // target space before calling this method.
1223 // See http://crbug.com/309656.
1224 reopenTime_ = base::TimeTicks::Now();
1226 ui::FocusWindowSetOnCurrentSpace(browserWindows);
1228 // Return NO; we've done (or soon will do) the deminiaturize, so
1229 // AppKit shouldn't do anything.
1234 // If launched as a hidden login item (due to installation of a persistent app
1235 // or by the user, for example in System Preferences->Accounts->Login Items),
1236 // allow session to be restored first time the user clicks on a Dock icon.
1237 // Normally, it'd just open a new empty page.
1239 static BOOL doneOnce = NO;
1240 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1241 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1243 if (attemptRestore) {
1244 SessionService* sessionService =
1245 SessionServiceFactory::GetForProfileForSessionRestore(
1246 [self lastProfile]);
1247 if (sessionService &&
1248 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1253 // Otherwise open a new window.
1254 // If the last profile was locked, we have to open the User Manager, as the
1255 // profile requires authentication. Similarly, because guest mode and system
1256 // profile are implemented as forced incognito, we can't open a new guest
1257 // browser either, so we have to show the User Manager as well.
1258 Profile* lastProfile = [self lastProfile];
1259 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1260 lastProfile->IsSystemProfile()) {
1261 UserManager::Show(base::FilePath(),
1262 profiles::USER_MANAGER_NO_TUTORIAL,
1263 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1265 CreateBrowser(lastProfile);
1268 // We've handled the reopen event, so return NO to tell AppKit not
1273 - (void)initMenuState {
1274 menuState_.reset(new CommandUpdater(NULL));
1275 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1276 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1277 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1278 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1279 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1280 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1281 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1282 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1283 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1284 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1285 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1286 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1287 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1288 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1289 #if defined(GOOGLE_CHROME_BUILD)
1290 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1292 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1293 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1296 // Conditionally adds the Profile menu to the main menu bar.
1297 - (void)initProfileMenu {
1298 NSMenu* mainMenu = [NSApp mainMenu];
1299 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1301 if (!profiles::IsMultipleProfilesEnabled()) {
1302 [mainMenu removeItem:profileMenu];
1306 // The controller will unhide the menu if necessary.
1307 [profileMenu setHidden:YES];
1309 profileMenuController_.reset(
1310 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1313 // The Confirm to Quit preference is atypical in that the preference lives in
1314 // the app menu right above the Quit menu item. This method will refresh the
1315 // display of that item depending on the preference state.
1316 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1317 // Format the string so that the correct key equivalent is displayed.
1318 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1319 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1320 base::SysNSStringToUTF16(acceleratorString));
1321 [item setTitle:title];
1323 const PrefService* prefService = g_browser_process->local_state();
1324 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1325 [item setState:enabled ? NSOnState : NSOffState];
1328 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1329 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1330 // handles requests from services.
1331 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1332 [app registerServicesMenuSendTypes:types returnTypes:types];
1335 - (Profile*)lastProfile {
1336 // Return the profile of the last-used Browser, if available.
1338 return lastProfile_;
1340 // On first launch, use the logic that ChromeBrowserMain uses to determine
1341 // the initial profile.
1342 ProfileManager* profile_manager = g_browser_process->profile_manager();
1343 if (!profile_manager)
1346 return profile_manager->GetProfile(
1347 GetStartupProfilePath(profile_manager->user_data_dir(),
1348 *base::CommandLine::ForCurrentProcess()));
1351 - (Profile*)safeLastProfileForNewWindows {
1352 Profile* profile = [self lastProfile];
1354 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1355 if (profile->IsGuestSession())
1356 return profile->GetOffTheRecordProfile();
1361 // Returns true if a browser window may be opened for the last active profile.
1362 - (bool)canOpenNewBrowser {
1363 Profile* profile = [self safeLastProfileForNewWindows];
1365 const PrefService* prefs = g_browser_process->local_state();
1366 return !profile->IsGuestSession() ||
1367 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1370 // Various methods to open URLs that we get in a native fashion. We use
1371 // StartupBrowserCreator here because on the other platforms, URLs to open come
1372 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1373 // to bottleneck the openings through that for uniform handling.
1374 - (void)openUrls:(const std::vector<GURL>&)urls {
1375 if (!startupComplete_) {
1376 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1380 Browser* browser = chrome::GetLastActiveBrowser();
1381 // if no browser window exists then create one with no tabs to be filled in
1383 browser = new Browser(Browser::CreateParams(
1384 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1385 browser->window()->Show();
1388 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1389 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1390 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1391 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1392 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1395 - (void)getUrl:(NSAppleEventDescriptor*)event
1396 withReply:(NSAppleEventDescriptor*)reply {
1397 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1400 GURL gurl(base::SysNSStringToUTF8(urlStr));
1401 std::vector<GURL> gurlVector;
1402 gurlVector.push_back(gurl);
1404 [self openUrlsReplacingNTP:gurlVector];
1407 - (void)application:(NSApplication*)sender
1408 openFiles:(NSArray*)filenames {
1409 std::vector<GURL> gurlVector;
1410 for (NSString* file in filenames) {
1412 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1413 gurlVector.push_back(gurl);
1415 if (!gurlVector.empty())
1416 [self openUrlsReplacingNTP:gurlVector];
1418 NOTREACHED() << "Nothing to open!";
1420 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1423 // Show the preferences window, or bring it to the front if it's already
1425 - (IBAction)showPreferences:(id)sender {
1426 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1427 // Show options tab in the active browser window.
1428 chrome::ShowSettings(browser);
1429 } else if ([self canOpenNewBrowser]) {
1430 // No browser window, so create one for the options tab.
1431 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
1433 // No way to create a browser, default to the User Manager.
1434 UserManager::Show(base::FilePath(),
1435 profiles::USER_MANAGER_NO_TUTORIAL,
1436 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
1440 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1441 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1442 chrome::ShowAboutChrome(browser);
1443 } else if ([self canOpenNewBrowser]) {
1444 // No browser window, so create one for the options tab.
1445 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
1447 // No way to create a browser, default to the User Manager.
1448 UserManager::Show(base::FilePath(),
1449 profiles::USER_MANAGER_NO_TUTORIAL,
1450 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
1454 - (IBAction)toggleConfirmToQuit:(id)sender {
1455 PrefService* prefService = g_browser_process->local_state();
1456 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1457 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1460 - (IBAction)toggleDisplayMessageCenter:(id)sender {
1461 // TODO(dewittj): Remove this (see crbug.com/530376) with a separate update to
1465 // Explicitly bring to the foreground when creating new windows from the dock.
1466 - (void)commandFromDock:(id)sender {
1467 [NSApp activateIgnoringOtherApps:YES];
1468 [self commandDispatch:sender];
1471 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1472 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1473 Profile* profile = [self lastProfile];
1475 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1479 [dockMenu addItem:[NSMenuItem separatorItem]];
1481 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1482 base::scoped_nsobject<NSMenuItem> item(
1483 [[NSMenuItem alloc] initWithTitle:titleStr
1484 action:@selector(commandFromDock:)
1485 keyEquivalent:@""]);
1486 [item setTarget:self];
1487 [item setTag:IDC_NEW_WINDOW];
1488 [item setEnabled:[self validateUserInterfaceItem:item]];
1489 [dockMenu addItem:item];
1491 // |profile| can be NULL during unit tests.
1493 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1494 IncognitoModePrefs::DISABLED) {
1495 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1497 [[NSMenuItem alloc] initWithTitle:titleStr
1498 action:@selector(commandFromDock:)
1499 keyEquivalent:@""]);
1500 [item setTarget:self];
1501 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1502 [item setEnabled:[self validateUserInterfaceItem:item]];
1503 [dockMenu addItem:item];
1506 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1507 // tests which use the mock in place of the profile-initialized model.
1509 // Avoid breaking unit tests which have no profile.
1511 BackgroundApplicationListModel applications(profile);
1512 if (applications.size()) {
1515 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1516 base::scoped_nsobject<NSMenu> appMenu(
1517 [[NSMenu alloc] initWithTitle:menuStr]);
1518 for (extensions::ExtensionList::const_iterator cursor =
1519 applications.begin();
1520 cursor != applications.end();
1521 ++cursor, ++position) {
1522 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1524 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1525 base::scoped_nsobject<NSMenuItem> appItem(
1526 [[NSMenuItem alloc] initWithTitle:itemStr
1527 action:@selector(executeApplication:)
1528 keyEquivalent:@""]);
1529 [appItem setTarget:self];
1530 [appItem setTag:position];
1531 [appMenu addItem:appItem];
1539 - (const std::vector<GURL>&)startupUrls {
1540 return startupUrls_;
1543 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1544 return bookmarkMenuBridge_;
1547 - (HistoryMenuBridge*)historyMenuBridge {
1548 return historyMenuBridge_.get();
1551 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1552 workAreaChangeObservers_.AddObserver(observer);
1555 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1556 workAreaChangeObservers_.RemoveObserver(observer);
1559 - (void)initAppShimMenuController {
1560 if (!appShimMenuController_)
1561 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1564 - (void)windowChangedToProfile:(Profile*)profile {
1565 if (lastProfile_ == profile)
1568 // Before tearing down the menu controller bridges, return the history menu to
1569 // its initial state.
1570 if (historyMenuBridge_)
1571 historyMenuBridge_->ResetMenu();
1573 // Rebuild the menus with the new profile. The bookmarks submenu is cached to
1574 // avoid slowdowns when switching between profiles with large numbers of
1575 // bookmarks. Before caching, store whether it is hidden, make the menu item
1576 // visible, and restore its original hidden state after resetting the submenu.
1577 // This works around an apparent AppKit bug where setting a *different* NSMenu
1578 // submenu on a *hidden* menu item forces the item to become visible.
1579 // See https://crbug.com/497813 for more details.
1580 NSMenuItem* bookmarkItem = [[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU];
1581 BOOL hidden = [bookmarkItem isHidden];
1582 [bookmarkItem setHidden:NO];
1583 lastProfile_ = profile;
1585 auto it = profileBookmarkMenuBridgeMap_.find(profile->GetPath());
1586 if (it == profileBookmarkMenuBridgeMap_.end()) {
1587 base::scoped_nsobject<NSMenu> submenu([[bookmarkItem submenu] copy]);
1588 bookmarkMenuBridge_ = new BookmarkMenuBridge(profile, submenu);
1589 profileBookmarkMenuBridgeMap_[profile->GetPath()] = bookmarkMenuBridge_;
1591 bookmarkMenuBridge_ = it->second;
1594 // No need to |BuildMenu| here. It is done lazily upon menu access.
1595 [bookmarkItem setSubmenu:bookmarkMenuBridge_->BookmarkMenu()];
1596 [bookmarkItem setHidden:hidden];
1598 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1599 historyMenuBridge_->BuildMenu();
1601 chrome::BrowserCommandController::
1602 UpdateSharedCommandsForIncognitoAvailability(
1603 menuState_.get(), lastProfile_);
1604 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1605 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1606 profilePrefRegistrar_->Add(
1607 prefs::kIncognitoModeAvailability,
1608 base::Bind(&chrome::BrowserCommandController::
1609 UpdateSharedCommandsForIncognitoAvailability,
1614 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1615 // During this callback the working area is not always already updated. Defer.
1616 [self performSelector:@selector(delayedScreenParametersUpdate)
1621 - (void)delayedScreenParametersUpdate {
1622 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1626 - (BOOL)application:(NSApplication*)application
1627 willContinueUserActivityWithType:(NSString*)userActivityType {
1628 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1631 - (BOOL)application:(NSApplication*)application
1632 continueUserActivity:(NSUserActivity*)userActivity
1633 restorationHandler:(void (^)(NSArray*))restorationHandler {
1634 if (![userActivity.activityType
1635 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1639 NSString* originString = base::mac::ObjCCast<NSString>(
1640 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1641 handoff::Origin origin = handoff::OriginFromString(originString);
1642 UMA_HISTOGRAM_ENUMERATION(
1643 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1645 NSURL* url = userActivity.webpageURL;
1649 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1650 std::vector<GURL> gurlVector;
1651 gurlVector.push_back(gurl);
1653 [self openUrlsReplacingNTP:gurlVector];
1657 - (void)application:(NSApplication*)application
1658 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1659 error:(NSError*)error {
1662 #pragma mark - Handoff Manager
1664 - (BOOL)shouldUseHandoff {
1665 return base::mac::IsOSYosemiteOrLater();
1668 - (void)passURLToHandoffManager:(const GURL&)handoffURL {
1669 [handoffManager_ updateActiveURL:handoffURL];
1672 - (void)updateHandoffManager:(content::WebContents*)webContents {
1673 if (![self shouldUseHandoff])
1676 if (!handoffManager_)
1677 handoffManager_.reset([[HandoffManager alloc] init]);
1679 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1680 [self passURLToHandoffManager:handoffURL];
1683 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1688 Profile::FromBrowserContext(webContents->GetBrowserContext());
1692 // Handoff is not allowed from an incognito profile. To err on the safe side,
1693 // also disallow Handoff from a guest profile.
1694 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1700 return webContents->GetVisibleURL();
1703 #pragma mark - HandoffActiveURLObserverBridgeDelegate
1705 - (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1706 [self updateHandoffManager:webContents];
1709 @end // @implementation AppController
1711 //---------------------------------------------------------------------------
1713 namespace app_controller_mac {
1715 bool IsOpeningNewWindow() {
1716 return g_is_opening_new_window;
1719 } // namespace app_controller_mac