Fix the System Profile to not load extensions. It could otherwise be forced to by...
[chromium-blink-merge.git] / chrome / browser / app_controller_mac.mm
blob40245a05184afadd655b39a71b512d565c2629ea
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 "base/auto_reset.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/files/file_path.h"
11 #include "base/mac/foundation_util.h"
12 #include "base/mac/mac_util.h"
13 #include "base/mac/sdk_forward_declarations.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/stl_util.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/apps/app_shim/extension_app_shim_handler_mac.h"
23 #include "chrome/browser/apps/app_window_registry_util.h"
24 #include "chrome/browser/background/background_application_list_model.h"
25 #include "chrome/browser/background/background_mode_manager.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/browser_shutdown.h"
28 #include "chrome/browser/chrome_notification_types.h"
29 #include "chrome/browser/command_updater.h"
30 #include "chrome/browser/download/download_service.h"
31 #include "chrome/browser/download/download_service_factory.h"
32 #include "chrome/browser/extensions/extension_service.h"
33 #include "chrome/browser/first_run/first_run.h"
34 #include "chrome/browser/lifetime/application_lifetime.h"
35 #include "chrome/browser/mac/mac_startup_profiler.h"
36 #include "chrome/browser/prefs/incognito_mode_prefs.h"
37 #include "chrome/browser/profiles/profile_info_cache_observer.h"
38 #include "chrome/browser/profiles/profile_manager.h"
39 #include "chrome/browser/profiles/profiles_state.h"
40 #include "chrome/browser/sessions/session_restore.h"
41 #include "chrome/browser/sessions/session_service.h"
42 #include "chrome/browser/sessions/session_service_factory.h"
43 #include "chrome/browser/sessions/tab_restore_service.h"
44 #include "chrome/browser/sessions/tab_restore_service_factory.h"
45 #include "chrome/browser/signin/signin_manager_factory.h"
46 #include "chrome/browser/signin/signin_promo.h"
47 #include "chrome/browser/signin/signin_ui_util.h"
48 #include "chrome/browser/sync/profile_sync_service.h"
49 #include "chrome/browser/sync/sync_ui_util.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_command_controller.h"
52 #include "chrome/browser/ui/browser_commands.h"
53 #include "chrome/browser/ui/browser_dialogs.h"
54 #include "chrome/browser/ui/browser_finder.h"
55 #include "chrome/browser/ui/browser_iterator.h"
56 #include "chrome/browser/ui/browser_mac.h"
57 #include "chrome/browser/ui/browser_window.h"
58 #include "chrome/browser/ui/chrome_pages.h"
59 #import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
60 #include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
61 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
62 #import "chrome/browser/ui/cocoa/confirm_quit.h"
63 #import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
64 #import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
65 #include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
66 #import "chrome/browser/ui/cocoa/history_menu_bridge.h"
67 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
68 #import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
69 #include "chrome/browser/ui/extensions/application_launch.h"
70 #include "chrome/browser/ui/host_desktop.h"
71 #include "chrome/browser/ui/startup/startup_browser_creator.h"
72 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
73 #include "chrome/browser/ui/tabs/tab_strip_model.h"
74 #include "chrome/browser/ui/user_manager.h"
75 #include "chrome/browser/web_applications/web_app_mac.h"
76 #include "chrome/common/chrome_paths_internal.h"
77 #include "chrome/common/chrome_switches.h"
78 #include "chrome/common/cloud_print/cloud_print_class_mac.h"
79 #include "chrome/common/extensions/extension_constants.h"
80 #include "chrome/common/mac/app_mode_common.h"
81 #include "chrome/common/pref_names.h"
82 #include "chrome/common/url_constants.h"
83 #include "chrome/grit/chromium_strings.h"
84 #include "chrome/grit/generated_resources.h"
85 #include "components/handoff/handoff_manager.h"
86 #include "components/handoff/handoff_utility.h"
87 #include "components/signin/core/browser/signin_manager.h"
88 #include "components/signin/core/common/profile_management_switches.h"
89 #include "content/public/browser/browser_thread.h"
90 #include "content/public/browser/download_manager.h"
91 #include "content/public/browser/notification_service.h"
92 #include "content/public/browser/notification_types.h"
93 #include "content/public/browser/plugin_service.h"
94 #include "content/public/browser/user_metrics.h"
95 #include "extensions/browser/extension_registry.h"
96 #include "extensions/browser/extension_system.h"
97 #include "net/base/filename_util.h"
98 #include "ui/base/cocoa/focus_window_set.h"
99 #include "ui/base/l10n/l10n_util.h"
100 #include "ui/base/l10n/l10n_util_mac.h"
102 using apps::AppShimHandler;
103 using apps::ExtensionAppShimHandler;
104 using base::UserMetricsAction;
105 using content::BrowserContext;
106 using content::BrowserThread;
107 using content::DownloadManager;
109 namespace {
111 // How long we allow a workspace change notification to wait to be
112 // associated with a dock activation. The animation lasts 250ms. See
113 // applicationShouldHandleReopen:hasVisibleWindows:.
114 static const int kWorkspaceChangeTimeoutMs = 500;
116 // True while AppController is calling chrome::NewEmptyWindow(). We need a
117 // global flag here, analogue to StartupBrowserCreator::InProcessStartup()
118 // because otherwise the SessionService will try to restore sessions when we
119 // make a new window while there are no other active windows.
120 bool g_is_opening_new_window = false;
122 // Activates a browser window having the given profile (the last one active) if
123 // possible and returns a pointer to the activate |Browser| or NULL if this was
124 // not possible. If the last active browser is minimized (in particular, if
125 // there are only minimized windows), it will unminimize it.
126 Browser* ActivateBrowser(Profile* profile) {
127   Browser* browser = chrome::FindLastActiveWithProfile(
128       profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile,
129       chrome::HOST_DESKTOP_TYPE_NATIVE);
130   if (browser)
131     browser->window()->Activate();
132   return browser;
135 // Creates an empty browser window with the given profile and returns a pointer
136 // to the new |Browser|.
137 Browser* CreateBrowser(Profile* profile) {
138   {
139     base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
140     chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
141   }
143   Browser* browser = chrome::GetLastActiveBrowser();
144   CHECK(browser);
145   return browser;
148 // Activates a browser window having the given profile (the last one active) if
149 // possible or creates an empty one if necessary. Returns a pointer to the
150 // activated/new |Browser|.
151 Browser* ActivateOrCreateBrowser(Profile* profile) {
152   if (Browser* browser = ActivateBrowser(profile))
153     return browser;
154   return CreateBrowser(profile);
157 CFStringRef BaseBundleID_CFString() {
158   NSString* base_bundle_id =
159       [NSString stringWithUTF8String:base::mac::BaseBundleID()];
160   return base::mac::NSToCFCast(base_bundle_id);
163 // This callback synchronizes preferences (under "org.chromium.Chromium" or
164 // "com.google.Chrome"), in particular, writes them out to disk.
165 void PrefsSyncCallback() {
166   if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
167     LOG(WARNING) << "Error recording application bundle path.";
170 // Record the location of the application bundle (containing the main framework)
171 // from which Chromium was loaded. This is used by app mode shims to find
172 // Chromium.
173 void RecordLastRunAppBundlePath() {
174   // Going up three levels from |chrome::GetVersionedDirectory()| gives the
175   // real, user-visible app bundle directory. (The alternatives give either the
176   // framework's path or the initial app's path, which may be an app mode shim
177   // or a unit test.)
178   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
180   base::FilePath app_bundle_path =
181       chrome::GetVersionedDirectory().DirName().DirName().DirName();
182   base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
183       base::SysUTF8ToCFStringRef(app_bundle_path.value()));
184   CFPreferencesSetAppValue(
185       base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
186       app_bundle_path_cfstring, BaseBundleID_CFString());
188   // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
189   BrowserThread::PostDelayedTask(
190       BrowserThread::FILE, FROM_HERE,
191       base::Bind(&PrefsSyncCallback),
192       base::TimeDelta::FromMilliseconds(1500));
195 bool IsProfileSignedOut(Profile* profile) {
196   // The signed out status only makes sense at the moment in the context of the
197   // --new-profile-management flag.
198   if (!switches::IsNewProfileManagement())
199     return false;
200   ProfileInfoCache& cache =
201       g_browser_process->profile_manager()->GetProfileInfoCache();
202   size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
203   if (profile_index == std::string::npos)
204     return false;
205   return cache.ProfileIsSigninRequiredAtIndex(profile_index);
208 }  // namespace
210 @interface AppController () <HandoffActiveURLObserverBridgeDelegate>
212 - (void)initMenuState;
213 - (void)initProfileMenu;
214 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
215 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
216 - (void)registerServicesMenuTypesTo:(NSApplication*)app;
217 - (void)getUrl:(NSAppleEventDescriptor*)event
218      withReply:(NSAppleEventDescriptor*)reply;
219 - (void)activeSpaceDidChange:(NSNotification*)inNotification;
220 - (void)checkForAnyKeyWindows;
221 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
222 - (BOOL)shouldQuitWithInProgressDownloads;
223 - (void)executeApplication:(id)sender;
224 - (void)profileWasRemoved:(const base::FilePath&)profilePath;
226 // Opens a tab for each GURL in |urls|.
227 - (void)openUrls:(const std::vector<GURL>&)urls;
229 // This class cannot open urls until startup has finished. The urls that cannot
230 // be opened are cached in |startupUrls_|. This method must be called exactly
231 // once after startup has completed. It opens the urls in |startupUrls_|, and
232 // clears |startupUrls_|.
233 - (void)openStartupUrls;
235 // Opens a tab for each GURL in |urls|. If there is exactly one tab open before
236 // this method is called, and that tab is the NTP, then this method closes the
237 // NTP after all the |urls| have been opened.
238 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
240 // Whether instances of this class should use the Handoff feature.
241 - (BOOL)shouldUseHandoff;
243 // This method passes |handoffURL| to |handoffManager_|.
244 - (void)passURLToHandoffManager:(const GURL&)handoffURL;
246 // Lazily creates the Handoff Manager. Updates the state of the Handoff
247 // Manager. This method is idempotent. This should be called:
248 // - During initialization.
249 // - When the current tab navigates to a new URL.
250 // - When the active browser changes.
251 // - When the active browser's active tab switches.
252 // |webContents| should be the new, active WebContents.
253 - (void)updateHandoffManager:(content::WebContents*)webContents;
255 // Given |webContents|, extracts a GURL to be used for Handoff. This may return
256 // the empty GURL.
257 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
258 @end
260 class AppControllerProfileObserver : public ProfileInfoCacheObserver {
261  public:
262   AppControllerProfileObserver(
263       ProfileManager* profile_manager, AppController* app_controller)
264       : profile_manager_(profile_manager),
265         app_controller_(app_controller) {
266     DCHECK(profile_manager_);
267     DCHECK(app_controller_);
268     profile_manager_->GetProfileInfoCache().AddObserver(this);
269   }
271   ~AppControllerProfileObserver() override {
272     DCHECK(profile_manager_);
273     profile_manager_->GetProfileInfoCache().RemoveObserver(this);
274   }
276  private:
277   // ProfileInfoCacheObserver implementation:
279   void OnProfileAdded(const base::FilePath& profile_path) override {}
281   void OnProfileWasRemoved(const base::FilePath& profile_path,
282                            const base::string16& profile_name) override {
283     // When a profile is deleted we need to notify the AppController,
284     // so it can correctly update its pointer to the last used profile.
285     [app_controller_ profileWasRemoved:profile_path];
286   }
288   void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
290   void OnProfileNameChanged(const base::FilePath& profile_path,
291                             const base::string16& old_profile_name) override {}
293   void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
295   ProfileManager* profile_manager_;
297   AppController* app_controller_;  // Weak; owns us.
299   DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
302 @implementation AppController
304 @synthesize startupComplete = startupComplete_;
306 + (void)updateSigninItem:(id)signinItem
307               shouldShow:(BOOL)showSigninMenuItem
308           currentProfile:(Profile*)profile {
309   DCHECK([signinItem isKindOfClass:[NSMenuItem class]]);
310   NSMenuItem* signinMenuItem = static_cast<NSMenuItem*>(signinItem);
312   // Look for a separator immediately after the menu item so it can be hidden
313   // or shown appropriately along with the signin menu item.
314   NSMenuItem* followingSeparator = nil;
315   NSMenu* menu = [signinItem menu];
316   if (menu) {
317     NSInteger signinItemIndex = [menu indexOfItem:signinMenuItem];
318     DCHECK_NE(signinItemIndex, -1);
319     if ((signinItemIndex + 1) < [menu numberOfItems]) {
320       NSMenuItem* menuItem = [menu itemAtIndex:(signinItemIndex + 1)];
321       if ([menuItem isSeparatorItem]) {
322         followingSeparator = menuItem;
323       }
324     }
325   }
327   base::string16 label = signin_ui_util::GetSigninMenuLabel(profile);
328   [signinMenuItem setTitle:l10n_util::FixUpWindowsStyleLabel(label)];
329   [signinMenuItem setHidden:!showSigninMenuItem];
330   [followingSeparator setHidden:!showSigninMenuItem];
333 - (void)dealloc {
334   [[closeTabMenuItem_ menu] setDelegate:nil];
335   [super dealloc];
338 // This method is called very early in application startup (ie, before
339 // the profile is loaded or any preferences have been registered). Defer any
340 // user-data initialization until -applicationDidFinishLaunching:.
341 - (void)awakeFromNib {
342   MacStartupProfiler::GetInstance()->Profile(
343       MacStartupProfiler::AWAKE_FROM_NIB);
344   // We need to register the handlers early to catch events fired on launch.
345   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
346   [em setEventHandler:self
347           andSelector:@selector(getUrl:withReply:)
348         forEventClass:kInternetEventClass
349            andEventID:kAEGetURL];
350   [em setEventHandler:self
351           andSelector:@selector(getUrl:withReply:)
352         forEventClass:'WWW!'    // A particularly ancient AppleEvent that dates
353            andEventID:'OURL'];  // back to the Spyglass days.
355   NSNotificationCenter* notificationCenter =
356       [NSNotificationCenter defaultCenter];
357   [notificationCenter
358       addObserver:self
359          selector:@selector(windowDidResignKey:)
360              name:NSWindowDidResignKeyNotification
361            object:nil];
362   [notificationCenter
363       addObserver:self
364          selector:@selector(windowDidBecomeMain:)
365              name:NSWindowDidBecomeMainNotification
366            object:nil];
367   [notificationCenter
368       addObserver:self
369          selector:@selector(windowDidResignMain:)
370              name:NSWindowDidResignMainNotification
371            object:nil];
373   // Register for space change notifications.
374   [[[NSWorkspace sharedWorkspace] notificationCenter]
375     addObserver:self
376        selector:@selector(activeSpaceDidChange:)
377            name:NSWorkspaceActiveSpaceDidChangeNotification
378          object:nil];
380   [[[NSWorkspace sharedWorkspace] notificationCenter]
381       addObserver:self
382          selector:@selector(willPowerOff:)
383              name:NSWorkspaceWillPowerOffNotification
384            object:nil];
386   // Set up the command updater for when there are no windows open
387   [self initMenuState];
389   // Initialize the Profile menu.
390   [self initProfileMenu];
393 - (void)unregisterEventHandlers {
394   NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
395   [em removeEventHandlerForEventClass:kInternetEventClass
396                            andEventID:kAEGetURL];
397   [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
398                            andEventID:cloud_print::kAECloudPrintClass];
399   [em removeEventHandlerForEventClass:'WWW!'
400                            andEventID:'OURL'];
401   [[NSNotificationCenter defaultCenter] removeObserver:self];
402   [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
405 // (NSApplicationDelegate protocol) This is the Apple-approved place to override
406 // the default handlers.
407 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
408   MacStartupProfiler::GetInstance()->Profile(
409       MacStartupProfiler::WILL_FINISH_LAUNCHING);
412 - (void)applicationWillHide:(NSNotification*)notification {
413   apps::ExtensionAppShimHandler::OnChromeWillHide();
416 - (BOOL)tryToTerminateApplication:(NSApplication*)app {
417   // Reset this now that we've received the call to terminate.
418   BOOL isPoweringOff = isPoweringOff_;
419   isPoweringOff_ = NO;
421   // Check for in-process downloads, and prompt the user if they really want
422   // to quit (and thus cancel downloads). Only check if we're not already
423   // shutting down, else the user might be prompted multiple times if the
424   // download isn't stopped before terminate is called again.
425   if (!browser_shutdown::IsTryingToQuit() &&
426       ![self shouldQuitWithInProgressDownloads])
427     return NO;
429   // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
430   // them in, but I'm not sure about UX; we'd also want to disable other things
431   // though.) http://crbug.com/40861
433   // Check if the user really wants to quit by employing the confirm-to-quit
434   // mechanism.
435   if (!browser_shutdown::IsTryingToQuit() &&
436       [self applicationShouldTerminate:app] != NSTerminateNow)
437     return NO;
439   // Check for active apps. If quitting is prevented, only close browsers and
440   // sessions.
441   if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
442       quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
443     if (base::CommandLine::ForCurrentProcess()->HasSwitch(
444             switches::kHostedAppQuitNotification)) {
445       return NO;
446     }
448     content::NotificationService::current()->Notify(
449         chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
450         content::NotificationService::AllSources(),
451         content::NotificationService::NoDetails());
452     // This will close all browser sessions.
453     chrome::CloseAllBrowsers();
454     return NO;
455   }
457   size_t num_browsers = chrome::GetTotalBrowserCount();
459   // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
460   // already shutting down.
461   if (!browser_shutdown::IsTryingToQuit()) {
462     content::NotificationService::current()->Notify(
463         chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
464         content::NotificationService::AllSources(),
465         content::NotificationService::NoDetails());
466     chrome::CloseAllBrowsersAndQuit();
467   }
469   return num_browsers == 0 ? YES : NO;
472 - (void)stopTryingToTerminateApplication:(NSApplication*)app {
473   if (browser_shutdown::IsTryingToQuit()) {
474     // Reset the "trying to quit" state, so that closing all browser windows
475     // will no longer lead to termination.
476     browser_shutdown::SetTryingToQuit(false);
478     // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
479     // would have to reinstall them here. http://crbug.com/40861
480   }
483 - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
484   // If there are no windows, quit immediately.
485   if (chrome::BrowserIterator().done() &&
486       !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
487     return NSTerminateNow;
488   }
490   // Check if the preference is turned on.
491   const PrefService* prefs = g_browser_process->local_state();
492   if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
493     confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
494     return NSTerminateNow;
495   }
497   // If the application is going to terminate as the result of a Cmd+Q
498   // invocation, use the special sauce to prevent accidental quitting.
499   // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
501   // This logic is only for keyboard-initiated quits.
502   if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
503     return NSTerminateNow;
505   return [[ConfirmQuitPanelController sharedController]
506       runModalLoopForApplication:app];
509 // Called when the app is shutting down. Clean-up as appropriate.
510 - (void)applicationWillTerminate:(NSNotification*)aNotification {
511   // There better be no browser windows left at this point.
512   CHECK_EQ(0u, chrome::GetTotalBrowserCount());
514   // Tell BrowserList not to keep the browser process alive. Once all the
515   // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
516   chrome::DecrementKeepAliveCount();
518   // Reset all pref watching, as this object outlives the prefs system.
519   profilePrefRegistrar_.reset();
520   localPrefRegistrar_.RemoveAll();
522   [self unregisterEventHandlers];
524   appShimMenuController_.reset();
526   STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
527                                        profileBookmarkMenuBridgeMap_.end());
530 - (void)didEndMainMessageLoop {
531   DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
532                                         chrome::HOST_DESKTOP_TYPE_NATIVE));
533   if (!chrome::GetBrowserCount([self lastProfile],
534                                chrome::HOST_DESKTOP_TYPE_NATIVE)) {
535     // As we're shutting down, we need to nuke the TabRestoreService, which
536     // will start the shutdown of the NavigationControllers and allow for
537     // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
538     // and may end up crashing when some thread tries to use the IO thread (or
539     // another thread) that is no longer valid.
540     TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
541   }
544 // If the window has a tab controller, make "close window" be cmd-shift-w,
545 // otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
546 // affects whether the shift modifier is used.
547 - (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
548   [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
549                                                                    @"w")];
550   [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
553 // If the window has a tab controller, make "close tab" take over cmd-w,
554 // otherwise it shouldn't have any key-equivalent because it should be disabled.
555 - (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
556   if (enableCloseTabShortcut) {
557     [closeTabMenuItem_ setKeyEquivalent:@"w"];
558     [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
559   } else {
560     [closeTabMenuItem_ setKeyEquivalent:@""];
561     [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
562   }
565 // See if the focused window window has tabs, and adjust the key equivalents for
566 // Close Tab/Close Window accordingly.
567 - (void)menuNeedsUpdate:(NSMenu*)menu {
568   DCHECK(menu == [closeTabMenuItem_ menu]);
570   BOOL enableCloseTabShortcut = NO;
571   id target = [NSApp targetForAction:@selector(performClose:)];
573   // |target| is an instance of NSPopover or NSWindow.
574   // If a popover (likely the dictionary lookup popover), we want Cmd-W to
575   // close the popover so map it to "Close Window".
576   // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
577   if ([target isKindOfClass:[NSWindow class]]) {
578     NSWindow* window = target;
579     NSWindow* mainWindow = [NSApp mainWindow];
580     if (!window || ([window parentWindow] == mainWindow)) {
581       // If the target window is a child of the main window (e.g. a bubble), the
582       // main window should be the one that handles the close menu item action.
583       window = mainWindow;
584     }
585     Browser* browser = chrome::FindBrowserWithWindow(window);
586     enableCloseTabShortcut = browser && browser->is_type_tabbed();
587   }
589   [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
590   [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
593 - (void)windowDidResignKey:(NSNotification*)notify {
594   // If a window is closed, this notification is fired but |[NSApp keyWindow]|
595   // returns nil regardless of whether any suitable candidates for the key
596   // window remain. It seems that the new key window for the app is not set
597   // until after this notification is fired, so a check is performed after the
598   // run loop is allowed to spin.
599   [self performSelector:@selector(checkForAnyKeyWindows)
600              withObject:nil
601              afterDelay:0.0];
604 - (void)windowDidBecomeMain:(NSNotification*)notify {
605   Browser* browser = chrome::FindBrowserWithWindow([notify object]);
606   if (browser)
607     [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
610 - (void)windowDidResignMain:(NSNotification*)notify {
611   if (chrome::GetTotalBrowserCount() == 0) {
612     [self windowChangedToProfile:
613         g_browser_process->profile_manager()->GetLastUsedProfile()];
614   }
617 - (void)activeSpaceDidChange:(NSNotification*)notify {
618   if (reopenTime_.is_null() ||
619       ![NSApp isActive] ||
620       (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
621       kWorkspaceChangeTimeoutMs) {
622     return;
623   }
625   // The last applicationShouldHandleReopen:hasVisibleWindows: call
626   // happened during a space change. Now that the change has
627   // completed, raise browser windows.
628   reopenTime_ = base::TimeTicks();
629   std::set<NSWindow*> browserWindows;
630   for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
631     Browser* browser = *iter;
632     browserWindows.insert(browser->window()->GetNativeWindow());
633   }
634   if (!browserWindows.empty()) {
635     ui::FocusWindowSetOnCurrentSpace(browserWindows);
636   }
639 // Called when shutting down or logging out.
640 - (void)willPowerOff:(NSNotification*)notify {
641   // Don't attempt any shutdown here. Cocoa will shortly call
642   // -[BrowserCrApplication terminate:].
643   isPoweringOff_ = YES;
646 - (void)checkForAnyKeyWindows {
647   if ([NSApp keyWindow])
648     return;
650   content::NotificationService::current()->Notify(
651       chrome::NOTIFICATION_NO_KEY_WINDOW,
652       content::NotificationService::AllSources(),
653       content::NotificationService::NoDetails());
656 // If the auto-update interval is not set, make it 5 hours.
657 // Placed here for 2 reasons:
658 // 1) Same spot as other Pref stuff
659 // 2) Try and be friendly by keeping this after app launch
660 - (void)setUpdateCheckInterval {
661 #if defined(GOOGLE_CHROME_BUILD)
662   CFStringRef app = CFSTR("com.google.Keystone.Agent");
663   CFStringRef checkInterval = CFSTR("checkInterval");
664   CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
665   if (!plist) {
666     const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
667     NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
668     CFPreferencesSetAppValue(checkInterval, value, app);
669     CFPreferencesAppSynchronize(app);
670   }
671 #endif
674 - (void)openStartupUrls {
675   DCHECK(startupComplete_);
676   [self openUrlsReplacingNTP:startupUrls_];
677   startupUrls_.clear();
680 - (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
681   if (urls.empty())
682     return;
684   // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
685   // NSApplication is created in MainMessageLoop, and then the shortcut urls
686   // are passed in via Apple events. At this point, the first browser is
687   // already loaded in PreMainMessageLoop. If we initialize NSApplication
688   // before PreMainMessageLoop to capture shortcut URL events, it may cause
689   // more problems because it relies on things created in PreMainMessageLoop
690   // and may break existing message loop design.
692   // If the browser hasn't started yet, just queue up the URLs.
693   if (!startupComplete_) {
694     startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
695     return;
696   }
698   // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
699   // startup urls in new tabs, because the omnibox will stay focused if we
700   // load url in NTP tab.
701   Browser* browser = chrome::GetLastActiveBrowser();
702   int startupIndex = TabStripModel::kNoTab;
703   content::WebContents* startupContent = NULL;
705   if (browser && browser->tab_strip_model()->count() == 1) {
706     startupIndex = browser->tab_strip_model()->active_index();
707     startupContent = browser->tab_strip_model()->GetActiveWebContents();
708   }
710   [self openUrls:urls];
712   if (startupIndex != TabStripModel::kNoTab &&
713       startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
714     browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
715         TabStripModel::CLOSE_NONE);
716   }
719 // This is called after profiles have been loaded and preferences registered.
720 // It is safe to access the default profile here.
721 - (void)applicationDidFinishLaunching:(NSNotification*)notify {
722   MacStartupProfiler::GetInstance()->Profile(
723       MacStartupProfiler::DID_FINISH_LAUNCHING);
724   MacStartupProfiler::GetInstance()->RecordMetrics();
726   // Notify BrowserList to keep the application running so it doesn't go away
727   // when all the browser windows get closed.
728   chrome::IncrementKeepAliveCount();
730   [self setUpdateCheckInterval];
732   // Start managing the menu for app windows. This needs to be done here because
733   // main menu item titles are not yet initialized in awakeFromNib.
734   [self initAppShimMenuController];
736   // If enabled, keep Chrome alive when apps are open instead of quitting all
737   // apps.
738   quitWithAppsController_ = new QuitWithAppsController();
740   // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
741   [[closeTabMenuItem_ menu] setDelegate:self];
743   // Build up the encoding menu, the order of the items differs based on the
744   // current locale (see http://crbug.com/7647 for details).
745   // We need a valid g_browser_process to get the profile which is why we can't
746   // call this from awakeFromNib.
747   NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
748   NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
749   NSMenu* encodingMenu = [encodingMenuItem submenu];
750   EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
751                                                     encodingMenu);
753   // Instantiate the ProfileInfoCache observer so that we can get
754   // notified when a profile is deleted.
755   profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
756       g_browser_process->profile_manager(), self));
758   // Since Chrome is localized to more languages than the OS, tell Cocoa which
759   // menu is the Help so it can add the search item to it.
760   [NSApp setHelpMenu:helpMenu_];
762   // Record the path to the (browser) app bundle; this is used by the app mode
763   // shim.  It has to be done in FILE thread because getting the path requires
764   // I/O.
765   BrowserThread::PostTask(
766       BrowserThread::FILE, FROM_HERE,
767       base::Bind(&RecordLastRunAppBundlePath));
769   // Makes "Services" menu items available.
770   [self registerServicesMenuTypesTo:[notify object]];
772   startupComplete_ = YES;
774   Browser* browser =
775       FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
776   content::WebContents* activeWebContents = nullptr;
777   if (browser)
778     activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
779   [self updateHandoffManager:activeWebContents];
780   [self openStartupUrls];
782   PrefService* localState = g_browser_process->local_state();
783   if (localState) {
784     localPrefRegistrar_.Init(localState);
785     localPrefRegistrar_.Add(
786         prefs::kAllowFileSelectionDialogs,
787         base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
788                    menuState_.get()));
789   }
791   handoff_active_url_observer_bridge_.reset(
792       new HandoffActiveURLObserverBridge(self));
795 // This is called after profiles have been loaded and preferences registered.
796 // It is safe to access the default profile here.
797 - (void)applicationDidBecomeActive:(NSNotification*)notify {
798   content::PluginService::GetInstance()->AppActivated();
801 // Helper function for populating and displaying the in progress downloads at
802 // exit alert panel.
803 - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
804   NSString* titleText = nil;
805   NSString* explanationText = nil;
806   NSString* waitTitle = nil;
807   NSString* exitTitle = nil;
809   // Set the dialog text based on whether or not there are multiple downloads.
810   // Dialog text: warning and explanation.
811   titleText = l10n_util::GetPluralNSStringF(
812       IDS_DOWNLOAD_REMOVE_CONFIRM_TITLE, downloadCount);
813   explanationText = l10n_util::GetPluralNSStringF(
814       IDS_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, downloadCount);
815   // Cancel download and exit button text.
816   exitTitle = l10n_util::GetPluralNSStringF(
817       IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL, downloadCount);
819   // Wait for download button text.
820   waitTitle = l10n_util::GetPluralNSStringF(
821       IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL, downloadCount);
823   // 'waitButton' is the default choice.
824   int choice = NSRunAlertPanel(titleText, @"%@",
825                                waitTitle, exitTitle, nil, explanationText);
826   return choice == NSAlertDefaultReturn ? YES : NO;
829 // Check all profiles for in progress downloads, and if we find any, prompt the
830 // user to see if we should continue to exit (and thus cancel the downloads), or
831 // if we should wait.
832 - (BOOL)shouldQuitWithInProgressDownloads {
833   ProfileManager* profile_manager = g_browser_process->profile_manager();
834   if (!profile_manager)
835     return YES;
837   std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
838   for (size_t i = 0; i < profiles.size(); ++i) {
839     DownloadService* download_service =
840       DownloadServiceFactory::GetForBrowserContext(profiles[i]);
841     DownloadManager* download_manager =
842         (download_service->HasCreatedDownloadManager() ?
843          BrowserContext::GetDownloadManager(profiles[i]) : NULL);
844     if (download_manager &&
845         download_manager->NonMaliciousInProgressCount() > 0) {
846       int downloadCount = download_manager->NonMaliciousInProgressCount();
847       if ([self userWillWaitForInProgressDownloads:downloadCount]) {
848         // Create a new browser window (if necessary) and navigate to the
849         // downloads page if the user chooses to wait.
850         Browser* browser = chrome::FindBrowserWithProfile(
851             profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
852         if (!browser) {
853           browser = new Browser(Browser::CreateParams(
854               profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
855           browser->window()->Show();
856         }
857         DCHECK(browser);
858         chrome::ShowDownloads(browser);
859         return NO;
860       }
862       // User wants to exit.
863       return YES;
864     }
865   }
867   // No profiles or active downloads found, okay to exit.
868   return YES;
871 // Called to determine if we should enable the "restore tab" menu item.
872 // Checks with the TabRestoreService to see if there's anything there to
873 // restore and returns YES if so.
874 - (BOOL)canRestoreTab {
875   TabRestoreService* service =
876       TabRestoreServiceFactory::GetForProfile([self lastProfile]);
877   return service && !service->entries().empty();
880 // Called from the AppControllerProfileObserver every time a profile is deleted.
881 - (void)profileWasRemoved:(const base::FilePath&)profilePath {
882   // If the lastProfile has been deleted, the profile manager has
883   // already loaded a new one, so the pointer needs to be updated;
884   // otherwise we will try to start up a browser window with a pointer
885   // to the old profile.
886   // In a browser test, the application is not brought to the front, so
887   // |lastProfile_| might be null.
888   if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
889     // Force windowChangedToProfile: to set the lastProfile_ and also update the
890     // relevant menuBridge objects.
891     lastProfile_ = nullptr;
892     [self windowChangedToProfile:g_browser_process->profile_manager()->
893         GetLastUsedProfile()];
894   }
896   auto it = profileBookmarkMenuBridgeMap_.find(profilePath);
897   if (it != profileBookmarkMenuBridgeMap_.end()) {
898     delete it->second;
899     profileBookmarkMenuBridgeMap_.erase(it);
900   }
903 // Returns true if there is a modal window (either window- or application-
904 // modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
905 // sheets) will not count as blocking the browser. But things like open/save
906 // dialogs that are window modal will block the browser.
907 - (BOOL)keyWindowIsModal {
908   if ([NSApp modalWindow])
909     return YES;
911   Browser* browser = chrome::GetLastActiveBrowser();
912   return browser &&
913          [[browser->window()->GetNativeWindow() attachedSheet]
914              isKindOfClass:[NSWindow class]];
917 // Called to validate menu items when there are no key windows. All the
918 // items we care about have been set with the |commandDispatch:| action and
919 // a target of FirstResponder in IB. If it's not one of those, let it
920 // continue up the responder chain to be handled elsewhere. We pull out the
921 // tag as the cross-platform constant to differentiate and dispatch the
922 // various commands.
923 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
924   SEL action = [item action];
925   BOOL enable = NO;
926   if (action == @selector(commandDispatch:) ||
927       action == @selector(commandFromDock:)) {
928     NSInteger tag = [item tag];
929     if (menuState_ &&  // NULL in tests.
930         menuState_->SupportsCommand(tag)) {
931       switch (tag) {
932         // The File Menu commands are not automatically disabled by Cocoa when a
933         // dialog sheet obscures the browser window, so we disable several of
934         // them here.  We don't need to include IDC_CLOSE_WINDOW, because
935         // app_controller is only activated when there are no key windows (see
936         // function comment).
937         case IDC_RESTORE_TAB:
938           enable = ![self keyWindowIsModal] && [self canRestoreTab];
939           break;
940         // Browser-level items that open in new tabs should not open if there's
941         // a window- or app-modal dialog.
942         case IDC_OPEN_FILE:
943         case IDC_NEW_TAB:
944         case IDC_SHOW_HISTORY:
945         case IDC_SHOW_BOOKMARK_MANAGER:
946           enable = ![self keyWindowIsModal];
947           break;
948         // Browser-level items that open in new windows.
949         case IDC_TASK_MANAGER:
950           // Allow the user to open a new window if there's a window-modal
951           // dialog.
952           enable = ![self keyWindowIsModal];
953           break;
954         case IDC_SHOW_SYNC_SETUP: {
955           Profile* lastProfile = [self lastProfile];
956           // The profile may be NULL during shutdown -- see
957           // http://code.google.com/p/chromium/issues/detail?id=43048 .
958           //
959           // TODO(akalin,viettrungluu): Figure out whether this method
960           // can be prevented from being called if lastProfile is
961           // NULL.
962           if (!lastProfile) {
963             LOG(WARNING)
964                 << "NULL lastProfile detected -- not doing anything";
965             break;
966           }
967           SigninManager* signin = SigninManagerFactory::GetForProfile(
968               lastProfile->GetOriginalProfile());
969           enable = signin->IsSigninAllowed() && ![self keyWindowIsModal];
970           [AppController updateSigninItem:item
971                                shouldShow:enable
972                            currentProfile:lastProfile];
973           break;
974         }
975 #if defined(GOOGLE_CHROME_BUILD)
976         case IDC_FEEDBACK:
977           enable = NO;
978           break;
979 #endif
980         default:
981           enable = menuState_->IsCommandEnabled(tag) ?
982                    ![self keyWindowIsModal] : NO;
983       }
984     }
985   } else if (action == @selector(terminate:)) {
986     enable = YES;
987   } else if (action == @selector(showPreferences:)) {
988     enable = YES;
989   } else if (action == @selector(orderFrontStandardAboutPanel:)) {
990     enable = YES;
991   } else if (action == @selector(commandFromDock:)) {
992     enable = YES;
993   } else if (action == @selector(toggleConfirmToQuit:)) {
994     [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
995     enable = YES;
996   } else if (action == @selector(toggleDisplayMessageCenter:)) {
997     NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
998     [self updateDisplayMessageCenterPrefMenuItem:menuItem];
999     enable = YES;
1000   } else if (action == @selector(executeApplication:)) {
1001     enable = YES;
1002   }
1003   return enable;
1006 // Called when the user picks a menu item when there are no key windows, or when
1007 // there is no foreground browser window. Calls through to the browser object to
1008 // execute the command. This assumes that the command is supported and doesn't
1009 // check, otherwise it should have been disabled in the UI in
1010 // |-validateUserInterfaceItem:|.
1011 - (void)commandDispatch:(id)sender {
1012   Profile* lastProfile = [self safeLastProfileForNewWindows];
1014   // Handle the case where we're dispatching a command from a sender that's in a
1015   // browser window. This means that the command came from a background window
1016   // and is getting here because the foreground window is not a browser window.
1017   if ([sender respondsToSelector:@selector(window)]) {
1018     id delegate = [[sender window] windowController];
1019     if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
1020       [delegate commandDispatch:sender];
1021       return;
1022     }
1023   }
1025   // Ignore commands during session restore's browser creation.  It uses a
1026   // nested message loop and commands dispatched during this operation cause
1027   // havoc.
1028   if (SessionRestore::IsRestoring(lastProfile) &&
1029       base::MessageLoop::current()->IsNested())
1030     return;
1032   NSInteger tag = [sender tag];
1034   // If there are no browser windows, and we are trying to open a browser
1035   // for a locked profile or the system profile, we have to show the User
1036   // Manager instead as the locked profile needs authentication and the system
1037   // profile cannot have a browser.
1038   if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile()) {
1039     UserManager::Show(base::FilePath(),
1040                       profiles::USER_MANAGER_NO_TUTORIAL,
1041                       profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1042     return;
1043   }
1045   switch (tag) {
1046     case IDC_NEW_TAB:
1047       // Create a new tab in an existing browser window (which we activate) if
1048       // possible.
1049       if (Browser* browser = ActivateBrowser(lastProfile)) {
1050         chrome::ExecuteCommand(browser, IDC_NEW_TAB);
1051         break;
1052       }
1053       // Else fall through to create new window.
1054     case IDC_NEW_WINDOW:
1055       CreateBrowser(lastProfile);
1056       break;
1057     case IDC_FOCUS_LOCATION:
1058       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1059                              IDC_FOCUS_LOCATION);
1060       break;
1061     case IDC_FOCUS_SEARCH:
1062       chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1063                              IDC_FOCUS_SEARCH);
1064       break;
1065     case IDC_NEW_INCOGNITO_WINDOW:
1066       CreateBrowser(lastProfile->GetOffTheRecordProfile());
1067       break;
1068     case IDC_RESTORE_TAB:
1069       // There is only the native desktop on Mac.
1070       chrome::OpenWindowWithRestoredTabs(lastProfile,
1071                                          chrome::HOST_DESKTOP_TYPE_NATIVE);
1072       break;
1073     case IDC_OPEN_FILE:
1074       chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
1075       break;
1076     case IDC_CLEAR_BROWSING_DATA: {
1077       // There may not be a browser open, so use the default profile.
1078       if (Browser* browser = ActivateBrowser(lastProfile)) {
1079         chrome::ShowClearBrowsingDataDialog(browser);
1080       } else {
1081         chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
1082       }
1083       break;
1084     }
1085     case IDC_IMPORT_SETTINGS: {
1086       if (Browser* browser = ActivateBrowser(lastProfile)) {
1087         chrome::ShowImportDialog(browser);
1088       } else {
1089         chrome::OpenImportSettingsDialogWindow(lastProfile);
1090       }
1091       break;
1092     }
1093     case IDC_SHOW_BOOKMARK_MANAGER:
1094       content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
1095       if (Browser* browser = ActivateBrowser(lastProfile)) {
1096         chrome::ShowBookmarkManager(browser);
1097       } else {
1098         // No browser window, so create one for the bookmark manager tab.
1099         chrome::OpenBookmarkManagerWindow(lastProfile);
1100       }
1101       break;
1102     case IDC_SHOW_HISTORY:
1103       if (Browser* browser = ActivateBrowser(lastProfile))
1104         chrome::ShowHistory(browser);
1105       else
1106         chrome::OpenHistoryWindow(lastProfile);
1107       break;
1108     case IDC_SHOW_DOWNLOADS:
1109       if (Browser* browser = ActivateBrowser(lastProfile))
1110         chrome::ShowDownloads(browser);
1111       else
1112         chrome::OpenDownloadsWindow(lastProfile);
1113       break;
1114     case IDC_MANAGE_EXTENSIONS:
1115       if (Browser* browser = ActivateBrowser(lastProfile))
1116         chrome::ShowExtensions(browser, std::string());
1117       else
1118         chrome::OpenExtensionsWindow(lastProfile);
1119       break;
1120     case IDC_HELP_PAGE_VIA_MENU:
1121       if (Browser* browser = ActivateBrowser(lastProfile))
1122         chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
1123       else
1124         chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
1125       break;
1126     case IDC_SHOW_SYNC_SETUP:
1127       if (Browser* browser = ActivateBrowser(lastProfile)) {
1128         chrome::ShowBrowserSigninOrSettings(browser,
1129                                             signin_metrics::SOURCE_MENU);
1130       } else {
1131         chrome::OpenSyncSetupWindow(lastProfile, signin_metrics::SOURCE_MENU);
1132       }
1133       break;
1134     case IDC_TASK_MANAGER:
1135       chrome::OpenTaskManager(NULL);
1136       break;
1137     case IDC_OPTIONS:
1138       [self showPreferences:sender];
1139       break;
1140   }
1143 // Run a (background) application in a new tab.
1144 - (void)executeApplication:(id)sender {
1145   NSInteger tag = [sender tag];
1146   Profile* profile = [self lastProfile];
1147   DCHECK(profile);
1148   BackgroundApplicationListModel applications(profile);
1149   DCHECK(tag >= 0 &&
1150          tag < static_cast<int>(applications.size()));
1151   const extensions::Extension* extension = applications.GetExtension(tag);
1152   BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
1155 // Same as |-commandDispatch:|, but executes commands using a disposition
1156 // determined by the key flags. This will get called in the case where the
1157 // frontmost window is not a browser window, and the user has command-clicked
1158 // a button in a background browser window whose action is
1159 // |-commandDispatchUsingKeyModifiers:|
1160 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1161   DCHECK(sender);
1162   if ([sender respondsToSelector:@selector(window)]) {
1163     id delegate = [[sender window] windowController];
1164     if ([delegate respondsToSelector:
1165             @selector(commandDispatchUsingKeyModifiers:)]) {
1166       [delegate commandDispatchUsingKeyModifiers:sender];
1167     }
1168   }
1171 // NSApplication delegate method called when someone clicks on the dock icon.
1172 // To match standard mac behavior, we should open a new window if there are no
1173 // browser windows.
1174 - (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
1175                     hasVisibleWindows:(BOOL)hasVisibleWindows {
1176   // If the browser is currently trying to quit, don't do anything and return NO
1177   // to prevent AppKit from doing anything.
1178   // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1179   if (browser_shutdown::IsTryingToQuit())
1180     return NO;
1182   // Bring all browser windows to the front. Specifically, this brings them in
1183   // front of any app windows. FocusWindowSet will also unminimize the most
1184   // recently minimized window if no windows in the set are visible.
1185   // If there are any, return here. Otherwise, the windows are panels or
1186   // notifications so we still need to open a new window.
1187   if (hasVisibleWindows) {
1188     std::set<NSWindow*> browserWindows;
1189     for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
1190       Browser* browser = *iter;
1191       // When focusing Chrome, don't focus any browser windows associated with
1192       // a currently running app shim, so ignore them.
1193       if (browser && browser->is_app()) {
1194         extensions::ExtensionRegistry* registry =
1195             extensions::ExtensionRegistry::Get(browser->profile());
1196         const extensions::Extension* extension = registry->GetExtensionById(
1197             web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1198             extensions::ExtensionRegistry::ENABLED);
1199         if (extension && extension->is_hosted_app())
1200           continue;
1201       }
1202       browserWindows.insert(browser->window()->GetNativeWindow());
1203     }
1204     if (!browserWindows.empty()) {
1205       NSWindow* keyWindow = [NSApp keyWindow];
1206       if (keyWindow && ![keyWindow isOnActiveSpace]) {
1207         // The key window is not on the active space. We must be mid-animation
1208         // for a space transition triggered by the dock. Delay the call to
1209         // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1210         // wrong space's windows get raised, resulting in an off-screen key
1211         // window. It does not work to |ui::FocusWindowSet| twice, once here
1212         // and once in |activeSpaceDidChange:|, as that appears to break when
1213         // the omnibox is focused.
1214         //
1215         // This check relies on OS X setting the key window to a window on the
1216         // target space before calling this method.
1217         //
1218         // See http://crbug.com/309656.
1219         reopenTime_ = base::TimeTicks::Now();
1220       } else {
1221         ui::FocusWindowSetOnCurrentSpace(browserWindows);
1222       }
1223       // Return NO; we've done (or soon will do) the deminiaturize, so
1224       // AppKit shouldn't do anything.
1225       return NO;
1226     }
1227   }
1229   // If launched as a hidden login item (due to installation of a persistent app
1230   // or by the user, for example in System Preferences->Accounts->Login Items),
1231   // allow session to be restored first time the user clicks on a Dock icon.
1232   // Normally, it'd just open a new empty page.
1233   {
1234     static BOOL doneOnce = NO;
1235     BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1236         (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1237     doneOnce = YES;
1238     if (attemptRestore) {
1239       SessionService* sessionService =
1240           SessionServiceFactory::GetForProfileForSessionRestore(
1241               [self lastProfile]);
1242       if (sessionService &&
1243           sessionService->RestoreIfNecessary(std::vector<GURL>()))
1244         return NO;
1245     }
1246   }
1248   // Otherwise open a new window.
1249   // If the last profile was locked, we have to open the User Manager, as the
1250   // profile requires authentication. Similarly, because guest mode and system
1251   // profile are implemented as forced incognito, we can't open a new guest
1252   // browser either, so we have to show the User Manager as well.
1253   Profile* lastProfile = [self lastProfile];
1254   if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1255       lastProfile->IsSystemProfile()) {
1256     UserManager::Show(base::FilePath(),
1257                       profiles::USER_MANAGER_NO_TUTORIAL,
1258                       profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1259   } else {
1260     CreateBrowser(lastProfile);
1261   }
1263   // We've handled the reopen event, so return NO to tell AppKit not
1264   // to do anything.
1265   return NO;
1268 - (void)initMenuState {
1269   menuState_.reset(new CommandUpdater(NULL));
1270   menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
1271   menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
1272   menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
1273   menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
1274   menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
1275   menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
1276   menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
1277   menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
1278   menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
1279   menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1280   menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
1281   menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
1282   menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
1283   menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
1284 #if defined(GOOGLE_CHROME_BUILD)
1285   menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
1286 #endif
1287   menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
1288   menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
1291 // Conditionally adds the Profile menu to the main menu bar.
1292 - (void)initProfileMenu {
1293   NSMenu* mainMenu = [NSApp mainMenu];
1294   NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
1296   if (!profiles::IsMultipleProfilesEnabled()) {
1297     [mainMenu removeItem:profileMenu];
1298     return;
1299   }
1301   // The controller will unhide the menu if necessary.
1302   [profileMenu setHidden:YES];
1304   profileMenuController_.reset(
1305       [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
1308 // The Confirm to Quit preference is atypical in that the preference lives in
1309 // the app menu right above the Quit menu item. This method will refresh the
1310 // display of that item depending on the preference state.
1311 - (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1312   // Format the string so that the correct key equivalent is displayed.
1313   NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1314   NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1315       base::SysNSStringToUTF16(acceleratorString));
1316   [item setTitle:title];
1318   const PrefService* prefService = g_browser_process->local_state();
1319   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1320   [item setState:enabled ? NSOnState : NSOffState];
1323 - (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
1324   const PrefService* prefService = g_browser_process->local_state();
1325   bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1326   // The item should be checked if "show icon" is false, since the text reads
1327   // "Hide notification center icon."
1328   [item setState:enabled ? NSOffState : NSOnState];
1331 - (void)registerServicesMenuTypesTo:(NSApplication*)app {
1332   // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1333   // handles requests from services.
1334   NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1335   [app registerServicesMenuSendTypes:types returnTypes:types];
1338 - (Profile*)lastProfile {
1339   // Return the profile of the last-used Browser, if available.
1340   if (lastProfile_)
1341     return lastProfile_;
1343   // On first launch, use the logic that ChromeBrowserMain uses to determine
1344   // the initial profile.
1345   ProfileManager* profile_manager = g_browser_process->profile_manager();
1346   if (!profile_manager)
1347     return NULL;
1349   return profile_manager->GetProfile(
1350       GetStartupProfilePath(profile_manager->user_data_dir(),
1351                             *base::CommandLine::ForCurrentProcess()));
1354 - (Profile*)safeLastProfileForNewWindows {
1355   Profile* profile = [self lastProfile];
1357   // Guest sessions must always be OffTheRecord. Use that when opening windows.
1358   if (profile->IsGuestSession())
1359     return profile->GetOffTheRecordProfile();
1361   return profile;
1364 // Returns true if a browser window may be opened for the last active profile.
1365 - (bool)canOpenNewBrowser {
1366   Profile* profile = [self safeLastProfileForNewWindows];
1368   const PrefService* prefs = g_browser_process->local_state();
1369   return !profile->IsGuestSession() ||
1370          prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1373 // Various methods to open URLs that we get in a native fashion. We use
1374 // StartupBrowserCreator here because on the other platforms, URLs to open come
1375 // through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1376 // to bottleneck the openings through that for uniform handling.
1377 - (void)openUrls:(const std::vector<GURL>&)urls {
1378   if (!startupComplete_) {
1379     startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
1380     return;
1381   }
1383   Browser* browser = chrome::GetLastActiveBrowser();
1384   // if no browser window exists then create one with no tabs to be filled in
1385   if (!browser) {
1386     browser = new Browser(Browser::CreateParams(
1387         [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
1388     browser->window()->Show();
1389   }
1391   base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1392   chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1393       chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1394   StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1395   launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
1398 - (void)getUrl:(NSAppleEventDescriptor*)event
1399      withReply:(NSAppleEventDescriptor*)reply {
1400   NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1401                       stringValue];
1403   GURL gurl(base::SysNSStringToUTF8(urlStr));
1404   std::vector<GURL> gurlVector;
1405   gurlVector.push_back(gurl);
1407   [self openUrlsReplacingNTP:gurlVector];
1410 - (void)application:(NSApplication*)sender
1411           openFiles:(NSArray*)filenames {
1412   std::vector<GURL> gurlVector;
1413   for (NSString* file in filenames) {
1414     GURL gurl =
1415         net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
1416     gurlVector.push_back(gurl);
1417   }
1418   if (!gurlVector.empty())
1419     [self openUrlsReplacingNTP:gurlVector];
1420   else
1421     NOTREACHED() << "Nothing to open!";
1423   [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
1426 // Show the preferences window, or bring it to the front if it's already
1427 // visible.
1428 - (IBAction)showPreferences:(id)sender {
1429   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1430     // Show options tab in the active browser window.
1431     chrome::ShowSettings(browser);
1432   } else if ([self canOpenNewBrowser]) {
1433     // No browser window, so create one for the options tab.
1434     chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
1435   } else {
1436     // No way to create a browser, default to the User Manager.
1437     UserManager::Show(base::FilePath(),
1438                       profiles::USER_MANAGER_NO_TUTORIAL,
1439                       profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
1440   }
1443 - (IBAction)orderFrontStandardAboutPanel:(id)sender {
1444   if (Browser* browser = ActivateBrowser([self lastProfile])) {
1445     chrome::ShowAboutChrome(browser);
1446   } else if ([self canOpenNewBrowser]) {
1447     // No browser window, so create one for the options tab.
1448     chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
1449   } else {
1450     // No way to create a browser, default to the User Manager.
1451     UserManager::Show(base::FilePath(),
1452                       profiles::USER_MANAGER_NO_TUTORIAL,
1453                       profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
1454   }
1457 - (IBAction)toggleConfirmToQuit:(id)sender {
1458   PrefService* prefService = g_browser_process->local_state();
1459   bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1460   prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1463 - (IBAction)toggleDisplayMessageCenter:(id)sender {
1464   PrefService* prefService = g_browser_process->local_state();
1465   bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1466   prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
1469 // Explicitly bring to the foreground when creating new windows from the dock.
1470 - (void)commandFromDock:(id)sender {
1471   [NSApp activateIgnoringOtherApps:YES];
1472   [self commandDispatch:sender];
1475 - (NSMenu*)applicationDockMenu:(NSApplication*)sender {
1476   NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
1477   Profile* profile = [self lastProfile];
1479   BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1480                                                           atOffset:0
1481                                                           fromDock:YES];
1482   if (profilesAdded)
1483     [dockMenu addItem:[NSMenuItem separatorItem]];
1485   NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
1486   base::scoped_nsobject<NSMenuItem> item(
1487       [[NSMenuItem alloc] initWithTitle:titleStr
1488                                  action:@selector(commandFromDock:)
1489                           keyEquivalent:@""]);
1490   [item setTarget:self];
1491   [item setTag:IDC_NEW_WINDOW];
1492   [item setEnabled:[self validateUserInterfaceItem:item]];
1493   [dockMenu addItem:item];
1495   // |profile| can be NULL during unit tests.
1496   if (!profile ||
1497       IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1498           IncognitoModePrefs::DISABLED) {
1499     titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1500     item.reset(
1501         [[NSMenuItem alloc] initWithTitle:titleStr
1502                                    action:@selector(commandFromDock:)
1503                             keyEquivalent:@""]);
1504     [item setTarget:self];
1505     [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1506     [item setEnabled:[self validateUserInterfaceItem:item]];
1507     [dockMenu addItem:item];
1508   }
1510   // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1511   // tests which use the mock in place of the profile-initialized model.
1513   // Avoid breaking unit tests which have no profile.
1514   if (profile) {
1515     BackgroundApplicationListModel applications(profile);
1516     if (applications.size()) {
1517       int position = 0;
1518       NSString* menuStr =
1519           l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1520       base::scoped_nsobject<NSMenu> appMenu(
1521           [[NSMenu alloc] initWithTitle:menuStr]);
1522       for (extensions::ExtensionList::const_iterator cursor =
1523                applications.begin();
1524            cursor != applications.end();
1525            ++cursor, ++position) {
1526         DCHECK_EQ(applications.GetPosition(cursor->get()), position);
1527         NSString* itemStr =
1528             base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
1529         base::scoped_nsobject<NSMenuItem> appItem(
1530             [[NSMenuItem alloc] initWithTitle:itemStr
1531                                        action:@selector(executeApplication:)
1532                                 keyEquivalent:@""]);
1533         [appItem setTarget:self];
1534         [appItem setTag:position];
1535         [appMenu addItem:appItem];
1536       }
1537     }
1538   }
1540   return dockMenu;
1543 - (const std::vector<GURL>&)startupUrls {
1544   return startupUrls_;
1547 - (BookmarkMenuBridge*)bookmarkMenuBridge {
1548   return bookmarkMenuBridge_;
1551 - (HistoryMenuBridge*)historyMenuBridge {
1552   return historyMenuBridge_.get();
1555 - (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1556   workAreaChangeObservers_.AddObserver(observer);
1559 - (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1560   workAreaChangeObservers_.RemoveObserver(observer);
1563 - (void)initAppShimMenuController {
1564   if (!appShimMenuController_)
1565     appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1568 - (void)windowChangedToProfile:(Profile*)profile {
1569   if (lastProfile_ == profile)
1570     return;
1572   // Before tearing down the menu controller bridges, return the history menu to
1573   // its initial state.
1574   if (historyMenuBridge_)
1575     historyMenuBridge_->ResetMenu();
1577   // Rebuild the menus with the new profile.
1578   lastProfile_ = profile;
1580   auto it = profileBookmarkMenuBridgeMap_.find(profile->GetPath());
1581   if (it == profileBookmarkMenuBridgeMap_.end()) {
1582     base::scoped_nsobject<NSMenu> submenu(
1583         [[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu] copy]);
1584     bookmarkMenuBridge_ = new BookmarkMenuBridge(profile, submenu);
1585     profileBookmarkMenuBridgeMap_[profile->GetPath()] = bookmarkMenuBridge_;
1586   } else {
1587     bookmarkMenuBridge_ = it->second;
1588   }
1590   [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] setSubmenu:
1591       bookmarkMenuBridge_->BookmarkMenu()];
1592   // No need to |BuildMenu| here.  It is done lazily upon menu access.
1594   historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1595   historyMenuBridge_->BuildMenu();
1597   chrome::BrowserCommandController::
1598       UpdateSharedCommandsForIncognitoAvailability(
1599           menuState_.get(), lastProfile_);
1600   profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1601   profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1602   profilePrefRegistrar_->Add(
1603       prefs::kIncognitoModeAvailability,
1604       base::Bind(&chrome::BrowserCommandController::
1605                      UpdateSharedCommandsForIncognitoAvailability,
1606                  menuState_.get(),
1607                  lastProfile_));
1610 - (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
1611   // During this callback the working area is not always already updated. Defer.
1612   [self performSelector:@selector(delayedScreenParametersUpdate)
1613              withObject:nil
1614              afterDelay:0];
1617 - (void)delayedScreenParametersUpdate {
1618   FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1619       WorkAreaChanged());
1622 - (BOOL)application:(NSApplication*)application
1623     willContinueUserActivityWithType:(NSString*)userActivityType {
1624   return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1627 - (BOOL)application:(NSApplication*)application
1628     continueUserActivity:(NSUserActivity*)userActivity
1629       restorationHandler:(void (^)(NSArray*))restorationHandler {
1630   if (![userActivity.activityType
1631           isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1632     return NO;
1633   }
1635   NSString* originString = base::mac::ObjCCast<NSString>(
1636       [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1637   handoff::Origin origin = handoff::OriginFromString(originString);
1638   UMA_HISTOGRAM_ENUMERATION(
1639       "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1641   NSURL* url = userActivity.webpageURL;
1642   if (!url)
1643     return NO;
1645   GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1646   std::vector<GURL> gurlVector;
1647   gurlVector.push_back(gurl);
1649   [self openUrlsReplacingNTP:gurlVector];
1650   return YES;
1653 - (void)application:(NSApplication*)application
1654     didFailToContinueUserActivityWithType:(NSString*)userActivityType
1655                                     error:(NSError*)error {
1658 #pragma mark - Handoff Manager
1660 - (BOOL)shouldUseHandoff {
1661   return base::mac::IsOSYosemiteOrLater();
1664 - (void)passURLToHandoffManager:(const GURL&)handoffURL {
1665   [handoffManager_ updateActiveURL:handoffURL];
1668 - (void)updateHandoffManager:(content::WebContents*)webContents {
1669   if (![self shouldUseHandoff])
1670     return;
1672   if (!handoffManager_)
1673     handoffManager_.reset([[HandoffManager alloc] init]);
1675   GURL handoffURL = [self handoffURLFromWebContents:webContents];
1676   [self passURLToHandoffManager:handoffURL];
1679 - (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1680   if (!webContents)
1681     return GURL();
1683   Profile* profile =
1684       Profile::FromBrowserContext(webContents->GetBrowserContext());
1685   if (!profile)
1686     return GURL();
1688   // Handoff is not allowed from an incognito profile. To err on the safe side,
1689   // also disallow Handoff from a guest profile.
1690   if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1691     return GURL();
1693   if (!webContents)
1694     return GURL();
1696   return webContents->GetVisibleURL();
1699 #pragma mark - HandoffActiveURLObserverBridgeDelegate
1701 - (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1702   [self updateHandoffManager:webContents];
1705 @end  // @implementation AppController
1707 //---------------------------------------------------------------------------
1709 namespace app_controller_mac {
1711 bool IsOpeningNewWindow() {
1712   return g_is_opening_new_window;
1715 }  // namespace app_controller_mac