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