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.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/browser_window_cocoa.h"
62 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
63 #import "chrome/browser/ui/cocoa/confirm_quit.h"
64 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
65 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
66 #include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
67 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
68 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
69 #import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
70 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
71 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
72 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
73 #include "chrome/browser/ui/extensions/application_launch.h"
74 #include "chrome/browser/ui/host_desktop.h"
75 #include "chrome/browser/ui/startup/startup_browser_creator.h"
76 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
77 #include "chrome/browser/ui/user_manager.h"
78 #include "chrome/browser/web_applications/web_app_mac.h"
79 #include "chrome/common/chrome_paths_internal.h"
80 #include "chrome/common/chrome_switches.h"
81 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
82 #include "chrome/common/extensions/extension_constants.h"
83 #include "chrome/common/mac/app_mode_common.h"
84 #include "chrome/common/pref_names.h"
85 #include "chrome/common/url_constants.h"
86 #include "chrome/grit/chromium_strings.h"
87 #include "chrome/grit/generated_resources.h"
88 #include "components/handoff/handoff_manager.h"
89 #include "components/handoff/handoff_utility.h"
90 #include "components/signin/core/browser/signin_manager.h"
91 #include "components/signin/core/common/profile_management_switches.h"
92 #include "content/public/browser/browser_thread.h"
93 #include "content/public/browser/download_manager.h"
94 #include "content/public/browser/notification_service.h"
95 #include "content/public/browser/notification_types.h"
96 #include "content/public/browser/plugin_service.h"
97 #include "content/public/browser/user_metrics.h"
98 #include "extensions/browser/extension_system.h"
99 #include "extensions/browser/extension_registry.h"
100 #include "net/base/filename_util.h"
101 #include "ui/base/cocoa/focus_window_set.h"
102 #include "ui/base/l10n/l10n_util.h"
103 #include "ui/base/l10n/l10n_util_mac.h"
105 using apps::AppShimHandler;
106 using apps::ExtensionAppShimHandler;
107 using base::UserMetricsAction;
108 using content::BrowserContext;
109 using content::BrowserThread;
110 using content::DownloadManager;
114 // Declare notification names from the 10.7 SDK.
115 #if !defined(MAC_OS_X_VERSION_10_7) || \
116 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
117 NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
118 NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
121 // How long we allow a workspace change notification to wait to be
122 // associated with a dock activation. The animation lasts 250ms. See
123 // applicationShouldHandleReopen:hasVisibleWindows:.
124 static const int kWorkspaceChangeTimeoutMs = 500;
126 // True while AppController is calling chrome::NewEmptyWindow(). We need a
127 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
128 // because otherwise the SessionService will try to restore sessions when we
129 // make a new window while there are no other active windows.
130 bool g_is_opening_new_window = false;
132 // Activates a browser window having the given profile (the last one active) if
133 // possible and returns a pointer to the activate |Browser| or NULL if this was
134 // not possible. If the last active browser is minimized (in particular, if
135 // there are only minimized windows), it will unminimize it.
136 Browser* ActivateBrowser(Profile* profile) {
137 Browser* browser = chrome::FindLastActiveWithProfile(
138 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile,
139 chrome::HOST_DESKTOP_TYPE_NATIVE);
141 browser->window()->Activate();
145 // Creates an empty browser window with the given profile and returns a pointer
146 // to the new |Browser|.
147 Browser* CreateBrowser(Profile* profile) {
149 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
150 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
153 Browser* browser = chrome::GetLastActiveBrowser();
158 // Activates a browser window having the given profile (the last one active) if
159 // possible or creates an empty one if necessary. Returns a pointer to the
160 // activated/new |Browser|.
161 Browser* ActivateOrCreateBrowser(Profile* profile) {
162 if (Browser* browser = ActivateBrowser(profile))
164 return CreateBrowser(profile);
167 CFStringRef BaseBundleID_CFString() {
168 NSString* base_bundle_id =
169 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
170 return base::mac::NSToCFCast(base_bundle_id);
173 // This callback synchronizes preferences (under "org.chromium.Chromium" or
174 // "com.google.Chrome"), in particular, writes them out to disk.
175 void PrefsSyncCallback() {
176 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
177 LOG(WARNING) << "Error recording application bundle path.";
180 // Record the location of the application bundle (containing the main framework)
181 // from which Chromium was loaded. This is used by app mode shims to find
183 void RecordLastRunAppBundlePath() {
184 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
185 // real, user-visible app bundle directory. (The alternatives give either the
186 // framework's path or the initial app's path, which may be an app mode shim
188 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
190 base::FilePath app_bundle_path =
191 chrome::GetVersionedDirectory().DirName().DirName().DirName();
192 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
193 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
194 CFPreferencesSetAppValue(
195 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
196 app_bundle_path_cfstring, BaseBundleID_CFString());
198 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
199 BrowserThread::PostDelayedTask(
200 BrowserThread::FILE, FROM_HERE,
201 base::Bind(&PrefsSyncCallback),
202 base::TimeDelta::FromMilliseconds(1500));
205 bool IsProfileSignedOut(Profile* profile) {
206 // The signed out status only makes sense at the moment in the context of the
207 // --new-profile-management flag.
208 if (!switches::IsNewProfileManagement())
210 ProfileInfoCache& cache =
211 g_browser_process->profile_manager()->GetProfileInfoCache();
212 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
213 if (profile_index == std::string::npos)
215 return cache.ProfileIsSigninRequiredAtIndex(profile_index);
220 @interface AppController () <HandoffActiveURLObserverBridgeDelegate>
222 - (void)initMenuState;
223 - (void)initProfileMenu;
224 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
225 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
226 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
227 - (void)getUrl:(NSAppleEventDescriptor*)event
228 withReply:(NSAppleEventDescriptor*)reply;
229 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
230 - (void)checkForAnyKeyWindows;
231 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
232 - (BOOL)shouldQuitWithInProgressDownloads;
233 - (void)executeApplication:(id)sender;
234 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
236 // Opens a tab for each GURL in |urls|.
237 - (void)openUrls:(const std::vector<GURL>&)urls;
239 // This class cannot open urls until startup has finished. The urls that cannot
240 // be opened are cached in |startupUrls_|. This method must be called exactly
241 // once after startup has completed. It opens the urls in |startupUrls_|, and
242 // clears |startupUrls_|.
243 - (void)openStartupUrls;
245 // Opens a tab for each GURL in |urls|. If there is exactly one tab open before
246 // this method is called, and that tab is the NTP, then this method closes the
247 // NTP after all the |urls| have been opened.
248 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
250 // Whether instances of this class should use the Handoff feature.
251 - (BOOL)shouldUseHandoff;
253 // This method passes |handoffURL| to |handoffManager_|.
254 - (void)passURLToHandoffManager:(const GURL&)handoffURL;
256 // Lazily creates the Handoff Manager. Updates the state of the Handoff
257 // Manager. This method is idempotent. This should be called:
258 // - During initialization.
259 // - When the current tab navigates to a new URL.
260 // - When the active browser changes.
261 // - When the active browser's active tab switches.
262 // |webContents| should be the new, active WebContents.
263 - (void)updateHandoffManager:(content::WebContents*)webContents;
265 // Given |webContents|, extracts a GURL to be used for Handoff. This may return
267 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
270 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
272 AppControllerProfileObserver(
273 ProfileManager* profile_manager, AppController* app_controller)
274 : profile_manager_(profile_manager),
275 app_controller_(app_controller) {
276 DCHECK(profile_manager_);
277 DCHECK(app_controller_);
278 profile_manager_->GetProfileInfoCache().AddObserver(this);
281 ~AppControllerProfileObserver() override {
282 DCHECK(profile_manager_);
283 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
287 // ProfileInfoCacheObserver implementation:
289 void OnProfileAdded(const base::FilePath& profile_path) override {}
291 void OnProfileWasRemoved(const base::FilePath& profile_path,
292 const base::string16& profile_name) override {
293 // When a profile is deleted we need to notify the AppController,
294 // so it can correctly update its pointer to the last used profile.
295 [app_controller_ profileWasRemoved:profile_path];
298 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
300 void OnProfileNameChanged(const base::FilePath& profile_path,
301 const base::string16& old_profile_name) override {}
303 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
305 ProfileManager* profile_manager_;
307 AppController* app_controller_; // Weak; owns us.
309 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
312 @implementation AppController
314 @synthesize startupComplete = startupComplete_;
317 [[closeTabMenuItem_ menu] setDelegate:nil];
321 // This method is called very early in application startup (ie, before
322 // the profile is loaded or any preferences have been registered). Defer any
323 // user-data initialization until -applicationDidFinishLaunching:.
324 - (void)awakeFromNib {
325 MacStartupProfiler::GetInstance()->Profile(
326 MacStartupProfiler::AWAKE_FROM_NIB);
327 // We need to register the handlers early to catch events fired on launch.
328 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
329 [em setEventHandler:self
330 andSelector:@selector(getUrl:withReply:)
331 forEventClass:kInternetEventClass
332 andEventID:kAEGetURL];
333 [em setEventHandler:self
334 andSelector:@selector(getUrl:withReply:)
335 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
336 andEventID:'OURL']; // back to the Spyglass days.
338 NSNotificationCenter* notificationCenter =
339 [NSNotificationCenter defaultCenter];
342 selector:@selector(windowDidResignKey:)
343 name:NSWindowDidResignKeyNotification
347 selector:@selector(windowDidBecomeMain:)
348 name:NSWindowDidBecomeMainNotification
352 selector:@selector(windowDidResignMain:)
353 name:NSWindowDidResignMainNotification
356 if (base::mac::IsOSLionOrLater()) {
359 selector:@selector(popoverDidShow:)
360 name:NSPopoverDidShowNotification
364 selector:@selector(popoverDidClose:)
365 name:NSPopoverDidCloseNotification
369 // Register for space change notifications.
370 [[[NSWorkspace sharedWorkspace] notificationCenter]
372 selector:@selector(activeSpaceDidChange:)
373 name:NSWorkspaceActiveSpaceDidChangeNotification
376 [[[NSWorkspace sharedWorkspace] notificationCenter]
378 selector:@selector(willPowerOff:)
379 name:NSWorkspaceWillPowerOffNotification
382 // Set up the command updater for when there are no windows open
383 [self initMenuState];
385 // Initialize the Profile menu.
386 [self initProfileMenu];
389 - (void)unregisterEventHandlers {
390 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
391 [em removeEventHandlerForEventClass:kInternetEventClass
392 andEventID:kAEGetURL];
393 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
394 andEventID:cloud_print::kAECloudPrintClass];
395 [em removeEventHandlerForEventClass:'WWW!'
397 [[NSNotificationCenter defaultCenter] removeObserver:self];
398 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
401 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
402 // the default handlers.
403 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
404 MacStartupProfiler::GetInstance()->Profile(
405 MacStartupProfiler::WILL_FINISH_LAUNCHING);
408 - (void)applicationWillHide:(NSNotification*)notification {
409 apps::ExtensionAppShimHandler::OnChromeWillHide();
412 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
413 // Reset this now that we've received the call to terminate.
414 BOOL isPoweringOff = isPoweringOff_;
417 // Check for in-process downloads, and prompt the user if they really want
418 // to quit (and thus cancel downloads). Only check if we're not already
419 // shutting down, else the user might be prompted multiple times if the
420 // download isn't stopped before terminate is called again.
421 if (!browser_shutdown::IsTryingToQuit() &&
422 ![self shouldQuitWithInProgressDownloads])
425 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
426 // them in, but I'm not sure about UX; we'd also want to disable other things
427 // though.) http://crbug.com/40861
429 // Check if the user really wants to quit by employing the confirm-to-quit
431 if (!browser_shutdown::IsTryingToQuit() &&
432 [self applicationShouldTerminate:app] != NSTerminateNow)
435 // Check for active apps. If quitting is prevented, only close browsers and
437 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
438 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
439 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
440 switches::kHostedAppQuitNotification)) {
444 content::NotificationService::current()->Notify(
445 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
446 content::NotificationService::AllSources(),
447 content::NotificationService::NoDetails());
448 // This will close all browser sessions.
449 chrome::CloseAllBrowsers();
453 size_t num_browsers = chrome::GetTotalBrowserCount();
455 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
456 // already shutting down.
457 if (!browser_shutdown::IsTryingToQuit()) {
458 content::NotificationService::current()->Notify(
459 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
460 content::NotificationService::AllSources(),
461 content::NotificationService::NoDetails());
462 chrome::CloseAllBrowsersAndQuit();
465 return num_browsers == 0 ? YES : NO;
468 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
469 if (browser_shutdown::IsTryingToQuit()) {
470 // Reset the "trying to quit" state, so that closing all browser windows
471 // will no longer lead to termination.
472 browser_shutdown::SetTryingToQuit(false);
474 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
475 // would have to reinstall them here. http://crbug.com/40861
479 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
480 // If there are no windows, quit immediately.
481 if (chrome::BrowserIterator().done() &&
482 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
483 return NSTerminateNow;
486 // Check if the preference is turned on.
487 const PrefService* prefs = g_browser_process->local_state();
488 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
489 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
490 return NSTerminateNow;
493 // If the application is going to terminate as the result of a Cmd+Q
494 // invocation, use the special sauce to prevent accidental quitting.
495 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
497 // This logic is only for keyboard-initiated quits.
498 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
499 return NSTerminateNow;
501 return [[ConfirmQuitPanelController sharedController]
502 runModalLoopForApplication:app];
505 // Called when the app is shutting down. Clean-up as appropriate.
506 - (void)applicationWillTerminate:(NSNotification*)aNotification {
507 // There better be no browser windows left at this point.
508 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
510 // Tell BrowserList not to keep the browser process alive. Once all the
511 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
512 chrome::DecrementKeepAliveCount();
514 // Reset all pref watching, as this object outlives the prefs system.
515 profilePrefRegistrar_.reset();
516 localPrefRegistrar_.RemoveAll();
518 [self unregisterEventHandlers];
520 appShimMenuController_.reset();
522 STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
523 profileBookmarkMenuBridgeMap_.end());
526 - (void)didEndMainMessageLoop {
527 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
528 chrome::HOST_DESKTOP_TYPE_NATIVE));
529 if (!chrome::GetBrowserCount([self lastProfile],
530 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
531 // As we're shutting down, we need to nuke the TabRestoreService, which
532 // will start the shutdown of the NavigationControllers and allow for
533 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
534 // and may end up crashing when some thread tries to use the IO thread (or
535 // another thread) that is no longer valid.
536 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
540 // If the window has a tab controller, make "close window" be cmd-shift-w,
541 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
542 // affects whether the shift modifier is used.
543 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
544 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
546 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
549 // If the window has a tab controller, make "close tab" take over cmd-w,
550 // otherwise it shouldn't have any key-equivalent because it should be disabled.
551 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
552 if (enableCloseTabShortcut) {
553 [closeTabMenuItem_ setKeyEquivalent:@"w"];
554 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
556 [closeTabMenuItem_ setKeyEquivalent:@""];
557 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
561 // See if the focused window window has tabs, and adjust the key equivalents for
562 // Close Tab/Close Window accordingly.
563 - (void)menuNeedsUpdate:(NSMenu*)menu {
564 DCHECK(menu == [closeTabMenuItem_ menu]);
565 NSWindow* window = [NSApp keyWindow];
566 NSWindow* mainWindow = [NSApp mainWindow];
567 if (!window || ([window parentWindow] == mainWindow)) {
568 // If the key window is a child of the main window (e.g. a bubble), the main
569 // window should be the one that handles the close menu item action.
570 // Also, there might be a small amount of time where there is no key window;
571 // in that case as well, just use our main browser window if there is one.
572 // You might think that we should just always use the main window, but the
573 // "About Chrome" window serves as a counterexample.
578 [[window windowController] isKindOfClass:[TabWindowController class]];
579 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
580 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
581 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
584 - (void)windowDidResignKey:(NSNotification*)notify {
585 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
586 // returns nil regardless of whether any suitable candidates for the key
587 // window remain. It seems that the new key window for the app is not set
588 // until after this notification is fired, so a check is performed after the
589 // run loop is allowed to spin.
590 [self performSelector:@selector(checkForAnyKeyWindows)
595 - (void)windowDidBecomeMain:(NSNotification*)notify {
596 // If the window changed to a new BrowserWindowController, update the profile.
597 id windowController = [[notify object] windowController];
598 if (![windowController isKindOfClass:[BrowserWindowController class]])
601 // If the profile is incognito, use the original profile.
602 Profile* newProfile = [windowController profile]->GetOriginalProfile();
603 [self windowChangedToProfile:newProfile];
606 - (void)windowDidResignMain:(NSNotification*)notify {
607 if (chrome::GetTotalBrowserCount() == 0) {
608 [self windowChangedToProfile:
609 g_browser_process->profile_manager()->GetLastUsedProfile()];
613 - (void)activeSpaceDidChange:(NSNotification*)notify {
614 if (reopenTime_.is_null() ||
616 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
617 kWorkspaceChangeTimeoutMs) {
621 // The last applicationShouldHandleReopen:hasVisibleWindows: call
622 // happened during a space change. Now that the change has
623 // completed, raise browser windows.
624 reopenTime_ = base::TimeTicks();
625 std::set<NSWindow*> browserWindows;
626 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
627 Browser* browser = *iter;
628 browserWindows.insert(browser->window()->GetNativeWindow());
630 if (!browserWindows.empty()) {
631 ui::FocusWindowSetOnCurrentSpace(browserWindows);
635 // Called when shutting down or logging out.
636 - (void)willPowerOff:(NSNotification*)notify {
637 // Don't attempt any shutdown here. Cocoa will shortly call
638 // -[BrowserCrApplication terminate:].
639 isPoweringOff_ = YES;
642 // Called on Lion and later when a popover (e.g. dictionary) is shown.
643 - (void)popoverDidShow:(NSNotification*)notify {
647 // Called on Lion and later when a popover (e.g. dictionary) is closed.
648 - (void)popoverDidClose:(NSNotification*)notify {
652 - (void)checkForAnyKeyWindows {
653 if ([NSApp keyWindow])
656 content::NotificationService::current()->Notify(
657 chrome::NOTIFICATION_NO_KEY_WINDOW,
658 content::NotificationService::AllSources(),
659 content::NotificationService::NoDetails());
662 // If the auto-update interval is not set, make it 5 hours.
663 // Placed here for 2 reasons:
664 // 1) Same spot as other Pref stuff
665 // 2) Try and be friendly by keeping this after app launch
666 - (void)setUpdateCheckInterval {
667 #if defined(GOOGLE_CHROME_BUILD)
668 CFStringRef app = CFSTR("com.google.Keystone.Agent");
669 CFStringRef checkInterval = CFSTR("checkInterval");
670 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
672 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
673 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
674 CFPreferencesSetAppValue(checkInterval, value, app);
675 CFPreferencesAppSynchronize(app);
680 - (void)openStartupUrls {
681 DCHECK(startupComplete_);
682 [self openUrlsReplacingNTP:startupUrls_];
683 startupUrls_.clear();
686 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
690 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
691 // NSApplication is created in MainMessageLoop, and then the shortcut urls
692 // are passed in via Apple events. At this point, the first browser is
693 // already loaded in PreMainMessageLoop. If we initialize NSApplication
694 // before PreMainMessageLoop to capture shortcut URL events, it may cause
695 // more problems because it relies on things created in PreMainMessageLoop
696 // and may break existing message loop design.
698 // If the browser hasn't started yet, just queue up the URLs.
699 if (!startupComplete_) {
700 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
704 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
705 // startup urls in new tabs, because the omnibox will stay focused if we
706 // load url in NTP tab.
707 Browser* browser = chrome::GetLastActiveBrowser();
708 int startupIndex = TabStripModel::kNoTab;
709 content::WebContents* startupContent = NULL;
711 if (browser && browser->tab_strip_model()->count() == 1) {
712 startupIndex = browser->tab_strip_model()->active_index();
713 startupContent = browser->tab_strip_model()->GetActiveWebContents();
716 [self openUrls:urls];
718 if (startupIndex != TabStripModel::kNoTab &&
719 startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
720 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
721 TabStripModel::CLOSE_NONE);
725 // This is called after profiles have been loaded and preferences registered.
726 // It is safe to access the default profile here.
727 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
728 MacStartupProfiler::GetInstance()->Profile(
729 MacStartupProfiler::DID_FINISH_LAUNCHING);
730 MacStartupProfiler::GetInstance()->RecordMetrics();
732 // Notify BrowserList to keep the application running so it doesn't go away
733 // when all the browser windows get closed.
734 chrome::IncrementKeepAliveCount();
736 [self setUpdateCheckInterval];
738 // Start managing the menu for app windows. This needs to be done here because
739 // main menu item titles are not yet initialized in awakeFromNib.
740 [self initAppShimMenuController];
742 // If enabled, keep Chrome alive when apps are open instead of quitting all
744 quitWithAppsController_ = new QuitWithAppsController();
746 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
747 [[closeTabMenuItem_ menu] setDelegate:self];
749 // Build up the encoding menu, the order of the items differs based on the
750 // current locale (see http://crbug.com/7647 for details).
751 // We need a valid g_browser_process to get the profile which is why we can't
752 // call this from awakeFromNib.
753 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
754 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
755 NSMenu* encodingMenu = [encodingMenuItem submenu];
756 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
759 // Instantiate the ProfileInfoCache observer so that we can get
760 // notified when a profile is deleted.
761 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
762 g_browser_process->profile_manager(), self));
764 // Since Chrome is localized to more languages than the OS, tell Cocoa which
765 // menu is the Help so it can add the search item to it.
766 [NSApp setHelpMenu:helpMenu_];
768 // Record the path to the (browser) app bundle; this is used by the app mode
769 // shim. It has to be done in FILE thread because getting the path requires
771 BrowserThread::PostTask(
772 BrowserThread::FILE, FROM_HERE,
773 base::Bind(&RecordLastRunAppBundlePath));
775 // Makes "Services" menu items available.
776 [self registerServicesMenuTypesTo:[notify object]];
778 startupComplete_ = YES;
781 FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
782 content::WebContents* activeWebContents = nullptr;
784 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
785 [self updateHandoffManager:activeWebContents];
786 [self openStartupUrls];
788 PrefService* localState = g_browser_process->local_state();
790 localPrefRegistrar_.Init(localState);
791 localPrefRegistrar_.Add(
792 prefs::kAllowFileSelectionDialogs,
793 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
797 handoff_active_url_observer_bridge_.reset(
798 new HandoffActiveURLObserverBridge(self));
801 // This is called after profiles have been loaded and preferences registered.
802 // It is safe to access the default profile here.
803 - (void)applicationDidBecomeActive:(NSNotification*)notify {
804 content::PluginService::GetInstance()->AppActivated();
807 // Helper function for populating and displaying the in progress downloads at
809 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
810 NSString* titleText = nil;
811 NSString* explanationText = nil;
812 NSString* waitTitle = nil;
813 NSString* exitTitle = nil;
815 // Set the dialog text based on whether or not there are multiple downloads.
816 if (downloadCount == 1) {
817 // Dialog text: warning and explanation.
818 titleText = l10n_util::GetNSString(
819 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
820 explanationText = l10n_util::GetNSString(
821 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
823 // Dialog text: warning and explanation.
824 titleText = l10n_util::GetNSString(
825 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE);
826 explanationText = l10n_util::GetNSString(
827 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
829 // Cancel download and exit button text.
830 exitTitle = l10n_util::GetNSString(
831 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
833 // Wait for download button text.
834 waitTitle = l10n_util::GetNSString(
835 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
837 // 'waitButton' is the default choice.
838 int choice = NSRunAlertPanel(titleText, @"%@",
839 waitTitle, exitTitle, nil, explanationText);
840 return choice == NSAlertDefaultReturn ? YES : NO;
843 // Check all profiles for in progress downloads, and if we find any, prompt the
844 // user to see if we should continue to exit (and thus cancel the downloads), or
845 // if we should wait.
846 - (BOOL)shouldQuitWithInProgressDownloads {
847 ProfileManager* profile_manager = g_browser_process->profile_manager();
848 if (!profile_manager)
851 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
852 for (size_t i = 0; i < profiles.size(); ++i) {
853 DownloadService* download_service =
854 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
855 DownloadManager* download_manager =
856 (download_service->HasCreatedDownloadManager() ?
857 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
858 if (download_manager &&
859 download_manager->NonMaliciousInProgressCount() > 0) {
860 int downloadCount = download_manager->NonMaliciousInProgressCount();
861 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
862 // Create a new browser window (if necessary) and navigate to the
863 // downloads page if the user chooses to wait.
864 Browser* browser = chrome::FindBrowserWithProfile(
865 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
867 browser = new Browser(Browser::CreateParams(
868 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
869 browser->window()->Show();
872 chrome::ShowDownloads(browser);
876 // User wants to exit.
881 // No profiles or active downloads found, okay to exit.
885 // Called to determine if we should enable the "restore tab" menu item.
886 // Checks with the TabRestoreService to see if there's anything there to
887 // restore and returns YES if so.
888 - (BOOL)canRestoreTab {
889 TabRestoreService* service =
890 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
891 return service && !service->entries().empty();
894 // Called from the AppControllerProfileObserver every time a profile is deleted.
895 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
896 // If the lastProfile has been deleted, the profile manager has
897 // already loaded a new one, so the pointer needs to be updated;
898 // otherwise we will try to start up a browser window with a pointer
899 // to the old profile.
900 // In a browser test, the application is not brought to the front, so
901 // |lastProfile_| might be null.
902 if (!lastProfile_ || profilePath == lastProfile_->GetPath())
903 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
905 auto it = profileBookmarkMenuBridgeMap_.find(profilePath);
906 if (it != profileBookmarkMenuBridgeMap_.end()) {
908 profileBookmarkMenuBridgeMap_.erase(it);
912 // Returns true if there is a modal window (either window- or application-
913 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
914 // sheets) will not count as blocking the browser. But things like open/save
915 // dialogs that are window modal will block the browser.
916 - (BOOL)keyWindowIsModal {
917 if ([NSApp modalWindow])
920 Browser* browser = chrome::GetLastActiveBrowser();
922 [[browser->window()->GetNativeWindow() attachedSheet]
923 isKindOfClass:[NSWindow class]];
926 // Called to validate menu items when there are no key windows. All the
927 // items we care about have been set with the |commandDispatch:| action and
928 // a target of FirstResponder in IB. If it's not one of those, let it
929 // continue up the responder chain to be handled elsewhere. We pull out the
930 // tag as the cross-platform constant to differentiate and dispatch the
932 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
933 SEL action = [item action];
935 if (action == @selector(commandDispatch:) ||
936 action == @selector(commandFromDock:)) {
937 NSInteger tag = [item tag];
938 if (menuState_ && // NULL in tests.
939 menuState_->SupportsCommand(tag)) {
941 // The File Menu commands are not automatically disabled by Cocoa when a
942 // dialog sheet obscures the browser window, so we disable several of
943 // them here. We don't need to include IDC_CLOSE_WINDOW, because
944 // app_controller is only activated when there are no key windows (see
945 // function comment).
946 case IDC_RESTORE_TAB:
947 enable = ![self keyWindowIsModal] && [self canRestoreTab];
949 // Browser-level items that open in new tabs should not open if there's
950 // a window- or app-modal dialog.
953 case IDC_SHOW_HISTORY:
954 case IDC_SHOW_BOOKMARK_MANAGER:
955 enable = ![self keyWindowIsModal];
957 // Browser-level items that open in new windows.
958 case IDC_TASK_MANAGER:
959 // Allow the user to open a new window if there's a window-modal
961 enable = ![self keyWindowIsModal];
963 case IDC_SHOW_SYNC_SETUP: {
964 Profile* lastProfile = [self lastProfile];
965 // The profile may be NULL during shutdown -- see
966 // http://code.google.com/p/chromium/issues/detail?id=43048 .
968 // TODO(akalin,viettrungluu): Figure out whether this method
969 // can be prevented from being called if lastProfile is
973 << "NULL lastProfile detected -- not doing anything";
976 SigninManager* signin = SigninManagerFactory::GetForProfile(
977 lastProfile->GetOriginalProfile());
978 enable = signin->IsSigninAllowed() &&
979 ![self keyWindowIsModal];
980 [BrowserWindowController updateSigninItem:item
982 currentProfile:lastProfile];
985 #if defined(GOOGLE_CHROME_BUILD)
991 enable = menuState_->IsCommandEnabled(tag) ?
992 ![self keyWindowIsModal] : NO;
995 } else if (action == @selector(terminate:)) {
997 } else if (action == @selector(showPreferences:)) {
999 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
1001 } else if (action == @selector(commandFromDock:)) {
1003 } else if (action == @selector(toggleConfirmToQuit:)) {
1004 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
1006 } else if (action == @selector(toggleDisplayMessageCenter:)) {
1007 NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
1008 [self updateDisplayMessageCenterPrefMenuItem:menuItem];
1010 } else if (action == @selector(executeApplication:)) {
1016 // Called when the user picks a menu item when there are no key windows, or when
1017 // there is no foreground browser window. Calls through to the browser object to
1018 // execute the command. This assumes that the command is supported and doesn't
1019 // check, otherwise it should have been disabled in the UI in
1020 // |-validateUserInterfaceItem:|.
1021 - (void)commandDispatch:(id)sender {
1022 Profile* lastProfile = [self safeLastProfileForNewWindows];
1024 // Handle the case where we're dispatching a command from a sender that's in a
1025 // browser window. This means that the command came from a background window
1026 // and is getting here because the foreground window is not a browser window.
1027 if ([sender respondsToSelector:@selector(window)]) {
1028 id delegate = [[sender window] windowController];
1029 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1030 [delegate commandDispatch:sender];
1035 // Ignore commands during session restore's browser creation. It uses a
1036 // nested message loop and commands dispatched during this operation cause
1038 if (SessionRestore::IsRestoring(lastProfile) &&
1039 base::MessageLoop::current()->IsNested())
1042 NSInteger tag = [sender tag];
1044 // If there are no browser windows, and we are trying to open a browser
1045 // for a locked profile, we have to show the User Manager instead as the
1046 // locked profile needs authentication.
1047 if (IsProfileSignedOut(lastProfile)) {
1048 UserManager::Show(base::FilePath(),
1049 profiles::USER_MANAGER_NO_TUTORIAL,
1050 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1056 // Create a new tab in an existing browser window (which we activate) if
1058 if (Browser* browser = ActivateBrowser(lastProfile)) {
1059 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1062 // Else fall through to create new window.
1063 case IDC_NEW_WINDOW:
1064 CreateBrowser(lastProfile);
1066 case IDC_FOCUS_LOCATION:
1067 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1068 IDC_FOCUS_LOCATION);
1070 case IDC_FOCUS_SEARCH:
1071 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1074 case IDC_NEW_INCOGNITO_WINDOW:
1075 CreateBrowser(lastProfile->GetOffTheRecordProfile());
1077 case IDC_RESTORE_TAB:
1078 // There is only the native desktop on Mac.
1079 chrome::OpenWindowWithRestoredTabs(lastProfile,
1080 chrome::HOST_DESKTOP_TYPE_NATIVE);
1083 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1085 case IDC_CLEAR_BROWSING_DATA: {
1086 // There may not be a browser open, so use the default profile.
1087 if (Browser* browser = ActivateBrowser(lastProfile)) {
1088 chrome::ShowClearBrowsingDataDialog(browser);
1090 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1094 case IDC_IMPORT_SETTINGS: {
1095 if (Browser* browser = ActivateBrowser(lastProfile)) {
1096 chrome::ShowImportDialog(browser);
1098 chrome::OpenImportSettingsDialogWindow(lastProfile);
1102 case IDC_SHOW_BOOKMARK_MANAGER:
1103 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1104 if (Browser* browser = ActivateBrowser(lastProfile)) {
1105 chrome::ShowBookmarkManager(browser);
1107 // No browser window, so create one for the bookmark manager tab.
1108 chrome::OpenBookmarkManagerWindow(lastProfile);
1111 case IDC_SHOW_HISTORY:
1112 if (Browser* browser = ActivateBrowser(lastProfile))
1113 chrome::ShowHistory(browser);
1115 chrome::OpenHistoryWindow(lastProfile);
1117 case IDC_SHOW_DOWNLOADS:
1118 if (Browser* browser = ActivateBrowser(lastProfile))
1119 chrome::ShowDownloads(browser);
1121 chrome::OpenDownloadsWindow(lastProfile);
1123 case IDC_MANAGE_EXTENSIONS:
1124 if (Browser* browser = ActivateBrowser(lastProfile))
1125 chrome::ShowExtensions(browser, std::string());
1127 chrome::OpenExtensionsWindow(lastProfile);
1129 case IDC_HELP_PAGE_VIA_MENU:
1130 if (Browser* browser = ActivateBrowser(lastProfile))
1131 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1133 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1135 case IDC_SHOW_SYNC_SETUP:
1136 if (Browser* browser = ActivateBrowser(lastProfile)) {
1137 chrome::ShowBrowserSigninOrSettings(browser,
1138 signin_metrics::SOURCE_MENU);
1140 chrome::OpenSyncSetupWindow(lastProfile, signin_metrics::SOURCE_MENU);
1143 case IDC_TASK_MANAGER:
1144 chrome::OpenTaskManager(NULL);
1147 [self showPreferences:sender];
1152 // Run a (background) application in a new tab.
1153 - (void)executeApplication:(id)sender {
1154 NSInteger tag = [sender tag];
1155 Profile* profile = [self lastProfile];
1157 BackgroundApplicationListModel applications(profile);
1159 tag < static_cast<int>(applications.size()));
1160 const extensions::Extension* extension = applications.GetExtension(tag);
1161 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1164 // Same as |-commandDispatch:|, but executes commands using a disposition
1165 // determined by the key flags. This will get called in the case where the
1166 // frontmost window is not a browser window, and the user has command-clicked
1167 // a button in a background browser window whose action is
1168 // |-commandDispatchUsingKeyModifiers:|
1169 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1171 if ([sender respondsToSelector:@selector(window)]) {
1172 id delegate = [[sender window] windowController];
1173 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1174 [delegate commandDispatchUsingKeyModifiers:sender];
1179 // NSApplication delegate method called when someone clicks on the dock icon.
1180 // To match standard mac behavior, we should open a new window if there are no
1182 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1183 hasVisibleWindows:(BOOL)hasVisibleWindows {
1184 // If the browser is currently trying to quit, don't do anything and return NO
1185 // to prevent AppKit from doing anything.
1186 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1187 if (browser_shutdown::IsTryingToQuit())
1190 // Bring all browser windows to the front. Specifically, this brings them in
1191 // front of any app windows. FocusWindowSet will also unminimize the most
1192 // recently minimized window if no windows in the set are visible.
1193 // If there are any, return here. Otherwise, the windows are panels or
1194 // notifications so we still need to open a new window.
1195 if (hasVisibleWindows) {
1196 std::set<NSWindow*> browserWindows;
1197 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1198 Browser* browser = *iter;
1199 // When focusing Chrome, don't focus any browser windows associated with
1200 // a currently running app shim, so ignore them.
1201 if (browser && browser->is_app()) {
1202 extensions::ExtensionRegistry* registry =
1203 extensions::ExtensionRegistry::Get(browser->profile());
1204 const extensions::Extension* extension = registry->GetExtensionById(
1205 web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1206 extensions::ExtensionRegistry::ENABLED);
1207 if (extension && extension->is_hosted_app())
1210 browserWindows.insert(browser->window()->GetNativeWindow());
1212 if (!browserWindows.empty()) {
1213 NSWindow* keyWindow = [NSApp keyWindow];
1214 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1215 // The key window is not on the active space. We must be mid-animation
1216 // for a space transition triggered by the dock. Delay the call to
1217 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1218 // wrong space's windows get raised, resulting in an off-screen key
1219 // window. It does not work to |ui::FocusWindowSet| twice, once here
1220 // and once in |activeSpaceDidChange:|, as that appears to break when
1221 // the omnibox is focused.
1223 // This check relies on OS X setting the key window to a window on the
1224 // target space before calling this method.
1226 // See http://crbug.com/309656.
1227 reopenTime_ = base::TimeTicks::Now();
1229 ui::FocusWindowSetOnCurrentSpace(browserWindows);
1231 // Return NO; we've done (or soon will do) the deminiaturize, so
1232 // AppKit shouldn't do anything.
1237 // If launched as a hidden login item (due to installation of a persistent app
1238 // or by the user, for example in System Preferences->Accounts->Login Items),
1239 // allow session to be restored first time the user clicks on a Dock icon.
1240 // Normally, it'd just open a new empty page.
1242 static BOOL doneOnce = NO;
1243 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1244 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1246 if (attemptRestore) {
1247 SessionService* sessionService =
1248 SessionServiceFactory::GetForProfileForSessionRestore(
1249 [self lastProfile]);
1250 if (sessionService &&
1251 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1256 // Otherwise open a new window.
1257 // If the last profile was locked, we have to open the User Manager, as the
1258 // profile requires authentication. Similarly, because guest mode is
1259 // implemented as forced incognito, we can't open a new guest browser either,
1260 // so we have to show the User Manager as well.
1261 Profile* lastProfile = [self lastProfile];
1262 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile)) {
1263 UserManager::Show(base::FilePath(),
1264 profiles::USER_MANAGER_NO_TUTORIAL,
1265 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1267 CreateBrowser(lastProfile);
1270 // We've handled the reopen event, so return NO to tell AppKit not
1275 - (void)initMenuState {
1276 menuState_.reset(new CommandUpdater(NULL));
1277 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1278 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1279 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1280 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1281 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1282 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1283 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1284 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1285 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1286 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1287 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1288 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1289 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1290 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1291 #if defined(GOOGLE_CHROME_BUILD)
1292 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1294 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1295 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1298 // Conditionally adds the Profile menu to the main menu bar.
1299 - (void)initProfileMenu {
1300 NSMenu* mainMenu = [NSApp mainMenu];
1301 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1303 if (!profiles::IsMultipleProfilesEnabled()) {
1304 [mainMenu removeItem:profileMenu];
1308 // The controller will unhide the menu if necessary.
1309 [profileMenu setHidden:YES];
1311 profileMenuController_.reset(
1312 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1315 // The Confirm to Quit preference is atypical in that the preference lives in
1316 // the app menu right above the Quit menu item. This method will refresh the
1317 // display of that item depending on the preference state.
1318 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1319 // Format the string so that the correct key equivalent is displayed.
1320 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1321 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1322 base::SysNSStringToUTF16(acceleratorString));
1323 [item setTitle:title];
1325 const PrefService* prefService = g_browser_process->local_state();
1326 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1327 [item setState:enabled ? NSOnState : NSOffState];
1330 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
1331 const PrefService* prefService = g_browser_process->local_state();
1332 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1333 // The item should be checked if "show icon" is false, since the text reads
1334 // "Hide notification center icon."
1335 [item setState:enabled ? NSOffState : NSOnState];
1338 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1339 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1340 // handles requests from services.
1341 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1342 [app registerServicesMenuSendTypes:types returnTypes:types];
1345 - (Profile*)lastProfile {
1346 // Return the profile of the last-used BrowserWindowController, if available.
1348 return lastProfile_;
1350 // On first launch, use the logic that ChromeBrowserMain uses to determine
1351 // the initial profile.
1352 ProfileManager* profile_manager = g_browser_process->profile_manager();
1353 if (!profile_manager)
1356 return profile_manager->GetProfile(
1357 GetStartupProfilePath(profile_manager->user_data_dir(),
1358 *base::CommandLine::ForCurrentProcess()));
1361 - (Profile*)safeLastProfileForNewWindows {
1362 Profile* profile = [self lastProfile];
1364 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1365 if (profile->IsGuestSession())
1366 return profile->GetOffTheRecordProfile();
1371 // Returns true if a browser window may be opened for the last active profile.
1372 - (bool)canOpenNewBrowser {
1373 Profile* profile = [self safeLastProfileForNewWindows];
1375 const PrefService* prefs = g_browser_process->local_state();
1376 return !profile->IsGuestSession() ||
1377 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1380 // Various methods to open URLs that we get in a native fashion. We use
1381 // StartupBrowserCreator here because on the other platforms, URLs to open come
1382 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1383 // to bottleneck the openings through that for uniform handling.
1384 - (void)openUrls:(const std::vector<GURL>&)urls {
1385 if (!startupComplete_) {
1386 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1390 Browser* browser = chrome::GetLastActiveBrowser();
1391 // if no browser window exists then create one with no tabs to be filled in
1393 browser = new Browser(Browser::CreateParams(
1394 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1395 browser->window()->Show();
1398 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1399 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1400 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1401 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1402 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1405 - (void)getUrl:(NSAppleEventDescriptor*)event
1406 withReply:(NSAppleEventDescriptor*)reply {
1407 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1410 GURL gurl(base::SysNSStringToUTF8(urlStr));
1411 std::vector<GURL> gurlVector;
1412 gurlVector.push_back(gurl);
1414 [self openUrlsReplacingNTP:gurlVector];
1417 - (void)application:(NSApplication*)sender
1418 openFiles:(NSArray*)filenames {
1419 std::vector<GURL> gurlVector;
1420 for (NSString* file in filenames) {
1422 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1423 gurlVector.push_back(gurl);
1425 if (!gurlVector.empty())
1426 [self openUrlsReplacingNTP:gurlVector];
1428 NOTREACHED() << "Nothing to open!";
1430 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1433 // Show the preferences window, or bring it to the front if it's already
1435 - (IBAction)showPreferences:(id)sender {
1436 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1437 // Show options tab in the active browser window.
1438 chrome::ShowSettings(browser);
1439 } else if ([self canOpenNewBrowser]) {
1440 // No browser window, so create one for the options tab.
1441 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
1443 // No way to create a browser, default to the User Manager.
1444 UserManager::Show(base::FilePath(),
1445 profiles::USER_MANAGER_NO_TUTORIAL,
1446 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
1450 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1451 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1452 chrome::ShowAboutChrome(browser);
1453 } else if ([self canOpenNewBrowser]) {
1454 // No browser window, so create one for the options tab.
1455 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
1457 // No way to create a browser, default to the User Manager.
1458 UserManager::Show(base::FilePath(),
1459 profiles::USER_MANAGER_NO_TUTORIAL,
1460 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
1464 - (IBAction)toggleConfirmToQuit:(id)sender {
1465 PrefService* prefService = g_browser_process->local_state();
1466 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1467 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1470 - (IBAction)toggleDisplayMessageCenter:(id)sender {
1471 PrefService* prefService = g_browser_process->local_state();
1472 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1473 prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
1476 // Explicitly bring to the foreground when creating new windows from the dock.
1477 - (void)commandFromDock:(id)sender {
1478 [NSApp activateIgnoringOtherApps:YES];
1479 [self commandDispatch:sender];
1482 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1483 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1484 Profile* profile = [self lastProfile];
1486 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1490 [dockMenu addItem:[NSMenuItem separatorItem]];
1492 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1493 base::scoped_nsobject<NSMenuItem> item(
1494 [[NSMenuItem alloc] initWithTitle:titleStr
1495 action:@selector(commandFromDock:)
1496 keyEquivalent:@""]);
1497 [item setTarget:self];
1498 [item setTag:IDC_NEW_WINDOW];
1499 [item setEnabled:[self validateUserInterfaceItem:item]];
1500 [dockMenu addItem:item];
1502 // |profile| can be NULL during unit tests.
1504 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1505 IncognitoModePrefs::DISABLED) {
1506 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1508 [[NSMenuItem alloc] initWithTitle:titleStr
1509 action:@selector(commandFromDock:)
1510 keyEquivalent:@""]);
1511 [item setTarget:self];
1512 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1513 [item setEnabled:[self validateUserInterfaceItem:item]];
1514 [dockMenu addItem:item];
1517 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1518 // tests which use the mock in place of the profile-initialized model.
1520 // Avoid breaking unit tests which have no profile.
1522 BackgroundApplicationListModel applications(profile);
1523 if (applications.size()) {
1526 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1527 base::scoped_nsobject<NSMenu> appMenu(
1528 [[NSMenu alloc] initWithTitle:menuStr]);
1529 for (extensions::ExtensionList::const_iterator cursor =
1530 applications.begin();
1531 cursor != applications.end();
1532 ++cursor, ++position) {
1533 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1535 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1536 base::scoped_nsobject<NSMenuItem> appItem(
1537 [[NSMenuItem alloc] initWithTitle:itemStr
1538 action:@selector(executeApplication:)
1539 keyEquivalent:@""]);
1540 [appItem setTarget:self];
1541 [appItem setTag:position];
1542 [appMenu addItem:appItem];
1550 - (const std::vector<GURL>&)startupUrls {
1551 return startupUrls_;
1554 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1555 return bookmarkMenuBridge_;
1558 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1559 workAreaChangeObservers_.AddObserver(observer);
1562 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1563 workAreaChangeObservers_.RemoveObserver(observer);
1566 - (void)initAppShimMenuController {
1567 if (!appShimMenuController_)
1568 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1571 - (void)windowChangedToProfile:(Profile*)profile {
1572 if (lastProfile_ == profile)
1575 // Before tearing down the menu controller bridges, return the history menu to
1576 // its initial state.
1577 if (historyMenuBridge_)
1578 historyMenuBridge_->ResetMenu();
1580 // Rebuild the menus with the new profile.
1581 lastProfile_ = profile;
1583 auto it = profileBookmarkMenuBridgeMap_.find(profile->GetPath());
1584 if (it == profileBookmarkMenuBridgeMap_.end()) {
1585 base::scoped_nsobject<NSMenu> submenu(
1586 [[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu] copy]);
1587 bookmarkMenuBridge_ = new BookmarkMenuBridge(profile, submenu);
1588 profileBookmarkMenuBridgeMap_[profile->GetPath()] = bookmarkMenuBridge_;
1590 bookmarkMenuBridge_ = it->second;
1593 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] setSubmenu:
1594 bookmarkMenuBridge_->BookmarkMenu()];
1595 // No need to |BuildMenu| here. It is done lazily upon menu access.
1597 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1598 historyMenuBridge_->BuildMenu();
1600 chrome::BrowserCommandController::
1601 UpdateSharedCommandsForIncognitoAvailability(
1602 menuState_.get(), lastProfile_);
1603 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1604 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1605 profilePrefRegistrar_->Add(
1606 prefs::kIncognitoModeAvailability,
1607 base::Bind(&chrome::BrowserCommandController::
1608 UpdateSharedCommandsForIncognitoAvailability,
1613 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1614 // During this callback the working area is not always already updated. Defer.
1615 [self performSelector:@selector(delayedScreenParametersUpdate)
1620 - (void)delayedScreenParametersUpdate {
1621 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1625 - (BOOL)application:(NSApplication*)application
1626 willContinueUserActivityWithType:(NSString*)userActivityType {
1627 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1630 - (BOOL)application:(NSApplication*)application
1631 continueUserActivity:(NSUserActivity*)userActivity
1632 restorationHandler:(void (^)(NSArray*))restorationHandler {
1633 if (![userActivity.activityType
1634 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1638 NSString* originString = base::mac::ObjCCast<NSString>(
1639 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1640 handoff::Origin origin = handoff::OriginFromString(originString);
1641 UMA_HISTOGRAM_ENUMERATION(
1642 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1644 NSURL* url = userActivity.webpageURL;
1648 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1649 std::vector<GURL> gurlVector;
1650 gurlVector.push_back(gurl);
1652 [self openUrlsReplacingNTP:gurlVector];
1656 - (void)application:(NSApplication*)application
1657 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1658 error:(NSError*)error {
1661 #pragma mark - Handoff Manager
1663 - (BOOL)shouldUseHandoff {
1664 return base::mac::IsOSYosemiteOrLater();
1667 - (void)passURLToHandoffManager:(const GURL&)handoffURL {
1668 [handoffManager_ updateActiveURL:handoffURL];
1671 - (void)updateHandoffManager:(content::WebContents*)webContents {
1672 if (![self shouldUseHandoff])
1675 if (!handoffManager_)
1676 handoffManager_.reset([[HandoffManager alloc] init]);
1678 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1679 [self passURLToHandoffManager:handoffURL];
1682 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1687 Profile::FromBrowserContext(webContents->GetBrowserContext());
1691 // Handoff is not allowed from an incognito profile. To err on the safe side,
1692 // also disallow Handoff from a guest profile.
1693 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1699 return webContents->GetVisibleURL();
1702 #pragma mark - HandoffActiveURLObserverBridgeDelegate
1704 - (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1705 [self updateHandoffManager:webContents];
1708 @end // @implementation AppController
1710 //---------------------------------------------------------------------------
1712 namespace app_controller_mac {
1714 bool IsOpeningNewWindow() {
1715 return g_is_opening_new_window;
1718 } // namespace app_controller_mac