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/shell_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/extensions/extension_system.h"
32 #include "chrome/browser/first_run/first_run.h"
33 #include "chrome/browser/lifetime/application_lifetime.h"
34 #include "chrome/browser/printing/print_dialog_cloud.h"
35 #include "chrome/browser/profiles/profile_info_cache_observer.h"
36 #include "chrome/browser/profiles/profile_manager.h"
37 #include "chrome/browser/profiles/profiles_state.h"
38 #include "chrome/browser/service_process/service_process_control.h"
39 #include "chrome/browser/sessions/session_restore.h"
40 #include "chrome/browser/sessions/session_service.h"
41 #include "chrome/browser/sessions/session_service_factory.h"
42 #include "chrome/browser/sessions/tab_restore_service.h"
43 #include "chrome/browser/sessions/tab_restore_service_factory.h"
44 #include "chrome/browser/signin/signin_manager.h"
45 #include "chrome/browser/signin/signin_manager_factory.h"
46 #include "chrome/browser/signin/signin_promo.h"
47 #include "chrome/browser/sync/profile_sync_service.h"
48 #include "chrome/browser/sync/sync_ui_util.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_command_controller.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_iterator.h"
54 #include "chrome/browser/ui/browser_mac.h"
55 #include "chrome/browser/ui/browser_window.h"
56 #include "chrome/browser/ui/chrome_pages.h"
57 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
58 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
59 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
60 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
61 #import "chrome/browser/ui/cocoa/confirm_quit.h"
62 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
63 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
64 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
65 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
66 #import "chrome/browser/ui/cocoa/profile_menu_controller.h"
67 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
68 #import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
69 #include "chrome/browser/ui/cocoa/task_manager_mac.h"
70 #include "chrome/browser/ui/extensions/application_launch.h"
71 #include "chrome/browser/ui/host_desktop.h"
72 #include "chrome/browser/ui/startup/startup_browser_creator.h"
73 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
74 #include "chrome/common/chrome_paths_internal.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
77 #include "chrome/common/extensions/extension_constants.h"
78 #include "chrome/common/mac/app_mode_common.h"
79 #include "chrome/common/pref_names.h"
80 #include "chrome/common/service_messages.h"
81 #include "chrome/common/url_constants.h"
82 #include "content/public/browser/browser_thread.h"
83 #include "content/public/browser/download_manager.h"
84 #include "content/public/browser/notification_service.h"
85 #include "content/public/browser/notification_types.h"
86 #include "content/public/browser/plugin_service.h"
87 #include "content/public/browser/user_metrics.h"
88 #include "grit/chromium_strings.h"
89 #include "grit/generated_resources.h"
90 #include "net/base/net_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 } // anonymous namespace
194 @interface AppController (Private)
195 - (void)initMenuState;
196 - (void)initProfileMenu;
197 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
198 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
199 - (void)openUrls:(const std::vector<GURL>&)urls;
200 - (void)getUrl:(NSAppleEventDescriptor*)event
201 withReply:(NSAppleEventDescriptor*)reply;
202 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
203 - (void)windowLayeringDidChange:(NSNotification*)inNotification;
204 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
205 - (void)windowChangedToProfile:(Profile*)profile;
206 - (void)checkForAnyKeyWindows;
207 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
208 - (BOOL)shouldQuitWithInProgressDownloads;
209 - (void)executeApplication:(id)sender;
210 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
213 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
215 AppControllerProfileObserver(
216 ProfileManager* profile_manager, AppController* app_controller)
217 : profile_manager_(profile_manager),
218 app_controller_(app_controller) {
219 DCHECK(profile_manager_);
220 DCHECK(app_controller_);
221 profile_manager_->GetProfileInfoCache().AddObserver(this);
224 virtual ~AppControllerProfileObserver() {
225 DCHECK(profile_manager_);
226 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
230 // ProfileInfoCacheObserver implementation:
232 virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
235 virtual void OnProfileWasRemoved(
236 const base::FilePath& profile_path,
237 const base::string16& profile_name) OVERRIDE {
238 // When a profile is deleted we need to notify the AppController,
239 // so it can correctly update its pointer to the last used profile.
240 [app_controller_ profileWasRemoved:profile_path];
243 virtual void OnProfileWillBeRemoved(
244 const base::FilePath& profile_path) OVERRIDE {
247 virtual void OnProfileNameChanged(
248 const base::FilePath& profile_path,
249 const base::string16& old_profile_name) OVERRIDE {
252 virtual void OnProfileAvatarChanged(
253 const base::FilePath& profile_path) OVERRIDE {
256 ProfileManager* profile_manager_;
258 AppController* app_controller_; // Weak; owns us.
260 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
263 @implementation AppController
265 @synthesize startupComplete = startupComplete_;
267 // This method is called very early in application startup (ie, before
268 // the profile is loaded or any preferences have been registered). Defer any
269 // user-data initialization until -applicationDidFinishLaunching:.
270 - (void)awakeFromNib {
271 // We need to register the handlers early to catch events fired on launch.
272 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
273 [em setEventHandler:self
274 andSelector:@selector(getUrl:withReply:)
275 forEventClass:kInternetEventClass
276 andEventID:kAEGetURL];
277 [em setEventHandler:self
278 andSelector:@selector(submitCloudPrintJob:)
279 forEventClass:cloud_print::kAECloudPrintClass
280 andEventID:cloud_print::kAECloudPrintClass];
281 [em setEventHandler:self
282 andSelector:@selector(getUrl:withReply:)
283 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
284 andEventID:'OURL']; // back to the Spyglass days.
286 // Register for various window layering changes. We use these to update
287 // various UI elements (command-key equivalents, etc) when the frontmost
289 NSNotificationCenter* notificationCenter =
290 [NSNotificationCenter defaultCenter];
293 selector:@selector(windowLayeringDidChange:)
294 name:NSWindowDidBecomeKeyNotification
298 selector:@selector(windowLayeringDidChange:)
299 name:NSWindowDidResignKeyNotification
303 selector:@selector(windowLayeringDidChange:)
304 name:NSWindowDidBecomeMainNotification
308 selector:@selector(windowLayeringDidChange:)
309 name:NSWindowDidResignMainNotification
312 if (base::mac::IsOSLionOrLater()) {
315 selector:@selector(popoverDidShow:)
316 name:NSPopoverDidShowNotification
320 selector:@selector(popoverDidClose:)
321 name:NSPopoverDidCloseNotification
325 // Register for space change notifications.
326 [[[NSWorkspace sharedWorkspace] notificationCenter]
328 selector:@selector(activeSpaceDidChange:)
329 name:NSWorkspaceActiveSpaceDidChangeNotification
332 // Set up the command updater for when there are no windows open
333 [self initMenuState];
335 // Initialize the Profile menu.
336 [self initProfileMenu];
339 - (void)unregisterEventHandlers {
340 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
341 [em removeEventHandlerForEventClass:kInternetEventClass
342 andEventID:kAEGetURL];
343 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
344 andEventID:cloud_print::kAECloudPrintClass];
345 [em removeEventHandlerForEventClass:'WWW!'
347 [[NSNotificationCenter defaultCenter] removeObserver:self];
348 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
351 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
352 // the default handlers.
353 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
354 // Nothing here right now.
357 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
358 // Check for in-process downloads, and prompt the user if they really want
359 // to quit (and thus cancel downloads). Only check if we're not already
360 // shutting down, else the user might be prompted multiple times if the
361 // download isn't stopped before terminate is called again.
362 if (!browser_shutdown::IsTryingToQuit() &&
363 ![self shouldQuitWithInProgressDownloads])
366 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
367 // them in, but I'm not sure about UX; we'd also want to disable other things
368 // though.) http://crbug.com/40861
370 // Check if the user really wants to quit by employing the confirm-to-quit
372 if (!browser_shutdown::IsTryingToQuit() &&
373 [self applicationShouldTerminate:app] != NSTerminateNow)
376 size_t num_browsers = chrome::GetTotalBrowserCount();
378 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
379 // already shutting down.
380 if (!browser_shutdown::IsTryingToQuit()) {
381 content::NotificationService::current()->Notify(
382 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
383 content::NotificationService::AllSources(),
384 content::NotificationService::NoDetails());
385 chrome::CloseAllBrowsersAndQuit();
388 return num_browsers == 0 ? YES : NO;
391 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
392 if (browser_shutdown::IsTryingToQuit()) {
393 // Reset the "trying to quit" state, so that closing all browser windows
394 // will no longer lead to termination.
395 browser_shutdown::SetTryingToQuit(false);
397 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
398 // would have to reinstall them here. http://crbug.com/40861
402 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
403 // If there are no windows, quit immediately.
404 if (chrome::BrowserIterator().done() &&
405 !apps::ShellWindowRegistry::IsShellWindowRegisteredInAnyProfile(0)) {
406 return NSTerminateNow;
409 // Check if the preference is turned on.
410 const PrefService* prefs = g_browser_process->local_state();
411 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
412 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
413 return NSTerminateNow;
416 // If the application is going to terminate as the result of a Cmd+Q
417 // invocation, use the special sauce to prevent accidental quitting.
418 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
420 // This logic is only for keyboard-initiated quits.
421 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
422 return NSTerminateNow;
424 return [[ConfirmQuitPanelController sharedController]
425 runModalLoopForApplication:app];
428 // Called when the app is shutting down. Clean-up as appropriate.
429 - (void)applicationWillTerminate:(NSNotification*)aNotification {
430 // There better be no browser windows left at this point.
431 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
433 // Tell BrowserList not to keep the browser process alive. Once all the
434 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
435 chrome::EndKeepAlive();
437 // Reset all pref watching, as this object outlives the prefs system.
438 profilePrefRegistrar_.reset();
439 localPrefRegistrar_.RemoveAll();
441 [self unregisterEventHandlers];
443 appShimMenuController_.reset();
446 - (void)didEndMainMessageLoop {
447 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
448 chrome::HOST_DESKTOP_TYPE_NATIVE));
449 if (!chrome::GetBrowserCount([self lastProfile],
450 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
451 // As we're shutting down, we need to nuke the TabRestoreService, which
452 // will start the shutdown of the NavigationControllers and allow for
453 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
454 // and may end up crashing when some thread tries to use the IO thread (or
455 // another thread) that is no longer valid.
456 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
460 // If the window has a tab controller, make "close window" be cmd-shift-w,
461 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
462 // affects whether the shift modifier is used.
463 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
464 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
466 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
469 // If the window has a tab controller, make "close tab" take over cmd-w,
470 // otherwise it shouldn't have any key-equivalent because it should be disabled.
471 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
472 if (enableCloseTabShortcut) {
473 [closeTabMenuItem_ setKeyEquivalent:@"w"];
474 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
476 [closeTabMenuItem_ setKeyEquivalent:@""];
477 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
481 // Explicitly remove any command-key equivalents from the close tab/window
482 // menus so that nothing can go haywire if we get a user action during pending
484 - (void)clearCloseMenuItemKeyEquivalents {
485 [closeTabMenuItem_ setKeyEquivalent:@""];
486 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
487 [closeWindowMenuItem_ setKeyEquivalent:@""];
488 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
491 // See if the focused window window has tabs, and adjust the key equivalents for
492 // Close Tab/Close Window accordingly.
493 - (void)fixCloseMenuItemKeyEquivalents {
494 fileMenuUpdatePending_ = NO;
496 NSWindow* window = [NSApp keyWindow];
497 NSWindow* mainWindow = [NSApp mainWindow];
498 if (!window || ([window parentWindow] == mainWindow)) {
499 // If the key window is a child of the main window (e.g. a bubble), the main
500 // window should be the one that handles the close menu item action.
501 // Also, there might be a small amount of time where there is no key window;
502 // in that case as well, just use our main browser window if there is one.
503 // You might think that we should just always use the main window, but the
504 // "About Chrome" window serves as a counterexample.
509 [[window windowController] isKindOfClass:[TabWindowController class]];
510 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
511 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
512 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
515 // Fix up the "close tab/close window" command-key equivalents. We do this
516 // after a delay to ensure that window layer state has been set by the time
517 // we do the enabling. This should only be called on the main thread, code that
518 // calls this (even as a side-effect) from other threads needs to be fixed.
519 - (void)delayedFixCloseMenuItemKeyEquivalents {
520 DCHECK([NSThread isMainThread]);
521 if (!fileMenuUpdatePending_) {
522 // The OS prefers keypresses to timers, so it's possible that a cmd-w
523 // can sneak in before this timer fires. In order to prevent that from
524 // having any bad consequences, just clear the keys combos altogether. They
525 // will be reset when the timer eventually fires.
526 if ([NSThread isMainThread]) {
527 fileMenuUpdatePending_ = YES;
528 [self clearCloseMenuItemKeyEquivalents];
529 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
533 // This shouldn't be happening, but if it does, force it to the main
534 // thread to avoid dropping the update. Don't mess with
535 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
536 // there could be a race between the selector finishing and setting the
539 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
546 // Called when we get a notification about the window layering changing to
547 // update the UI based on the new main window.
548 - (void)windowLayeringDidChange:(NSNotification*)notify {
549 [self delayedFixCloseMenuItemKeyEquivalents];
551 if ([notify name] == NSWindowDidResignKeyNotification) {
552 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
553 // returns nil regardless of whether any suitable candidates for the key
554 // window remain. It seems that the new key window for the app is not set
555 // until after this notification is fired, so a check is performed after the
556 // run loop is allowed to spin.
557 [self performSelector:@selector(checkForAnyKeyWindows)
562 // If the window changed to a new BrowserWindowController, update the profile.
563 id windowController = [[notify object] windowController];
564 if (![windowController isKindOfClass:[BrowserWindowController class]])
567 if ([notify name] == NSWindowDidBecomeMainNotification) {
568 // If the profile is incognito, use the original profile.
569 Profile* newProfile = [windowController profile]->GetOriginalProfile();
570 [self windowChangedToProfile:newProfile];
571 } else if (chrome::GetTotalBrowserCount() == 0) {
572 [self windowChangedToProfile:
573 g_browser_process->profile_manager()->GetLastUsedProfile()];
577 - (void)activeSpaceDidChange:(NSNotification*)notify {
578 if (reopenTime_.is_null() ||
580 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
581 kWorkspaceChangeTimeoutMs) {
585 // The last applicationShouldHandleReopen:hasVisibleWindows: call
586 // happened during a space change. Now that the change has
587 // completed, raise browser windows.
588 reopenTime_ = base::TimeTicks();
589 std::set<NSWindow*> browserWindows;
590 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
591 Browser* browser = *iter;
592 browserWindows.insert(browser->window()->GetNativeWindow());
594 if (!browserWindows.empty()) {
595 ui::FocusWindowSet(browserWindows, false);
599 // Called on Lion and later when a popover (e.g. dictionary) is shown.
600 - (void)popoverDidShow:(NSNotification*)notify {
602 [self fixCloseMenuItemKeyEquivalents];
605 // Called on Lion and later when a popover (e.g. dictionary) is closed.
606 - (void)popoverDidClose:(NSNotification*)notify {
608 [self fixCloseMenuItemKeyEquivalents];
611 // Called when the user has changed browser windows, meaning the backing profile
612 // may have changed. This can cause a rebuild of the user-data menus. This is a
613 // no-op if the new profile is the same as the current one. This will always be
614 // the original profile and never incognito.
615 - (void)windowChangedToProfile:(Profile*)profile {
616 if (lastProfile_ == profile)
619 // Before tearing down the menu controller bridges, return the Cocoa menus to
620 // their initial state.
621 if (bookmarkMenuBridge_.get())
622 bookmarkMenuBridge_->ResetMenu();
623 if (historyMenuBridge_.get())
624 historyMenuBridge_->ResetMenu();
626 // Rebuild the menus with the new profile.
627 lastProfile_ = profile;
629 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
630 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
631 // No need to |BuildMenu| here. It is done lazily upon menu access.
633 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
634 historyMenuBridge_->BuildMenu();
636 chrome::BrowserCommandController::
637 UpdateSharedCommandsForIncognitoAvailability(
638 menuState_.get(), lastProfile_);
639 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
640 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
641 profilePrefRegistrar_->Add(
642 prefs::kIncognitoModeAvailability,
643 base::Bind(&chrome::BrowserCommandController::
644 UpdateSharedCommandsForIncognitoAvailability,
649 - (void)checkForAnyKeyWindows {
650 if ([NSApp keyWindow])
653 content::NotificationService::current()->Notify(
654 chrome::NOTIFICATION_NO_KEY_WINDOW,
655 content::NotificationService::AllSources(),
656 content::NotificationService::NoDetails());
659 // If the auto-update interval is not set, make it 5 hours.
660 // Placed here for 2 reasons:
661 // 1) Same spot as other Pref stuff
662 // 2) Try and be friendly by keeping this after app launch
663 - (void)setUpdateCheckInterval {
664 #if defined(GOOGLE_CHROME_BUILD)
665 CFStringRef app = CFSTR("com.google.Keystone.Agent");
666 CFStringRef checkInterval = CFSTR("checkInterval");
667 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
669 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
670 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
671 CFPreferencesSetAppValue(checkInterval, value, app);
672 CFPreferencesAppSynchronize(app);
677 // This is called after profiles have been loaded and preferences registered.
678 // It is safe to access the default profile here.
679 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
680 // Notify BrowserList to keep the application running so it doesn't go away
681 // when all the browser windows get closed.
682 chrome::StartKeepAlive();
684 [self setUpdateCheckInterval];
686 // Start managing the menu for app windows. This needs to be done here because
687 // main menu item titles are not yet initialized in awakeFromNib.
688 [self initAppShimMenuController];
690 // Build up the encoding menu, the order of the items differs based on the
691 // current locale (see http://crbug.com/7647 for details).
692 // We need a valid g_browser_process to get the profile which is why we can't
693 // call this from awakeFromNib.
694 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
695 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
696 NSMenu* encodingMenu = [encodingMenuItem submenu];
697 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
700 // Instantiate the ProfileInfoCache observer so that we can get
701 // notified when a profile is deleted.
702 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
703 g_browser_process->profile_manager(), self));
705 // Since Chrome is localized to more languages than the OS, tell Cocoa which
706 // menu is the Help so it can add the search item to it.
707 [NSApp setHelpMenu:helpMenu_];
709 // Record the path to the (browser) app bundle; this is used by the app mode
710 // shim. It has to be done in FILE thread because getting the path requires
712 BrowserThread::PostTask(
713 BrowserThread::FILE, FROM_HERE,
714 base::Bind(&RecordLastRunAppBundlePath));
716 // Makes "Services" menu items available.
717 [self registerServicesMenuTypesTo:[notify object]];
719 startupComplete_ = YES;
721 // TODO(viettrungluu): This is very temporary, since this should be done "in"
722 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
723 // (probably-empty) list of URLs from the command line.
724 if (startupUrls_.size()) {
725 [self openUrls:startupUrls_];
726 [self clearStartupUrls];
729 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
730 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
731 [tabposeMenuItem_ setHidden:YES];
734 PrefService* localState = g_browser_process->local_state();
736 localPrefRegistrar_.Init(localState);
737 localPrefRegistrar_.Add(
738 prefs::kAllowFileSelectionDialogs,
739 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
744 // This is called after profiles have been loaded and preferences registered.
745 // It is safe to access the default profile here.
746 - (void)applicationDidBecomeActive:(NSNotification*)notify {
747 content::PluginService::GetInstance()->AppActivated();
750 // Helper function for populating and displaying the in progress downloads at
752 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
753 NSString* titleText = nil;
754 NSString* explanationText = nil;
755 NSString* waitTitle = nil;
756 NSString* exitTitle = nil;
758 // Set the dialog text based on whether or not there are multiple downloads.
759 if (downloadCount == 1) {
760 // Dialog text: warning and explanation.
761 titleText = l10n_util::GetNSString(
762 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
763 explanationText = l10n_util::GetNSString(
764 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
766 // Dialog text: warning and explanation.
767 titleText = l10n_util::GetNSStringF(
768 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
769 base::IntToString16(downloadCount));
770 explanationText = l10n_util::GetNSString(
771 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
773 // Cancel download and exit button text.
774 exitTitle = l10n_util::GetNSString(
775 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
777 // Wait for download button text.
778 waitTitle = l10n_util::GetNSString(
779 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
781 // 'waitButton' is the default choice.
782 int choice = NSRunAlertPanel(titleText, @"%@",
783 waitTitle, exitTitle, nil, explanationText);
784 return choice == NSAlertDefaultReturn ? YES : NO;
787 // Check all profiles for in progress downloads, and if we find any, prompt the
788 // user to see if we should continue to exit (and thus cancel the downloads), or
789 // if we should wait.
790 - (BOOL)shouldQuitWithInProgressDownloads {
791 ProfileManager* profile_manager = g_browser_process->profile_manager();
792 if (!profile_manager)
795 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
796 for (size_t i = 0; i < profiles.size(); ++i) {
797 DownloadService* download_service =
798 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
799 DownloadManager* download_manager =
800 (download_service->HasCreatedDownloadManager() ?
801 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
802 if (download_manager &&
803 download_manager->NonMaliciousInProgressCount() > 0) {
804 int downloadCount = download_manager->NonMaliciousInProgressCount();
805 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
806 // Create a new browser window (if necessary) and navigate to the
807 // downloads page if the user chooses to wait.
808 Browser* browser = chrome::FindBrowserWithProfile(
809 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
811 browser = new Browser(Browser::CreateParams(
812 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
813 browser->window()->Show();
816 chrome::ShowDownloads(browser);
820 // User wants to exit.
825 // No profiles or active downloads found, okay to exit.
829 // Called to determine if we should enable the "restore tab" menu item.
830 // Checks with the TabRestoreService to see if there's anything there to
831 // restore and returns YES if so.
832 - (BOOL)canRestoreTab {
833 TabRestoreService* service =
834 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
835 return service && !service->entries().empty();
838 // Called from the AppControllerProfileObserver every time a profile is deleted.
839 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
840 Profile* lastProfile = [self lastProfile];
842 // If the lastProfile has been deleted, the profile manager has
843 // already loaded a new one, so the pointer needs to be updated;
844 // otherwise we will try to start up a browser window with a pointer
845 // to the old profile.
846 if (profilePath == lastProfile->GetPath())
847 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
850 // Returns true if there is a modal window (either window- or application-
851 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
852 // sheets) will not count as blocking the browser. But things like open/save
853 // dialogs that are window modal will block the browser.
854 - (BOOL)keyWindowIsModal {
855 if ([NSApp modalWindow])
858 Browser* browser = chrome::GetLastActiveBrowser();
860 [[browser->window()->GetNativeWindow() attachedSheet]
861 isKindOfClass:[NSWindow class]];
864 // Called to validate menu items when there are no key windows. All the
865 // items we care about have been set with the |commandDispatch:| action and
866 // a target of FirstResponder in IB. If it's not one of those, let it
867 // continue up the responder chain to be handled elsewhere. We pull out the
868 // tag as the cross-platform constant to differentiate and dispatch the
870 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
871 SEL action = [item action];
873 if (action == @selector(commandDispatch:) ||
874 action == @selector(commandFromDock:)) {
875 NSInteger tag = [item tag];
876 if (menuState_ && // NULL in tests.
877 menuState_->SupportsCommand(tag)) {
879 // The File Menu commands are not automatically disabled by Cocoa when a
880 // dialog sheet obscures the browser window, so we disable several of
881 // them here. We don't need to include IDC_CLOSE_WINDOW, because
882 // app_controller is only activated when there are no key windows (see
883 // function comment).
884 case IDC_RESTORE_TAB:
885 enable = ![self keyWindowIsModal] && [self canRestoreTab];
887 // Browser-level items that open in new tabs should not open if there's
888 // a window- or app-modal dialog.
891 case IDC_SHOW_HISTORY:
892 case IDC_SHOW_BOOKMARK_MANAGER:
893 enable = ![self keyWindowIsModal];
895 // Browser-level items that open in new windows.
896 case IDC_TASK_MANAGER:
897 // Allow the user to open a new window if there's a window-modal
899 enable = ![self keyWindowIsModal];
901 case IDC_SHOW_SYNC_SETUP: {
902 Profile* lastProfile = [self lastProfile];
903 // The profile may be NULL during shutdown -- see
904 // http://code.google.com/p/chromium/issues/detail?id=43048 .
906 // TODO(akalin,viettrungluu): Figure out whether this method
907 // can be prevented from being called if lastProfile is
911 << "NULL lastProfile detected -- not doing anything";
914 SigninManager* signin = SigninManagerFactory::GetForProfile(
915 lastProfile->GetOriginalProfile());
916 enable = signin->IsSigninAllowed() &&
917 ![self keyWindowIsModal];
918 [BrowserWindowController updateSigninItem:item
920 currentProfile:lastProfile];
923 #if defined(GOOGLE_CHROME_BUILD)
929 enable = menuState_->IsCommandEnabled(tag) ?
930 ![self keyWindowIsModal] : NO;
933 } else if (action == @selector(terminate:)) {
935 } else if (action == @selector(showPreferences:)) {
937 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
939 } else if (action == @selector(commandFromDock:)) {
941 } else if (action == @selector(toggleConfirmToQuit:)) {
942 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
944 } else if (action == @selector(executeApplication:)) {
950 // Called when the user picks a menu item when there are no key windows, or when
951 // there is no foreground browser window. Calls through to the browser object to
952 // execute the command. This assumes that the command is supported and doesn't
953 // check, otherwise it should have been disabled in the UI in
954 // |-validateUserInterfaceItem:|.
955 - (void)commandDispatch:(id)sender {
956 Profile* lastProfile = [self lastProfile];
958 // Handle the case where we're dispatching a command from a sender that's in a
959 // browser window. This means that the command came from a background window
960 // and is getting here because the foreground window is not a browser window.
961 if ([sender respondsToSelector:@selector(window)]) {
962 id delegate = [[sender window] windowController];
963 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
964 [delegate commandDispatch:sender];
969 // Ignore commands during session restore's browser creation. It uses a
970 // nested message loop and commands dispatched during this operation cause
972 if (SessionRestore::IsRestoring(lastProfile) &&
973 base::MessageLoop::current()->IsNested())
976 NSInteger tag = [sender tag];
979 // Create a new tab in an existing browser window (which we activate) if
981 if (Browser* browser = ActivateBrowser(lastProfile)) {
982 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
985 // Else fall through to create new window.
987 CreateBrowser(lastProfile);
989 case IDC_FOCUS_LOCATION:
990 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
993 case IDC_FOCUS_SEARCH:
994 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
997 case IDC_NEW_INCOGNITO_WINDOW:
998 CreateBrowser(lastProfile->GetOffTheRecordProfile());
1000 case IDC_RESTORE_TAB:
1001 // There is only the native desktop on Mac.
1002 chrome::OpenWindowWithRestoredTabs(lastProfile,
1003 chrome::HOST_DESKTOP_TYPE_NATIVE);
1006 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1008 case IDC_CLEAR_BROWSING_DATA: {
1009 // There may not be a browser open, so use the default profile.
1010 if (Browser* browser = ActivateBrowser(lastProfile)) {
1011 chrome::ShowClearBrowsingDataDialog(browser);
1013 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1017 case IDC_IMPORT_SETTINGS: {
1018 if (Browser* browser = ActivateBrowser(lastProfile)) {
1019 chrome::ShowImportDialog(browser);
1021 chrome::OpenImportSettingsDialogWindow(lastProfile);
1025 case IDC_SHOW_BOOKMARK_MANAGER:
1026 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1027 if (Browser* browser = ActivateBrowser(lastProfile)) {
1028 chrome::ShowBookmarkManager(browser);
1030 // No browser window, so create one for the bookmark manager tab.
1031 chrome::OpenBookmarkManagerWindow(lastProfile);
1034 case IDC_SHOW_HISTORY:
1035 if (Browser* browser = ActivateBrowser(lastProfile))
1036 chrome::ShowHistory(browser);
1038 chrome::OpenHistoryWindow(lastProfile);
1040 case IDC_SHOW_DOWNLOADS:
1041 if (Browser* browser = ActivateBrowser(lastProfile))
1042 chrome::ShowDownloads(browser);
1044 chrome::OpenDownloadsWindow(lastProfile);
1046 case IDC_MANAGE_EXTENSIONS:
1047 if (Browser* browser = ActivateBrowser(lastProfile))
1048 chrome::ShowExtensions(browser, std::string());
1050 chrome::OpenExtensionsWindow(lastProfile);
1052 case IDC_HELP_PAGE_VIA_MENU:
1053 if (Browser* browser = ActivateBrowser(lastProfile))
1054 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1056 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1058 case IDC_SHOW_SYNC_SETUP:
1059 if (Browser* browser = ActivateBrowser(lastProfile)) {
1060 chrome::ShowBrowserSignin(browser, signin::SOURCE_MENU);
1062 chrome::OpenSyncSetupWindow(lastProfile, signin::SOURCE_MENU);
1065 case IDC_TASK_MANAGER:
1066 content::RecordAction(UserMetricsAction("TaskManager"));
1067 TaskManagerMac::Show();
1070 [self showPreferences:sender];
1075 // Run a (background) application in a new tab.
1076 - (void)executeApplication:(id)sender {
1077 NSInteger tag = [sender tag];
1078 Profile* profile = [self lastProfile];
1080 BackgroundApplicationListModel applications(profile);
1082 tag < static_cast<int>(applications.size()));
1083 const extensions::Extension* extension = applications.GetExtension(tag);
1084 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1087 // Same as |-commandDispatch:|, but executes commands using a disposition
1088 // determined by the key flags. This will get called in the case where the
1089 // frontmost window is not a browser window, and the user has command-clicked
1090 // a button in a background browser window whose action is
1091 // |-commandDispatchUsingKeyModifiers:|
1092 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1094 if ([sender respondsToSelector:@selector(window)]) {
1095 id delegate = [[sender window] windowController];
1096 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1097 [delegate commandDispatchUsingKeyModifiers:sender];
1102 // NSApplication delegate method called when someone clicks on the dock icon.
1103 // To match standard mac behavior, we should open a new window if there are no
1105 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1106 hasVisibleWindows:(BOOL)hasVisibleWindows {
1107 // If the browser is currently trying to quit, don't do anything and return NO
1108 // to prevent AppKit from doing anything.
1109 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1110 if (browser_shutdown::IsTryingToQuit())
1113 // Bring all browser windows to the front. Specifically, this brings them in
1114 // front of any app windows. FocusWindowSet will also unminimize the most
1115 // recently minimized window if no windows in the set are visible.
1116 // If there are any, return here. Otherwise, the windows are panels or
1117 // notifications so we still need to open a new window.
1118 if (hasVisibleWindows) {
1119 std::set<NSWindow*> browserWindows;
1120 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1121 Browser* browser = *iter;
1122 browserWindows.insert(browser->window()->GetNativeWindow());
1124 if (!browserWindows.empty()) {
1125 NSWindow* keyWindow = [NSApp keyWindow];
1126 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1127 // The key window is not on the active space. We must be mid-animation
1128 // for a space transition triggered by the dock. Delay the call to
1129 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1130 // wrong space's windows get raised, resulting in an off-screen key
1131 // window. It does not work to |ui::FocusWindowSet| twice, once here
1132 // and once in |activeSpaceDidChange:|, as that appears to break when
1133 // the omnibox is focused.
1135 // This check relies on OS X setting the key window to a window on the
1136 // target space before calling this method.
1138 // See http://crbug.com/309656.
1139 reopenTime_ = base::TimeTicks::Now();
1141 ui::FocusWindowSet(browserWindows, false);
1143 // Return NO; we've done (or soon will do) the deminiaturize, so
1144 // AppKit shouldn't do anything.
1149 // If launched as a hidden login item (due to installation of a persistent app
1150 // or by the user, for example in System Preferences->Accounts->Login Items),
1151 // allow session to be restored first time the user clicks on a Dock icon.
1152 // Normally, it'd just open a new empty page.
1154 static BOOL doneOnce = NO;
1157 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
1158 SessionService* sessionService =
1159 SessionServiceFactory::GetForProfileForSessionRestore(
1160 [self lastProfile]);
1161 if (sessionService &&
1162 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1168 // Platform apps don't use browser windows so don't do anything if there are
1169 // visible windows, otherwise, launch the browser with the same command line
1170 // which should launch the app again.
1171 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1172 if (command_line.HasSwitch(switches::kAppId)) {
1173 if (hasVisibleWindows)
1177 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1179 StartupBrowserCreator browser_creator;
1180 browser_creator.LaunchBrowser(
1181 command_line, [self lastProfile], base::FilePath(),
1182 chrome::startup::IS_NOT_PROCESS_STARTUP,
1183 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
1188 // Otherwise open a new window.
1189 CreateBrowser([self lastProfile]);
1191 // We've handled the reopen event, so return NO to tell AppKit not
1196 - (void)initMenuState {
1197 menuState_.reset(new CommandUpdater(NULL));
1198 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1199 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1200 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1201 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1202 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1203 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1204 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1205 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1206 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1207 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1208 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1209 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1210 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1211 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1212 #if defined(GOOGLE_CHROME_BUILD)
1213 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1215 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1216 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1219 // Conditionally adds the Profile menu to the main menu bar.
1220 - (void)initProfileMenu {
1221 NSMenu* mainMenu = [NSApp mainMenu];
1222 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1224 if (!profiles::IsMultipleProfilesEnabled()) {
1225 [mainMenu removeItem:profileMenu];
1229 // The controller will unhide the menu if necessary.
1230 [profileMenu setHidden:YES];
1232 profileMenuController_.reset(
1233 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1236 // The Confirm to Quit preference is atypical in that the preference lives in
1237 // the app menu right above the Quit menu item. This method will refresh the
1238 // display of that item depending on the preference state.
1239 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1240 // Format the string so that the correct key equivalent is displayed.
1241 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1242 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1243 base::SysNSStringToUTF16(acceleratorString));
1244 [item setTitle:title];
1246 const PrefService* prefService = g_browser_process->local_state();
1247 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1248 [item setState:enabled ? NSOnState : NSOffState];
1251 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1252 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1253 // handles requests from services.
1254 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1255 [app registerServicesMenuSendTypes:types returnTypes:types];
1258 - (Profile*)lastProfile {
1259 // Return the profile of the last-used BrowserWindowController, if available.
1261 return lastProfile_;
1263 // On first launch, use the logic that ChromeBrowserMain uses to determine
1264 // the initial profile.
1265 ProfileManager* profile_manager = g_browser_process->profile_manager();
1266 if (!profile_manager)
1269 return profile_manager->GetProfile(GetStartupProfilePath(
1270 profile_manager->user_data_dir(),
1271 *CommandLine::ForCurrentProcess()));
1274 // Various methods to open URLs that we get in a native fashion. We use
1275 // StartupBrowserCreator here because on the other platforms, URLs to open come
1276 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1277 // to bottleneck the openings through that for uniform handling.
1279 - (void)openUrls:(const std::vector<GURL>&)urls {
1280 // If the browser hasn't started yet, just queue up the URLs.
1281 if (!startupComplete_) {
1282 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1286 Browser* browser = chrome::GetLastActiveBrowser();
1287 // if no browser window exists then create one with no tabs to be filled in
1289 browser = new Browser(Browser::CreateParams(
1290 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1291 browser->window()->Show();
1294 CommandLine dummy(CommandLine::NO_PROGRAM);
1295 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1296 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1297 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1298 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1301 - (void)getUrl:(NSAppleEventDescriptor*)event
1302 withReply:(NSAppleEventDescriptor*)reply {
1303 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1306 GURL gurl(base::SysNSStringToUTF8(urlStr));
1307 std::vector<GURL> gurlVector;
1308 gurlVector.push_back(gurl);
1310 [self openUrls:gurlVector];
1313 // Apple Event handler that receives print event from service
1314 // process, gets the required data and launches Print dialog.
1315 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1316 // Pull parameter list out of Apple Event.
1317 NSAppleEventDescriptor* paramList =
1318 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
1320 if (paramList != nil) {
1321 // Pull required fields out of parameter list.
1322 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1323 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1324 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
1325 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
1326 // Convert the title to UTF 16 as required.
1327 base::string16 title16 = base::SysNSStringToUTF16(printTitle);
1328 base::string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
1329 print_dialog_cloud::CreatePrintDialogForFile(
1330 ProfileManager::GetActiveUserProfile(), NULL,
1331 base::FilePath([inputPath fileSystemRepresentation]), title16,
1332 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
1336 - (void)application:(NSApplication*)sender
1337 openFiles:(NSArray*)filenames {
1338 std::vector<GURL> gurlVector;
1339 for (NSString* file in filenames) {
1341 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1342 gurlVector.push_back(gurl);
1344 if (!gurlVector.empty())
1345 [self openUrls:gurlVector];
1347 NOTREACHED() << "Nothing to open!";
1349 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1352 // Show the preferences window, or bring it to the front if it's already
1354 - (IBAction)showPreferences:(id)sender {
1355 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1356 // Show options tab in the active browser window.
1357 chrome::ShowSettings(browser);
1359 // No browser window, so create one for the options tab.
1360 chrome::OpenOptionsWindow([self lastProfile]);
1364 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1365 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1366 chrome::ShowAboutChrome(browser);
1368 // No browser window, so create one for the about tab.
1369 chrome::OpenAboutWindow([self lastProfile]);
1373 - (IBAction)toggleConfirmToQuit:(id)sender {
1374 PrefService* prefService = g_browser_process->local_state();
1375 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1376 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1379 // Explicitly bring to the foreground when creating new windows from the dock.
1380 - (void)commandFromDock:(id)sender {
1381 [NSApp activateIgnoringOtherApps:YES];
1382 [self commandDispatch:sender];
1385 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1386 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1387 Profile* profile = [self lastProfile];
1389 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1393 [dockMenu addItem:[NSMenuItem separatorItem]];
1395 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1396 base::scoped_nsobject<NSMenuItem> item(
1397 [[NSMenuItem alloc] initWithTitle:titleStr
1398 action:@selector(commandFromDock:)
1399 keyEquivalent:@""]);
1400 [item setTarget:self];
1401 [item setTag:IDC_NEW_WINDOW];
1402 [item setEnabled:[self validateUserInterfaceItem:item]];
1403 [dockMenu addItem:item];
1405 // |profile| can be NULL during unit tests.
1406 if (!profile || !profile->IsManaged()) {
1407 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1409 [[NSMenuItem alloc] initWithTitle:titleStr
1410 action:@selector(commandFromDock:)
1411 keyEquivalent:@""]);
1412 [item setTarget:self];
1413 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1414 [item setEnabled:[self validateUserInterfaceItem:item]];
1415 [dockMenu addItem:item];
1418 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1419 // tests which use the mock in place of the profile-initialized model.
1421 // Avoid breaking unit tests which have no profile.
1423 BackgroundApplicationListModel applications(profile);
1424 if (applications.size()) {
1427 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1428 base::scoped_nsobject<NSMenu> appMenu(
1429 [[NSMenu alloc] initWithTitle:menuStr]);
1430 for (extensions::ExtensionList::const_iterator cursor =
1431 applications.begin();
1432 cursor != applications.end();
1433 ++cursor, ++position) {
1434 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1436 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1437 base::scoped_nsobject<NSMenuItem> appItem(
1438 [[NSMenuItem alloc] initWithTitle:itemStr
1439 action:@selector(executeApplication:)
1440 keyEquivalent:@""]);
1441 [appItem setTarget:self];
1442 [appItem setTag:position];
1443 [appMenu addItem:appItem];
1451 - (const std::vector<GURL>&)startupUrls {
1452 return startupUrls_;
1455 - (void)clearStartupUrls {
1456 startupUrls_.clear();
1459 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1460 return bookmarkMenuBridge_.get();
1463 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1464 workAreaChangeObservers_.AddObserver(observer);
1467 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1468 workAreaChangeObservers_.RemoveObserver(observer);
1471 - (void)initAppShimMenuController {
1472 if (!appShimMenuController_)
1473 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1476 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1477 // During this callback the working area is not always already updated. Defer.
1478 [self performSelector:@selector(delayedScreenParametersUpdate)
1483 - (void)delayedScreenParametersUpdate {
1484 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1488 @end // @implementation AppController
1490 //---------------------------------------------------------------------------
1492 namespace app_controller_mac {
1494 bool IsOpeningNewWindow() {
1495 return g_is_opening_new_window;
1498 } // namespace app_controller_mac