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/app_shim_mac.h"
8 #include "apps/app_shim/extension_app_shim_handler_mac.h"
9 #include "apps/app_window_registry.h"
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/files/file_path.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/mac_util.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/profiles/profile_info_cache_observer.h"
34 #include "chrome/browser/profiles/profile_manager.h"
35 #include "chrome/browser/profiles/profiles_state.h"
36 #include "chrome/browser/sessions/session_restore.h"
37 #include "chrome/browser/sessions/session_service.h"
38 #include "chrome/browser/sessions/session_service_factory.h"
39 #include "chrome/browser/sessions/tab_restore_service.h"
40 #include "chrome/browser/sessions/tab_restore_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/signin/signin_promo.h"
43 #include "chrome/browser/sync/profile_sync_service.h"
44 #include "chrome/browser/sync/sync_ui_util.h"
45 #include "chrome/browser/ui/browser.h"
46 #include "chrome/browser/ui/browser_command_controller.h"
47 #include "chrome/browser/ui/browser_commands.h"
48 #include "chrome/browser/ui/browser_dialogs.h"
49 #include "chrome/browser/ui/browser_finder.h"
50 #include "chrome/browser/ui/browser_iterator.h"
51 #include "chrome/browser/ui/browser_mac.h"
52 #include "chrome/browser/ui/browser_window.h"
53 #include "chrome/browser/ui/chrome_pages.h"
54 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
55 #include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
56 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
57 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
58 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
59 #import "chrome/browser/ui/cocoa/confirm_quit.h"
60 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
61 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
62 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
63 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
64 #import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
65 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
66 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
67 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
68 #include "chrome/browser/ui/extensions/application_launch.h"
69 #include "chrome/browser/ui/host_desktop.h"
70 #include "chrome/browser/ui/startup/startup_browser_creator.h"
71 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
72 #include "chrome/common/chrome_paths_internal.h"
73 #include "chrome/common/chrome_switches.h"
74 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
75 #include "chrome/common/extensions/extension_constants.h"
76 #include "chrome/common/mac/app_mode_common.h"
77 #include "chrome/common/pref_names.h"
78 #include "chrome/common/url_constants.h"
79 #include "components/signin/core/common/profile_management_switches.h"
80 #include "components/signin/core/browser/signin_manager.h"
81 #include "content/public/browser/browser_thread.h"
82 #include "content/public/browser/download_manager.h"
83 #include "content/public/browser/notification_service.h"
84 #include "content/public/browser/notification_types.h"
85 #include "content/public/browser/plugin_service.h"
86 #include "content/public/browser/user_metrics.h"
87 #include "extensions/browser/extension_system.h"
88 #include "grit/chromium_strings.h"
89 #include "grit/generated_resources.h"
90 #include "net/base/filename_util.h"
91 #include "ui/base/cocoa/focus_window_set.h"
92 #include "ui/base/l10n/l10n_util.h"
93 #include "ui/base/l10n/l10n_util_mac.h"
95 using base::UserMetricsAction;
96 using content::BrowserContext;
97 using content::BrowserThread;
98 using content::DownloadManager;
102 // Declare notification names from the 10.7 SDK.
103 #if !defined(MAC_OS_X_VERSION_10_7) || \
104 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
105 NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
106 NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
109 // How long we allow a workspace change notification to wait to be
110 // associated with a dock activation. The animation lasts 250ms. See
111 // applicationShouldHandleReopen:hasVisibleWindows:.
112 static const int kWorkspaceChangeTimeoutMs = 500;
114 // True while AppController is calling chrome::NewEmptyWindow(). We need a
115 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
116 // because otherwise the SessionService will try to restore sessions when we
117 // make a new window while there are no other active windows.
118 bool g_is_opening_new_window = false;
120 // Activates a browser window having the given profile (the last one active) if
121 // possible and returns a pointer to the activate |Browser| or NULL if this was
122 // not possible. If the last active browser is minimized (in particular, if
123 // there are only minimized windows), it will unminimize it.
124 Browser* ActivateBrowser(Profile* profile) {
125 Browser* browser = chrome::FindLastActiveWithProfile(profile,
126 chrome::HOST_DESKTOP_TYPE_NATIVE);
128 browser->window()->Activate();
132 // Creates an empty browser window with the given profile and returns a pointer
133 // to the new |Browser|.
134 Browser* CreateBrowser(Profile* profile) {
136 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
137 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
140 Browser* browser = chrome::GetLastActiveBrowser();
145 // Activates a browser window having the given profile (the last one active) if
146 // possible or creates an empty one if necessary. Returns a pointer to the
147 // activated/new |Browser|.
148 Browser* ActivateOrCreateBrowser(Profile* profile) {
149 if (Browser* browser = ActivateBrowser(profile))
151 return CreateBrowser(profile);
154 CFStringRef BaseBundleID_CFString() {
155 NSString* base_bundle_id =
156 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
157 return base::mac::NSToCFCast(base_bundle_id);
160 // This callback synchronizes preferences (under "org.chromium.Chromium" or
161 // "com.google.Chrome"), in particular, writes them out to disk.
162 void PrefsSyncCallback() {
163 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
164 LOG(WARNING) << "Error recording application bundle path.";
167 // Record the location of the application bundle (containing the main framework)
168 // from which Chromium was loaded. This is used by app mode shims to find
170 void RecordLastRunAppBundlePath() {
171 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
172 // real, user-visible app bundle directory. (The alternatives give either the
173 // framework's path or the initial app's path, which may be an app mode shim
175 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
177 base::FilePath app_bundle_path =
178 chrome::GetVersionedDirectory().DirName().DirName().DirName();
179 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
180 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
181 CFPreferencesSetAppValue(
182 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
183 app_bundle_path_cfstring, BaseBundleID_CFString());
185 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
186 BrowserThread::PostDelayedTask(
187 BrowserThread::FILE, FROM_HERE,
188 base::Bind(&PrefsSyncCallback),
189 base::TimeDelta::FromMilliseconds(1500));
192 bool IsProfileSignedOut(Profile* profile) {
193 // The signed out status only makes sense at the moment in the context of the
194 // --new-profile-management flag.
195 if (!switches::IsNewProfileManagement())
197 ProfileInfoCache& cache =
198 g_browser_process->profile_manager()->GetProfileInfoCache();
199 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
200 if (profile_index == std::string::npos)
202 return cache.ProfileIsSigninRequiredAtIndex(profile_index);
205 } // anonymous namespace
207 @interface AppController (Private)
208 - (void)initMenuState;
209 - (void)initProfileMenu;
210 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
211 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
212 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
213 - (void)openUrls:(const std::vector<GURL>&)urls;
214 - (void)getUrl:(NSAppleEventDescriptor*)event
215 withReply:(NSAppleEventDescriptor*)reply;
216 - (void)windowLayeringDidChange:(NSNotification*)inNotification;
217 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
218 - (void)windowChangedToProfile:(Profile*)profile;
219 - (void)checkForAnyKeyWindows;
220 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
221 - (BOOL)shouldQuitWithInProgressDownloads;
222 - (void)executeApplication:(id)sender;
223 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
226 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
228 AppControllerProfileObserver(
229 ProfileManager* profile_manager, AppController* app_controller)
230 : profile_manager_(profile_manager),
231 app_controller_(app_controller) {
232 DCHECK(profile_manager_);
233 DCHECK(app_controller_);
234 profile_manager_->GetProfileInfoCache().AddObserver(this);
237 virtual ~AppControllerProfileObserver() {
238 DCHECK(profile_manager_);
239 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
243 // ProfileInfoCacheObserver implementation:
245 virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
248 virtual void OnProfileWasRemoved(
249 const base::FilePath& profile_path,
250 const base::string16& profile_name) OVERRIDE {
251 // When a profile is deleted we need to notify the AppController,
252 // so it can correctly update its pointer to the last used profile.
253 [app_controller_ profileWasRemoved:profile_path];
256 virtual void OnProfileWillBeRemoved(
257 const base::FilePath& profile_path) OVERRIDE {
260 virtual void OnProfileNameChanged(
261 const base::FilePath& profile_path,
262 const base::string16& old_profile_name) OVERRIDE {
265 virtual void OnProfileAvatarChanged(
266 const base::FilePath& profile_path) OVERRIDE {
269 ProfileManager* profile_manager_;
271 AppController* app_controller_; // Weak; owns us.
273 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
276 @implementation AppController
278 @synthesize startupComplete = startupComplete_;
280 // This method is called very early in application startup (ie, before
281 // the profile is loaded or any preferences have been registered). Defer any
282 // user-data initialization until -applicationDidFinishLaunching:.
283 - (void)awakeFromNib {
284 // We need to register the handlers early to catch events fired on launch.
285 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
286 [em setEventHandler:self
287 andSelector:@selector(getUrl:withReply:)
288 forEventClass:kInternetEventClass
289 andEventID:kAEGetURL];
290 [em setEventHandler:self
291 andSelector:@selector(getUrl:withReply:)
292 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
293 andEventID:'OURL']; // back to the Spyglass days.
295 // Register for various window layering changes. We use these to update
296 // various UI elements (command-key equivalents, etc) when the frontmost
298 NSNotificationCenter* notificationCenter =
299 [NSNotificationCenter defaultCenter];
302 selector:@selector(windowLayeringDidChange:)
303 name:NSWindowDidBecomeKeyNotification
307 selector:@selector(windowLayeringDidChange:)
308 name:NSWindowDidResignKeyNotification
312 selector:@selector(windowLayeringDidChange:)
313 name:NSWindowDidBecomeMainNotification
317 selector:@selector(windowLayeringDidChange:)
318 name:NSWindowDidResignMainNotification
321 if (base::mac::IsOSLionOrLater()) {
324 selector:@selector(popoverDidShow:)
325 name:NSPopoverDidShowNotification
329 selector:@selector(popoverDidClose:)
330 name:NSPopoverDidCloseNotification
334 // Register for space change notifications.
335 [[[NSWorkspace sharedWorkspace] notificationCenter]
337 selector:@selector(activeSpaceDidChange:)
338 name:NSWorkspaceActiveSpaceDidChangeNotification
341 // Set up the command updater for when there are no windows open
342 [self initMenuState];
344 // Initialize the Profile menu.
345 [self initProfileMenu];
348 - (void)unregisterEventHandlers {
349 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
350 [em removeEventHandlerForEventClass:kInternetEventClass
351 andEventID:kAEGetURL];
352 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
353 andEventID:cloud_print::kAECloudPrintClass];
354 [em removeEventHandlerForEventClass:'WWW!'
356 [[NSNotificationCenter defaultCenter] removeObserver:self];
357 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
360 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
361 // the default handlers.
362 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
363 // Nothing here right now.
366 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
367 // Check for in-process downloads, and prompt the user if they really want
368 // to quit (and thus cancel downloads). Only check if we're not already
369 // shutting down, else the user might be prompted multiple times if the
370 // download isn't stopped before terminate is called again.
371 if (!browser_shutdown::IsTryingToQuit() &&
372 ![self shouldQuitWithInProgressDownloads])
375 // Check for active apps, and prompt the user if they really want to quit
376 // (and also quit the apps).
377 if (!browser_shutdown::IsTryingToQuit() &&
378 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit())
381 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
382 // them in, but I'm not sure about UX; we'd also want to disable other things
383 // though.) http://crbug.com/40861
385 // Check if the user really wants to quit by employing the confirm-to-quit
387 if (!browser_shutdown::IsTryingToQuit() &&
388 [self applicationShouldTerminate:app] != NSTerminateNow)
391 size_t num_browsers = chrome::GetTotalBrowserCount();
393 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
394 // already shutting down.
395 if (!browser_shutdown::IsTryingToQuit()) {
396 content::NotificationService::current()->Notify(
397 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
398 content::NotificationService::AllSources(),
399 content::NotificationService::NoDetails());
400 chrome::CloseAllBrowsersAndQuit();
403 return num_browsers == 0 ? YES : NO;
406 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
407 if (browser_shutdown::IsTryingToQuit()) {
408 // Reset the "trying to quit" state, so that closing all browser windows
409 // will no longer lead to termination.
410 browser_shutdown::SetTryingToQuit(false);
412 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
413 // would have to reinstall them here. http://crbug.com/40861
417 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
418 // If there are no windows, quit immediately.
419 if (chrome::BrowserIterator().done() &&
420 !apps::AppWindowRegistry::IsAppWindowRegisteredInAnyProfile(0)) {
421 return NSTerminateNow;
424 // Check if the preference is turned on.
425 const PrefService* prefs = g_browser_process->local_state();
426 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
427 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
428 return NSTerminateNow;
431 // If the application is going to terminate as the result of a Cmd+Q
432 // invocation, use the special sauce to prevent accidental quitting.
433 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
435 // This logic is only for keyboard-initiated quits.
436 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
437 return NSTerminateNow;
439 return [[ConfirmQuitPanelController sharedController]
440 runModalLoopForApplication:app];
443 // Called when the app is shutting down. Clean-up as appropriate.
444 - (void)applicationWillTerminate:(NSNotification*)aNotification {
445 // There better be no browser windows left at this point.
446 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
448 // Tell BrowserList not to keep the browser process alive. Once all the
449 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
450 chrome::DecrementKeepAliveCount();
452 // Reset all pref watching, as this object outlives the prefs system.
453 profilePrefRegistrar_.reset();
454 localPrefRegistrar_.RemoveAll();
456 [self unregisterEventHandlers];
458 appShimMenuController_.reset();
461 - (void)didEndMainMessageLoop {
462 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
463 chrome::HOST_DESKTOP_TYPE_NATIVE));
464 if (!chrome::GetBrowserCount([self lastProfile],
465 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
466 // As we're shutting down, we need to nuke the TabRestoreService, which
467 // will start the shutdown of the NavigationControllers and allow for
468 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
469 // and may end up crashing when some thread tries to use the IO thread (or
470 // another thread) that is no longer valid.
471 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
475 // If the window has a tab controller, make "close window" be cmd-shift-w,
476 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
477 // affects whether the shift modifier is used.
478 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
479 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
481 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
484 // If the window has a tab controller, make "close tab" take over cmd-w,
485 // otherwise it shouldn't have any key-equivalent because it should be disabled.
486 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
487 if (enableCloseTabShortcut) {
488 [closeTabMenuItem_ setKeyEquivalent:@"w"];
489 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
491 [closeTabMenuItem_ setKeyEquivalent:@""];
492 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
496 // Explicitly remove any command-key equivalents from the close tab/window
497 // menus so that nothing can go haywire if we get a user action during pending
499 - (void)clearCloseMenuItemKeyEquivalents {
500 [closeTabMenuItem_ setKeyEquivalent:@""];
501 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
502 [closeWindowMenuItem_ setKeyEquivalent:@""];
503 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
506 // See if the focused window window has tabs, and adjust the key equivalents for
507 // Close Tab/Close Window accordingly.
508 - (void)fixCloseMenuItemKeyEquivalents {
509 fileMenuUpdatePending_ = NO;
511 NSWindow* window = [NSApp keyWindow];
512 NSWindow* mainWindow = [NSApp mainWindow];
513 if (!window || ([window parentWindow] == mainWindow)) {
514 // If the key window is a child of the main window (e.g. a bubble), the main
515 // window should be the one that handles the close menu item action.
516 // Also, there might be a small amount of time where there is no key window;
517 // in that case as well, just use our main browser window if there is one.
518 // You might think that we should just always use the main window, but the
519 // "About Chrome" window serves as a counterexample.
524 [[window windowController] isKindOfClass:[TabWindowController class]];
525 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
526 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
527 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
530 // Fix up the "close tab/close window" command-key equivalents. We do this
531 // after a delay to ensure that window layer state has been set by the time
532 // we do the enabling. This should only be called on the main thread, code that
533 // calls this (even as a side-effect) from other threads needs to be fixed.
534 - (void)delayedFixCloseMenuItemKeyEquivalents {
535 DCHECK([NSThread isMainThread]);
536 if (!fileMenuUpdatePending_) {
537 // The OS prefers keypresses to timers, so it's possible that a cmd-w
538 // can sneak in before this timer fires. In order to prevent that from
539 // having any bad consequences, just clear the keys combos altogether. They
540 // will be reset when the timer eventually fires.
541 if ([NSThread isMainThread]) {
542 fileMenuUpdatePending_ = YES;
543 [self clearCloseMenuItemKeyEquivalents];
544 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
548 // This shouldn't be happening, but if it does, force it to the main
549 // thread to avoid dropping the update. Don't mess with
550 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
551 // there could be a race between the selector finishing and setting the
554 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
561 // Called when we get a notification about the window layering changing to
562 // update the UI based on the new main window.
563 - (void)windowLayeringDidChange:(NSNotification*)notify {
564 [self delayedFixCloseMenuItemKeyEquivalents];
566 if ([notify name] == NSWindowDidResignKeyNotification) {
567 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
568 // returns nil regardless of whether any suitable candidates for the key
569 // window remain. It seems that the new key window for the app is not set
570 // until after this notification is fired, so a check is performed after the
571 // run loop is allowed to spin.
572 [self performSelector:@selector(checkForAnyKeyWindows)
577 // If the window changed to a new BrowserWindowController, update the profile.
578 id windowController = [[notify object] windowController];
579 if (![windowController isKindOfClass:[BrowserWindowController class]])
582 if ([notify name] == NSWindowDidBecomeMainNotification) {
583 // If the profile is incognito, use the original profile.
584 Profile* newProfile = [windowController profile]->GetOriginalProfile();
585 [self windowChangedToProfile:newProfile];
586 } else if (chrome::GetTotalBrowserCount() == 0) {
587 [self windowChangedToProfile:
588 g_browser_process->profile_manager()->GetLastUsedProfile()];
592 - (void)activeSpaceDidChange:(NSNotification*)notify {
593 if (reopenTime_.is_null() ||
595 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
596 kWorkspaceChangeTimeoutMs) {
600 // The last applicationShouldHandleReopen:hasVisibleWindows: call
601 // happened during a space change. Now that the change has
602 // completed, raise browser windows.
603 reopenTime_ = base::TimeTicks();
604 std::set<NSWindow*> browserWindows;
605 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
606 Browser* browser = *iter;
607 browserWindows.insert(browser->window()->GetNativeWindow());
609 if (!browserWindows.empty()) {
610 ui::FocusWindowSet(browserWindows, false);
614 // Called on Lion and later when a popover (e.g. dictionary) is shown.
615 - (void)popoverDidShow:(NSNotification*)notify {
617 [self fixCloseMenuItemKeyEquivalents];
620 // Called on Lion and later when a popover (e.g. dictionary) is closed.
621 - (void)popoverDidClose:(NSNotification*)notify {
623 [self fixCloseMenuItemKeyEquivalents];
626 // Called when the user has changed browser windows, meaning the backing profile
627 // may have changed. This can cause a rebuild of the user-data menus. This is a
628 // no-op if the new profile is the same as the current one. This will always be
629 // the original profile and never incognito.
630 - (void)windowChangedToProfile:(Profile*)profile {
631 if (lastProfile_ == profile)
634 // Before tearing down the menu controller bridges, return the Cocoa menus to
635 // their initial state.
636 if (bookmarkMenuBridge_.get())
637 bookmarkMenuBridge_->ResetMenu();
638 if (historyMenuBridge_.get())
639 historyMenuBridge_->ResetMenu();
641 // Rebuild the menus with the new profile.
642 lastProfile_ = profile;
644 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
645 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
646 // No need to |BuildMenu| here. It is done lazily upon menu access.
648 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
649 historyMenuBridge_->BuildMenu();
651 chrome::BrowserCommandController::
652 UpdateSharedCommandsForIncognitoAvailability(
653 menuState_.get(), lastProfile_);
654 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
655 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
656 profilePrefRegistrar_->Add(
657 prefs::kIncognitoModeAvailability,
658 base::Bind(&chrome::BrowserCommandController::
659 UpdateSharedCommandsForIncognitoAvailability,
664 - (void)checkForAnyKeyWindows {
665 if ([NSApp keyWindow])
668 content::NotificationService::current()->Notify(
669 chrome::NOTIFICATION_NO_KEY_WINDOW,
670 content::NotificationService::AllSources(),
671 content::NotificationService::NoDetails());
674 // If the auto-update interval is not set, make it 5 hours.
675 // Placed here for 2 reasons:
676 // 1) Same spot as other Pref stuff
677 // 2) Try and be friendly by keeping this after app launch
678 - (void)setUpdateCheckInterval {
679 #if defined(GOOGLE_CHROME_BUILD)
680 CFStringRef app = CFSTR("com.google.Keystone.Agent");
681 CFStringRef checkInterval = CFSTR("checkInterval");
682 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
684 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
685 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
686 CFPreferencesSetAppValue(checkInterval, value, app);
687 CFPreferencesAppSynchronize(app);
692 - (void)openStartupUrls {
693 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
694 // NSApplication is created in MainMessageLoop, and then the shortcut urls
695 // are passed in via Apple events. At this point, the first browser is
696 // already loaded in PreMainMessageLoop. If we initialize NSApplication
697 // before PreMainMessageLoop to capture shortcut URL events, it may cause
698 // more problems because it relies on things created in PreMainMessageLoop
699 // and may break existing message loop design.
700 if (startupUrls_.empty())
703 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
704 // startup urls in new tabs, because the omnibox will stay focused if we
705 // load url in NTP tab.
706 Browser* browser = chrome::GetLastActiveBrowser();
707 int startupIndex = TabStripModel::kNoTab;
708 content::WebContents* startupContent = NULL;
710 if (browser && browser->tab_strip_model()->count() == 1) {
711 startupIndex = browser->tab_strip_model()->active_index();
712 startupContent = browser->tab_strip_model()->GetActiveWebContents();
715 if (startupUrls_.size()) {
716 [self openUrls:startupUrls_];
717 startupUrls_.clear();
720 if (startupIndex != TabStripModel::kNoTab &&
721 startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
722 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
723 TabStripModel::CLOSE_NONE);
727 // This is called after profiles have been loaded and preferences registered.
728 // It is safe to access the default profile here.
729 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
730 // Notify BrowserList to keep the application running so it doesn't go away
731 // when all the browser windows get closed.
732 chrome::IncrementKeepAliveCount();
734 [self setUpdateCheckInterval];
736 // Start managing the menu for app windows. This needs to be done here because
737 // main menu item titles are not yet initialized in awakeFromNib.
738 [self initAppShimMenuController];
740 // If enabled, keep Chrome alive when apps are open instead of quitting all
742 quitWithAppsController_ = new QuitWithAppsController();
744 // Build up the encoding menu, the order of the items differs based on the
745 // current locale (see http://crbug.com/7647 for details).
746 // We need a valid g_browser_process to get the profile which is why we can't
747 // call this from awakeFromNib.
748 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
749 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
750 NSMenu* encodingMenu = [encodingMenuItem submenu];
751 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
754 // Instantiate the ProfileInfoCache observer so that we can get
755 // notified when a profile is deleted.
756 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
757 g_browser_process->profile_manager(), self));
759 // Since Chrome is localized to more languages than the OS, tell Cocoa which
760 // menu is the Help so it can add the search item to it.
761 [NSApp setHelpMenu:helpMenu_];
763 // Record the path to the (browser) app bundle; this is used by the app mode
764 // shim. It has to be done in FILE thread because getting the path requires
766 BrowserThread::PostTask(
767 BrowserThread::FILE, FROM_HERE,
768 base::Bind(&RecordLastRunAppBundlePath));
770 // Makes "Services" menu items available.
771 [self registerServicesMenuTypesTo:[notify object]];
773 startupComplete_ = YES;
775 [self openStartupUrls];
777 PrefService* localState = g_browser_process->local_state();
779 localPrefRegistrar_.Init(localState);
780 localPrefRegistrar_.Add(
781 prefs::kAllowFileSelectionDialogs,
782 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
787 // This is called after profiles have been loaded and preferences registered.
788 // It is safe to access the default profile here.
789 - (void)applicationDidBecomeActive:(NSNotification*)notify {
790 content::PluginService::GetInstance()->AppActivated();
793 // Helper function for populating and displaying the in progress downloads at
795 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
796 NSString* titleText = nil;
797 NSString* explanationText = nil;
798 NSString* waitTitle = nil;
799 NSString* exitTitle = nil;
801 // Set the dialog text based on whether or not there are multiple downloads.
802 if (downloadCount == 1) {
803 // Dialog text: warning and explanation.
804 titleText = l10n_util::GetNSString(
805 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
806 explanationText = l10n_util::GetNSString(
807 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
809 // Dialog text: warning and explanation.
810 titleText = l10n_util::GetNSStringF(
811 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
812 base::IntToString16(downloadCount));
813 explanationText = l10n_util::GetNSString(
814 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
816 // Cancel download and exit button text.
817 exitTitle = l10n_util::GetNSString(
818 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
820 // Wait for download button text.
821 waitTitle = l10n_util::GetNSString(
822 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
824 // 'waitButton' is the default choice.
825 int choice = NSRunAlertPanel(titleText, @"%@",
826 waitTitle, exitTitle, nil, explanationText);
827 return choice == NSAlertDefaultReturn ? YES : NO;
830 // Check all profiles for in progress downloads, and if we find any, prompt the
831 // user to see if we should continue to exit (and thus cancel the downloads), or
832 // if we should wait.
833 - (BOOL)shouldQuitWithInProgressDownloads {
834 ProfileManager* profile_manager = g_browser_process->profile_manager();
835 if (!profile_manager)
838 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
839 for (size_t i = 0; i < profiles.size(); ++i) {
840 DownloadService* download_service =
841 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
842 DownloadManager* download_manager =
843 (download_service->HasCreatedDownloadManager() ?
844 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
845 if (download_manager &&
846 download_manager->NonMaliciousInProgressCount() > 0) {
847 int downloadCount = download_manager->NonMaliciousInProgressCount();
848 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
849 // Create a new browser window (if necessary) and navigate to the
850 // downloads page if the user chooses to wait.
851 Browser* browser = chrome::FindBrowserWithProfile(
852 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
854 browser = new Browser(Browser::CreateParams(
855 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
856 browser->window()->Show();
859 chrome::ShowDownloads(browser);
863 // User wants to exit.
868 // No profiles or active downloads found, okay to exit.
872 // Called to determine if we should enable the "restore tab" menu item.
873 // Checks with the TabRestoreService to see if there's anything there to
874 // restore and returns YES if so.
875 - (BOOL)canRestoreTab {
876 TabRestoreService* service =
877 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
878 return service && !service->entries().empty();
881 // Called from the AppControllerProfileObserver every time a profile is deleted.
882 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
883 Profile* lastProfile = [self lastProfile];
885 // If the lastProfile has been deleted, the profile manager has
886 // already loaded a new one, so the pointer needs to be updated;
887 // otherwise we will try to start up a browser window with a pointer
888 // to the old profile.
889 if (profilePath == lastProfile->GetPath())
890 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
893 // Returns true if there is a modal window (either window- or application-
894 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
895 // sheets) will not count as blocking the browser. But things like open/save
896 // dialogs that are window modal will block the browser.
897 - (BOOL)keyWindowIsModal {
898 if ([NSApp modalWindow])
901 Browser* browser = chrome::GetLastActiveBrowser();
903 [[browser->window()->GetNativeWindow() attachedSheet]
904 isKindOfClass:[NSWindow class]];
907 // Called to validate menu items when there are no key windows. All the
908 // items we care about have been set with the |commandDispatch:| action and
909 // a target of FirstResponder in IB. If it's not one of those, let it
910 // continue up the responder chain to be handled elsewhere. We pull out the
911 // tag as the cross-platform constant to differentiate and dispatch the
913 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
914 SEL action = [item action];
916 if (action == @selector(commandDispatch:) ||
917 action == @selector(commandFromDock:)) {
918 NSInteger tag = [item tag];
919 if (menuState_ && // NULL in tests.
920 menuState_->SupportsCommand(tag)) {
922 // The File Menu commands are not automatically disabled by Cocoa when a
923 // dialog sheet obscures the browser window, so we disable several of
924 // them here. We don't need to include IDC_CLOSE_WINDOW, because
925 // app_controller is only activated when there are no key windows (see
926 // function comment).
927 case IDC_RESTORE_TAB:
928 enable = ![self keyWindowIsModal] && [self canRestoreTab];
930 // Browser-level items that open in new tabs should not open if there's
931 // a window- or app-modal dialog.
934 case IDC_SHOW_HISTORY:
935 case IDC_SHOW_BOOKMARK_MANAGER:
936 enable = ![self keyWindowIsModal];
938 // Browser-level items that open in new windows.
939 case IDC_TASK_MANAGER:
940 // Allow the user to open a new window if there's a window-modal
942 enable = ![self keyWindowIsModal];
944 case IDC_SHOW_SYNC_SETUP: {
945 Profile* lastProfile = [self lastProfile];
946 // The profile may be NULL during shutdown -- see
947 // http://code.google.com/p/chromium/issues/detail?id=43048 .
949 // TODO(akalin,viettrungluu): Figure out whether this method
950 // can be prevented from being called if lastProfile is
954 << "NULL lastProfile detected -- not doing anything";
957 SigninManager* signin = SigninManagerFactory::GetForProfile(
958 lastProfile->GetOriginalProfile());
959 enable = signin->IsSigninAllowed() &&
960 ![self keyWindowIsModal];
961 [BrowserWindowController updateSigninItem:item
963 currentProfile:lastProfile];
966 #if defined(GOOGLE_CHROME_BUILD)
972 enable = menuState_->IsCommandEnabled(tag) ?
973 ![self keyWindowIsModal] : NO;
976 } else if (action == @selector(terminate:)) {
978 } else if (action == @selector(showPreferences:)) {
980 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
982 } else if (action == @selector(commandFromDock:)) {
984 } else if (action == @selector(toggleConfirmToQuit:)) {
985 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
987 } else if (action == @selector(toggleDisplayMessageCenter:)) {
988 NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
989 [self updateDisplayMessageCenterPrefMenuItem:menuItem];
991 } else if (action == @selector(executeApplication:)) {
997 // Called when the user picks a menu item when there are no key windows, or when
998 // there is no foreground browser window. Calls through to the browser object to
999 // execute the command. This assumes that the command is supported and doesn't
1000 // check, otherwise it should have been disabled in the UI in
1001 // |-validateUserInterfaceItem:|.
1002 - (void)commandDispatch:(id)sender {
1003 Profile* lastProfile = [self safeLastProfileForNewWindows];
1005 // Handle the case where we're dispatching a command from a sender that's in a
1006 // browser window. This means that the command came from a background window
1007 // and is getting here because the foreground window is not a browser window.
1008 if ([sender respondsToSelector:@selector(window)]) {
1009 id delegate = [[sender window] windowController];
1010 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1011 [delegate commandDispatch:sender];
1016 // Ignore commands during session restore's browser creation. It uses a
1017 // nested message loop and commands dispatched during this operation cause
1019 if (SessionRestore::IsRestoring(lastProfile) &&
1020 base::MessageLoop::current()->IsNested())
1023 NSInteger tag = [sender tag];
1025 // If there are no browser windows, and we are trying to open a browser
1026 // for a locked profile, we have to show the User Manager instead as the
1027 // locked profile needs authentication.
1028 if (IsProfileSignedOut(lastProfile)) {
1029 chrome::ShowUserManager(lastProfile->GetPath());
1035 // Create a new tab in an existing browser window (which we activate) if
1037 if (Browser* browser = ActivateBrowser(lastProfile)) {
1038 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1041 // Else fall through to create new window.
1042 case IDC_NEW_WINDOW:
1043 CreateBrowser(lastProfile);
1045 case IDC_FOCUS_LOCATION:
1046 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1047 IDC_FOCUS_LOCATION);
1049 case IDC_FOCUS_SEARCH:
1050 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1053 case IDC_NEW_INCOGNITO_WINDOW:
1054 CreateBrowser(lastProfile->GetOffTheRecordProfile());
1056 case IDC_RESTORE_TAB:
1057 // There is only the native desktop on Mac.
1058 chrome::OpenWindowWithRestoredTabs(lastProfile,
1059 chrome::HOST_DESKTOP_TYPE_NATIVE);
1062 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1064 case IDC_CLEAR_BROWSING_DATA: {
1065 // There may not be a browser open, so use the default profile.
1066 if (Browser* browser = ActivateBrowser(lastProfile)) {
1067 chrome::ShowClearBrowsingDataDialog(browser);
1069 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1073 case IDC_IMPORT_SETTINGS: {
1074 if (Browser* browser = ActivateBrowser(lastProfile)) {
1075 chrome::ShowImportDialog(browser);
1077 chrome::OpenImportSettingsDialogWindow(lastProfile);
1081 case IDC_SHOW_BOOKMARK_MANAGER:
1082 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1083 if (Browser* browser = ActivateBrowser(lastProfile)) {
1084 chrome::ShowBookmarkManager(browser);
1086 // No browser window, so create one for the bookmark manager tab.
1087 chrome::OpenBookmarkManagerWindow(lastProfile);
1090 case IDC_SHOW_HISTORY:
1091 if (Browser* browser = ActivateBrowser(lastProfile))
1092 chrome::ShowHistory(browser);
1094 chrome::OpenHistoryWindow(lastProfile);
1096 case IDC_SHOW_DOWNLOADS:
1097 if (Browser* browser = ActivateBrowser(lastProfile))
1098 chrome::ShowDownloads(browser);
1100 chrome::OpenDownloadsWindow(lastProfile);
1102 case IDC_MANAGE_EXTENSIONS:
1103 if (Browser* browser = ActivateBrowser(lastProfile))
1104 chrome::ShowExtensions(browser, std::string());
1106 chrome::OpenExtensionsWindow(lastProfile);
1108 case IDC_HELP_PAGE_VIA_MENU:
1109 if (Browser* browser = ActivateBrowser(lastProfile))
1110 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1112 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1114 case IDC_SHOW_SYNC_SETUP:
1115 if (Browser* browser = ActivateBrowser(lastProfile)) {
1116 chrome::ShowBrowserSignin(browser, signin::SOURCE_MENU);
1118 chrome::OpenSyncSetupWindow(lastProfile, signin::SOURCE_MENU);
1121 case IDC_TASK_MANAGER:
1122 content::RecordAction(UserMetricsAction("TaskManager"));
1123 TaskManagerMac::Show();
1126 [self showPreferences:sender];
1131 // Run a (background) application in a new tab.
1132 - (void)executeApplication:(id)sender {
1133 NSInteger tag = [sender tag];
1134 Profile* profile = [self lastProfile];
1136 BackgroundApplicationListModel applications(profile);
1138 tag < static_cast<int>(applications.size()));
1139 const extensions::Extension* extension = applications.GetExtension(tag);
1140 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1143 // Same as |-commandDispatch:|, but executes commands using a disposition
1144 // determined by the key flags. This will get called in the case where the
1145 // frontmost window is not a browser window, and the user has command-clicked
1146 // a button in a background browser window whose action is
1147 // |-commandDispatchUsingKeyModifiers:|
1148 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1150 if ([sender respondsToSelector:@selector(window)]) {
1151 id delegate = [[sender window] windowController];
1152 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1153 [delegate commandDispatchUsingKeyModifiers:sender];
1158 // NSApplication delegate method called when someone clicks on the dock icon.
1159 // To match standard mac behavior, we should open a new window if there are no
1161 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1162 hasVisibleWindows:(BOOL)hasVisibleWindows {
1163 // If the browser is currently trying to quit, don't do anything and return NO
1164 // to prevent AppKit from doing anything.
1165 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1166 if (browser_shutdown::IsTryingToQuit())
1169 // Bring all browser windows to the front. Specifically, this brings them in
1170 // front of any app windows. FocusWindowSet will also unminimize the most
1171 // recently minimized window if no windows in the set are visible.
1172 // If there are any, return here. Otherwise, the windows are panels or
1173 // notifications so we still need to open a new window.
1174 if (hasVisibleWindows) {
1175 std::set<NSWindow*> browserWindows;
1176 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1177 Browser* browser = *iter;
1178 browserWindows.insert(browser->window()->GetNativeWindow());
1180 if (!browserWindows.empty()) {
1181 NSWindow* keyWindow = [NSApp keyWindow];
1182 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1183 // The key window is not on the active space. We must be mid-animation
1184 // for a space transition triggered by the dock. Delay the call to
1185 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1186 // wrong space's windows get raised, resulting in an off-screen key
1187 // window. It does not work to |ui::FocusWindowSet| twice, once here
1188 // and once in |activeSpaceDidChange:|, as that appears to break when
1189 // the omnibox is focused.
1191 // This check relies on OS X setting the key window to a window on the
1192 // target space before calling this method.
1194 // See http://crbug.com/309656.
1195 reopenTime_ = base::TimeTicks::Now();
1197 ui::FocusWindowSet(browserWindows, false);
1199 // Return NO; we've done (or soon will do) the deminiaturize, so
1200 // AppKit shouldn't do anything.
1205 // If launched as a hidden login item (due to installation of a persistent app
1206 // or by the user, for example in System Preferences->Accounts->Login Items),
1207 // allow session to be restored first time the user clicks on a Dock icon.
1208 // Normally, it'd just open a new empty page.
1210 static BOOL doneOnce = NO;
1213 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
1214 SessionService* sessionService =
1215 SessionServiceFactory::GetForProfileForSessionRestore(
1216 [self lastProfile]);
1217 if (sessionService &&
1218 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1224 // Platform apps don't use browser windows so don't do anything if there are
1225 // visible windows, otherwise, launch the browser with the same command line
1226 // which should launch the app again.
1227 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1228 if (command_line.HasSwitch(switches::kAppId)) {
1229 if (hasVisibleWindows)
1233 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1235 StartupBrowserCreator browser_creator;
1236 browser_creator.LaunchBrowser(
1237 command_line, [self lastProfile], base::FilePath(),
1238 chrome::startup::IS_NOT_PROCESS_STARTUP,
1239 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
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->IsManaged()) {
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 @end // @implementation AppController
1551 //---------------------------------------------------------------------------
1553 namespace app_controller_mac {
1555 bool IsOpeningNewWindow() {
1556 return g_is_opening_new_window;
1559 } // namespace app_controller_mac