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/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 content::BrowserContext;
96 using content::BrowserThread;
97 using content::DownloadManager;
98 using content::UserMetricsAction;
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 // True while AppController is calling chrome::NewEmptyWindow(). We need a
110 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
111 // because otherwise the SessionService will try to restore sessions when we
112 // make a new window while there are no other active windows.
113 bool g_is_opening_new_window = false;
115 // Activates a browser window having the given profile (the last one active) if
116 // possible and returns a pointer to the activate |Browser| or NULL if this was
117 // not possible. If the last active browser is minimized (in particular, if
118 // there are only minimized windows), it will unminimize it.
119 Browser* ActivateBrowser(Profile* profile) {
120 Browser* browser = chrome::FindLastActiveWithProfile(profile,
121 chrome::HOST_DESKTOP_TYPE_NATIVE);
123 browser->window()->Activate();
127 // Creates an empty browser window with the given profile and returns a pointer
128 // to the new |Browser|.
129 Browser* CreateBrowser(Profile* profile) {
131 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
132 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
135 Browser* browser = chrome::GetLastActiveBrowser();
140 // Activates a browser window having the given profile (the last one active) if
141 // possible or creates an empty one if necessary. Returns a pointer to the
142 // activated/new |Browser|.
143 Browser* ActivateOrCreateBrowser(Profile* profile) {
144 if (Browser* browser = ActivateBrowser(profile))
146 return CreateBrowser(profile);
149 CFStringRef BaseBundleID_CFString() {
150 NSString* base_bundle_id =
151 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
152 return base::mac::NSToCFCast(base_bundle_id);
155 // This callback synchronizes preferences (under "org.chromium.Chromium" or
156 // "com.google.Chrome"), in particular, writes them out to disk.
157 void PrefsSyncCallback() {
158 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
159 LOG(WARNING) << "Error recording application bundle path.";
162 // Record the location of the application bundle (containing the main framework)
163 // from which Chromium was loaded. This is used by app mode shims to find
165 void RecordLastRunAppBundlePath() {
166 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
167 // real, user-visible app bundle directory. (The alternatives give either the
168 // framework's path or the initial app's path, which may be an app mode shim
170 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
172 base::FilePath app_bundle_path =
173 chrome::GetVersionedDirectory().DirName().DirName().DirName();
174 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
175 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
176 CFPreferencesSetAppValue(
177 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
178 app_bundle_path_cfstring, BaseBundleID_CFString());
180 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
181 BrowserThread::PostDelayedTask(
182 BrowserThread::FILE, FROM_HERE,
183 base::Bind(&PrefsSyncCallback),
184 base::TimeDelta::FromMilliseconds(1500));
187 } // anonymous namespace
189 @interface AppController (Private)
190 - (void)initMenuState;
191 - (void)initProfileMenu;
192 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
193 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
194 - (void)openUrls:(const std::vector<GURL>&)urls;
195 - (void)getUrl:(NSAppleEventDescriptor*)event
196 withReply:(NSAppleEventDescriptor*)reply;
197 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
198 - (void)windowLayeringDidChange:(NSNotification*)inNotification;
199 - (void)windowChangedToProfile:(Profile*)profile;
200 - (void)checkForAnyKeyWindows;
201 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
202 - (BOOL)shouldQuitWithInProgressDownloads;
203 - (void)executeApplication:(id)sender;
204 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
207 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
209 AppControllerProfileObserver(
210 ProfileManager* profile_manager, AppController* app_controller)
211 : profile_manager_(profile_manager),
212 app_controller_(app_controller) {
213 DCHECK(profile_manager_);
214 DCHECK(app_controller_);
215 profile_manager_->GetProfileInfoCache().AddObserver(this);
218 virtual ~AppControllerProfileObserver() {
219 DCHECK(profile_manager_);
220 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
224 // ProfileInfoCacheObserver implementation:
226 virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
229 virtual void OnProfileWasRemoved(const base::FilePath& profile_path,
230 const string16& profile_name) OVERRIDE {
231 // When a profile is deleted we need to notify the AppController,
232 // so it can correctly update its pointer to the last used profile.
233 [app_controller_ profileWasRemoved:profile_path];
236 virtual void OnProfileWillBeRemoved(
237 const base::FilePath& profile_path) OVERRIDE {
240 virtual void OnProfileNameChanged(const base::FilePath& profile_path,
241 const string16& old_profile_name) OVERRIDE {
244 virtual void OnProfileAvatarChanged(
245 const base::FilePath& profile_path) OVERRIDE {
248 ProfileManager* profile_manager_;
250 AppController* app_controller_; // Weak; owns us.
252 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
255 @implementation AppController
257 @synthesize startupComplete = startupComplete_;
259 // This method is called very early in application startup (ie, before
260 // the profile is loaded or any preferences have been registered). Defer any
261 // user-data initialization until -applicationDidFinishLaunching:.
262 - (void)awakeFromNib {
263 // We need to register the handlers early to catch events fired on launch.
264 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
265 [em setEventHandler:self
266 andSelector:@selector(getUrl:withReply:)
267 forEventClass:kInternetEventClass
268 andEventID:kAEGetURL];
269 [em setEventHandler:self
270 andSelector:@selector(submitCloudPrintJob:)
271 forEventClass:cloud_print::kAECloudPrintClass
272 andEventID:cloud_print::kAECloudPrintClass];
273 [em setEventHandler:self
274 andSelector:@selector(getUrl:withReply:)
275 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
276 andEventID:'OURL']; // back to the Spyglass days.
278 // Register for various window layering changes. We use these to update
279 // various UI elements (command-key equivalents, etc) when the frontmost
281 NSNotificationCenter* notificationCenter =
282 [NSNotificationCenter defaultCenter];
285 selector:@selector(windowLayeringDidChange:)
286 name:NSWindowDidBecomeKeyNotification
290 selector:@selector(windowLayeringDidChange:)
291 name:NSWindowDidResignKeyNotification
295 selector:@selector(windowLayeringDidChange:)
296 name:NSWindowDidBecomeMainNotification
300 selector:@selector(windowLayeringDidChange:)
301 name:NSWindowDidResignMainNotification
304 if (base::mac::IsOSLionOrLater()) {
307 selector:@selector(popoverDidShow:)
308 name:NSPopoverDidShowNotification
312 selector:@selector(popoverDidClose:)
313 name:NSPopoverDidCloseNotification
317 // Set up the command updater for when there are no windows open
318 [self initMenuState];
320 // Initialize the Profile menu.
321 [self initProfileMenu];
324 - (void)unregisterEventHandlers {
325 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
326 [em removeEventHandlerForEventClass:kInternetEventClass
327 andEventID:kAEGetURL];
328 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
329 andEventID:cloud_print::kAECloudPrintClass];
330 [em removeEventHandlerForEventClass:'WWW!'
332 [[NSNotificationCenter defaultCenter] removeObserver:self];
335 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
336 // the default handlers.
337 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
338 // Nothing here right now.
341 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
342 // Check for in-process downloads, and prompt the user if they really want
343 // to quit (and thus cancel downloads). Only check if we're not already
344 // shutting down, else the user might be prompted multiple times if the
345 // download isn't stopped before terminate is called again.
346 if (!browser_shutdown::IsTryingToQuit() &&
347 ![self shouldQuitWithInProgressDownloads])
350 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
351 // them in, but I'm not sure about UX; we'd also want to disable other things
352 // though.) http://crbug.com/40861
354 // Check if the user really wants to quit by employing the confirm-to-quit
356 if (!browser_shutdown::IsTryingToQuit() &&
357 [self applicationShouldTerminate:app] != NSTerminateNow)
360 size_t num_browsers = chrome::GetTotalBrowserCount();
362 // Initiate a shutdown (via chrome::CloseAllBrowsers()) if we aren't
363 // already shutting down.
364 if (!browser_shutdown::IsTryingToQuit()) {
365 content::NotificationService::current()->Notify(
366 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
367 content::NotificationService::AllSources(),
368 content::NotificationService::NoDetails());
369 chrome::CloseAllBrowsers();
372 return num_browsers == 0 ? YES : NO;
375 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
376 if (browser_shutdown::IsTryingToQuit()) {
377 // Reset the "trying to quit" state, so that closing all browser windows
378 // will no longer lead to termination.
379 browser_shutdown::SetTryingToQuit(false);
381 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
382 // would have to reinstall them here. http://crbug.com/40861
386 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
387 // If there are no windows, quit immediately.
388 if (chrome::BrowserIterator().done() &&
389 !apps::ShellWindowRegistry::IsShellWindowRegisteredInAnyProfile(0)) {
390 return NSTerminateNow;
393 // Check if the preference is turned on.
394 const PrefService* prefs = g_browser_process->local_state();
395 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
396 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
397 return NSTerminateNow;
400 // If the application is going to terminate as the result of a Cmd+Q
401 // invocation, use the special sauce to prevent accidental quitting.
402 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
404 // This logic is only for keyboard-initiated quits.
405 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
406 return NSTerminateNow;
408 return [[ConfirmQuitPanelController sharedController]
409 runModalLoopForApplication:app];
412 // Called when the app is shutting down. Clean-up as appropriate.
413 - (void)applicationWillTerminate:(NSNotification*)aNotification {
414 // There better be no browser windows left at this point.
415 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
417 // Tell BrowserList not to keep the browser process alive. Once all the
418 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
419 chrome::EndKeepAlive();
421 // Reset all pref watching, as this object outlives the prefs system.
422 profilePrefRegistrar_.reset();
423 localPrefRegistrar_.RemoveAll();
425 [self unregisterEventHandlers];
427 appShimMenuController_.reset();
430 - (void)didEndMainMessageLoop {
431 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
432 chrome::HOST_DESKTOP_TYPE_NATIVE));
433 if (!chrome::GetBrowserCount([self lastProfile],
434 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
435 // As we're shutting down, we need to nuke the TabRestoreService, which
436 // will start the shutdown of the NavigationControllers and allow for
437 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
438 // and may end up crashing when some thread tries to use the IO thread (or
439 // another thread) that is no longer valid.
440 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
444 // If the window has a tab controller, make "close window" be cmd-shift-w,
445 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
446 // affects whether the shift modifier is used.
447 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
448 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
450 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
453 // If the window has a tab controller, make "close tab" take over cmd-w,
454 // otherwise it shouldn't have any key-equivalent because it should be disabled.
455 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
456 if (enableCloseTabShortcut) {
457 [closeTabMenuItem_ setKeyEquivalent:@"w"];
458 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
460 [closeTabMenuItem_ setKeyEquivalent:@""];
461 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
465 // Explicitly remove any command-key equivalents from the close tab/window
466 // menus so that nothing can go haywire if we get a user action during pending
468 - (void)clearCloseMenuItemKeyEquivalents {
469 [closeTabMenuItem_ setKeyEquivalent:@""];
470 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
471 [closeWindowMenuItem_ setKeyEquivalent:@""];
472 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
475 // See if the focused window window has tabs, and adjust the key equivalents for
476 // Close Tab/Close Window accordingly.
477 - (void)fixCloseMenuItemKeyEquivalents {
478 fileMenuUpdatePending_ = NO;
480 NSWindow* window = [NSApp keyWindow];
481 NSWindow* mainWindow = [NSApp mainWindow];
482 if (!window || ([window parentWindow] == mainWindow)) {
483 // If the key window is a child of the main window (e.g. a bubble), the main
484 // window should be the one that handles the close menu item action.
485 // Also, there might be a small amount of time where there is no key window;
486 // in that case as well, just use our main browser window if there is one.
487 // You might think that we should just always use the main window, but the
488 // "About Chrome" window serves as a counterexample.
493 [[window windowController] isKindOfClass:[TabWindowController class]];
494 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
495 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
496 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
499 // Fix up the "close tab/close window" command-key equivalents. We do this
500 // after a delay to ensure that window layer state has been set by the time
501 // we do the enabling. This should only be called on the main thread, code that
502 // calls this (even as a side-effect) from other threads needs to be fixed.
503 - (void)delayedFixCloseMenuItemKeyEquivalents {
504 DCHECK([NSThread isMainThread]);
505 if (!fileMenuUpdatePending_) {
506 // The OS prefers keypresses to timers, so it's possible that a cmd-w
507 // can sneak in before this timer fires. In order to prevent that from
508 // having any bad consequences, just clear the keys combos altogether. They
509 // will be reset when the timer eventually fires.
510 if ([NSThread isMainThread]) {
511 fileMenuUpdatePending_ = YES;
512 [self clearCloseMenuItemKeyEquivalents];
513 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
517 // This shouldn't be happening, but if it does, force it to the main
518 // thread to avoid dropping the update. Don't mess with
519 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
520 // there could be a race between the selector finishing and setting the
523 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
530 // Called when we get a notification about the window layering changing to
531 // update the UI based on the new main window.
532 - (void)windowLayeringDidChange:(NSNotification*)notify {
533 [self delayedFixCloseMenuItemKeyEquivalents];
535 if ([notify name] == NSWindowDidResignKeyNotification) {
536 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
537 // returns nil regardless of whether any suitable candidates for the key
538 // window remain. It seems that the new key window for the app is not set
539 // until after this notification is fired, so a check is performed after the
540 // run loop is allowed to spin.
541 [self performSelector:@selector(checkForAnyKeyWindows)
546 // If the window changed to a new BrowserWindowController, update the profile.
547 id windowController = [[notify object] windowController];
548 if ([notify name] == NSWindowDidBecomeMainNotification &&
549 [windowController isKindOfClass:[BrowserWindowController class]]) {
550 // If the profile is incognito, use the original profile.
551 Profile* newProfile = [windowController profile]->GetOriginalProfile();
552 [self windowChangedToProfile:newProfile];
553 } else if (chrome::GetTotalBrowserCount() == 0) {
554 [self windowChangedToProfile:
555 g_browser_process->profile_manager()->GetLastUsedProfile()];
559 // Called on Lion and later when a popover (e.g. dictionary) is shown.
560 - (void)popoverDidShow:(NSNotification*)notify {
562 [self fixCloseMenuItemKeyEquivalents];
565 // Called on Lion and later when a popover (e.g. dictionary) is closed.
566 - (void)popoverDidClose:(NSNotification*)notify {
568 [self fixCloseMenuItemKeyEquivalents];
571 // Called when the user has changed browser windows, meaning the backing profile
572 // may have changed. This can cause a rebuild of the user-data menus. This is a
573 // no-op if the new profile is the same as the current one. This will always be
574 // the original profile and never incognito.
575 - (void)windowChangedToProfile:(Profile*)profile {
576 if (lastProfile_ == profile)
579 // Before tearing down the menu controller bridges, return the Cocoa menus to
580 // their initial state.
581 if (bookmarkMenuBridge_.get())
582 bookmarkMenuBridge_->ResetMenu();
583 if (historyMenuBridge_.get())
584 historyMenuBridge_->ResetMenu();
586 // Rebuild the menus with the new profile.
587 lastProfile_ = profile;
589 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
590 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
591 // No need to |BuildMenu| here. It is done lazily upon menu access.
593 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
594 historyMenuBridge_->BuildMenu();
596 chrome::BrowserCommandController::
597 UpdateSharedCommandsForIncognitoAvailability(
598 menuState_.get(), lastProfile_);
599 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
600 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
601 profilePrefRegistrar_->Add(
602 prefs::kIncognitoModeAvailability,
603 base::Bind(&chrome::BrowserCommandController::
604 UpdateSharedCommandsForIncognitoAvailability,
609 - (void)checkForAnyKeyWindows {
610 if ([NSApp keyWindow])
613 content::NotificationService::current()->Notify(
614 chrome::NOTIFICATION_NO_KEY_WINDOW,
615 content::NotificationService::AllSources(),
616 content::NotificationService::NoDetails());
619 // If the auto-update interval is not set, make it 5 hours.
620 // Placed here for 2 reasons:
621 // 1) Same spot as other Pref stuff
622 // 2) Try and be friendly by keeping this after app launch
623 - (void)setUpdateCheckInterval {
624 #if defined(GOOGLE_CHROME_BUILD)
625 CFStringRef app = CFSTR("com.google.Keystone.Agent");
626 CFStringRef checkInterval = CFSTR("checkInterval");
627 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
629 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
630 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
631 CFPreferencesSetAppValue(checkInterval, value, app);
632 CFPreferencesAppSynchronize(app);
637 // This is called after profiles have been loaded and preferences registered.
638 // It is safe to access the default profile here.
639 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
640 // Notify BrowserList to keep the application running so it doesn't go away
641 // when all the browser windows get closed.
642 chrome::StartKeepAlive();
644 [self setUpdateCheckInterval];
646 // Start managing the menu for app windows. This needs to be done here because
647 // main menu item titles are not yet initialized in awakeFromNib.
648 if (apps::IsAppShimsEnabled())
649 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
651 // Build up the encoding menu, the order of the items differs based on the
652 // current locale (see http://crbug.com/7647 for details).
653 // We need a valid g_browser_process to get the profile which is why we can't
654 // call this from awakeFromNib.
655 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
656 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
657 NSMenu* encodingMenu = [encodingMenuItem submenu];
658 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
661 // Instantiate the ProfileInfoCache observer so that we can get
662 // notified when a profile is deleted.
663 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
664 g_browser_process->profile_manager(), self));
666 // Since Chrome is localized to more languages than the OS, tell Cocoa which
667 // menu is the Help so it can add the search item to it.
668 [NSApp setHelpMenu:helpMenu_];
670 // Record the path to the (browser) app bundle; this is used by the app mode
671 // shim. It has to be done in FILE thread because getting the path requires
673 BrowserThread::PostTask(
674 BrowserThread::FILE, FROM_HERE,
675 base::Bind(&RecordLastRunAppBundlePath));
677 // Makes "Services" menu items available.
678 [self registerServicesMenuTypesTo:[notify object]];
680 startupComplete_ = YES;
682 // TODO(viettrungluu): This is very temporary, since this should be done "in"
683 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
684 // (probably-empty) list of URLs from the command line.
685 if (startupUrls_.size()) {
686 [self openUrls:startupUrls_];
687 [self clearStartupUrls];
690 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
691 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
692 [tabposeMenuItem_ setHidden:YES];
695 PrefService* localState = g_browser_process->local_state();
697 localPrefRegistrar_.Init(localState);
698 localPrefRegistrar_.Add(
699 prefs::kAllowFileSelectionDialogs,
700 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
705 // This is called after profiles have been loaded and preferences registered.
706 // It is safe to access the default profile here.
707 - (void)applicationDidBecomeActive:(NSNotification*)notify {
708 content::PluginService::GetInstance()->AppActivated();
711 // Helper function for populating and displaying the in progress downloads at
713 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
714 NSString* titleText = nil;
715 NSString* explanationText = nil;
716 NSString* waitTitle = nil;
717 NSString* exitTitle = nil;
719 // Set the dialog text based on whether or not there are multiple downloads.
720 if (downloadCount == 1) {
721 // Dialog text: warning and explanation.
722 titleText = l10n_util::GetNSString(
723 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
724 explanationText = l10n_util::GetNSString(
725 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
727 // Dialog text: warning and explanation.
728 titleText = l10n_util::GetNSStringF(
729 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
730 base::IntToString16(downloadCount));
731 explanationText = l10n_util::GetNSString(
732 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
734 // Cancel download and exit button text.
735 exitTitle = l10n_util::GetNSString(
736 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
738 // Wait for download button text.
739 waitTitle = l10n_util::GetNSString(
740 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
742 // 'waitButton' is the default choice.
743 int choice = NSRunAlertPanel(titleText, @"%@",
744 waitTitle, exitTitle, nil, explanationText);
745 return choice == NSAlertDefaultReturn ? YES : NO;
748 // Check all profiles for in progress downloads, and if we find any, prompt the
749 // user to see if we should continue to exit (and thus cancel the downloads), or
750 // if we should wait.
751 - (BOOL)shouldQuitWithInProgressDownloads {
752 ProfileManager* profile_manager = g_browser_process->profile_manager();
753 if (!profile_manager)
756 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
757 for (size_t i = 0; i < profiles.size(); ++i) {
758 DownloadService* download_service =
759 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
760 DownloadManager* download_manager =
761 (download_service->HasCreatedDownloadManager() ?
762 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
763 if (download_manager && download_manager->InProgressCount() > 0) {
764 int downloadCount = download_manager->InProgressCount();
765 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
766 // Create a new browser window (if necessary) and navigate to the
767 // downloads page if the user chooses to wait.
768 Browser* browser = chrome::FindBrowserWithProfile(
769 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
771 browser = new Browser(Browser::CreateParams(
772 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
773 browser->window()->Show();
776 chrome::ShowDownloads(browser);
780 // User wants to exit.
785 // No profiles or active downloads found, okay to exit.
789 // Called to determine if we should enable the "restore tab" menu item.
790 // Checks with the TabRestoreService to see if there's anything there to
791 // restore and returns YES if so.
792 - (BOOL)canRestoreTab {
793 TabRestoreService* service =
794 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
795 return service && !service->entries().empty();
798 // Called from the AppControllerProfileObserver every time a profile is deleted.
799 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
800 Profile* lastProfile = [self lastProfile];
802 // If the lastProfile has been deleted, the profile manager has
803 // already loaded a new one, so the pointer needs to be updated;
804 // otherwise we will try to start up a browser window with a pointer
805 // to the old profile.
806 if (profilePath == lastProfile->GetPath())
807 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
810 // Returns true if there is a modal window (either window- or application-
811 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
812 // sheets) will not count as blocking the browser. But things like open/save
813 // dialogs that are window modal will block the browser.
814 - (BOOL)keyWindowIsModal {
815 if ([NSApp modalWindow])
818 Browser* browser = chrome::GetLastActiveBrowser();
820 [[browser->window()->GetNativeWindow() attachedSheet]
821 isKindOfClass:[NSWindow class]];
824 // Called to validate menu items when there are no key windows. All the
825 // items we care about have been set with the |commandDispatch:| action and
826 // a target of FirstResponder in IB. If it's not one of those, let it
827 // continue up the responder chain to be handled elsewhere. We pull out the
828 // tag as the cross-platform constant to differentiate and dispatch the
830 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
831 SEL action = [item action];
833 if (action == @selector(commandDispatch:) ||
834 action == @selector(commandFromDock:)) {
835 NSInteger tag = [item tag];
836 if (menuState_ && // NULL in tests.
837 menuState_->SupportsCommand(tag)) {
839 // The File Menu commands are not automatically disabled by Cocoa when a
840 // dialog sheet obscures the browser window, so we disable several of
841 // them here. We don't need to include IDC_CLOSE_WINDOW, because
842 // app_controller is only activated when there are no key windows (see
843 // function comment).
844 case IDC_RESTORE_TAB:
845 enable = ![self keyWindowIsModal] && [self canRestoreTab];
847 // Browser-level items that open in new tabs should not open if there's
848 // a window- or app-modal dialog.
851 case IDC_SHOW_HISTORY:
852 case IDC_SHOW_BOOKMARK_MANAGER:
853 enable = ![self keyWindowIsModal];
855 // Browser-level items that open in new windows.
856 case IDC_TASK_MANAGER:
857 // Allow the user to open a new window if there's a window-modal
859 enable = ![self keyWindowIsModal];
861 case IDC_SHOW_SYNC_SETUP: {
862 Profile* lastProfile = [self lastProfile];
863 // The profile may be NULL during shutdown -- see
864 // http://code.google.com/p/chromium/issues/detail?id=43048 .
866 // TODO(akalin,viettrungluu): Figure out whether this method
867 // can be prevented from being called if lastProfile is
871 << "NULL lastProfile detected -- not doing anything";
874 SigninManager* signin = SigninManagerFactory::GetForProfile(
875 lastProfile->GetOriginalProfile());
876 enable = signin->IsSigninAllowed() &&
877 ![self keyWindowIsModal];
878 [BrowserWindowController updateSigninItem:item
880 currentProfile:lastProfile];
883 #if defined(GOOGLE_CHROME_BUILD)
889 enable = menuState_->IsCommandEnabled(tag) ?
890 ![self keyWindowIsModal] : NO;
893 } else if (action == @selector(terminate:)) {
895 } else if (action == @selector(showPreferences:)) {
897 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
899 } else if (action == @selector(commandFromDock:)) {
901 } else if (action == @selector(toggleConfirmToQuit:)) {
902 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
904 } else if (action == @selector(executeApplication:)) {
910 // Called when the user picks a menu item when there are no key windows, or when
911 // there is no foreground browser window. Calls through to the browser object to
912 // execute the command. This assumes that the command is supported and doesn't
913 // check, otherwise it should have been disabled in the UI in
914 // |-validateUserInterfaceItem:|.
915 - (void)commandDispatch:(id)sender {
916 Profile* lastProfile = [self lastProfile];
918 // Handle the case where we're dispatching a command from a sender that's in a
919 // browser window. This means that the command came from a background window
920 // and is getting here because the foreground window is not a browser window.
921 if ([sender respondsToSelector:@selector(window)]) {
922 id delegate = [[sender window] windowController];
923 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
924 [delegate commandDispatch:sender];
929 // Ignore commands during session restore's browser creation. It uses a
930 // nested message loop and commands dispatched during this operation cause
932 if (SessionRestore::IsRestoring(lastProfile) &&
933 base::MessageLoop::current()->IsNested())
936 NSInteger tag = [sender tag];
939 // Create a new tab in an existing browser window (which we activate) if
941 if (Browser* browser = ActivateBrowser(lastProfile)) {
942 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
945 // Else fall through to create new window.
947 CreateBrowser(lastProfile);
949 case IDC_FOCUS_LOCATION:
950 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
953 case IDC_FOCUS_SEARCH:
954 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
957 case IDC_NEW_INCOGNITO_WINDOW:
958 CreateBrowser(lastProfile->GetOffTheRecordProfile());
960 case IDC_RESTORE_TAB:
961 // There is only the native desktop on Mac.
962 chrome::OpenWindowWithRestoredTabs(lastProfile,
963 chrome::HOST_DESKTOP_TYPE_NATIVE);
966 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
968 case IDC_CLEAR_BROWSING_DATA: {
969 // There may not be a browser open, so use the default profile.
970 if (Browser* browser = ActivateBrowser(lastProfile)) {
971 chrome::ShowClearBrowsingDataDialog(browser);
973 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
977 case IDC_IMPORT_SETTINGS: {
978 if (Browser* browser = ActivateBrowser(lastProfile)) {
979 chrome::ShowImportDialog(browser);
981 chrome::OpenImportSettingsDialogWindow(lastProfile);
985 case IDC_SHOW_BOOKMARK_MANAGER:
986 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
987 if (Browser* browser = ActivateBrowser(lastProfile)) {
988 chrome::ShowBookmarkManager(browser);
990 // No browser window, so create one for the bookmark manager tab.
991 chrome::OpenBookmarkManagerWindow(lastProfile);
994 case IDC_SHOW_HISTORY:
995 if (Browser* browser = ActivateBrowser(lastProfile))
996 chrome::ShowHistory(browser);
998 chrome::OpenHistoryWindow(lastProfile);
1000 case IDC_SHOW_DOWNLOADS:
1001 if (Browser* browser = ActivateBrowser(lastProfile))
1002 chrome::ShowDownloads(browser);
1004 chrome::OpenDownloadsWindow(lastProfile);
1006 case IDC_MANAGE_EXTENSIONS:
1007 if (Browser* browser = ActivateBrowser(lastProfile))
1008 chrome::ShowExtensions(browser, std::string());
1010 chrome::OpenExtensionsWindow(lastProfile);
1012 case IDC_HELP_PAGE_VIA_MENU:
1013 if (Browser* browser = ActivateBrowser(lastProfile))
1014 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1016 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1018 case IDC_SHOW_SYNC_SETUP:
1019 if (Browser* browser = ActivateBrowser(lastProfile)) {
1020 chrome::ShowBrowserSignin(browser, signin::SOURCE_MENU);
1022 chrome::OpenSyncSetupWindow(lastProfile, signin::SOURCE_MENU);
1025 case IDC_TASK_MANAGER:
1026 content::RecordAction(UserMetricsAction("TaskManager"));
1027 TaskManagerMac::Show();
1030 [self showPreferences:sender];
1035 // Run a (background) application in a new tab.
1036 - (void)executeApplication:(id)sender {
1037 NSInteger tag = [sender tag];
1038 Profile* profile = [self lastProfile];
1040 BackgroundApplicationListModel applications(profile);
1042 tag < static_cast<int>(applications.size()));
1043 const extensions::Extension* extension = applications.GetExtension(tag);
1044 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1047 // Same as |-commandDispatch:|, but executes commands using a disposition
1048 // determined by the key flags. This will get called in the case where the
1049 // frontmost window is not a browser window, and the user has command-clicked
1050 // a button in a background browser window whose action is
1051 // |-commandDispatchUsingKeyModifiers:|
1052 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1054 if ([sender respondsToSelector:@selector(window)]) {
1055 id delegate = [[sender window] windowController];
1056 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1057 [delegate commandDispatchUsingKeyModifiers:sender];
1062 // NSApplication delegate method called when someone clicks on the dock icon.
1063 // To match standard mac behavior, we should open a new window if there are no
1065 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1066 hasVisibleWindows:(BOOL)hasVisibleWindows {
1067 // If the browser is currently trying to quit, don't do anything and return NO
1068 // to prevent AppKit from doing anything.
1069 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1070 if (browser_shutdown::IsTryingToQuit())
1073 // Bring all browser windows to the front. Specifically, this brings them in
1074 // front of any app windows. FocusWindowSet will also unminimize the most
1075 // recently minimized window if no windows in the set are visible.
1076 // If there are any, return here. Otherwise, the windows are panels or
1077 // notifications so we still need to open a new window.
1078 if (hasVisibleWindows) {
1079 std::set<NSWindow*> browserWindows;
1080 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1081 Browser* browser = *iter;
1082 browserWindows.insert(browser->window()->GetNativeWindow());
1084 if (!browserWindows.empty()) {
1085 ui::FocusWindowSet(browserWindows, false);
1086 // Return NO; we've done the unminimize, so AppKit shouldn't do
1092 // If launched as a hidden login item (due to installation of a persistent app
1093 // or by the user, for example in System Preferences->Accounts->Login Items),
1094 // allow session to be restored first time the user clicks on a Dock icon.
1095 // Normally, it'd just open a new empty page.
1097 static BOOL doneOnce = NO;
1100 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
1101 SessionService* sessionService =
1102 SessionServiceFactory::GetForProfile([self lastProfile]);
1103 if (sessionService &&
1104 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1110 // Platform apps don't use browser windows so don't do anything if there are
1111 // visible windows, otherwise, launch the browser with the same command line
1112 // which should launch the app again.
1113 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1114 if (command_line.HasSwitch(switches::kAppId)) {
1115 if (hasVisibleWindows)
1119 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1121 StartupBrowserCreator browser_creator;
1122 browser_creator.LaunchBrowser(
1123 command_line, [self lastProfile], base::FilePath(),
1124 chrome::startup::IS_NOT_PROCESS_STARTUP,
1125 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
1130 // Otherwise open a new window.
1131 CreateBrowser([self lastProfile]);
1133 // We've handled the reopen event, so return NO to tell AppKit not
1138 - (void)initMenuState {
1139 menuState_.reset(new CommandUpdater(NULL));
1140 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1141 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1142 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1143 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1144 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1145 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1146 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1147 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1148 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1149 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1150 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1151 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1152 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1153 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1154 #if defined(GOOGLE_CHROME_BUILD)
1155 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1157 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1158 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1161 // Conditionally adds the Profile menu to the main menu bar.
1162 - (void)initProfileMenu {
1163 NSMenu* mainMenu = [NSApp mainMenu];
1164 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1166 if (!profiles::IsMultipleProfilesEnabled()) {
1167 [mainMenu removeItem:profileMenu];
1171 // The controller will unhide the menu if necessary.
1172 [profileMenu setHidden:YES];
1174 profileMenuController_.reset(
1175 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1178 // The Confirm to Quit preference is atypical in that the preference lives in
1179 // the app menu right above the Quit menu item. This method will refresh the
1180 // display of that item depending on the preference state.
1181 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1182 // Format the string so that the correct key equivalent is displayed.
1183 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1184 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1185 base::SysNSStringToUTF16(acceleratorString));
1186 [item setTitle:title];
1188 const PrefService* prefService = g_browser_process->local_state();
1189 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1190 [item setState:enabled ? NSOnState : NSOffState];
1193 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1194 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1195 // handles requests from services.
1196 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1197 [app registerServicesMenuSendTypes:types returnTypes:types];
1200 - (Profile*)lastProfile {
1201 // Return the profile of the last-used BrowserWindowController, if available.
1203 return lastProfile_;
1205 // On first launch, no profile will be stored, so use last from Local State.
1206 if (g_browser_process->profile_manager())
1207 return g_browser_process->profile_manager()->GetLastUsedProfile();
1212 // Various methods to open URLs that we get in a native fashion. We use
1213 // StartupBrowserCreator here because on the other platforms, URLs to open come
1214 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1215 // to bottleneck the openings through that for uniform handling.
1217 - (void)openUrls:(const std::vector<GURL>&)urls {
1218 // If the browser hasn't started yet, just queue up the URLs.
1219 if (!startupComplete_) {
1220 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1224 Browser* browser = chrome::GetLastActiveBrowser();
1225 // if no browser window exists then create one with no tabs to be filled in
1227 browser = new Browser(Browser::CreateParams(
1228 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1229 browser->window()->Show();
1232 CommandLine dummy(CommandLine::NO_PROGRAM);
1233 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1234 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1235 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1236 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1239 - (void)getUrl:(NSAppleEventDescriptor*)event
1240 withReply:(NSAppleEventDescriptor*)reply {
1241 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1244 GURL gurl(base::SysNSStringToUTF8(urlStr));
1245 std::vector<GURL> gurlVector;
1246 gurlVector.push_back(gurl);
1248 [self openUrls:gurlVector];
1251 // Apple Event handler that receives print event from service
1252 // process, gets the required data and launches Print dialog.
1253 - (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1254 // Pull parameter list out of Apple Event.
1255 NSAppleEventDescriptor* paramList =
1256 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
1258 if (paramList != nil) {
1259 // Pull required fields out of parameter list.
1260 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1261 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1262 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
1263 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
1264 // Convert the title to UTF 16 as required.
1265 string16 title16 = base::SysNSStringToUTF16(printTitle);
1266 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
1267 print_dialog_cloud::CreatePrintDialogForFile(
1268 ProfileManager::GetDefaultProfile(), NULL,
1269 base::FilePath([inputPath UTF8String]), title16,
1270 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
1274 - (void)application:(NSApplication*)sender
1275 openFiles:(NSArray*)filenames {
1276 std::vector<GURL> gurlVector;
1277 for (NSString* file in filenames) {
1279 net::FilePathToFileURL(base::FilePath(base::SysNSStringToUTF8(file)));
1280 gurlVector.push_back(gurl);
1282 if (!gurlVector.empty())
1283 [self openUrls:gurlVector];
1285 NOTREACHED() << "Nothing to open!";
1287 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1290 // Show the preferences window, or bring it to the front if it's already
1292 - (IBAction)showPreferences:(id)sender {
1293 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1294 // Show options tab in the active browser window.
1295 chrome::ShowSettings(browser);
1297 // No browser window, so create one for the options tab.
1298 chrome::OpenOptionsWindow([self lastProfile]);
1302 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1303 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1304 chrome::ShowAboutChrome(browser);
1306 // No browser window, so create one for the about tab.
1307 chrome::OpenAboutWindow([self lastProfile]);
1311 - (IBAction)toggleConfirmToQuit:(id)sender {
1312 PrefService* prefService = g_browser_process->local_state();
1313 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1314 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1317 // Explicitly bring to the foreground when creating new windows from the dock.
1318 - (void)commandFromDock:(id)sender {
1319 [NSApp activateIgnoringOtherApps:YES];
1320 [self commandDispatch:sender];
1323 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1324 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1325 Profile* profile = [self lastProfile];
1327 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1331 [dockMenu addItem:[NSMenuItem separatorItem]];
1333 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1334 base::scoped_nsobject<NSMenuItem> item(
1335 [[NSMenuItem alloc] initWithTitle:titleStr
1336 action:@selector(commandFromDock:)
1337 keyEquivalent:@""]);
1338 [item setTarget:self];
1339 [item setTag:IDC_NEW_WINDOW];
1340 [item setEnabled:[self validateUserInterfaceItem:item]];
1341 [dockMenu addItem:item];
1343 // |profile| can be NULL during unit tests.
1344 if (!profile || !profile->IsManaged()) {
1345 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1347 [[NSMenuItem alloc] initWithTitle:titleStr
1348 action:@selector(commandFromDock:)
1349 keyEquivalent:@""]);
1350 [item setTarget:self];
1351 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1352 [item setEnabled:[self validateUserInterfaceItem:item]];
1353 [dockMenu addItem:item];
1356 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1357 // tests which use the mock in place of the profile-initialized model.
1359 // Avoid breaking unit tests which have no profile.
1361 BackgroundApplicationListModel applications(profile);
1362 if (applications.size()) {
1365 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1366 base::scoped_nsobject<NSMenu> appMenu(
1367 [[NSMenu alloc] initWithTitle:menuStr]);
1368 for (extensions::ExtensionList::const_iterator cursor =
1369 applications.begin();
1370 cursor != applications.end();
1371 ++cursor, ++position) {
1372 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1374 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
1375 base::scoped_nsobject<NSMenuItem> appItem(
1376 [[NSMenuItem alloc] initWithTitle:itemStr
1377 action:@selector(executeApplication:)
1378 keyEquivalent:@""]);
1379 [appItem setTarget:self];
1380 [appItem setTag:position];
1381 [appMenu addItem:appItem];
1389 - (const std::vector<GURL>&)startupUrls {
1390 return startupUrls_;
1393 - (void)clearStartupUrls {
1394 startupUrls_.clear();
1397 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1398 return bookmarkMenuBridge_.get();
1401 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1402 workAreaChangeObservers_.AddObserver(observer);
1405 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1406 workAreaChangeObservers_.RemoveObserver(observer);
1409 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1410 // During this callback the working area is not always already updated. Defer.
1411 [self performSelector:@selector(delayedScreenParametersUpdate)
1416 - (void)delayedScreenParametersUpdate {
1417 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1421 @end // @implementation AppController
1423 //---------------------------------------------------------------------------
1425 namespace app_controller_mac {
1427 bool IsOpeningNewWindow() {
1428 return g_is_opening_new_window;
1431 } // namespace app_controller_mac