blob: 12b43984496b36e272a8dafe31f2c302521f9e4b [file] [log] [blame]
[email protected]71c0eb92012-01-03 17:57:301// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]1bcdb532009-01-16 17:47:572// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]2c47bc12009-04-10 20:14:005#import "chrome/browser/app_controller_mac.h"
[email protected]1bcdb532009-01-16 17:47:576
[email protected]d630d7d52010-02-21 00:55:117#include "base/auto_reset.h"
[email protected]0b8caad2011-11-28 23:33:278#include "base/bind.h"
[email protected]57750f822009-04-21 21:43:099#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5210#include "base/files/file_path.h"
[email protected]151c4a62011-04-22 04:15:1311#include "base/mac/foundation_util.h"
[email protected]0378bf42011-01-01 18:20:1412#include "base/mac/mac_util.h"
[email protected]2f301672014-06-07 00:58:5213#include "base/mac/sdk_forward_declarations.h"
[email protected]fa1e0e12013-07-18 00:10:1414#include "base/message_loop/message_loop.h"
erikchen96e537d52014-10-28 23:43:1715#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5716#include "base/prefs/pref_service.h"
lgarron9e6dee22014-11-18 01:03:3917#include "base/stl_util.h"
[email protected]3ea1b182013-02-08 22:38:4118#include "base/strings/string_number_conversions.h"
[email protected]3268d7b72013-03-28 17:41:4319#include "base/strings/sys_string_conversions.h"
[email protected]135cb802013-06-09 16:44:2020#include "base/strings/utf_string_conversions.h"
[email protected]1a3aba82010-11-08 23:52:5421#include "chrome/app/chrome_command_ids.h"
tapted63829f72014-09-24 23:50:5022#include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
hashimotoc350c3c2014-09-26 04:51:3623#include "chrome/browser/apps/app_window_registry_util.h"
[email protected]a07676b22011-06-17 16:36:5324#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3325#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0726#include "chrome/browser/browser_process.h"
[email protected]41741a962009-02-18 21:51:3927#include "chrome/browser/browser_shutdown.h"
[email protected]fdf40f3e2013-07-11 23:55:4628#include "chrome/browser/chrome_notification_types.h"
[email protected]2c47bc12009-04-10 20:14:0029#include "chrome/browser/command_updater.h"
[email protected]9bb54ee2011-10-12 17:43:3530#include "chrome/browser/download/download_service.h"
31#include "chrome/browser/download/download_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3232#include "chrome/browser/extensions/extension_service.h"
[email protected]e4a377cf2011-10-05 02:51:4933#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2534#include "chrome/browser/lifetime/application_lifetime.h"
[email protected]7d1aaa62014-07-18 02:21:3035#include "chrome/browser/mac/mac_startup_profiler.h"
treib6f9598012014-11-11 12:21:2436#include "chrome/browser/prefs/incognito_mode_prefs.h"
[email protected]1c62b2f2013-06-28 00:15:0037#include "chrome/browser/profiles/profile_info_cache_observer.h"
[email protected]8ecad5e2010-12-02 21:18:3338#include "chrome/browser/profiles/profile_manager.h"
[email protected]de71ae992013-07-18 03:30:3839#include "chrome/browser/profiles/profiles_state.h"
[email protected]8d4bbdc2012-09-20 21:36:4940#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5041#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1542#include "chrome/browser/sessions/session_service_factory.h"
[email protected]fbc947b2009-06-19 13:28:2443#include "chrome/browser/sessions/tab_restore_service.h"
[email protected]92371eb2011-04-28 11:50:1544#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]074311a2013-02-28 23:14:0945#include "chrome/browser/signin/signin_manager_factory.h"
[email protected]3d27d272013-07-31 03:15:1646#include "chrome/browser/signin/signin_promo.h"
[email protected]f9bc9b92009-11-24 00:55:3547#include "chrome/browser/sync/profile_sync_service.h"
[email protected]40f047972009-11-25 03:54:4048#include "chrome/browser/sync/sync_ui_util.h"
[email protected]ae04f592010-11-18 20:41:3549#include "chrome/browser/ui/browser.h"
[email protected]05454532013-01-22 21:09:0850#include "chrome/browser/ui/browser_command_controller.h"
[email protected]a37d4b02012-06-25 21:56:1051#include "chrome/browser/ui/browser_commands.h"
[email protected]7108d912014-01-30 08:10:4552#include "chrome/browser/ui/browser_dialogs.h"
[email protected]d8748142012-05-16 21:13:4353#include "chrome/browser/ui/browser_finder.h"
[email protected]b4207c42013-02-12 06:44:2054#include "chrome/browser/ui/browser_iterator.h"
[email protected]a13b76f2012-06-20 15:36:2955#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3556#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1257#include "chrome/browser/ui/chrome_pages.h"
[email protected]edb2d032013-08-30 09:03:1758#import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
[email protected]425f7a02014-04-29 01:51:4459#include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
[email protected]7d791652010-12-01 16:34:4960#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
61#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
62#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2663#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4964#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
65#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
erikchen600f7962014-12-12 00:17:3866#include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
[email protected]7d791652010-12-01 16:34:4967#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1368#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]ced445e92014-04-09 21:43:5969#import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4770#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
71#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4972#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]ccfab592013-01-15 06:24:3273#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]3b265312013-01-17 02:49:5574#include "chrome/browser/ui/host_desktop.h"
[email protected]4feb37d92012-07-01 20:22:1375#include "chrome/browser/ui/startup/startup_browser_creator.h"
76#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
mlermane29d0032014-09-24 19:31:2677#include "chrome/browser/ui/user_manager.h"
mitchelljonese59a1612014-12-16 00:34:5978#include "chrome/browser/web_applications/web_app_mac.h"
[email protected]12dc3d42010-02-22 23:37:1279#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3880#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0881#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]ccfab592013-01-15 06:24:3282#include "chrome/common/extensions/extension_constants.h"
[email protected]6c583d32011-08-19 14:46:2283#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4884#include "chrome/common/pref_names.h"
[email protected]024617a2010-08-20 05:08:0585#include "chrome/common/url_constants.h"
[email protected]af39f002014-08-22 10:18:1886#include "chrome/grit/chromium_strings.h"
87#include "chrome/grit/generated_resources.h"
erikchen600f7962014-12-12 00:17:3888#include "components/handoff/handoff_manager.h"
erikchen332265b2014-11-14 19:59:5289#include "components/handoff/handoff_utility.h"
[email protected]7fbd3b12014-04-01 11:19:1690#include "components/signin/core/browser/signin_manager.h"
[email protected]af39f002014-08-22 10:18:1891#include "components/signin/core/common/profile_management_switches.h"
[email protected]c38831a12011-10-28 12:44:4992#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1793#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0794#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1695#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:2096#include "content/public/browser/plugin_service.h"
[email protected]7f6f44c2011-12-14 13:23:3897#include "content/public/browser/user_metrics.h"
[email protected]59b0e602014-01-30 00:41:2498#include "extensions/browser/extension_system.h"
mitchelljonese59a1612014-12-16 00:34:5999#include "extensions/browser/extension_registry.h"
[email protected]d96cf752014-04-09 04:05:28100#include "net/base/filename_util.h"
[email protected]2e29e2232013-07-26 10:40:59101#include "ui/base/cocoa/focus_window_set.h"
[email protected]c051a1b2011-01-21 23:30:17102#include "ui/base/l10n/l10n_util.h"
103#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:44104
mitchelljonese59a1612014-12-16 00:34:59105using apps::AppShimHandler;
106using apps::ExtensionAppShimHandler;
[email protected]e6e30ac2014-01-13 21:24:39107using base::UserMetricsAction;
[email protected]b441a8492012-06-06 14:55:57108using content::BrowserContext;
[email protected]631bb742011-11-02 11:29:39109using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:17110using content::DownloadManager;
[email protected]631bb742011-11-02 11:29:39111
[email protected]d630d7d52010-02-21 00:55:11112namespace {
113
[email protected]ebbe94b2012-01-18 20:11:56114// Declare notification names from the 10.7 SDK.
115#if !defined(MAC_OS_X_VERSION_10_7) || \
116 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
117NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
118NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
119#endif
120
[email protected]d4c811e72013-10-29 21:57:55121// How long we allow a workspace change notification to wait to be
122// associated with a dock activation. The animation lasts 250ms. See
123// applicationShouldHandleReopen:hasVisibleWindows:.
124static const int kWorkspaceChangeTimeoutMs = 500;
125
[email protected]a37d4b02012-06-25 21:56:10126// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03127// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
128// because otherwise the SessionService will try to restore sessions when we
129// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11130bool g_is_opening_new_window = false;
131
132// Activates a browser window having the given profile (the last one active) if
133// possible and returns a pointer to the activate |Browser| or NULL if this was
134// not possible. If the last active browser is minimized (in particular, if
135// there are only minimized windows), it will unminimize it.
136Browser* ActivateBrowser(Profile* profile) {
[email protected]5595ce6d2014-07-24 04:01:13137 Browser* browser = chrome::FindLastActiveWithProfile(
138 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile,
[email protected]694256072012-11-29 13:40:34139 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11140 if (browser)
141 browser->window()->Activate();
142 return browser;
143}
144
145// Creates an empty browser window with the given profile and returns a pointer
146// to the new |Browser|.
147Browser* CreateBrowser(Profile* profile) {
148 {
[email protected]997ec9f2012-11-21 04:44:14149 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]a8e3c532013-02-20 06:03:41150 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11151 }
152
[email protected]f2bc6e92012-10-14 02:08:38153 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11154 CHECK(browser);
155 return browser;
156}
157
158// Activates a browser window having the given profile (the last one active) if
159// possible or creates an empty one if necessary. Returns a pointer to the
160// activated/new |Browser|.
161Browser* ActivateOrCreateBrowser(Profile* profile) {
162 if (Browser* browser = ActivateBrowser(profile))
163 return browser;
164 return CreateBrowser(profile);
165}
166
[email protected]151c4a62011-04-22 04:15:13167CFStringRef BaseBundleID_CFString() {
168 NSString* base_bundle_id =
169 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
170 return base::mac::NSToCFCast(base_bundle_id);
171}
172
[email protected]0b8caad2011-11-28 23:33:27173// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12174// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27175void PrefsSyncCallback() {
176 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
177 LOG(WARNING) << "Error recording application bundle path.";
178}
[email protected]12dc3d42010-02-22 23:37:12179
180// Record the location of the application bundle (containing the main framework)
181// from which Chromium was loaded. This is used by app mode shims to find
182// Chromium.
183void RecordLastRunAppBundlePath() {
184 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
185 // real, user-visible app bundle directory. (The alternatives give either the
186 // framework's path or the initial app's path, which may be an app mode shim
187 // or a unit test.)
[email protected]bf0d26b2013-08-29 03:09:14188 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
189
[email protected]1c958682013-09-17 03:38:13190 base::FilePath app_bundle_path =
[email protected]12dc3d42010-02-22 23:37:12191 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]1c958682013-09-17 03:38:13192 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
193 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
[email protected]b6b72222012-02-11 02:04:13194 CFPreferencesSetAppValue(
195 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
[email protected]1c958682013-09-17 03:38:13196 app_bundle_path_cfstring, BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12197
198 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]df32e89c2012-05-17 17:47:34199 BrowserThread::PostDelayedTask(
200 BrowserThread::FILE, FROM_HERE,
201 base::Bind(&PrefsSyncCallback),
202 base::TimeDelta::FromMilliseconds(1500));
[email protected]12dc3d42010-02-22 23:37:12203}
204
[email protected]7108d912014-01-30 08:10:45205bool IsProfileSignedOut(Profile* profile) {
206 // The signed out status only makes sense at the moment in the context of the
207 // --new-profile-management flag.
208 if (!switches::IsNewProfileManagement())
209 return false;
210 ProfileInfoCache& cache =
211 g_browser_process->profile_manager()->GetProfileInfoCache();
212 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
213 if (profile_index == std::string::npos)
214 return false;
215 return cache.ProfileIsSigninRequiredAtIndex(profile_index);
216}
217
erikchen600f7962014-12-12 00:17:38218} // namespace
[email protected]d630d7d52010-02-21 00:55:11219
erikchen600f7962014-12-12 00:17:38220@interface AppController () <HandoffActiveURLObserverBridgeDelegate>
221
[email protected]88d74942009-01-21 22:04:44222- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46223- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48224- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]e0b0d1ba2014-04-24 03:22:29225- (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16226- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]57750f822009-04-21 21:43:09227- (void)getUrl:(NSAppleEventDescriptor*)event
228 withReply:(NSAppleEventDescriptor*)reply;
[email protected]449dd2f2009-05-27 13:04:00229- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]d4c811e72013-10-29 21:57:55230- (void)activeSpaceDidChange:(NSNotification*)inNotification;
[email protected]dd6ab1282010-07-20 01:07:32231- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21232- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41233- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47234- (void)executeApplication:(id)sender;
[email protected]1c62b2f2013-06-28 00:15:00235- (void)profileWasRemoved:(const base::FilePath&)profilePath;
erikchen19ee3922014-10-31 19:14:22236
237// Opens a tab for each GURL in |urls|.
238- (void)openUrls:(const std::vector<GURL>&)urls;
239
240// This class cannot open urls until startup has finished. The urls that cannot
241// be opened are cached in |startupUrls_|. This method must be called exactly
242// once after startup has completed. It opens the urls in |startupUrls_|, and
243// clears |startupUrls_|.
244- (void)openStartupUrls;
245
246// Opens a tab for each GURL in |urls|. If there is exactly one tab open before
247// this method is called, and that tab is the NTP, then this method closes the
248// NTP after all the |urls| have been opened.
249- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
erikchen600f7962014-12-12 00:17:38250
251// Whether instances of this class should use the Handoff feature.
252- (BOOL)shouldUseHandoff;
253
254// This method passes |handoffURL| to |handoffManager_|.
255- (void)passURLToHandoffManager:(const GURL&)handoffURL;
256
257// Lazily creates the Handoff Manager. Updates the state of the Handoff
258// Manager. This method is idempotent. This should be called:
259// - During initialization.
260// - When the current tab navigates to a new URL.
261// - When the active browser changes.
262// - When the active browser's active tab switches.
263// |webContents| should be the new, active WebContents.
264- (void)updateHandoffManager:(content::WebContents*)webContents;
265
266// Given |webContents|, extracts a GURL to be used for Handoff. This may return
267// the empty GURL.
268- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
[email protected]88d74942009-01-21 22:04:44269@end
[email protected]1bcdb532009-01-16 17:47:57270
[email protected]1c62b2f2013-06-28 00:15:00271class AppControllerProfileObserver : public ProfileInfoCacheObserver {
272 public:
273 AppControllerProfileObserver(
274 ProfileManager* profile_manager, AppController* app_controller)
275 : profile_manager_(profile_manager),
276 app_controller_(app_controller) {
277 DCHECK(profile_manager_);
278 DCHECK(app_controller_);
279 profile_manager_->GetProfileInfoCache().AddObserver(this);
280 }
281
Daniel Chenga542fca2014-10-21 09:51:29282 ~AppControllerProfileObserver() override {
[email protected]1c62b2f2013-06-28 00:15:00283 DCHECK(profile_manager_);
284 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
285 }
286
287 private:
288 // ProfileInfoCacheObserver implementation:
289
Daniel Chenga542fca2014-10-21 09:51:29290 void OnProfileAdded(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00291
Daniel Chenga542fca2014-10-21 09:51:29292 void OnProfileWasRemoved(const base::FilePath& profile_path,
293 const base::string16& profile_name) override {
[email protected]1c62b2f2013-06-28 00:15:00294 // When a profile is deleted we need to notify the AppController,
295 // so it can correctly update its pointer to the last used profile.
296 [app_controller_ profileWasRemoved:profile_path];
297 }
298
Daniel Chenga542fca2014-10-21 09:51:29299 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00300
Daniel Chenga542fca2014-10-21 09:51:29301 void OnProfileNameChanged(const base::FilePath& profile_path,
302 const base::string16& old_profile_name) override {}
[email protected]1c62b2f2013-06-28 00:15:00303
Daniel Chenga542fca2014-10-21 09:51:29304 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00305
306 ProfileManager* profile_manager_;
307
308 AppController* app_controller_; // Weak; owns us.
309
310 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
311};
312
[email protected]1bcdb532009-01-16 17:47:57313@implementation AppController
314
[email protected]caadfca2010-01-22 21:51:21315@synthesize startupComplete = startupComplete_;
316
[email protected]cd63ef62009-05-06 19:41:37317// This method is called very early in application startup (ie, before
318// the profile is loaded or any preferences have been registered). Defer any
319// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44320- (void)awakeFromNib {
[email protected]7d1aaa62014-07-18 02:21:30321 MacStartupProfiler::GetInstance()->Profile(
322 MacStartupProfiler::AWAKE_FROM_NIB);
[email protected]136140c2009-05-19 13:58:25323 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09324 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
325 [em setEventHandler:self
326 andSelector:@selector(getUrl:withReply:)
327 forEventClass:kInternetEventClass
328 andEventID:kAEGetURL];
329 [em setEventHandler:self
330 andSelector:@selector(getUrl:withReply:)
331 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
332 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37333
[email protected]449dd2f2009-05-27 13:04:00334 // Register for various window layering changes. We use these to update
335 // various UI elements (command-key equivalents, etc) when the frontmost
336 // window changes.
337 NSNotificationCenter* notificationCenter =
338 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44339 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00340 addObserver:self
341 selector:@selector(windowLayeringDidChange:)
342 name:NSWindowDidBecomeKeyNotification
343 object:nil];
344 [notificationCenter
345 addObserver:self
346 selector:@selector(windowLayeringDidChange:)
347 name:NSWindowDidResignKeyNotification
348 object:nil];
349 [notificationCenter
350 addObserver:self
351 selector:@selector(windowLayeringDidChange:)
352 name:NSWindowDidBecomeMainNotification
353 object:nil];
354 [notificationCenter
355 addObserver:self
356 selector:@selector(windowLayeringDidChange:)
357 name:NSWindowDidResignMainNotification
358 object:nil];
359
[email protected]ebbe94b2012-01-18 20:11:56360 if (base::mac::IsOSLionOrLater()) {
361 [notificationCenter
362 addObserver:self
363 selector:@selector(popoverDidShow:)
364 name:NSPopoverDidShowNotification
365 object:nil];
366 [notificationCenter
367 addObserver:self
368 selector:@selector(popoverDidClose:)
369 name:NSPopoverDidCloseNotification
370 object:nil];
371 }
372
[email protected]d4c811e72013-10-29 21:57:55373 // Register for space change notifications.
374 [[[NSWorkspace sharedWorkspace] notificationCenter]
375 addObserver:self
376 selector:@selector(activeSpaceDidChange:)
377 name:NSWorkspaceActiveSpaceDidChangeNotification
378 object:nil];
379
jochenbf9420152015-01-13 14:12:57380 [[[NSWorkspace sharedWorkspace] notificationCenter]
381 addObserver:self
382 selector:@selector(willPowerOff:)
383 name:NSWorkspaceWillPowerOffNotification
384 object:nil];
385
[email protected]136140c2009-05-19 13:58:25386 // Set up the command updater for when there are no windows open
387 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46388
389 // Initialize the Profile menu.
390 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25391}
392
[email protected]71c0eb92012-01-03 17:57:30393- (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];
[email protected]71c0eb92012-01-03 17:57:30399 [em removeEventHandlerForEventClass:'WWW!'
400 andEventID:'OURL'];
401 [[NSNotificationCenter defaultCenter] removeObserver:self];
[email protected]d4c811e72013-10-29 21:57:55402 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[email protected]71c0eb92012-01-03 17:57:30403}
404
[email protected]7dc8c6b2010-04-09 17:02:50405// (NSApplicationDelegate protocol) This is the Apple-approved place to override
406// the default handlers.
407- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]7d1aaa62014-07-18 02:21:30408 MacStartupProfiler::GetInstance()->Profile(
409 MacStartupProfiler::WILL_FINISH_LAUNCHING);
[email protected]7dc8c6b2010-04-09 17:02:50410}
411
[email protected]8a5bd59042014-07-22 04:10:06412- (void)applicationWillHide:(NSNotification*)notification {
413 apps::ExtensionAppShimHandler::OnChromeWillHide();
414}
415
[email protected]7dc8c6b2010-04-09 17:02:50416- (BOOL)tryToTerminateApplication:(NSApplication*)app {
jochenbf9420152015-01-13 14:12:57417 // Reset this now that we've received the call to terminate.
418 BOOL isPoweringOff = isPoweringOff_;
419 isPoweringOff_ = NO;
420
[email protected]3076fad2010-04-28 18:11:45421 // 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;
428
[email protected]7dc8c6b2010-04-09 17:02:50429 // 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
432
[email protected]177aceb2010-11-03 16:17:41433 // 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;
438
[email protected]70593e52014-05-15 08:30:23439 // Check for active apps. If quitting is prevented, only close browsers and
440 // sessions.
jochenbf9420152015-01-13 14:12:57441 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
442 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
avi3ef9ec9e2014-12-22 22:50:17443 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
mitchelljones3bc6ced2014-12-19 05:01:37444 switches::kHostedAppQuitNotification)) {
445 return NO;
446 }
447
[email protected]70593e52014-05-15 08:30:23448 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 }
456
[email protected]0665ebe2013-02-13 09:53:19457 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50458
[email protected]0c95faf42013-10-28 06:27:20459 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20460 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56461 if (!browser_shutdown::IsTryingToQuit()) {
462 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30463 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56464 content::NotificationService::AllSources(),
465 content::NotificationService::NoDetails());
[email protected]0c95faf42013-10-28 06:27:20466 chrome::CloseAllBrowsersAndQuit();
[email protected]ef61b8c2012-01-20 10:54:56467 }
[email protected]7dc8c6b2010-04-09 17:02:50468
[email protected]c984d9f2010-07-20 20:52:20469 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50470}
471
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);
477
478 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
479 // would have to reinstall them here. http://crbug.com/40861
480 }
[email protected]a9e8afc2009-08-11 22:03:17481}
482
[email protected]177aceb2010-11-03 16:17:41483- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]90a4b9d2013-07-31 12:14:40484 // If there are no windows, quit immediately.
485 if (chrome::BrowserIterator().done() &&
jackhou261f7f32015-01-07 00:59:03486 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
[email protected]90a4b9d2013-07-31 12:14:40487 return NSTerminateNow;
488 }
489
[email protected]a99fce0e2011-03-21 20:58:48490 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26491 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23492 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
493 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41494 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23495 }
[email protected]177aceb2010-11-03 16:17:41496
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
[email protected]177aceb2010-11-03 16:17:41500
[email protected]2020fd0b2010-12-10 01:16:50501 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26502 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50503 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41504
[email protected]5df54fb2011-03-07 18:15:26505 return [[ConfirmQuitPanelController sharedController]
506 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41507}
508
[email protected]449dd2f2009-05-27 13:04:00509// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50510- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50511 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19512 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11513
[email protected]c984d9f2010-07-20 20:52:20514 // 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().
[email protected]9a718b22014-02-25 15:17:27516 chrome::DecrementKeepAliveCount();
[email protected]fbc947b2009-06-19 13:28:24517
[email protected]02a31dd2013-02-05 08:40:52518 // Reset all pref watching, as this object outlives the prefs system.
519 profilePrefRegistrar_.reset();
520 localPrefRegistrar_.RemoveAll();
521
[email protected]71c0eb92012-01-03 17:57:30522 [self unregisterEventHandlers];
[email protected]edb2d032013-08-30 09:03:17523
524 appShimMenuController_.reset();
lgarron9e6dee22014-11-18 01:03:39525
526 STLDeleteContainerPairSecondPointers(profileBookmarkMenuBridgeMap_.begin(),
527 profileBookmarkMenuBridgeMap_.end());
[email protected]449dd2f2009-05-27 13:04:00528}
529
[email protected]3b6aa8b62009-09-15 21:36:11530- (void)didEndMainMessageLoop {
[email protected]c987a242013-02-28 01:17:41531 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)) {
[email protected]3b6aa8b62009-09-15 21:36:11535 // 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.
[email protected]a585a8db2011-06-20 18:58:35540 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11541 }
542}
543
[email protected]8cfbdbd2011-06-16 04:17:17544// 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
[email protected]eddcf7502012-02-09 22:43:48546// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56547- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
548 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
549 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17550 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
551}
552
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.
[email protected]ebbe94b2012-01-18 20:11:56555- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
556 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17557 [closeTabMenuItem_ setKeyEquivalent:@"w"];
558 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
559 } else {
560 [closeTabMenuItem_ setKeyEquivalent:@""];
561 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
562 }
563}
564
565// Explicitly remove any command-key equivalents from the close tab/window
566// menus so that nothing can go haywire if we get a user action during pending
567// updates.
568- (void)clearCloseMenuItemKeyEquivalents {
569 [closeTabMenuItem_ setKeyEquivalent:@""];
570 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
571 [closeWindowMenuItem_ setKeyEquivalent:@""];
572 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
573}
574
[email protected]9f5f79b62011-10-28 00:43:45575// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17576// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45577- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17578 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17579
[email protected]9f5f79b62011-10-28 00:43:45580 NSWindow* window = [NSApp keyWindow];
581 NSWindow* mainWindow = [NSApp mainWindow];
582 if (!window || ([window parentWindow] == mainWindow)) {
583 // If the key window is a child of the main window (e.g. a bubble), the main
584 // window should be the one that handles the close menu item action.
585 // Also, there might be a small amount of time where there is no key window;
586 // in that case as well, just use our main browser window if there is one.
587 // You might think that we should just always use the main window, but the
588 // "About Chrome" window serves as a counterexample.
589 window = mainWindow;
590 }
591
592 BOOL hasTabs =
593 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56594 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
595 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
596 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17597}
598
599// Fix up the "close tab/close window" command-key equivalents. We do this
600// after a delay to ensure that window layer state has been set by the time
601// we do the enabling. This should only be called on the main thread, code that
602// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45603- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17604 DCHECK([NSThread isMainThread]);
605 if (!fileMenuUpdatePending_) {
606 // The OS prefers keypresses to timers, so it's possible that a cmd-w
607 // can sneak in before this timer fires. In order to prevent that from
608 // having any bad consequences, just clear the keys combos altogether. They
609 // will be reset when the timer eventually fires.
610 if ([NSThread isMainThread]) {
611 fileMenuUpdatePending_ = YES;
612 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45613 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
614 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17615 afterDelay:0];
616 } else {
617 // This shouldn't be happening, but if it does, force it to the main
618 // thread to avoid dropping the update. Don't mess with
619 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
620 // there could be a race between the selector finishing and setting the
621 // flag.
622 [self
[email protected]9f5f79b62011-10-28 00:43:45623 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
624 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17625 waitUntilDone:NO];
626 }
627 }
628}
629
[email protected]449dd2f2009-05-27 13:04:00630// Called when we get a notification about the window layering changing to
631// update the UI based on the new main window.
632- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45633 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17634
[email protected]dd6ab1282010-07-20 01:07:32635 if ([notify name] == NSWindowDidResignKeyNotification) {
636 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
637 // returns nil regardless of whether any suitable candidates for the key
638 // window remain. It seems that the new key window for the app is not set
639 // until after this notification is fired, so a check is performed after the
640 // run loop is allowed to spin.
641 [self performSelector:@selector(checkForAnyKeyWindows)
642 withObject:nil
643 afterDelay:0.0];
644 }
[email protected]5c593702011-06-17 18:35:24645
646 // If the window changed to a new BrowserWindowController, update the profile.
647 id windowController = [[notify object] windowController];
[email protected]fbb04552014-01-16 15:47:38648 if (![windowController isKindOfClass:[BrowserWindowController class]])
649 return;
650
651 if ([notify name] == NSWindowDidBecomeMainNotification) {
[email protected]5c593702011-06-17 18:35:24652 // If the profile is incognito, use the original profile.
653 Profile* newProfile = [windowController profile]->GetOriginalProfile();
654 [self windowChangedToProfile:newProfile];
[email protected]0665ebe2013-02-13 09:53:19655 } else if (chrome::GetTotalBrowserCount() == 0) {
[email protected]cae68b3a2011-11-21 23:29:49656 [self windowChangedToProfile:
657 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24658 }
659}
660
[email protected]d4c811e72013-10-29 21:57:55661- (void)activeSpaceDidChange:(NSNotification*)notify {
662 if (reopenTime_.is_null() ||
663 ![NSApp isActive] ||
664 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
665 kWorkspaceChangeTimeoutMs) {
666 return;
667 }
668
669 // The last applicationShouldHandleReopen:hasVisibleWindows: call
670 // happened during a space change. Now that the change has
671 // completed, raise browser windows.
672 reopenTime_ = base::TimeTicks();
673 std::set<NSWindow*> browserWindows;
674 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
675 Browser* browser = *iter;
676 browserWindows.insert(browser->window()->GetNativeWindow());
677 }
678 if (!browserWindows.empty()) {
[email protected]6c4b79602014-05-28 16:47:21679 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:55680 }
681}
682
jochenbf9420152015-01-13 14:12:57683// Called when shutting down or logging out.
684- (void)willPowerOff:(NSNotification*)notify {
685 // Don't attempt any shutdown here. Cocoa will shortly call
686 // -[BrowserCrApplication terminate:].
687 isPoweringOff_ = YES;
688}
689
[email protected]ebbe94b2012-01-18 20:11:56690// Called on Lion and later when a popover (e.g. dictionary) is shown.
691- (void)popoverDidShow:(NSNotification*)notify {
692 hasPopover_ = YES;
693 [self fixCloseMenuItemKeyEquivalents];
694}
695
696// Called on Lion and later when a popover (e.g. dictionary) is closed.
697- (void)popoverDidClose:(NSNotification*)notify {
698 hasPopover_ = NO;
699 [self fixCloseMenuItemKeyEquivalents];
700}
701
[email protected]dd6ab1282010-07-20 01:07:32702- (void)checkForAnyKeyWindows {
703 if ([NSApp keyWindow])
704 return;
705
[email protected]ad50def52011-10-19 23:17:07706 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30707 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07708 content::NotificationService::AllSources(),
709 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00710}
711
[email protected]414fde592009-05-21 16:14:43712// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43713// Placed here for 2 reasons:
714// 1) Same spot as other Pref stuff
715// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43716- (void)setUpdateCheckInterval {
717#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49718 CFStringRef app = CFSTR("com.google.Keystone.Agent");
719 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43720 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
721 if (!plist) {
722 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50723 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43724 CFPreferencesSetAppValue(checkInterval, value, app);
725 CFPreferencesAppSynchronize(app);
726 }
727#endif
728}
729
[email protected]66791aff2014-04-29 09:45:38730- (void)openStartupUrls {
erikchen19ee3922014-10-31 19:14:22731 DCHECK(startupComplete_);
732 [self openUrlsReplacingNTP:startupUrls_];
733 startupUrls_.clear();
734}
735
736- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
737 if (urls.empty())
738 return;
739
[email protected]66791aff2014-04-29 09:45:38740 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
741 // NSApplication is created in MainMessageLoop, and then the shortcut urls
742 // are passed in via Apple events. At this point, the first browser is
743 // already loaded in PreMainMessageLoop. If we initialize NSApplication
744 // before PreMainMessageLoop to capture shortcut URL events, it may cause
745 // more problems because it relies on things created in PreMainMessageLoop
746 // and may break existing message loop design.
erikchen19ee3922014-10-31 19:14:22747
748 // If the browser hasn't started yet, just queue up the URLs.
749 if (!startupComplete_) {
750 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]66791aff2014-04-29 09:45:38751 return;
erikchen19ee3922014-10-31 19:14:22752 }
[email protected]66791aff2014-04-29 09:45:38753
754 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
755 // startup urls in new tabs, because the omnibox will stay focused if we
756 // load url in NTP tab.
757 Browser* browser = chrome::GetLastActiveBrowser();
758 int startupIndex = TabStripModel::kNoTab;
759 content::WebContents* startupContent = NULL;
760
761 if (browser && browser->tab_strip_model()->count() == 1) {
762 startupIndex = browser->tab_strip_model()->active_index();
763 startupContent = browser->tab_strip_model()->GetActiveWebContents();
764 }
765
erikchen19ee3922014-10-31 19:14:22766 [self openUrls:urls];
[email protected]66791aff2014-04-29 09:45:38767
768 if (startupIndex != TabStripModel::kNoTab &&
769 startupContent->GetVisibleURL() == GURL(chrome::kChromeUINewTabURL)) {
770 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
771 TabStripModel::CLOSE_NONE);
772 }
773}
774
[email protected]136140c2009-05-19 13:58:25775// This is called after profiles have been loaded and preferences registered.
776// It is safe to access the default profile here.
777- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]7d1aaa62014-07-18 02:21:30778 MacStartupProfiler::GetInstance()->Profile(
779 MacStartupProfiler::DID_FINISH_LAUNCHING);
780 MacStartupProfiler::GetInstance()->RecordMetrics();
781
[email protected]c984d9f2010-07-20 20:52:20782 // Notify BrowserList to keep the application running so it doesn't go away
783 // when all the browser windows get closed.
[email protected]9a718b22014-02-25 15:17:27784 chrome::IncrementKeepAliveCount();
[email protected]136140c2009-05-19 13:58:25785
[email protected]414fde592009-05-21 16:14:43786 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53787
[email protected]edb2d032013-08-30 09:03:17788 // Start managing the menu for app windows. This needs to be done here because
789 // main menu item titles are not yet initialized in awakeFromNib.
[email protected]e7dc3992013-11-06 02:16:42790 [self initAppShimMenuController];
[email protected]edb2d032013-08-30 09:03:17791
[email protected]425f7a02014-04-29 01:51:44792 // If enabled, keep Chrome alive when apps are open instead of quitting all
793 // apps.
794 quitWithAppsController_ = new QuitWithAppsController();
795
[email protected]2bcec612009-05-14 17:50:53796 // Build up the encoding menu, the order of the items differs based on the
797 // current locale (see http://crbug.com/7647 for details).
798 // We need a valid g_browser_process to get the profile which is why we can't
799 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14800 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
801 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
802 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35803 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14804 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53805
[email protected]1c62b2f2013-06-28 00:15:00806 // Instantiate the ProfileInfoCache observer so that we can get
807 // notified when a profile is deleted.
808 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
809 g_browser_process->profile_manager(), self));
810
[email protected]f2c20fa2009-12-01 17:42:02811 // Since Chrome is localized to more languages than the OS, tell Cocoa which
812 // menu is the Help so it can add the search item to it.
[email protected]73980132012-07-26 20:09:28813 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02814
[email protected]12dc3d42010-02-22 23:37:12815 // Record the path to the (browser) app bundle; this is used by the app mode
[email protected]bf0d26b2013-08-29 03:09:14816 // shim. It has to be done in FILE thread because getting the path requires
817 // I/O.
818 BrowserThread::PostTask(
819 BrowserThread::FILE, FROM_HERE,
820 base::Bind(&RecordLastRunAppBundlePath));
[email protected]12dc3d42010-02-22 23:37:12821
[email protected]eef99c22010-08-17 05:55:16822 // Makes "Services" menu items available.
823 [self registerServicesMenuTypesTo:[notify object]];
824
[email protected]caadfca2010-01-22 21:51:21825 startupComplete_ = YES;
826
erikchen600f7962014-12-12 00:17:38827 Browser* browser =
828 FindLastActiveWithHostDesktopType(chrome::HOST_DESKTOP_TYPE_NATIVE);
829 content::WebContents* activeWebContents = nullptr;
830 if (browser)
831 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
832 [self updateHandoffManager:activeWebContents];
[email protected]66791aff2014-04-29 09:45:38833 [self openStartupUrls];
[email protected]aac169d2011-03-18 19:53:03834
[email protected]05454532013-01-22 21:09:08835 PrefService* localState = g_browser_process->local_state();
836 if (localState) {
837 localPrefRegistrar_.Init(localState);
838 localPrefRegistrar_.Add(
839 prefs::kAllowFileSelectionDialogs,
840 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
841 menuState_.get()));
842 }
erikchen600f7962014-12-12 00:17:38843
844 handoff_active_url_observer_bridge_.reset(
845 new HandoffActiveURLObserverBridge(self));
[email protected]7c321082009-02-09 15:35:47846}
847
[email protected]a96ec6a2009-11-04 17:27:08848// This is called after profiles have been loaded and preferences registered.
849// It is safe to access the default profile here.
850- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]5904cb42012-09-24 15:05:20851 content::PluginService::GetInstance()->AppActivated();
[email protected]a96ec6a2009-11-04 17:27:08852}
853
[email protected]73f5b362009-08-10 23:58:21854// Helper function for populating and displaying the in progress downloads at
855// exit alert panel.
856- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48857 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13858 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21859 NSString* waitTitle = nil;
860 NSString* exitTitle = nil;
861
862 // Set the dialog text based on whether or not there are multiple downloads.
863 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13864 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48865 titleText = l10n_util::GetNSString(
866 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16867 explanationText = l10n_util::GetNSString(
868 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21869 } else {
[email protected]e8b5f7882009-09-14 20:59:13870 // Dialog text: warning and explanation.
mattm84f8c1672014-09-12 22:08:07871 titleText = l10n_util::GetNSString(
872 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16873 explanationText = l10n_util::GetNSString(
874 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21875 }
[email protected]83a9f652012-04-25 21:03:48876 // Cancel download and exit button text.
877 exitTitle = l10n_util::GetNSString(
878 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
879
880 // Wait for download button text.
881 waitTitle = l10n_util::GetNSString(
882 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21883
884 // 'waitButton' is the default choice.
[email protected]361b47c2013-07-02 15:13:24885 int choice = NSRunAlertPanel(titleText, @"%@",
886 waitTitle, exitTitle, nil, explanationText);
[email protected]73f5b362009-08-10 23:58:21887 return choice == NSAlertDefaultReturn ? YES : NO;
888}
889
890// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41891// user to see if we should continue to exit (and thus cancel the downloads), or
892// if we should wait.
893- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21894 ProfileManager* profile_manager = g_browser_process->profile_manager();
895 if (!profile_manager)
896 return YES;
[email protected]09729a552009-08-03 23:21:41897
[email protected]844a1002011-04-19 11:37:21898 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
899 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35900 DownloadService* download_service =
[email protected]423939d2013-07-31 20:00:08901 DownloadServiceFactory::GetForBrowserContext(profiles[i]);
[email protected]9bb54ee2011-10-12 17:43:35902 DownloadManager* download_manager =
903 (download_service->HasCreatedDownloadManager() ?
[email protected]b441a8492012-06-06 14:55:57904 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
[email protected]422a7d12013-10-21 12:10:42905 if (download_manager &&
906 download_manager->NonMaliciousInProgressCount() > 0) {
907 int downloadCount = download_manager->NonMaliciousInProgressCount();
[email protected]73f5b362009-08-10 23:58:21908 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
909 // Create a new browser window (if necessary) and navigate to the
910 // downloads page if the user chooses to wait.
[email protected]3c6a0952012-12-17 11:56:09911 Browser* browser = chrome::FindBrowserWithProfile(
[email protected]323fd7122012-08-24 14:45:11912 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]73f5b362009-08-10 23:58:21913 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:21914 browser = new Browser(Browser::CreateParams(
915 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]73f5b362009-08-10 23:58:21916 browser->window()->Show();
917 }
918 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12919 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21920 return NO;
921 }
[email protected]09729a552009-08-03 23:21:41922
[email protected]73f5b362009-08-10 23:58:21923 // User wants to exit.
924 return YES;
[email protected]09729a552009-08-03 23:21:41925 }
[email protected]09729a552009-08-03 23:21:41926 }
927
[email protected]73f5b362009-08-10 23:58:21928 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41929 return YES;
930}
931
[email protected]fbc947b2009-06-19 13:28:24932// Called to determine if we should enable the "restore tab" menu item.
933// Checks with the TabRestoreService to see if there's anything there to
934// restore and returns YES if so.
935- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15936 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35937 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24938 return service && !service->entries().empty();
939}
940
[email protected]1c62b2f2013-06-28 00:15:00941// Called from the AppControllerProfileObserver every time a profile is deleted.
942- (void)profileWasRemoved:(const base::FilePath&)profilePath {
943 Profile* lastProfile = [self lastProfile];
944
945 // If the lastProfile has been deleted, the profile manager has
946 // already loaded a new one, so the pointer needs to be updated;
947 // otherwise we will try to start up a browser window with a pointer
948 // to the old profile.
949 if (profilePath == lastProfile->GetPath())
950 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
lgarron9e6dee22014-11-18 01:03:39951
952 Profile* profile =
953 g_browser_process->profile_manager()->GetProfile(profilePath);
954 auto it = profileBookmarkMenuBridgeMap_.find(profile);
955 if (it != profileBookmarkMenuBridgeMap_.end()) {
956 delete it->second;
957 profileBookmarkMenuBridgeMap_.erase(it);
958 }
[email protected]1c62b2f2013-06-28 00:15:00959}
960
[email protected]05454532013-01-22 21:09:08961// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21962// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
963// sheets) will not count as blocking the browser. But things like open/save
964// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08965- (BOOL)keyWindowIsModal {
966 if ([NSApp modalWindow])
967 return YES;
968
[email protected]f2bc6e92012-10-14 02:08:38969 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]05454532013-01-22 21:09:08970 return browser &&
971 [[browser->window()->GetNativeWindow() attachedSheet]
972 isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06973}
974
[email protected]88d74942009-01-21 22:04:44975// Called to validate menu items when there are no key windows. All the
976// items we care about have been set with the |commandDispatch:| action and
977// a target of FirstResponder in IB. If it's not one of those, let it
978// continue up the responder chain to be handled elsewhere. We pull out the
979// tag as the cross-platform constant to differentiate and dispatch the
980// various commands.
981- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
982 SEL action = [item action];
983 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08984 if (action == @selector(commandDispatch:) ||
985 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44986 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08987 if (menuState_ && // NULL in tests.
988 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24989 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26990 // The File Menu commands are not automatically disabled by Cocoa when a
991 // dialog sheet obscures the browser window, so we disable several of
992 // them here. We don't need to include IDC_CLOSE_WINDOW, because
993 // app_controller is only activated when there are no key windows (see
994 // function comment).
[email protected]fbc947b2009-06-19 13:28:24995 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08996 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06997 break;
[email protected]f6c15fa2010-06-04 20:08:21998 // Browser-level items that open in new tabs should not open if there's
999 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:061000 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:061001 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:211002 case IDC_SHOW_HISTORY:
1003 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:081004 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:211005 break;
1006 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:211007 case IDC_TASK_MANAGER:
1008 // Allow the user to open a new window if there's a window-modal
1009 // dialog.
[email protected]05454532013-01-22 21:09:081010 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:241011 break;
[email protected]65549182012-02-25 00:45:401012 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:351013 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:581014 // The profile may be NULL during shutdown -- see
1015 // http://code.google.com/p/chromium/issues/detail?id=43048 .
1016 //
1017 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:351018 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:581019 // NULL.
[email protected]a585a8db2011-06-20 18:58:351020 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:581021 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:351022 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:581023 break;
1024 }
[email protected]074311a2013-02-28 23:14:091025 SigninManager* signin = SigninManagerFactory::GetForProfile(
1026 lastProfile->GetOriginalProfile());
1027 enable = signin->IsSigninAllowed() &&
1028 ![self keyWindowIsModal];
[email protected]6bf51192013-01-18 12:35:251029 [BrowserWindowController updateSigninItem:item
1030 shouldShow:enable
1031 currentProfile:lastProfile];
[email protected]f9bc9b92009-11-24 00:55:351032 break;
[email protected]446e16a2010-05-03 21:23:581033 }
[email protected]236ad3022013-09-04 03:27:431034#if defined(GOOGLE_CHROME_BUILD)
[email protected]acaa37b2011-08-31 07:19:111035 case IDC_FEEDBACK:
1036 enable = NO;
1037 break;
[email protected]236ad3022013-09-04 03:27:431038#endif
[email protected]fbc947b2009-06-19 13:28:241039 default:
[email protected]f6c15fa2010-06-04 20:08:211040 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:081041 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:241042 }
1043 }
[email protected]3b6aa8b62009-09-15 21:36:111044 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:441045 enable = YES;
[email protected]3111f08b2009-04-30 16:01:521046 } else if (action == @selector(showPreferences:)) {
1047 enable = YES;
[email protected]bde3dda2009-05-20 22:13:071048 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
1049 enable = YES;
[email protected]93b59fc2010-12-21 20:00:471050 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:381051 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:481052 } else if (action == @selector(toggleConfirmToQuit:)) {
1053 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
1054 enable = YES;
[email protected]e0b0d1ba2014-04-24 03:22:291055 } else if (action == @selector(toggleDisplayMessageCenter:)) {
1056 NSMenuItem* menuItem = static_cast<NSMenuItem*>(item);
1057 [self updateDisplayMessageCenterPrefMenuItem:menuItem];
1058 enable = YES;
[email protected]3a90b452013-02-15 04:33:481059 } else if (action == @selector(executeApplication:)) {
1060 enable = YES;
[email protected]88d74942009-01-21 22:04:441061 }
1062 return enable;
1063}
1064
[email protected]947fc0d2010-01-14 22:33:051065// Called when the user picks a menu item when there are no key windows, or when
1066// there is no foreground browser window. Calls through to the browser object to
1067// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:111068// check, otherwise it should have been disabled in the UI in
1069// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:441070- (void)commandDispatch:(id)sender {
[email protected]2a39d1a2014-04-10 05:46:241071 Profile* lastProfile = [self safeLastProfileForNewWindows];
[email protected]f0a51fb52009-03-05 12:46:381072
[email protected]947fc0d2010-01-14 22:33:051073 // Handle the case where we're dispatching a command from a sender that's in a
1074 // browser window. This means that the command came from a background window
1075 // and is getting here because the foreground window is not a browser window.
1076 if ([sender respondsToSelector:@selector(window)]) {
1077 id delegate = [[sender window] windowController];
1078 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1079 [delegate commandDispatch:sender];
1080 return;
1081 }
1082 }
1083
[email protected]8d4bbdc2012-09-20 21:36:491084 // Ignore commands during session restore's browser creation. It uses a
1085 // nested message loop and commands dispatched during this operation cause
1086 // havoc.
1087 if (SessionRestore::IsRestoring(lastProfile) &&
[email protected]b3a25092013-05-28 22:08:161088 base::MessageLoop::current()->IsNested())
[email protected]8d4bbdc2012-09-20 21:36:491089 return;
1090
[email protected]88d74942009-01-21 22:04:441091 NSInteger tag = [sender tag];
[email protected]7108d912014-01-30 08:10:451092
1093 // If there are no browser windows, and we are trying to open a browser
1094 // for a locked profile, we have to show the User Manager instead as the
1095 // locked profile needs authentication.
1096 if (IsProfileSignedOut(lastProfile)) {
mlermane6e040a2014-10-31 00:53:211097 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261098 profiles::USER_MANAGER_NO_TUTORIAL,
1099 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
[email protected]7108d912014-01-30 08:10:451100 return;
1101 }
1102
[email protected]88d74942009-01-21 22:04:441103 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:241104 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:111105 // Create a new tab in an existing browser window (which we activate) if
1106 // possible.
[email protected]a585a8db2011-06-20 18:58:351107 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:401108 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:111109 break;
1110 }
1111 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:441112 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:351113 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:111114 break;
[email protected]91a5b3e2009-10-30 19:32:221115 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:401116 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1117 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:441118 break;
[email protected]cddc5242009-12-07 18:54:331119 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:401120 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1121 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:331122 break;
[email protected]863ff662009-01-26 20:18:181123 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:481124 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:181125 break;
[email protected]fbc947b2009-06-19 13:28:241126 case IDC_RESTORE_TAB:
[email protected]3b265312013-01-17 02:49:551127 // There is only the native desktop on Mac.
1128 chrome::OpenWindowWithRestoredTabs(lastProfile,
1129 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]fbc947b2009-06-19 13:28:241130 break;
[email protected]e19516d2009-04-28 17:15:191131 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:401132 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:191133 break;
[email protected]1fdff702009-10-22 00:36:181134 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:381135 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:351136 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121137 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231138 } else {
[email protected]1f0b50b2012-06-22 20:37:161139 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231140 }
[email protected]93e181762009-05-29 14:30:381141 break;
[email protected]1fdff702009-10-22 00:36:181142 }
[email protected]4aee5652009-11-19 18:59:211143 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:351144 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121145 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231146 } else {
[email protected]1f0b50b2012-06-22 20:37:161147 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231148 }
[email protected]4aee5652009-11-19 18:59:211149 break;
1150 }
[email protected]af7c25e2010-01-23 05:46:451151 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:381152 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:351153 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121154 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:471155 } else {
[email protected]47e532b2010-04-23 17:46:401156 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:161157 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:471158 }
[email protected]af7c25e2010-01-23 05:46:451159 break;
[email protected]91a5b3e2009-10-30 19:32:221160 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:351161 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121162 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:111163 else
[email protected]1f0b50b2012-06-22 20:37:161164 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221165 break;
1166 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:351167 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121168 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:111169 else
[email protected]1f0b50b2012-06-22 20:37:161170 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221171 break;
[email protected]bb37e6ec2009-11-18 17:59:361172 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:351173 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:081174 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:111175 else
[email protected]1f0b50b2012-06-22 20:37:161176 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:361177 break;
[email protected]2ca35612012-06-12 03:49:481178 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:351179 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121180 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:111181 else
[email protected]1f0b50b2012-06-22 20:37:161182 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:181183 break;
[email protected]65549182012-02-25 00:45:401184 case IDC_SHOW_SYNC_SETUP:
[email protected]3d27d272013-07-31 03:15:161185 if (Browser* browser = ActivateBrowser(lastProfile)) {
noms5fb66fe2014-12-17 23:01:101186 chrome::ShowBrowserSignin(browser, signin_metrics::SOURCE_MENU);
[email protected]3d27d272013-07-31 03:15:161187 } else {
noms5fb66fe2014-12-17 23:01:101188 chrome::OpenSyncSetupWindow(lastProfile, signin_metrics::SOURCE_MENU);
[email protected]3d27d272013-07-31 03:15:161189 }
[email protected]f9bc9b92009-11-24 00:55:351190 break;
[email protected]ceaaf1812010-01-20 22:13:091191 case IDC_TASK_MANAGER:
mlermane6e040a2014-10-31 00:53:211192 chrome::OpenTaskManager(NULL);
[email protected]ceaaf1812010-01-20 22:13:091193 break;
[email protected]4a42d272010-06-18 01:29:421194 case IDC_OPTIONS:
1195 [self showPreferences:sender];
1196 break;
[email protected]d630d7d52010-02-21 00:55:111197 }
[email protected]88d74942009-01-21 22:04:441198}
1199
[email protected]93b59fc2010-12-21 20:00:471200// Run a (background) application in a new tab.
1201- (void)executeApplication:(id)sender {
1202 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351203 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471204 DCHECK(profile);
1205 BackgroundApplicationListModel applications(profile);
1206 DCHECK(tag >= 0 &&
1207 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341208 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331209 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471210}
1211
[email protected]947fc0d2010-01-14 22:33:051212// Same as |-commandDispatch:|, but executes commands using a disposition
1213// determined by the key flags. This will get called in the case where the
1214// frontmost window is not a browser window, and the user has command-clicked
1215// a button in a background browser window whose action is
1216// |-commandDispatchUsingKeyModifiers:|
1217- (void)commandDispatchUsingKeyModifiers:(id)sender {
1218 DCHECK(sender);
1219 if ([sender respondsToSelector:@selector(window)]) {
1220 id delegate = [[sender window] windowController];
1221 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1222 [delegate commandDispatchUsingKeyModifiers:sender];
1223 }
1224 }
1225}
1226
[email protected]2e29e2232013-07-26 10:40:591227// NSApplication delegate method called when someone clicks on the dock icon.
1228// To match standard mac behavior, we should open a new window if there are no
1229// browser windows.
[email protected]ff81e0a2009-04-13 14:58:541230- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581231 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541232 // If the browser is currently trying to quit, don't do anything and return NO
1233 // to prevent AppKit from doing anything.
1234 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1235 if (browser_shutdown::IsTryingToQuit())
1236 return NO;
1237
[email protected]2e29e2232013-07-26 10:40:591238 // Bring all browser windows to the front. Specifically, this brings them in
1239 // front of any app windows. FocusWindowSet will also unminimize the most
1240 // recently minimized window if no windows in the set are visible.
[email protected]a25920ee2013-09-05 19:38:491241 // If there are any, return here. Otherwise, the windows are panels or
1242 // notifications so we still need to open a new window.
[email protected]bf193bc52013-06-08 04:39:581243 if (hasVisibleWindows) {
[email protected]2e29e2232013-07-26 10:40:591244 std::set<NSWindow*> browserWindows;
[email protected]b4207c42013-02-12 06:44:201245 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
[email protected]0236be22012-01-11 01:05:351246 Browser* browser = *iter;
mitchelljonese59a1612014-12-16 00:34:591247 // When focusing Chrome, don't focus any browser windows associated with
1248 // a currently running app shim, so ignore them.
1249 if (browser && browser->is_app()) {
mitchelljonesf00422082015-01-05 23:38:031250 extensions::ExtensionRegistry* registry =
1251 extensions::ExtensionRegistry::Get(browser->profile());
1252 const extensions::Extension* extension = registry->GetExtensionById(
1253 web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1254 extensions::ExtensionRegistry::ENABLED);
mitchelljonesb118a0c2015-01-07 02:51:341255 if (extension && extension->is_hosted_app())
mitchelljonese59a1612014-12-16 00:34:591256 continue;
mitchelljonese59a1612014-12-16 00:34:591257 }
[email protected]2e29e2232013-07-26 10:40:591258 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]0236be22012-01-11 01:05:351259 }
[email protected]a25920ee2013-09-05 19:38:491260 if (!browserWindows.empty()) {
[email protected]d4c811e72013-10-29 21:57:551261 NSWindow* keyWindow = [NSApp keyWindow];
1262 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1263 // The key window is not on the active space. We must be mid-animation
1264 // for a space transition triggered by the dock. Delay the call to
1265 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1266 // wrong space's windows get raised, resulting in an off-screen key
1267 // window. It does not work to |ui::FocusWindowSet| twice, once here
1268 // and once in |activeSpaceDidChange:|, as that appears to break when
1269 // the omnibox is focused.
1270 //
1271 // This check relies on OS X setting the key window to a window on the
1272 // target space before calling this method.
1273 //
1274 // See http://crbug.com/309656.
1275 reopenTime_ = base::TimeTicks::Now();
1276 } else {
[email protected]6c4b79602014-05-28 16:47:211277 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:551278 }
1279 // Return NO; we've done (or soon will do) the deminiaturize, so
1280 // AppKit shouldn't do anything.
[email protected]a25920ee2013-09-05 19:38:491281 return NO;
1282 }
[email protected]0236be22012-01-11 01:05:351283 }
[email protected]ff81e0a2009-04-13 14:58:541284
[email protected]0d1210d62010-09-07 17:31:381285 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481286 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381287 // allow session to be restored first time the user clicks on a Dock icon.
1288 // Normally, it'd just open a new empty page.
1289 {
[email protected]eddcf7502012-02-09 22:43:481290 static BOOL doneOnce = NO;
[email protected]70593e52014-05-15 08:30:231291 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1292 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1293 doneOnce = YES;
1294 if (attemptRestore) {
1295 SessionService* sessionService =
1296 SessionServiceFactory::GetForProfileForSessionRestore(
1297 [self lastProfile]);
1298 if (sessionService &&
1299 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1300 return NO;
[email protected]eddcf7502012-02-09 22:43:481301 }
[email protected]0d1210d62010-09-07 17:31:381302 }
[email protected]fc44f242012-02-14 16:54:391303
[email protected]ff81e0a2009-04-13 14:58:541304 // Otherwise open a new window.
[email protected]7108d912014-01-30 08:10:451305 // If the last profile was locked, we have to open the User Manager, as the
1306 // profile requires authentication. Similarly, because guest mode is
1307 // implemented as forced incognito, we can't open a new guest browser either,
1308 // so we have to show the User Manager as well.
1309 Profile* lastProfile = [self lastProfile];
mlermane29d0032014-09-24 19:31:261310 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile)) {
mlermane6e040a2014-10-31 00:53:211311 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261312 profiles::USER_MANAGER_NO_TUTORIAL,
1313 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1314 } else {
[email protected]7108d912014-01-30 08:10:451315 CreateBrowser(lastProfile);
mlermane29d0032014-09-24 19:31:261316 }
[email protected]ff81e0a2009-04-13 14:58:541317
1318 // We've handled the reopen event, so return NO to tell AppKit not
1319 // to do anything.
1320 return NO;
1321}
1322
[email protected]88d74942009-01-21 22:04:441323- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521324 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241325 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441326 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181327 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191328 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381329 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241330 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221331 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331332 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451333 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221334 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1335 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361336 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481337 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211338 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]236ad3022013-09-04 03:27:431339#if defined(GOOGLE_CHROME_BUILD)
[email protected]1c41a932010-11-22 23:41:231340 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]236ad3022013-09-04 03:27:431341#endif
[email protected]65549182012-02-25 00:45:401342 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091343 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441344}
[email protected]1bcdb532009-01-16 17:47:571345
[email protected]961a6932011-07-19 19:52:461346// Conditionally adds the Profile menu to the main menu bar.
1347- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461348 NSMenu* mainMenu = [NSApp mainMenu];
1349 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401350
[email protected]de71ae992013-07-18 03:30:381351 if (!profiles::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401352 [mainMenu removeItem:profileMenu];
1353 return;
1354 }
1355
[email protected]6b2d30bc2011-10-11 18:16:391356 // The controller will unhide the menu if necessary.
1357 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461358
[email protected]6b2d30bc2011-10-11 18:16:391359 profileMenuController_.reset(
1360 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461361}
1362
[email protected]a99fce0e2011-03-21 20:58:481363// The Confirm to Quit preference is atypical in that the preference lives in
1364// the app menu right above the Quit menu item. This method will refresh the
1365// display of that item depending on the preference state.
1366- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1367 // Format the string so that the correct key equivalent is displayed.
1368 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1369 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1370 base::SysNSStringToUTF16(acceleratorString));
1371 [item setTitle:title];
1372
[email protected]b6366ffa2012-02-29 17:12:261373 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481374 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1375 [item setState:enabled ? NSOnState : NSOffState];
1376}
1377
[email protected]e0b0d1ba2014-04-24 03:22:291378- (void)updateDisplayMessageCenterPrefMenuItem:(NSMenuItem*)item {
1379 const PrefService* prefService = g_browser_process->local_state();
1380 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1381 // The item should be checked if "show icon" is false, since the text reads
1382 // "Hide notification center icon."
1383 [item setState:enabled ? NSOffState : NSOnState];
1384}
1385
[email protected]eef99c22010-08-17 05:55:161386- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411387 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1388 // handles requests from services.
1389 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1390 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161391}
1392
[email protected]a585a8db2011-06-20 18:58:351393- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231394 // Return the profile of the last-used BrowserWindowController, if available.
1395 if (lastProfile_)
1396 return lastProfile_;
1397
[email protected]fbb04552014-01-16 15:47:381398 // On first launch, use the logic that ChromeBrowserMain uses to determine
1399 // the initial profile.
1400 ProfileManager* profile_manager = g_browser_process->profile_manager();
1401 if (!profile_manager)
1402 return NULL;
[email protected]3f34599d2009-03-25 22:11:431403
avi3ef9ec9e2014-12-22 22:50:171404 return profile_manager->GetProfile(
1405 GetStartupProfilePath(profile_manager->user_data_dir(),
1406 *base::CommandLine::ForCurrentProcess()));
[email protected]3f34599d2009-03-25 22:11:431407}
1408
[email protected]2a39d1a2014-04-10 05:46:241409- (Profile*)safeLastProfileForNewWindows {
1410 Profile* profile = [self lastProfile];
1411
1412 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1413 if (profile->IsGuestSession())
1414 return profile->GetOffTheRecordProfile();
1415
1416 return profile;
1417}
1418
mlermane6e040a2014-10-31 00:53:211419// Returns true if a browser window may be opened for the last active profile.
1420- (bool)canOpenNewBrowser {
1421 Profile* profile = [self safeLastProfileForNewWindows];
1422
1423 const PrefService* prefs = g_browser_process->local_state();
1424 return !profile->IsGuestSession() ||
1425 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1426}
1427
[email protected]57750f822009-04-21 21:43:091428// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031429// StartupBrowserCreator here because on the other platforms, URLs to open come
1430// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1431// to bottleneck the openings through that for uniform handling.
[email protected]d630d7d52010-02-21 00:55:111432- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211433 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111434 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251435 return;
1436 }
[email protected]57750f822009-04-21 21:43:091437
[email protected]f2bc6e92012-10-14 02:08:381438 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]0e863512009-05-28 19:45:071439 // if no browser window exists then create one with no tabs to be filled in
1440 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:211441 browser = new Browser(Browser::CreateParams(
1442 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]ce560f82009-06-03 09:39:441443 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071444 }
1445
avi3ef9ec9e2014-12-22 22:50:171446 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
[email protected]4feb37d92012-07-01 20:22:131447 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1448 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
[email protected]650b2d52013-02-10 03:41:451449 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
[email protected]921071f852013-05-25 03:22:081450 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
[email protected]57750f822009-04-21 21:43:091451}
1452
[email protected]57750f822009-04-21 21:43:091453- (void)getUrl:(NSAppleEventDescriptor*)event
1454 withReply:(NSAppleEventDescriptor*)reply {
1455 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1456 stringValue];
1457
1458 GURL gurl(base::SysNSStringToUTF8(urlStr));
1459 std::vector<GURL> gurlVector;
1460 gurlVector.push_back(gurl);
1461
erikchen19ee3922014-10-31 19:14:221462 [self openUrlsReplacingNTP:gurlVector];
[email protected]57750f822009-04-21 21:43:091463}
1464
[email protected]caadfca2010-01-22 21:51:211465- (void)application:(NSApplication*)sender
1466 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091467 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211468 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451469 GURL gurl =
[email protected]77d83542013-12-13 08:54:291470 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
[email protected]57750f822009-04-21 21:43:091471 gurlVector.push_back(gurl);
1472 }
[email protected]caadfca2010-01-22 21:51:211473 if (!gurlVector.empty())
erikchen19ee3922014-10-31 19:14:221474 [self openUrlsReplacingNTP:gurlVector];
[email protected]caadfca2010-01-22 21:51:211475 else
1476 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091477
[email protected]caadfca2010-01-22 21:51:211478 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091479}
[email protected]3f34599d2009-03-25 22:11:431480
[email protected]3111f08b2009-04-30 16:01:521481// Show the preferences window, or bring it to the front if it's already
1482// visible.
1483- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351484 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051485 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121486 chrome::ShowSettings(browser);
mlermane6e040a2014-10-31 00:53:211487 } else if ([self canOpenNewBrowser]) {
[email protected]445177652011-03-09 02:04:051488 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241489 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211490 } else {
1491 // No way to create a browser, default to the User Manager.
1492 UserManager::Show(base::FilePath(),
1493 profiles::USER_MANAGER_NO_TUTORIAL,
1494 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
[email protected]4a42d272010-06-18 01:29:421495 }
[email protected]d989f07c2009-11-14 00:35:461496}
1497
[email protected]bde3dda2009-05-20 22:13:071498- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561499 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121500 chrome::ShowAboutChrome(browser);
mlermane6e040a2014-10-31 00:53:211501 } else if ([self canOpenNewBrowser]) {
1502 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241503 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211504 } else {
1505 // No way to create a browser, default to the User Manager.
1506 UserManager::Show(base::FilePath(),
1507 profiles::USER_MANAGER_NO_TUTORIAL,
1508 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
[email protected]bde3dda2009-05-20 22:13:071509 }
[email protected]bde3dda2009-05-20 22:13:071510}
1511
[email protected]a99fce0e2011-03-21 20:58:481512- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261513 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481514 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1515 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1516}
1517
[email protected]e0b0d1ba2014-04-24 03:22:291518- (IBAction)toggleDisplayMessageCenter:(id)sender {
1519 PrefService* prefService = g_browser_process->local_state();
1520 bool enabled = prefService->GetBoolean(prefs::kMessageCenterShowIcon);
1521 prefService->SetBoolean(prefs::kMessageCenterShowIcon, !enabled);
1522}
1523
[email protected]3d4bd23f2009-10-06 03:58:381524// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471525- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381526 [NSApp activateIgnoringOtherApps:YES];
1527 [self commandDispatch:sender];
1528}
1529
[email protected]227fcee2010-06-11 19:19:371530- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441531 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351532 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471533
[email protected]646fadbf2012-09-08 01:49:011534 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1535 atOffset:0
1536 fromDock:YES];
1537 if (profilesAdded)
1538 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331539
[email protected]646fadbf2012-09-08 01:49:011540 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461541 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511542 [[NSMenuItem alloc] initWithTitle:titleStr
1543 action:@selector(commandFromDock:)
1544 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461545 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011546 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081547 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011548 [dockMenu addItem:item];
1549
[email protected]8d10a412013-08-09 19:18:001550 // |profile| can be NULL during unit tests.
treib6f9598012014-11-11 12:21:241551 if (!profile ||
1552 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1553 IncognitoModePrefs::DISABLED) {
[email protected]8d10a412013-08-09 19:18:001554 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1555 item.reset(
1556 [[NSMenuItem alloc] initWithTitle:titleStr
1557 action:@selector(commandFromDock:)
1558 keyEquivalent:@""]);
1559 [item setTarget:self];
1560 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1561 [item setEnabled:[self validateUserInterfaceItem:item]];
1562 [dockMenu addItem:item];
1563 }
[email protected]288bfcd32009-09-14 18:14:461564
[email protected]8c6b029d2011-01-21 22:39:511565 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1566 // tests which use the mock in place of the profile-initialized model.
1567
1568 // Avoid breaking unit tests which have no profile.
1569 if (profile) {
1570 BackgroundApplicationListModel applications(profile);
1571 if (applications.size()) {
1572 int position = 0;
1573 NSString* menuStr =
1574 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461575 base::scoped_nsobject<NSMenu> appMenu(
1576 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341577 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481578 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511579 cursor != applications.end();
1580 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501581 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511582 NSString* itemStr =
[email protected]670d3232013-12-24 17:58:581583 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461584 base::scoped_nsobject<NSMenuItem> appItem(
1585 [[NSMenuItem alloc] initWithTitle:itemStr
1586 action:@selector(executeApplication:)
1587 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511588 [appItem setTarget:self];
1589 [appItem setTag:position];
1590 [appMenu addItem:appItem];
1591 }
[email protected]8c6b029d2011-01-21 22:39:511592 }
1593 }
1594
[email protected]018a3962009-09-17 22:23:441595 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461596}
1597
[email protected]d630d7d52010-02-21 00:55:111598- (const std::vector<GURL>&)startupUrls {
1599 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211600}
1601
[email protected]7e4c69d02011-05-11 22:16:471602- (BookmarkMenuBridge*)bookmarkMenuBridge {
lgarron9e6dee22014-11-18 01:03:391603 return bookmarkMenuBridge_;
[email protected]7e4c69d02011-05-11 22:16:471604}
1605
[email protected]33190c82012-04-10 17:04:441606- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1607 workAreaChangeObservers_.AddObserver(observer);
1608}
1609
1610- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1611 workAreaChangeObservers_.RemoveObserver(observer);
1612}
1613
[email protected]e7dc3992013-11-06 02:16:421614- (void)initAppShimMenuController {
[email protected]e4c63ec2014-01-14 15:50:541615 if (!appShimMenuController_)
[email protected]e7dc3992013-11-06 02:16:421616 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1617}
1618
nomsdd5b6a612014-09-23 15:20:161619- (void)windowChangedToProfile:(Profile*)profile {
1620 if (lastProfile_ == profile)
1621 return;
1622
lgarron9e6dee22014-11-18 01:03:391623 // Before tearing down the menu controller bridges, return the history menu to
1624 // its initial state.
1625 if (historyMenuBridge_)
nomsdd5b6a612014-09-23 15:20:161626 historyMenuBridge_->ResetMenu();
1627
1628 // Rebuild the menus with the new profile.
1629 lastProfile_ = profile;
1630
lgarron9e6dee22014-11-18 01:03:391631 auto it = profileBookmarkMenuBridgeMap_.find(profile);
1632 if (it == profileBookmarkMenuBridgeMap_.end()) {
1633 base::scoped_nsobject<NSMenu> submenu(
1634 [[[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu] copy]);
1635 bookmarkMenuBridge_ = new BookmarkMenuBridge(lastProfile_, submenu);
1636 profileBookmarkMenuBridgeMap_[profile] = bookmarkMenuBridge_;
1637 } else {
1638 bookmarkMenuBridge_ = it->second;
1639 }
1640
1641 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] setSubmenu:
1642 bookmarkMenuBridge_->BookmarkMenu()];
nomsdd5b6a612014-09-23 15:20:161643 // No need to |BuildMenu| here. It is done lazily upon menu access.
1644
1645 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1646 historyMenuBridge_->BuildMenu();
1647
1648 chrome::BrowserCommandController::
1649 UpdateSharedCommandsForIncognitoAvailability(
1650 menuState_.get(), lastProfile_);
1651 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1652 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1653 profilePrefRegistrar_->Add(
1654 prefs::kIncognitoModeAvailability,
1655 base::Bind(&chrome::BrowserCommandController::
1656 UpdateSharedCommandsForIncognitoAvailability,
1657 menuState_.get(),
1658 lastProfile_));
1659}
1660
[email protected]ebbe94b2012-01-18 20:11:561661- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281662 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441663 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281664 withObject:nil
1665 afterDelay:0];
1666}
1667
[email protected]33190c82012-04-10 17:04:441668- (void)delayedScreenParametersUpdate {
1669 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1670 WorkAreaChanged());
[email protected]6a455072011-11-02 01:32:281671}
1672
[email protected]92747fe42014-08-18 23:25:261673- (BOOL)application:(NSApplication*)application
1674 willContinueUserActivityWithType:(NSString*)userActivityType {
1675 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1676}
1677
1678- (BOOL)application:(NSApplication*)application
1679 continueUserActivity:(NSUserActivity*)userActivity
1680 restorationHandler:(void (^)(NSArray*))restorationHandler {
1681 if (![userActivity.activityType
1682 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1683 return NO;
1684 }
1685
erikchen96e537d52014-10-28 23:43:171686 NSString* originString = base::mac::ObjCCast<NSString>(
1687 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1688 handoff::Origin origin = handoff::OriginFromString(originString);
1689 UMA_HISTOGRAM_ENUMERATION(
1690 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1691
jiangjc0c568c2014-12-04 19:02:121692 NSURL* url = userActivity.webpageURL;
[email protected]92747fe42014-08-18 23:25:261693 if (!url)
1694 return NO;
1695
1696 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1697 std::vector<GURL> gurlVector;
1698 gurlVector.push_back(gurl);
1699
erikchen19ee3922014-10-31 19:14:221700 [self openUrlsReplacingNTP:gurlVector];
[email protected]92747fe42014-08-18 23:25:261701 return YES;
1702}
1703
1704- (void)application:(NSApplication*)application
1705 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1706 error:(NSError*)error {
1707}
1708
erikchen600f7962014-12-12 00:17:381709#pragma mark - Handoff Manager
1710
1711- (BOOL)shouldUseHandoff {
1712 return base::mac::IsOSYosemiteOrLater();
1713}
1714
1715- (void)passURLToHandoffManager:(const GURL&)handoffURL {
1716 [handoffManager_ updateActiveURL:handoffURL];
1717}
1718
1719- (void)updateHandoffManager:(content::WebContents*)webContents {
1720 if (![self shouldUseHandoff])
1721 return;
1722
1723 if (!handoffManager_)
1724 handoffManager_.reset([[HandoffManager alloc] init]);
1725
1726 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1727 [self passURLToHandoffManager:handoffURL];
1728}
1729
1730- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1731 if (!webContents)
1732 return GURL();
1733
1734 Profile* profile =
1735 Profile::FromBrowserContext(webContents->GetBrowserContext());
1736 if (!profile)
1737 return GURL();
1738
1739 // Handoff is not allowed from an incognito profile. To err on the safe side,
1740 // also disallow Handoff from a guest profile.
1741 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1742 return GURL();
1743
1744 if (!webContents)
1745 return GURL();
1746
1747 return webContents->GetVisibleURL();
1748}
1749
1750#pragma mark - HandoffActiveURLObserverBridgeDelegate
1751
1752- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1753 [self updateHandoffManager:webContents];
1754}
1755
[email protected]d630d7d52010-02-21 00:55:111756@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191757
1758//---------------------------------------------------------------------------
1759
[email protected]216e9042009-10-29 17:05:231760namespace app_controller_mac {
1761
1762bool IsOpeningNewWindow() {
1763 return g_is_opening_new_window;
1764}
1765
1766} // namespace app_controller_mac