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/message_loop/message_loop.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "chrome/app/chrome_command_ids.h"
21 #include "chrome/browser/background/background_application_list_model.h"
22 #include "chrome/browser/background/background_mode_manager.h"
23 #include "chrome/browser/browser_process.h"
24 #include "chrome/browser/browser_shutdown.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/command_updater.h"
27 #include "chrome/browser/download/download_service.h"
28 #include "chrome/browser/download/download_service_factory.h"
29 #include "chrome/browser/extensions/extension_service.h"
30 #include "chrome/browser/first_run/first_run.h"
31 #include "chrome/browser/lifetime/application_lifetime.h"
32 #include "chrome/browser/profiles/profile_info_cache_observer.h"
33 #include "chrome/browser/profiles/profile_manager.h"
34 #include "chrome/browser/profiles/profiles_state.h"
35 #include "chrome/browser/sessions/session_restore.h"
36 #include "chrome/browser/sessions/session_service.h"
37 #include "chrome/browser/sessions/session_service_factory.h"
38 #include "chrome/browser/sessions/tab_restore_service.h"
39 #include "chrome/browser/sessions/tab_restore_service_factory.h"
40 #include "chrome/browser/signin/signin_manager_factory.h"
41 #include "chrome/browser/signin/signin_promo.h"
42 #include "chrome/browser/sync/profile_sync_service.h"
43 #include "chrome/browser/sync/sync_ui_util.h"
44 #include "chrome/browser/ui/browser.h"
45 #include "chrome/browser/ui/browser_command_controller.h"
46 #include "chrome/browser/ui/browser_commands.h"
47 #include "chrome/browser/ui/browser_dialogs.h"
48 #include "chrome/browser/ui/browser_finder.h"
49 #include "chrome/browser/ui/browser_iterator.h"
50 #include "chrome/browser/ui/browser_mac.h"
51 #include "chrome/browser/ui/browser_window.h"
52 #include "chrome/browser/ui/chrome_pages.h"
53 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
54 #include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
55 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
56 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
57 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
58 #import "chrome/browser/ui/cocoa/confirm_quit.h"
59 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
60 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
61 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
62 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
63 #import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
64 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
65 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
66 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
67 #include "chrome/browser/ui/extensions/application_launch.h"
68 #include "chrome/browser/ui/host_desktop.h"
69 #include "chrome/browser/ui/startup/startup_browser_creator.h"
70 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
71 #include "chrome/common/chrome_paths_internal.h"
72 #include "chrome/common/chrome_switches.h"
73 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
74 #include "chrome/common/extensions/extension_constants.h"
75 #include "chrome/common/mac/app_mode_common.h"
76 #include "chrome/common/pref_names.h"
77 #include "chrome/common/url_constants.h"
78 #include "components/signin/core/common/profile_management_switches.h"
79 #include "components/signin/core/browser/signin_manager.h"
80 #include "content/public/browser/browser_thread.h"
81 #include "content/public/browser/download_manager.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/notification_types.h"
84 #include "content/public/browser/plugin_service.h"
85 #include "content/public/browser/user_metrics.h"
86 #include "extensions/browser/extension_system.h"
87 #include "grit/chromium_strings.h"
88 #include "grit/generated_resources.h"
89 #include "net/base/filename_util.h"
90 #include "ui/base/cocoa/focus_window_set.h"
91 #include "ui/base/l10n/l10n_util.h"
92 #include "ui/base/l10n/l10n_util_mac.h"
94 using base::UserMetricsAction;
95 using content::BrowserContext;
96 using content::BrowserThread;
97 using content::DownloadManager;
101 // Declare notification names from the 10.7 SDK.
102 #if !defined(MAC_OS_X_VERSION_10_7) || \
103 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
104 NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
105 NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
108 // How long we allow a workspace change notification to wait to be
109 // associated with a dock activation. The animation lasts 250ms. See
110 // applicationShouldHandleReopen:hasVisibleWindows:.
111 static const int kWorkspaceChangeTimeoutMs = 500;
113 // True while AppController is calling chrome::NewEmptyWindow(). We need a
114 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
115 // because otherwise the SessionService will try to restore sessions when we
116 // make a new window while there are no other active windows.
117 bool g_is_opening_new_window = false;
119 // Activates a browser window having the given profile (the last one active) if
120 // possible and returns a pointer to the activate |Browser| or NULL if this was
121 // not possible. If the last active browser is minimized (in particular, if
122 // there are only minimized windows), it will unminimize it.
123 Browser* ActivateBrowser(Profile* profile) {
124 Browser* browser = chrome::FindLastActiveWithProfile(profile,
125 chrome::HOST_DESKTOP_TYPE_NATIVE);
127 browser->window()->Activate();
131 // Creates an empty browser window with the given profile and returns a pointer
132 // to the new |Browser|.
133 Browser* CreateBrowser(Profile* profile) {
135 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
136 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
139 Browser* browser = chrome::GetLastActiveBrowser();
144 // Activates a browser window having the given profile (the last one active) if
145 // possible or creates an empty one if necessary. Returns a pointer to the
146 // activated/new |Browser|.
147 Browser* ActivateOrCreateBrowser(Profile* profile) {
148 if (Browser* browser = ActivateBrowser(profile))
150 return CreateBrowser(profile);
153 CFStringRef BaseBundleID_CFString() {
154 NSString* base_bundle_id =
155 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
156 return base::mac::NSToCFCast(base_bundle_id);
159 // This callback synchronizes preferences (under "org.chromium.Chromium" or
160 // "com.google.Chrome"), in particular, writes them out to disk.
161 void PrefsSyncCallback() {
162 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
163 LOG(WARNING) << "Error recording application bundle path.";
166 // Record the location of the application bundle (containing the main framework)
167 // from which Chromium was loaded. This is used by app mode shims to find
169 void RecordLastRunAppBundlePath() {
170 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
171 // real, user-visible app bundle directory. (The alternatives give either the
172 // framework's path or the initial app's path, which may be an app mode shim
174 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
176 base::FilePath app_bundle_path =
177 chrome::GetVersionedDirectory().DirName().DirName().DirName();
178 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
179 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
180 CFPreferencesSetAppValue(
181 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
182 app_bundle_path_cfstring, BaseBundleID_CFString());
184 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
185 BrowserThread::PostDelayedTask(
186 BrowserThread::FILE, FROM_HERE,
187 base::Bind(&PrefsSyncCallback),
188 base::TimeDelta::FromMilliseconds(1500));
191 bool IsProfileSignedOut(Profile* profile) {
192 // The signed out status only makes sense at the moment in the context of the
193 // --new-profile-management flag.
194 if (!switches::IsNewProfileManagement())
196 ProfileInfoCache& cache =
197 g_browser_process->profile_manager()->GetProfileInfoCache();
198 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
199 if (profile_index == std::string::npos)
201 return cache.ProfileIsSigninRequiredAtIndex(profile_index);
204 } // anonymous namespace
206 @interface AppController (Private)
207 - (void)initMenuState;
208 - (void)initProfileMenu;
209 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
210 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
211 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
212 - (void)openUrls:(const std::vector<GURL>&)urls;
213 - (void)getUrl:(NSAppleEventDescriptor*)event
214 withReply:(NSAppleEventDescriptor*)reply;
215 - (void)windowLayeringDidChange:(NSNotification*)inNotification;
216 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
217 - (void)windowChangedToProfile:(Profile*)profile;
218 - (void)checkForAnyKeyWindows;
219 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
220 - (BOOL)shouldQuitWithInProgressDownloads;
221 - (void)executeApplication:(id)sender;
222 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
225 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
227 AppControllerProfileObserver(
228 ProfileManager* profile_manager, AppController* app_controller)
229 : profile_manager_(profile_manager),
230 app_controller_(app_controller) {
231 DCHECK(profile_manager_);
232 DCHECK(app_controller_);
233 profile_manager_->GetProfileInfoCache().AddObserver(this);
236 virtual ~AppControllerProfileObserver() {
237 DCHECK(profile_manager_);
238 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
242 // ProfileInfoCacheObserver implementation:
244 virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
247 virtual void OnProfileWasRemoved(
248 const base::FilePath& profile_path,
249 const base::string16& profile_name) OVERRIDE {
250 // When a profile is deleted we need to notify the AppController,
251 // so it can correctly update its pointer to the last used profile.
252 [app_controller_ profileWasRemoved:profile_path];
255 virtual void OnProfileWillBeRemoved(
256 const base::FilePath& profile_path) OVERRIDE {
259 virtual void OnProfileNameChanged(
260 const base::FilePath& profile_path,
261 const base::string16& old_profile_name) OVERRIDE {
264 virtual void OnProfileAvatarChanged(
265 const base::FilePath& profile_path) OVERRIDE {
268 ProfileManager* profile_manager_;
270 AppController* app_controller_; // Weak; owns us.
272 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
275 @implementation AppController
277 @synthesize startupComplete = startupComplete_;
279 // This method is called very early in application startup (ie, before
280 // the profile is loaded or any preferences have been registered). Defer any
281 // user-data initialization until -applicationDidFinishLaunching:.
282 - (void)awakeFromNib {
283 // We need to register the handlers early to catch events fired on launch.
284 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
285 [em setEventHandler:self
286 andSelector:@selector(getUrl:withReply:)
287 forEventClass:kInternetEventClass
288 andEventID:kAEGetURL];
289 [em setEventHandler:self
290 andSelector:@selector(getUrl:withReply:)
291 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
292 andEventID:'OURL']; // back to the Spyglass days.
294 // Register for various window layering changes. We use these to update
295 // various UI elements (command-key equivalents, etc) when the frontmost
297 NSNotificationCenter* notificationCenter =
298 [NSNotificationCenter defaultCenter];
301 selector:@selector(windowLayeringDidChange:)
302 name:NSWindowDidBecomeKeyNotification
306 selector:@selector(windowLayeringDidChange:)
307 name:NSWindowDidResignKeyNotification
311 selector:@selector(windowLayeringDidChange:)
312 name:NSWindowDidBecomeMainNotification
316 selector:@selector(windowLayeringDidChange:)
317 name:NSWindowDidResignMainNotification
320 if (base::mac::IsOSLionOrLater()) {
323 selector:@selector(popoverDidShow:)
324 name:NSPopoverDidShowNotification
328 selector:@selector(popoverDidClose:)
329 name:NSPopoverDidCloseNotification
333 // Register for space change notifications.
334 [[[NSWorkspace sharedWorkspace] notificationCenter]
336 selector:@selector(activeSpaceDidChange:)
337 name:NSWorkspaceActiveSpaceDidChangeNotification
340 // Set up the command updater for when there are no windows open
341 [self initMenuState];
343 // Initialize the Profile menu.
344 [self initProfileMenu];
347 - (void)unregisterEventHandlers {
348 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
349 [em removeEventHandlerForEventClass:kInternetEventClass
350 andEventID:kAEGetURL];
351 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
352 andEventID:cloud_print::kAECloudPrintClass];
353 [em removeEventHandlerForEventClass:'WWW!'
355 [[NSNotificationCenter defaultCenter] removeObserver:self];
356 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
359 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
360 // the default handlers.
361 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
362 // Nothing here right now.
365 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
366 // Check for in-process downloads, and prompt the user if they really want
367 // to quit (and thus cancel downloads). Only check if we're not already
368 // shutting down, else the user might be prompted multiple times if the
369 // download isn't stopped before terminate is called again.
370 if (!browser_shutdown::IsTryingToQuit() &&
371 ![self shouldQuitWithInProgressDownloads])
374 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
375 // them in, but I'm not sure about UX; we'd also want to disable other things
376 // though.) http://crbug.com/40861
378 // Check if the user really wants to quit by employing the confirm-to-quit
380 if (!browser_shutdown::IsTryingToQuit() &&
381 [self applicationShouldTerminate:app] != NSTerminateNow)
384 // Check for active apps. If quitting is prevented, only close browsers and
386 if (!browser_shutdown::IsTryingToQuit() &&
387 quitWithAppsController_ && !quitWithAppsController_->ShouldQuit()) {
388 content::NotificationService::current()->Notify(
389 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
390 content::NotificationService::AllSources(),
391 content::NotificationService::NoDetails());
392 // This will close all browser sessions.
393 chrome::CloseAllBrowsers();
397 size_t num_browsers = chrome::GetTotalBrowserCount();
399 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
400 // already shutting down.
401 if (!browser_shutdown::IsTryingToQuit()) {
402 content::NotificationService::current()->Notify(
403 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
404 content::NotificationService::AllSources(),
405 content::NotificationService::NoDetails());
406 chrome::CloseAllBrowsersAndQuit();
409 return num_browsers == 0 ? YES : NO;
412 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
413 if (browser_shutdown::IsTryingToQuit()) {
414 // Reset the "trying to quit" state, so that closing all browser windows
415 // will no longer lead to termination.
416 browser_shutdown::SetTryingToQuit(false);
418 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
419 // would have to reinstall them here. http://crbug.com/40861
423 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
424 // If there are no windows, quit immediately.
425 if (chrome::BrowserIterator().done() &&
426 !apps::AppWindowRegistry::IsAppWindowRegisteredInAnyProfile(0)) {
427 return NSTerminateNow;
430 // Check if the preference is turned on.
431 const PrefService* prefs = g_browser_process->local_state();
432 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
433 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
434 return NSTerminateNow;
437 // If the application is going to terminate as the result of a Cmd+Q
438 // invocation, use the special sauce to prevent accidental quitting.
439 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
441 // This logic is only for keyboard-initiated quits.
442 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
443 return NSTerminateNow;
445 return [[ConfirmQuitPanelController sharedController]
446 runModalLoopForApplication:app];
449 // Called when the app is shutting down. Clean-up as appropriate.
450 - (void)applicationWillTerminate:(NSNotification*)aNotification {
451 // There better be no browser windows left at this point.
452 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
454 // Tell BrowserList not to keep the browser process alive. Once all the
455 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
456 chrome::DecrementKeepAliveCount();
458 // Reset all pref watching, as this object outlives the prefs system.
459 profilePrefRegistrar_.reset();
460 localPrefRegistrar_.RemoveAll();
462 [self unregisterEventHandlers];
464 appShimMenuController_.reset();
467 - (void)didEndMainMessageLoop {
468 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
469 chrome::HOST_DESKTOP_TYPE_NATIVE));
470 if (!chrome::GetBrowserCount([self lastProfile],
471 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
472 // As we're shutting down, we need to nuke the TabRestoreService, which
473 // will start the shutdown of the NavigationControllers and allow for
474 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
475 // and may end up crashing when some thread tries to use the IO thread (or
476 // another thread) that is no longer valid.
477 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
481 // If the window has a tab controller, make "close window" be cmd-shift-w,
482 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
483 // affects whether the shift modifier is used.
484 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
485 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
487 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
490 // If the window has a tab controller, make "close tab" take over cmd-w,
491 // otherwise it shouldn't have any key-equivalent because it should be disabled.
492 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
493 if (enableCloseTabShortcut) {
494 [closeTabMenuItem_ setKeyEquivalent:@"w"];
495 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
497 [closeTabMenuItem_ setKeyEquivalent:@""];
498 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
502 // Explicitly remove any command-key equivalents from the close tab/window
503 // menus so that nothing can go haywire if we get a user action during pending
505 - (void)clearCloseMenuItemKeyEquivalents {
506 [closeTabMenuItem_ setKeyEquivalent:@""];
507 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
508 [closeWindowMenuItem_ setKeyEquivalent:@""];
509 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
512 // See if the focused window window has tabs, and adjust the key equivalents for
513 // Close Tab/Close Window accordingly.
514 - (void)fixCloseMenuItemKeyEquivalents {
515 fileMenuUpdatePending_ = NO;
517 NSWindow* window = [NSApp keyWindow];
518 NSWindow* mainWindow = [NSApp mainWindow];
519 if (!window || ([window parentWindow] == mainWindow)) {
520 // If the key window is a child of the main window (e.g. a bubble), the main
521 // window should be the one that handles the close menu item action.
522 // Also, there might be a small amount of time where there is no key window;
523 // in that case as well, just use our main browser window if there is one.
524 // You might think that we should just always use the main window, but the
525 // "About Chrome" window serves as a counterexample.
530 [[window windowController] isKindOfClass:[TabWindowController class]];
531 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
532 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
533 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
536 // Fix up the "close tab/close window" command-key equivalents. We do this
537 // after a delay to ensure that window layer state has been set by the time
538 // we do the enabling. This should only be called on the main thread, code that
539 // calls this (even as a side-effect) from other threads needs to be fixed.
540 - (void)delayedFixCloseMenuItemKeyEquivalents {
541 DCHECK([NSThread isMainThread]);
542 if (!fileMenuUpdatePending_) {
543 // The OS prefers keypresses to timers, so it's possible that a cmd-w
544 // can sneak in before this timer fires. In order to prevent that from
545 // having any bad consequences, just clear the keys combos altogether. They
546 // will be reset when the timer eventually fires.
547 if ([NSThread isMainThread]) {
548 fileMenuUpdatePending_ = YES;
549 [self clearCloseMenuItemKeyEquivalents];
550 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
554 // This shouldn't be happening, but if it does, force it to the main
555 // thread to avoid dropping the update. Don't mess with
556 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
557 // there could be a race between the selector finishing and setting the
560 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
567 // Called when we get a notification about the window layering changing to
568 // update the UI based on the new main window.
569 - (void)windowLayeringDidChange:(NSNotification*)notify {
570 [self delayedFixCloseMenuItemKeyEquivalents];
572 if ([notify name] == NSWindowDidResignKeyNotification) {
573 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
574 // returns nil regardless of whether any suitable candidates for the key
575 // window remain. It seems that the new key window for the app is not set
576 // until after this notification is fired, so a check is performed after the
577 // run loop is allowed to spin.
578 [self performSelector:@selector(checkForAnyKeyWindows)
583 // If the window changed to a new BrowserWindowController, update the profile.
584 id windowController = [[notify object] windowController];
585 if (![windowController isKindOfClass:[BrowserWindowController class]])
588 if ([notify name] == NSWindowDidBecomeMainNotification) {
589 // If the profile is incognito, use the original profile.
590 Profile* newProfile = [windowController profile]->GetOriginalProfile();
591 [self windowChangedToProfile:newProfile];
592 } else if (chrome::GetTotalBrowserCount() == 0) {
593 [self windowChangedToProfile:
594 g_browser_process->profile_manager()->GetLastUsedProfile()];
598 - (void)activeSpaceDidChange:(NSNotification*)notify {
599 if (reopenTime_.is_null() ||
601 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
602 kWorkspaceChangeTimeoutMs) {
606 // The last applicationShouldHandleReopen:hasVisibleWindows: call
607 // happened during a space change. Now that the change has
608 // completed, raise browser windows.
609 reopenTime_ = base::TimeTicks();
610 std::set<NSWindow*> browserWindows;
611 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
612 Browser* browser = *iter;
613 browserWindows.insert(browser->window()->GetNativeWindow());
615 if (!browserWindows.empty()) {
616 ui::FocusWindowSetOnCurrentSpace(browserWindows);
620 // Called on Lion and later when a popover (e.g. dictionary) is shown.
621 - (void)popoverDidShow:(NSNotification*)notify {
623 [self fixCloseMenuItemKeyEquivalents];
626 // Called on Lion and later when a popover (e.g. dictionary) is closed.
627 - (void)popoverDidClose:(NSNotification*)notify {
629 [self fixCloseMenuItemKeyEquivalents];
632 // Called when the user has changed browser windows, meaning the backing profile
633 // may have changed. This can cause a rebuild of the user-data menus. This is a
634 // no-op if the new profile is the same as the current one. This will always be
635 // the original profile and never incognito.
636 - (void)windowChangedToProfile:(Profile*)profile {
637 if (lastProfile_ == profile)
640 // Before tearing down the menu controller bridges, return the Cocoa menus to
641 // their initial state.
642 if (bookmarkMenuBridge_.get())
643 bookmarkMenuBridge_->ResetMenu();
644 if (historyMenuBridge_.get())
645 historyMenuBridge_->ResetMenu();
647 // Rebuild the menus with the new profile.
648 lastProfile_ = profile;
650 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
651 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
652 // No need to |BuildMenu| here. It is done lazily upon menu access.
654 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
655 historyMenuBridge_->BuildMenu();
657 chrome::BrowserCommandController::
658 UpdateSharedCommandsForIncognitoAvailability(
659 menuState_.get(), lastProfile_);
660 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
661 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
662 profilePrefRegistrar_->Add(
663 prefs::kIncognitoModeAvailability,
664 base::Bind(&chrome::BrowserCommandController::
665 UpdateSharedCommandsForIncognitoAvailability,
670 - (void)checkForAnyKeyWindows {
671 if ([NSApp keyWindow])
674 content::NotificationService::current()->Notify(
675 chrome::NOTIFICATION_NO_KEY_WINDOW,
676 content::NotificationService::AllSources(),
677 content::NotificationService::NoDetails());
680 // If the auto-update interval is not set, make it 5 hours.
681 // Placed here for 2 reasons:
682 // 1) Same spot as other Pref stuff
683 // 2) Try and be friendly by keeping this after app launch
684 - (void)setUpdateCheckInterval {
685 #if defined(GOOGLE_CHROME_BUILD)
686 CFStringRef app = CFSTR("com.google.Keystone.Agent");
687 CFStringRef checkInterval = CFSTR("checkInterval");
688 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
690 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
691 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
692 CFPreferencesSetAppValue(checkInterval, value, app);
693 CFPreferencesAppSynchronize(app);
698 - (void)openStartupUrls {
699 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
700 // NSApplication is created in MainMessageLoop, and then the shortcut urls
701 // are passed in via Apple events. At this point, the first browser is
702 // already loaded in PreMainMessageLoop. If we initialize NSApplication
703 // before PreMainMessageLoop to capture shortcut URL events, it may cause
704 // more problems because it relies on things created in PreMainMessageLoop
705 // and may break existing message loop design.
706 if (startupUrls_.empty())
709 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
710 // startup urls in new tabs, because the omnibox will stay focused if we
711 // load url in NTP tab.
712 Browser* browser = chrome::GetLastActiveBrowser();
713 int startupIndex = TabStripModel::kNoTab;
714 content::WebContents* startupContent = NULL;
716 if (browser && browser->tab_strip_model()->count() == 1) {
717 startupIndex = browser->tab_strip_model()->active_index();
718 startupContent = browser->tab_strip_model()->GetActiveWebContents();
721 if (startupUrls_.size()) {
722 [self openUrls:startupUrls_];
723 startupUrls_.clear();
726 if (startupIndex != TabStripModel::kNoTab &&
727 startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
728 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
729 TabStripModel::CLOSE_NONE);
733 // This is called after profiles have been loaded and preferences registered.
734 // It is safe to access the default profile here.
735 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
736 // Notify BrowserList to keep the application running so it doesn't go away
737 // when all the browser windows get closed.
738 chrome::IncrementKeepAliveCount();
740 [self setUpdateCheckInterval];
742 // Start managing the menu for app windows. This needs to be done here because
743 // main menu item titles are not yet initialized in awakeFromNib.
744 [self initAppShimMenuController];
746 // If enabled, keep Chrome alive when apps are open instead of quitting all
748 quitWithAppsController_ = new QuitWithAppsController();
750 // Build up the encoding menu, the order of the items differs based on the
751 // current locale (see http://crbug.com/7647 for details).
752 // We need a valid g_browser_process to get the profile which is why we can't
753 // call this from awakeFromNib.
754 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
755 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
756 NSMenu* encodingMenu = [encodingMenuItem submenu];
757 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
760 // Instantiate the ProfileInfoCache observer so that we can get
761 // notified when a profile is deleted.
762 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
763 g_browser_process->profile_manager(), self));
765 // Since Chrome is localized to more languages than the OS, tell Cocoa which
766 // menu is the Help so it can add the search item to it.
767 [NSApp setHelpMenu:helpMenu_];
769 // Record the path to the (browser) app bundle; this is used by the app mode
770 // shim. It has to be done in FILE thread because getting the path requires
772 BrowserThread::PostTask(
773 BrowserThread::FILE, FROM_HERE,
774 base::Bind(&RecordLastRunAppBundlePath));
776 // Makes "Services" menu items available.
777 [self registerServicesMenuTypesTo:[notify object]];
779 startupComplete_ = YES;
781 [self openStartupUrls];
783 PrefService* localState = g_browser_process->local_state();
785 localPrefRegistrar_.Init(localState);
786 localPrefRegistrar_.Add(
787 prefs::kAllowFileSelectionDialogs,
788 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
793 // This is called after profiles have been loaded and preferences registered.
794 // It is safe to access the default profile here.
795 - (void)applicationDidBecomeActive:(NSNotification*)notify {
796 content::PluginService::GetInstance()->AppActivated();
799 // Helper function for populating and displaying the in progress downloads at
801 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
802 NSString* titleText = nil;
803 NSString* explanationText = nil;
804 NSString* waitTitle = nil;
805 NSString* exitTitle = nil;
807 // Set the dialog text based on whether or not there are multiple downloads.
808 if (downloadCount == 1) {
809 // Dialog text: warning and explanation.
810 titleText = l10n_util::GetNSString(
811 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
812 explanationText = l10n_util::GetNSString(
813 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
815 // Dialog text: warning and explanation.
816 titleText = l10n_util::GetNSStringF(
817 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
818 base::IntToString16(downloadCount));
819 explanationText = l10n_util::GetNSString(
820 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
822 // Cancel download and exit button text.
823 exitTitle = l10n_util::GetNSString(
824 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
826 // Wait for download button text.
827 waitTitle = l10n_util::GetNSString(
828 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
830 // 'waitButton' is the default choice.
831 int choice = NSRunAlertPanel(titleText, @"%@",
832 waitTitle, exitTitle, nil, explanationText);
833 return choice == NSAlertDefaultReturn ? YES : NO;
836 // Check all profiles for in progress downloads, and if we find any, prompt the
837 // user to see if we should continue to exit (and thus cancel the downloads), or
838 // if we should wait.
839 - (BOOL)shouldQuitWithInProgressDownloads {
840 ProfileManager* profile_manager = g_browser_process->profile_manager();
841 if (!profile_manager)
844 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
845 for (size_t i = 0; i < profiles.size(); ++i) {
846 DownloadService* download_service =
847 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
848 DownloadManager* download_manager =
849 (download_service->HasCreatedDownloadManager() ?
850 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
851 if (download_manager &&
852 download_manager->NonMaliciousInProgressCount() > 0) {
853 int downloadCount = download_manager->NonMaliciousInProgressCount();
854 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
855 // Create a new browser window (if necessary) and navigate to the
856 // downloads page if the user chooses to wait.
857 Browser* browser = chrome::FindBrowserWithProfile(
858 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
860 browser = new Browser(Browser::CreateParams(
861 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
862 browser->window()->Show();
865 chrome::ShowDownloads(browser);
869 // User wants to exit.
874 // No profiles or active downloads found, okay to exit.
878 // Called to determine if we should enable the "restore tab" menu item.
879 // Checks with the TabRestoreService to see if there's anything there to
880 // restore and returns YES if so.
881 - (BOOL)canRestoreTab {
882 TabRestoreService* service =
883 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
884 return service && !service->entries().empty();
887 // Called from the AppControllerProfileObserver every time a profile is deleted.
888 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
889 Profile* lastProfile = [self lastProfile];
891 // If the lastProfile has been deleted, the profile manager has
892 // already loaded a new one, so the pointer needs to be updated;
893 // otherwise we will try to start up a browser window with a pointer
894 // to the old profile.
895 if (profilePath == lastProfile->GetPath())
896 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
899 // Returns true if there is a modal window (either window- or application-
900 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
901 // sheets) will not count as blocking the browser. But things like open/save
902 // dialogs that are window modal will block the browser.
903 - (BOOL)keyWindowIsModal {
904 if ([NSApp modalWindow])
907 Browser* browser = chrome::GetLastActiveBrowser();
909 [[browser->window()->GetNativeWindow() attachedSheet]
910 isKindOfClass:[NSWindow class]];
913 // Called to validate menu items when there are no key windows. All the
914 // items we care about have been set with the |commandDispatch:| action and
915 // a target of FirstResponder in IB. If it's not one of those, let it
916 // continue up the responder chain to be handled elsewhere. We pull out the
917 // tag as the cross-platform constant to differentiate and dispatch the
919 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
920 SEL action = [item action];
922 if (action == @selector(commandDispatch:) ||
923 action == @selector(commandFromDock:)) {
924 NSInteger tag = [item tag];
925 if (menuState_ && // NULL in tests.
926 menuState_->SupportsCommand(tag)) {
928 // The File Menu commands are not automatically disabled by Cocoa when a
929 // dialog sheet obscures the browser window, so we disable several of
930 // them here. We don't need to include IDC_CLOSE_WINDOW, because
931 // app_controller is only activated when there are no key windows (see
932 // function comment).
933 case IDC_RESTORE_TAB:
934 enable = ![self keyWindowIsModal] && [self canRestoreTab];
936 // Browser-level items that open in new tabs should not open if there's
937 // a window- or app-modal dialog.
940 case IDC_SHOW_HISTORY:
941 case IDC_SHOW_BOOKMARK_MANAGER:
942 enable = ![self keyWindowIsModal];
944 // Browser-level items that open in new windows.
945 case IDC_TASK_MANAGER:
946 // Allow the user to open a new window if there's a window-modal
948 enable = ![self keyWindowIsModal];
950 case IDC_SHOW_SYNC_SETUP: {
951 Profile* lastProfile = [self lastProfile];
952 // The profile may be NULL during shutdown -- see
953 // http://code.google.com/p/chromium/issues/detail?id=43048 .
955 // TODO(akalin,viettrungluu): Figure out whether this method
956 // can be prevented from being called if lastProfile is
960 << "NULL lastProfile detected -- not doing anything";
963 SigninManager* signin = SigninManagerFactory::GetForProfile(
964 lastProfile->GetOriginalProfile());
965 enable = signin->IsSigninAllowed() &&
966 ![self keyWindowIsModal];
967 [BrowserWindowController updateSigninItem:item
969 currentProfile:lastProfile];
972 #if defined(GOOGLE_CHROME_BUILD)
978 enable = menuState_->IsCommandEnabled(tag) ?
979 ![self keyWindowIsModal] : NO;
982 } else if (action == @selector(terminate:)) {
984 } else if (action == @selector(showPreferences:)) {
986 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
988 } else if (action == @selector(commandFromDock:)) {
990 } else if (action == @selector(toggleConfirmToQuit:)) {
991 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
993 } else if (action == @selector(toggleDisplayMessageCenter:)) {
994 NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
995 [self updateDisplayMessageCenterPrefMenuItem:menuItem];
997 } else if (action == @selector(executeApplication:)) {
1003 // Called when the user picks a menu item when there are no key windows, or when
1004 // there is no foreground browser window. Calls through to the browser object to
1005 // execute the command. This assumes that the command is supported and doesn't
1006 // check, otherwise it should have been disabled in the UI in
1007 // |-validateUserInterfaceItem:|.
1008 - (void)commandDispatch:(id)sender {
1009 Profile* lastProfile = [self safeLastProfileForNewWindows];
1011 // Handle the case where we're dispatching a command from a sender that's in a
1012 // browser window. This means that the command came from a background window
1013 // and is getting here because the foreground window is not a browser window.
1014 if ([sender respondsToSelector:@selector(window)]) {
1015 id delegate = [[sender window] windowController];
1016 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1017 [delegate commandDispatch:sender];
1022 // Ignore commands during session restore's browser creation. It uses a
1023 // nested message loop and commands dispatched during this operation cause
1025 if (SessionRestore::IsRestoring(lastProfile) &&
1026 base::MessageLoop::current()->IsNested())
1029 NSInteger tag = [sender tag];
1031 // If there are no browser windows, and we are trying to open a browser
1032 // for a locked profile, we have to show the User Manager instead as the
1033 // locked profile needs authentication.
1034 if (IsProfileSignedOut(lastProfile)) {
1035 chrome::ShowUserManager(lastProfile->GetPath());
1041 // Create a new tab in an existing browser window (which we activate) if
1043 if (Browser* browser = ActivateBrowser(lastProfile)) {
1044 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1047 // Else fall through to create new window.
1048 case IDC_NEW_WINDOW:
1049 CreateBrowser(lastProfile);
1051 case IDC_FOCUS_LOCATION:
1052 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1053 IDC_FOCUS_LOCATION);
1055 case IDC_FOCUS_SEARCH:
1056 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1059 case IDC_NEW_INCOGNITO_WINDOW:
1060 CreateBrowser(lastProfile->GetOffTheRecordProfile());
1062 case IDC_RESTORE_TAB:
1063 // There is only the native desktop on Mac.
1064 chrome::OpenWindowWithRestoredTabs(lastProfile,
1065 chrome::HOST_DESKTOP_TYPE_NATIVE);
1068 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1070 case IDC_CLEAR_BROWSING_DATA: {
1071 // There may not be a browser open, so use the default profile.
1072 if (Browser* browser = ActivateBrowser(lastProfile)) {
1073 chrome::ShowClearBrowsingDataDialog(browser);
1075 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1079 case IDC_IMPORT_SETTINGS: {
1080 if (Browser* browser = ActivateBrowser(lastProfile)) {
1081 chrome::ShowImportDialog(browser);
1083 chrome::OpenImportSettingsDialogWindow(lastProfile);
1087 case IDC_SHOW_BOOKMARK_MANAGER:
1088 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1089 if (Browser* browser = ActivateBrowser(lastProfile)) {
1090 chrome::ShowBookmarkManager(browser);
1092 // No browser window, so create one for the bookmark manager tab.
1093 chrome::OpenBookmarkManagerWindow(lastProfile);
1096 case IDC_SHOW_HISTORY:
1097 if (Browser* browser = ActivateBrowser(lastProfile))
1098 chrome::ShowHistory(browser);
1100 chrome::OpenHistoryWindow(lastProfile);
1102 case IDC_SHOW_DOWNLOADS:
1103 if (Browser* browser = ActivateBrowser(lastProfile))
1104 chrome::ShowDownloads(browser);
1106 chrome::OpenDownloadsWindow(lastProfile);
1108 case IDC_MANAGE_EXTENSIONS:
1109 if (Browser* browser = ActivateBrowser(lastProfile))
1110 chrome::ShowExtensions(browser, std::string());
1112 chrome::OpenExtensionsWindow(lastProfile);
1114 case IDC_HELP_PAGE_VIA_MENU:
1115 if (Browser* browser = ActivateBrowser(lastProfile))
1116 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1118 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1120 case IDC_SHOW_SYNC_SETUP:
1121 if (Browser* browser = ActivateBrowser(lastProfile)) {
1122 chrome::ShowBrowserSignin(browser, signin::SOURCE_MENU);
1124 chrome::OpenSyncSetupWindow(lastProfile, signin::SOURCE_MENU);
1127 case IDC_TASK_MANAGER:
1128 content::RecordAction(UserMetricsAction("TaskManager"));
1129 TaskManagerMac::Show();
1132 [self showPreferences:sender];
1137 // Run a (background) application in a new tab.
1138 - (void)executeApplication:(id)sender {
1139 NSInteger tag = [sender tag];
1140 Profile* profile = [self lastProfile];
1142 BackgroundApplicationListModel applications(profile);
1144 tag < static_cast<int>(applications.size()));
1145 const extensions::Extension* extension = applications.GetExtension(tag);
1146 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1149 // Same as |-commandDispatch:|, but executes commands using a disposition
1150 // determined by the key flags. This will get called in the case where the
1151 // frontmost window is not a browser window, and the user has command-clicked
1152 // a button in a background browser window whose action is
1153 // |-commandDispatchUsingKeyModifiers:|
1154 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1156 if ([sender respondsToSelector:@selector(window)]) {
1157 id delegate = [[sender window] windowController];
1158 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1159 [delegate commandDispatchUsingKeyModifiers:sender];
1164 // NSApplication delegate method called when someone clicks on the dock icon.
1165 // To match standard mac behavior, we should open a new window if there are no
1167 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1168 hasVisibleWindows:(BOOL)hasVisibleWindows {
1169 // If the browser is currently trying to quit, don't do anything and return NO
1170 // to prevent AppKit from doing anything.
1171 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1172 if (browser_shutdown::IsTryingToQuit())
1175 // Bring all browser windows to the front. Specifically, this brings them in
1176 // front of any app windows. FocusWindowSet will also unminimize the most
1177 // recently minimized window if no windows in the set are visible.
1178 // If there are any, return here. Otherwise, the windows are panels or
1179 // notifications so we still need to open a new window.
1180 if (hasVisibleWindows) {
1181 std::set<NSWindow*> browserWindows;
1182 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1183 Browser* browser = *iter;
1184 browserWindows.insert(browser->window()->GetNativeWindow());
1186 if (!browserWindows.empty()) {
1187 NSWindow* keyWindow = [NSApp keyWindow];
1188 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1189 // The key window is not on the active space. We must be mid-animation
1190 // for a space transition triggered by the dock. Delay the call to
1191 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1192 // wrong space's windows get raised, resulting in an off-screen key
1193 // window. It does not work to |ui::FocusWindowSet| twice, once here
1194 // and once in |activeSpaceDidChange:|, as that appears to break when
1195 // the omnibox is focused.
1197 // This check relies on OS X setting the key window to a window on the
1198 // target space before calling this method.
1200 // See http://crbug.com/309656.
1201 reopenTime_ = base::TimeTicks::Now();
1203 ui::FocusWindowSetOnCurrentSpace(browserWindows);
1205 // Return NO; we've done (or soon will do) the deminiaturize, so
1206 // AppKit shouldn't do anything.
1211 // If launched as a hidden login item (due to installation of a persistent app
1212 // or by the user, for example in System Preferences->Accounts->Login Items),
1213 // allow session to be restored first time the user clicks on a Dock icon.
1214 // Normally, it'd just open a new empty page.
1216 static BOOL doneOnce = NO;
1217 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1218 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1220 if (attemptRestore) {
1221 SessionService* sessionService =
1222 SessionServiceFactory::GetForProfileForSessionRestore(
1223 [self lastProfile]);
1224 if (sessionService &&
1225 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1230 // Otherwise open a new window.
1231 // If the last profile was locked, we have to open the User Manager, as the
1232 // profile requires authentication. Similarly, because guest mode is
1233 // implemented as forced incognito, we can't open a new guest browser either,
1234 // so we have to show the User Manager as well.
1235 Profile* lastProfile = [self lastProfile];
1236 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile))
1237 chrome::ShowUserManager(lastProfile->GetPath());
1239 CreateBrowser(lastProfile);
1241 // We've handled the reopen event, so return NO to tell AppKit not
1246 - (void)initMenuState {
1247 menuState_.reset(new CommandUpdater(NULL));
1248 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1249 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1250 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1251 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1252 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1253 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1254 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1255 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1256 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1257 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1258 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1259 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1260 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1261 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1262 #if defined(GOOGLE_CHROME_BUILD)
1263 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1265 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1266 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1269 // Conditionally adds the Profile menu to the main menu bar.
1270 - (void)initProfileMenu {
1271 NSMenu* mainMenu = [NSApp mainMenu];
1272 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1274 if (!profiles::IsMultipleProfilesEnabled()) {
1275 [mainMenu removeItem:profileMenu];
1279 // The controller will unhide the menu if necessary.
1280 [profileMenu setHidden:YES];
1282 profileMenuController_.reset(
1283 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1286 // The Confirm to Quit preference is atypical in that the preference lives in
1287 // the app menu right above the Quit menu item. This method will refresh the
1288 // display of that item depending on the preference state.
1289 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1290 // Format the string so that the correct key equivalent is displayed.
1291 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1292 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1293 base::SysNSStringToUTF16(acceleratorString));
1294 [item setTitle:title];
1296 const PrefService* prefService = g_browser_process->local_state();
1297 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1298 [item setState:enabled ? NSOnState : NSOffState];
1301 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
1302 const PrefService* prefService = g_browser_process->local_state();
1303 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1304 // The item should be checked if "show icon" is false, since the text reads
1305 // "Hide notification center icon."
1306 [item setState:enabled ? NSOffState : NSOnState];
1309 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1310 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1311 // handles requests from services.
1312 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1313 [app registerServicesMenuSendTypes:types returnTypes:types];
1316 - (Profile*)lastProfile {
1317 // Return the profile of the last-used BrowserWindowController, if available.
1319 return lastProfile_;
1321 // On first launch, use the logic that ChromeBrowserMain uses to determine
1322 // the initial profile.
1323 ProfileManager* profile_manager = g_browser_process->profile_manager();
1324 if (!profile_manager)
1327 return profile_manager->GetProfile(GetStartupProfilePath(
1328 profile_manager->user_data_dir(),
1329 *CommandLine::ForCurrentProcess()));
1332 - (Profile*)safeLastProfileForNewWindows {
1333 Profile* profile = [self lastProfile];
1335 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1336 if (profile->IsGuestSession())
1337 return profile->GetOffTheRecordProfile();
1342 // Various methods to open URLs that we get in a native fashion. We use
1343 // StartupBrowserCreator here because on the other platforms, URLs to open come
1344 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1345 // to bottleneck the openings through that for uniform handling.
1347 - (void)openUrls:(const std::vector<GURL>&)urls {
1348 // If the browser hasn't started yet, just queue up the URLs.
1349 if (!startupComplete_) {
1350 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1354 Browser* browser = chrome::GetLastActiveBrowser();
1355 // if no browser window exists then create one with no tabs to be filled in
1357 browser = new Browser(Browser::CreateParams(
1358 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1359 browser->window()->Show();
1362 CommandLine dummy(CommandLine::NO_PROGRAM);
1363 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1364 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1365 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1366 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1369 - (void)getUrl:(NSAppleEventDescriptor*)event
1370 withReply:(NSAppleEventDescriptor*)reply {
1371 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1374 GURL gurl(base::SysNSStringToUTF8(urlStr));
1375 std::vector<GURL> gurlVector;
1376 gurlVector.push_back(gurl);
1378 [self openUrls:gurlVector];
1381 - (void)application:(NSApplication*)sender
1382 openFiles:(NSArray*)filenames {
1383 std::vector<GURL> gurlVector;
1384 for (NSString* file in filenames) {
1386 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1387 gurlVector.push_back(gurl);
1389 if (!gurlVector.empty())
1390 [self openUrls:gurlVector];
1392 NOTREACHED() << "Nothing to open!";
1394 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1397 // Show the preferences window, or bring it to the front if it's already
1399 - (IBAction)showPreferences:(id)sender {
1400 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1401 // Show options tab in the active browser window.
1402 chrome::ShowSettings(browser);
1404 // No browser window, so create one for the options tab.
1405 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
1409 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1410 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1411 chrome::ShowAboutChrome(browser);
1413 // No browser window, so create one for the about tab.
1414 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
1418 - (IBAction)toggleConfirmToQuit:(id)sender {
1419 PrefService* prefService = g_browser_process->local_state();
1420 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1421 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1424 - (IBAction)toggleDisplayMessageCenter:(id)sender {
1425 PrefService* prefService = g_browser_process->local_state();
1426 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1427 prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
1430 // Explicitly bring to the foreground when creating new windows from the dock.
1431 - (void)commandFromDock:(id)sender {
1432 [NSApp activateIgnoringOtherApps:YES];
1433 [self commandDispatch:sender];
1436 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1437 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1438 Profile* profile = [self lastProfile];
1440 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1444 [dockMenu addItem:[NSMenuItem separatorItem]];
1446 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1447 base::scoped_nsobject<NSMenuItem> item(
1448 [[NSMenuItem alloc] initWithTitle:titleStr
1449 action:@selector(commandFromDock:)
1450 keyEquivalent:@""]);
1451 [item setTarget:self];
1452 [item setTag:IDC_NEW_WINDOW];
1453 [item setEnabled:[self validateUserInterfaceItem:item]];
1454 [dockMenu addItem:item];
1456 // |profile| can be NULL during unit tests.
1457 if (!profile || !profile->IsManaged()) {
1458 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1460 [[NSMenuItem alloc] initWithTitle:titleStr
1461 action:@selector(commandFromDock:)
1462 keyEquivalent:@""]);
1463 [item setTarget:self];
1464 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1465 [item setEnabled:[self validateUserInterfaceItem:item]];
1466 [dockMenu addItem:item];
1469 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1470 // tests which use the mock in place of the profile-initialized model.
1472 // Avoid breaking unit tests which have no profile.
1474 BackgroundApplicationListModel applications(profile);
1475 if (applications.size()) {
1478 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1479 base::scoped_nsobject<NSMenu> appMenu(
1480 [[NSMenu alloc] initWithTitle:menuStr]);
1481 for (extensions::ExtensionList::const_iterator cursor =
1482 applications.begin();
1483 cursor != applications.end();
1484 ++cursor, ++position) {
1485 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1487 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1488 base::scoped_nsobject<NSMenuItem> appItem(
1489 [[NSMenuItem alloc] initWithTitle:itemStr
1490 action:@selector(executeApplication:)
1491 keyEquivalent:@""]);
1492 [appItem setTarget:self];
1493 [appItem setTag:position];
1494 [appMenu addItem:appItem];
1502 - (const std::vector<GURL>&)startupUrls {
1503 return startupUrls_;
1506 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1507 return bookmarkMenuBridge_.get();
1510 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1511 workAreaChangeObservers_.AddObserver(observer);
1514 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1515 workAreaChangeObservers_.RemoveObserver(observer);
1518 - (void)initAppShimMenuController {
1519 if (!appShimMenuController_)
1520 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1523 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1524 // During this callback the working area is not always already updated. Defer.
1525 [self performSelector:@selector(delayedScreenParametersUpdate)
1530 - (void)delayedScreenParametersUpdate {
1531 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1535 @end // @implementation AppController
1537 //---------------------------------------------------------------------------
1539 namespace app_controller_mac {
1541 bool IsOpeningNewWindow() {
1542 return g_is_opening_new_window;
1545 } // namespace app_controller_mac