blob: 130aedb755183880414239429e3b5388dfc4f087 [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
avie4d7b6f2015-12-26 00:59:187#include <stddef.h>
8
Robert Sesek99845182017-08-24 20:53:339#include "base/allocator/allocator_shim.h"
[email protected]d630d7d52010-02-21 00:55:1110#include "base/auto_reset.h"
[email protected]0b8caad2011-11-28 23:33:2711#include "base/bind.h"
[email protected]57750f822009-04-21 21:43:0912#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5213#include "base/files/file_path.h"
[email protected]151c4a62011-04-22 04:15:1314#include "base/mac/foundation_util.h"
[email protected]0378bf42011-01-01 18:20:1415#include "base/mac/mac_util.h"
Robert Sesek99845182017-08-24 20:53:3316#include "base/mac/scoped_objc_class_swizzler.h"
[email protected]2f301672014-06-07 00:58:5217#include "base/mac/sdk_forward_declarations.h"
avie4d7b6f2015-12-26 00:59:1818#include "base/macros.h"
avi82554752016-09-23 17:48:5019#include "base/memory/ptr_util.h"
asvitkineaa060312016-09-01 22:44:1320#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3721#include "base/metrics/user_metrics.h"
gab7af9dc02017-05-05 13:38:5422#include "base/run_loop.h"
[email protected]3ea1b182013-02-08 22:38:4123#include "base/strings/string_number_conversions.h"
[email protected]3268d7b72013-03-28 17:41:4324#include "base/strings/sys_string_conversions.h"
[email protected]135cb802013-06-09 16:44:2025#include "base/strings/utf_string_conversions.h"
Gabriel Charette66d79ed22017-06-21 17:58:2226#include "base/task_scheduler/post_task.h"
27#include "base/threading/thread_restrictions.h"
[email protected]1a3aba82010-11-08 23:52:5428#include "chrome/app/chrome_command_ids.h"
tapted63829f72014-09-24 23:50:5029#include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
hashimotoc350c3c2014-09-26 04:51:3630#include "chrome/browser/apps/app_window_registry_util.h"
[email protected]a07676b22011-06-17 16:36:5331#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3332#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0733#include "chrome/browser/browser_process.h"
[email protected]41741a962009-02-18 21:51:3934#include "chrome/browser/browser_shutdown.h"
[email protected]fdf40f3e2013-07-11 23:55:4635#include "chrome/browser/chrome_notification_types.h"
[email protected]2c47bc12009-04-10 20:14:0036#include "chrome/browser/command_updater.h"
peterccb33e82017-05-02 19:00:4437#include "chrome/browser/download/download_core_service.h"
38#include "chrome/browser/download/download_core_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3239#include "chrome/browser/extensions/extension_service.h"
[email protected]e4a377cf2011-10-05 02:51:4940#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2541#include "chrome/browser/lifetime/application_lifetime.h"
dgn02377782016-03-12 00:58:3842#include "chrome/browser/lifetime/keep_alive_types.h"
43#include "chrome/browser/lifetime/scoped_keep_alive.h"
[email protected]7d1aaa62014-07-18 02:21:3044#include "chrome/browser/mac/mac_startup_profiler.h"
treib6f9598012014-11-11 12:21:2445#include "chrome/browser/prefs/incognito_mode_prefs.h"
lwchkg9c183942016-03-13 06:29:5446#include "chrome/browser/profiles/profile_attributes_entry.h"
47#include "chrome/browser/profiles/profile_attributes_storage.h"
[email protected]8ecad5e2010-12-02 21:18:3348#include "chrome/browser/profiles/profile_manager.h"
[email protected]de71ae992013-07-18 03:30:3849#include "chrome/browser/profiles/profiles_state.h"
[email protected]8d4bbdc2012-09-20 21:36:4950#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5051#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1552#include "chrome/browser/sessions/session_service_factory.h"
[email protected]92371eb2011-04-28 11:50:1553#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]074311a2013-02-28 23:14:0954#include "chrome/browser/signin/signin_manager_factory.h"
[email protected]3d27d272013-07-31 03:15:1655#include "chrome/browser/signin/signin_promo.h"
estade8c0780f2015-08-21 23:36:4156#include "chrome/browser/signin/signin_ui_util.h"
[email protected]40f047972009-11-25 03:54:4057#include "chrome/browser/sync/sync_ui_util.h"
[email protected]ae04f592010-11-18 20:41:3558#include "chrome/browser/ui/browser.h"
[email protected]05454532013-01-22 21:09:0859#include "chrome/browser/ui/browser_command_controller.h"
[email protected]a37d4b02012-06-25 21:56:1060#include "chrome/browser/ui/browser_commands.h"
[email protected]7108d912014-01-30 08:10:4561#include "chrome/browser/ui/browser_dialogs.h"
[email protected]d8748142012-05-16 21:13:4362#include "chrome/browser/ui/browser_finder.h"
scottmg8abbff832016-01-28 22:57:3763#include "chrome/browser/ui/browser_list.h"
[email protected]a13b76f2012-06-20 15:36:2964#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3565#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1266#include "chrome/browser/ui/chrome_pages.h"
[email protected]edb2d032013-08-30 09:03:1767#import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
[email protected]425f7a02014-04-29 01:51:4468#include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
[email protected]7d791652010-12-01 16:34:4969#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
[email protected]b6366ffa2012-02-29 17:12:2670#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4971#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
erikchen600f7962014-12-12 00:17:3872#include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
[email protected]7d791652010-12-01 16:34:4973#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1374#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]ced445e92014-04-09 21:43:5975#import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
[email protected]ccfab592013-01-15 06:24:3276#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]4feb37d92012-07-01 20:22:1377#include "chrome/browser/ui/startup/startup_browser_creator.h"
78#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
andresantoso55fd2512015-04-01 21:07:0479#include "chrome/browser/ui/tabs/tab_strip_model.h"
mlermane29d0032014-09-24 19:31:2680#include "chrome/browser/ui/user_manager.h"
mitchelljonese59a1612014-12-16 00:34:5981#include "chrome/browser/web_applications/web_app_mac.h"
spqchan210e2ed2017-07-27 23:17:4082#include "chrome/common/chrome_features.h"
[email protected]12dc3d42010-02-22 23:37:1283#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3884#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0885#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]ccfab592013-01-15 06:24:3286#include "chrome/common/extensions/extension_constants.h"
[email protected]6c583d32011-08-19 14:46:2287#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4888#include "chrome/common/pref_names.h"
[email protected]024617a2010-08-20 05:08:0589#include "chrome/common/url_constants.h"
[email protected]af39f002014-08-22 10:18:1890#include "chrome/grit/chromium_strings.h"
91#include "chrome/grit/generated_resources.h"
maxbogue26f40222016-09-16 20:22:1892#include "components/browser_sync/profile_sync_service.h"
erikchen600f7962014-12-12 00:17:3893#include "components/handoff/handoff_manager.h"
erikchen332265b2014-11-14 19:59:5294#include "components/handoff/handoff_utility.h"
brettwb1fc1b82016-02-02 00:19:0895#include "components/prefs/pref_service.h"
blundella08c5dd2015-09-18 06:14:1696#include "components/sessions/core/tab_restore_service.h"
[email protected]7fbd3b12014-04-01 11:19:1697#include "components/signin/core/browser/signin_manager.h"
[email protected]e582fdd2011-12-20 16:48:1798#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0799#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:16100#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:20101#include "content/public/browser/plugin_service.h"
mitchelljonese59a1612014-12-16 00:34:59102#include "extensions/browser/extension_registry.h"
tapted574f09c2015-05-19 13:08:08103#include "extensions/browser/extension_system.h"
[email protected]d96cf752014-04-09 04:05:28104#include "net/base/filename_util.h"
[email protected]2e29e2232013-07-26 10:40:59105#include "ui/base/cocoa/focus_window_set.h"
[email protected]c051a1b2011-01-21 23:30:17106#include "ui/base/l10n/l10n_util.h"
107#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:44108
mitchelljonese59a1612014-12-16 00:34:59109using apps::AppShimHandler;
110using apps::ExtensionAppShimHandler;
[email protected]e6e30ac2014-01-13 21:24:39111using base::UserMetricsAction;
[email protected]b441a8492012-06-06 14:55:57112using content::BrowserContext;
[email protected]e582fdd2011-12-20 16:48:17113using content::DownloadManager;
[email protected]631bb742011-11-02 11:29:39114
[email protected]d630d7d52010-02-21 00:55:11115namespace {
116
[email protected]d4c811e72013-10-29 21:57:55117// How long we allow a workspace change notification to wait to be
118// associated with a dock activation. The animation lasts 250ms. See
119// applicationShouldHandleReopen:hasVisibleWindows:.
120static const int kWorkspaceChangeTimeoutMs = 500;
121
[email protected]a37d4b02012-06-25 21:56:10122// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03123// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
124// because otherwise the SessionService will try to restore sessions when we
125// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11126bool g_is_opening_new_window = false;
127
128// Activates a browser window having the given profile (the last one active) if
129// possible and returns a pointer to the activate |Browser| or NULL if this was
130// not possible. If the last active browser is minimized (in particular, if
131// there are only minimized windows), it will unminimize it.
132Browser* ActivateBrowser(Profile* profile) {
[email protected]5595ce6d2014-07-24 04:01:13133 Browser* browser = chrome::FindLastActiveWithProfile(
scottmg5c03fe022016-02-03 01:27:24134 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile);
[email protected]d630d7d52010-02-21 00:55:11135 if (browser)
136 browser->window()->Activate();
137 return browser;
138}
139
140// Creates an empty browser window with the given profile and returns a pointer
141// to the new |Browser|.
142Browser* CreateBrowser(Profile* profile) {
143 {
[email protected]997ec9f2012-11-21 04:44:14144 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
scottmg851949002016-02-09 20:09:44145 chrome::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11146 }
147
[email protected]f2bc6e92012-10-14 02:08:38148 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11149 CHECK(browser);
150 return browser;
151}
152
153// Activates a browser window having the given profile (the last one active) if
154// possible or creates an empty one if necessary. Returns a pointer to the
155// activated/new |Browser|.
156Browser* ActivateOrCreateBrowser(Profile* profile) {
157 if (Browser* browser = ActivateBrowser(profile))
158 return browser;
159 return CreateBrowser(profile);
160}
161
[email protected]151c4a62011-04-22 04:15:13162CFStringRef BaseBundleID_CFString() {
163 NSString* base_bundle_id =
164 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
165 return base::mac::NSToCFCast(base_bundle_id);
166}
167
[email protected]12dc3d42010-02-22 23:37:12168// Record the location of the application bundle (containing the main framework)
169// from which Chromium was loaded. This is used by app mode shims to find
170// Chromium.
171void RecordLastRunAppBundlePath() {
172 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
173 // real, user-visible app bundle directory. (The alternatives give either the
174 // framework's path or the initial app's path, which may be an app mode shim
175 // or a unit test.)
Gabriel Charette66d79ed22017-06-21 17:58:22176 base::ThreadRestrictions::AssertIOAllowed();
[email protected]bf0d26b2013-08-29 03:09:14177
[email protected]1c958682013-09-17 03:38:13178 base::FilePath app_bundle_path =
[email protected]12dc3d42010-02-22 23:37:12179 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]1c958682013-09-17 03:38:13180 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
181 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
[email protected]b6b72222012-02-11 02:04:13182 CFPreferencesSetAppValue(
183 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
[email protected]1c958682013-09-17 03:38:13184 app_bundle_path_cfstring, BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12185}
186
[email protected]7108d912014-01-30 08:10:45187bool IsProfileSignedOut(Profile* profile) {
lwchkg9c183942016-03-13 06:29:54188 ProfileAttributesEntry* entry;
189 bool has_entry =
190 g_browser_process->profile_manager()->GetProfileAttributesStorage().
191 GetProfileAttributesWithPath(profile->GetPath(), &entry);
192 return has_entry && entry->IsSigninRequired();
[email protected]7108d912014-01-30 08:10:45193}
194
erikchen600f7962014-12-12 00:17:38195} // namespace
[email protected]d630d7d52010-02-21 00:55:11196
erikchen600f7962014-12-12 00:17:38197@interface AppController () <HandoffActiveURLObserverBridgeDelegate>
198
[email protected]88d74942009-01-21 22:04:44199- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46200- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48201- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16202- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]57750f822009-04-21 21:43:09203- (void)getUrl:(NSAppleEventDescriptor*)event
204 withReply:(NSAppleEventDescriptor*)reply;
[email protected]d4c811e72013-10-29 21:57:55205- (void)activeSpaceDidChange:(NSNotification*)inNotification;
[email protected]dd6ab1282010-07-20 01:07:32206- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21207- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41208- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47209- (void)executeApplication:(id)sender;
[email protected]1c62b2f2013-06-28 00:15:00210- (void)profileWasRemoved:(const base::FilePath&)profilePath;
erikchen19ee3922014-10-31 19:14:22211
212// Opens a tab for each GURL in |urls|.
213- (void)openUrls:(const std::vector<GURL>&)urls;
214
erikchen19ee3922014-10-31 19:14:22215// This class cannot open urls until startup has finished. The urls that cannot
216// be opened are cached in |startupUrls_|. This method must be called exactly
217// once after startup has completed. It opens the urls in |startupUrls_|, and
218// clears |startupUrls_|.
219- (void)openStartupUrls;
220
221// Opens a tab for each GURL in |urls|. If there is exactly one tab open before
222// this method is called, and that tab is the NTP, then this method closes the
223// NTP after all the |urls| have been opened.
224- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
erikchen600f7962014-12-12 00:17:38225
226// Whether instances of this class should use the Handoff feature.
227- (BOOL)shouldUseHandoff;
228
229// This method passes |handoffURL| to |handoffManager_|.
230- (void)passURLToHandoffManager:(const GURL&)handoffURL;
231
232// Lazily creates the Handoff Manager. Updates the state of the Handoff
233// Manager. This method is idempotent. This should be called:
234// - During initialization.
235// - When the current tab navigates to a new URL.
236// - When the active browser changes.
237// - When the active browser's active tab switches.
238// |webContents| should be the new, active WebContents.
239- (void)updateHandoffManager:(content::WebContents*)webContents;
240
241// Given |webContents|, extracts a GURL to be used for Handoff. This may return
242// the empty GURL.
243- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
[email protected]88d74942009-01-21 22:04:44244@end
[email protected]1bcdb532009-01-16 17:47:57245
lwchkg9c183942016-03-13 06:29:54246class AppControllerProfileObserver : public ProfileAttributesStorage::Observer {
[email protected]1c62b2f2013-06-28 00:15:00247 public:
248 AppControllerProfileObserver(
249 ProfileManager* profile_manager, AppController* app_controller)
250 : profile_manager_(profile_manager),
251 app_controller_(app_controller) {
252 DCHECK(profile_manager_);
253 DCHECK(app_controller_);
lwchkg9c183942016-03-13 06:29:54254 profile_manager_->GetProfileAttributesStorage().AddObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00255 }
256
Daniel Chenga542fca2014-10-21 09:51:29257 ~AppControllerProfileObserver() override {
[email protected]1c62b2f2013-06-28 00:15:00258 DCHECK(profile_manager_);
lwchkg9c183942016-03-13 06:29:54259 profile_manager_->GetProfileAttributesStorage().RemoveObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00260 }
261
262 private:
lwchkg9c183942016-03-13 06:29:54263 // ProfileAttributesStorage::Observer implementation:
[email protected]1c62b2f2013-06-28 00:15:00264
Daniel Chenga542fca2014-10-21 09:51:29265 void OnProfileAdded(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00266
Daniel Chenga542fca2014-10-21 09:51:29267 void OnProfileWasRemoved(const base::FilePath& profile_path,
268 const base::string16& profile_name) override {
[email protected]1c62b2f2013-06-28 00:15:00269 // When a profile is deleted we need to notify the AppController,
270 // so it can correctly update its pointer to the last used profile.
271 [app_controller_ profileWasRemoved:profile_path];
272 }
273
Daniel Chenga542fca2014-10-21 09:51:29274 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00275
Daniel Chenga542fca2014-10-21 09:51:29276 void OnProfileNameChanged(const base::FilePath& profile_path,
277 const base::string16& old_profile_name) override {}
[email protected]1c62b2f2013-06-28 00:15:00278
Daniel Chenga542fca2014-10-21 09:51:29279 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00280
281 ProfileManager* profile_manager_;
282
283 AppController* app_controller_; // Weak; owns us.
284
285 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
286};
287
Robert Sesek99845182017-08-24 20:53:33288// On macOS 10.12, the IME system attempts to allocate a 2^64 size buffer,
289// which would typically cause an OOM crash. To avoid this, the problematic
290// method is swizzled out and the make-OOM-fatal bit is disabled for the
291// duration of the original call. https://crbug.com/654695
292static base::mac::ScopedObjCClassSwizzler* g_swizzle_imk_input_session;
293
294@interface OOMDisabledIMKInputSession : NSObject
295@end
296
297@implementation OOMDisabledIMKInputSession
298
299- (void)_coreAttributesFromRange:(NSRange)range
300 whichAttributes:(long long)attributes
301 completionHandler:(void (^)(void))block {
302 // The allocator flag is per-process, so other threads may temporarily
303 // not have fatal OOM occur while this method executes, but it is better
304 // than crashing when using IME.
305 base::allocator::SetCallNewHandlerOnMallocFailure(false);
306 g_swizzle_imk_input_session->GetOriginalImplementation()(self, _cmd, range,
307 attributes, block);
308 base::allocator::SetCallNewHandlerOnMallocFailure(true);
309}
310
311@end
312
[email protected]1bcdb532009-01-16 17:47:57313@implementation AppController
314
[email protected]caadfca2010-01-22 21:51:21315@synthesize startupComplete = startupComplete_;
316
andresantoso04f7bab2015-01-15 19:19:16317- (void)dealloc {
318 [[closeTabMenuItem_ menu] setDelegate:nil];
319 [super dealloc];
320}
321
[email protected]cd63ef62009-05-06 19:41:37322// This method is called very early in application startup (ie, before
323// the profile is loaded or any preferences have been registered). Defer any
324// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44325- (void)awakeFromNib {
[email protected]7d1aaa62014-07-18 02:21:30326 MacStartupProfiler::GetInstance()->Profile(
327 MacStartupProfiler::AWAKE_FROM_NIB);
[email protected]136140c2009-05-19 13:58:25328 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09329 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
330 [em setEventHandler:self
331 andSelector:@selector(getUrl:withReply:)
332 forEventClass:kInternetEventClass
333 andEventID:kAEGetURL];
334 [em setEventHandler:self
335 andSelector:@selector(getUrl:withReply:)
336 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
337 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37338
[email protected]449dd2f2009-05-27 13:04:00339 NSNotificationCenter* notificationCenter =
340 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44341 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00342 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16343 selector:@selector(windowDidResignKey:)
[email protected]449dd2f2009-05-27 13:04:00344 name:NSWindowDidResignKeyNotification
345 object:nil];
346 [notificationCenter
347 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16348 selector:@selector(windowDidBecomeMain:)
[email protected]449dd2f2009-05-27 13:04:00349 name:NSWindowDidBecomeMainNotification
350 object:nil];
351 [notificationCenter
352 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16353 selector:@selector(windowDidResignMain:)
[email protected]449dd2f2009-05-27 13:04:00354 name:NSWindowDidResignMainNotification
355 object:nil];
356
[email protected]d4c811e72013-10-29 21:57:55357 // Register for space change notifications.
358 [[[NSWorkspace sharedWorkspace] notificationCenter]
359 addObserver:self
360 selector:@selector(activeSpaceDidChange:)
361 name:NSWorkspaceActiveSpaceDidChangeNotification
362 object:nil];
363
jochenbf9420152015-01-13 14:12:57364 [[[NSWorkspace sharedWorkspace] notificationCenter]
365 addObserver:self
366 selector:@selector(willPowerOff:)
367 name:NSWorkspaceWillPowerOffNotification
368 object:nil];
369
[email protected]136140c2009-05-19 13:58:25370 // Set up the command updater for when there are no windows open
371 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46372
373 // Initialize the Profile menu.
374 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25375}
376
[email protected]71c0eb92012-01-03 17:57:30377- (void)unregisterEventHandlers {
378 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
379 [em removeEventHandlerForEventClass:kInternetEventClass
380 andEventID:kAEGetURL];
381 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
382 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30383 [em removeEventHandlerForEventClass:'WWW!'
384 andEventID:'OURL'];
385 [[NSNotificationCenter defaultCenter] removeObserver:self];
[email protected]d4c811e72013-10-29 21:57:55386 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[email protected]71c0eb92012-01-03 17:57:30387}
388
[email protected]7dc8c6b2010-04-09 17:02:50389// (NSApplicationDelegate protocol) This is the Apple-approved place to override
390// the default handlers.
391- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]7d1aaa62014-07-18 02:21:30392 MacStartupProfiler::GetInstance()->Profile(
393 MacStartupProfiler::WILL_FINISH_LAUNCHING);
sdy57883382016-09-12 16:00:37394
Erik Chen2d245df72017-07-15 03:16:06395 if (@available(macOS 10.12, *)) {
sdy57883382016-09-12 16:00:37396 NSWindow.allowsAutomaticWindowTabbing = NO;
397 }
spqchan210e2ed2017-07-27 23:17:40398
399 // If the OSX version supports this method, the system will automatically
400 // hide the item if there's no touch bar. However, for unsupported versions,
401 // we'll have to manually remove the item from the menu. The item also has
402 // to be removed if the feature is disabled.
403 if (![NSApp
404 respondsToSelector:@selector(toggleTouchBarCustomizationPalette:)] ||
405 !base::FeatureList::IsEnabled(features::kBrowserTouchBar)) {
406 NSMenu* mainMenu = [NSApp mainMenu];
407 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
408 NSMenuItem* customizeItem = [viewMenu itemWithTag:IDC_CUSTOMIZE_TOUCH_BAR];
409 if (customizeItem)
410 [viewMenu removeItem:customizeItem];
411 }
[email protected]7dc8c6b2010-04-09 17:02:50412}
413
[email protected]8a5bd59042014-07-22 04:10:06414- (void)applicationWillHide:(NSNotification*)notification {
415 apps::ExtensionAppShimHandler::OnChromeWillHide();
416}
417
[email protected]7dc8c6b2010-04-09 17:02:50418- (BOOL)tryToTerminateApplication:(NSApplication*)app {
jochenbf9420152015-01-13 14:12:57419 // Reset this now that we've received the call to terminate.
420 BOOL isPoweringOff = isPoweringOff_;
421 isPoweringOff_ = NO;
422
[email protected]3076fad2010-04-28 18:11:45423 // Check for in-process downloads, and prompt the user if they really want
424 // to quit (and thus cancel downloads). Only check if we're not already
425 // shutting down, else the user might be prompted multiple times if the
426 // download isn't stopped before terminate is called again.
427 if (!browser_shutdown::IsTryingToQuit() &&
428 ![self shouldQuitWithInProgressDownloads])
429 return NO;
430
[email protected]7dc8c6b2010-04-09 17:02:50431 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
432 // them in, but I'm not sure about UX; we'd also want to disable other things
433 // though.) http://crbug.com/40861
434
[email protected]177aceb2010-11-03 16:17:41435 // Check if the user really wants to quit by employing the confirm-to-quit
436 // mechanism.
437 if (!browser_shutdown::IsTryingToQuit() &&
438 [self applicationShouldTerminate:app] != NSTerminateNow)
439 return NO;
440
[email protected]70593e52014-05-15 08:30:23441 // Check for active apps. If quitting is prevented, only close browsers and
442 // sessions.
jochenbf9420152015-01-13 14:12:57443 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
444 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
avi3ef9ec9e2014-12-22 22:50:17445 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
mitchelljones3bc6ced2014-12-19 05:01:37446 switches::kHostedAppQuitNotification)) {
447 return NO;
448 }
449
[email protected]70593e52014-05-15 08:30:23450 content::NotificationService::current()->Notify(
451 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
452 content::NotificationService::AllSources(),
453 content::NotificationService::NoDetails());
454 // This will close all browser sessions.
455 chrome::CloseAllBrowsers();
jackhouae8e6e52015-05-29 06:36:46456
457 // At this point, the user has already chosen to cancel downloads. If we
458 // were to shut down as usual, the downloads would be cancelled in
peterccb33e82017-05-02 19:00:44459 // DownloadCoreService::Shutdown().
460 DownloadCoreService::CancelAllDownloads();
jackhouae8e6e52015-05-29 06:36:46461
[email protected]70593e52014-05-15 08:30:23462 return NO;
463 }
464
[email protected]0665ebe2013-02-13 09:53:19465 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50466
[email protected]0c95faf42013-10-28 06:27:20467 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20468 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56469 if (!browser_shutdown::IsTryingToQuit()) {
470 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30471 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56472 content::NotificationService::AllSources(),
473 content::NotificationService::NoDetails());
[email protected]0c95faf42013-10-28 06:27:20474 chrome::CloseAllBrowsersAndQuit();
[email protected]ef61b8c2012-01-20 10:54:56475 }
[email protected]7dc8c6b2010-04-09 17:02:50476
[email protected]c984d9f2010-07-20 20:52:20477 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50478}
479
480- (void)stopTryingToTerminateApplication:(NSApplication*)app {
481 if (browser_shutdown::IsTryingToQuit()) {
482 // Reset the "trying to quit" state, so that closing all browser windows
483 // will no longer lead to termination.
484 browser_shutdown::SetTryingToQuit(false);
485
486 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
487 // would have to reinstall them here. http://crbug.com/40861
488 }
[email protected]a9e8afc2009-08-11 22:03:17489}
490
[email protected]177aceb2010-11-03 16:17:41491- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]90a4b9d2013-07-31 12:14:40492 // If there are no windows, quit immediately.
scottmg8abbff832016-01-28 22:57:37493 if (BrowserList::GetInstance()->empty() &&
jackhou261f7f32015-01-07 00:59:03494 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
[email protected]90a4b9d2013-07-31 12:14:40495 return NSTerminateNow;
496 }
497
[email protected]a99fce0e2011-03-21 20:58:48498 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26499 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23500 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
501 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41502 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23503 }
[email protected]177aceb2010-11-03 16:17:41504
505 // If the application is going to terminate as the result of a Cmd+Q
506 // invocation, use the special sauce to prevent accidental quitting.
507 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41508
[email protected]2020fd0b2010-12-10 01:16:50509 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26510 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50511 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41512
[email protected]5df54fb2011-03-07 18:15:26513 return [[ConfirmQuitPanelController sharedController]
514 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41515}
516
[email protected]449dd2f2009-05-27 13:04:00517// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50518- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50519 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19520 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11521
[email protected]c984d9f2010-07-20 20:52:20522 // Tell BrowserList not to keep the browser process alive. Once all the
523 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
dgn02377782016-03-12 00:58:38524 keep_alive_.reset();
[email protected]fbc947b2009-06-19 13:28:24525
[email protected]02a31dd2013-02-05 08:40:52526 // Reset all pref watching, as this object outlives the prefs system.
527 profilePrefRegistrar_.reset();
528 localPrefRegistrar_.RemoveAll();
529
[email protected]71c0eb92012-01-03 17:57:30530 [self unregisterEventHandlers];
[email protected]edb2d032013-08-30 09:03:17531
532 appShimMenuController_.reset();
lgarron9e6dee22014-11-18 01:03:39533
avi82554752016-09-23 17:48:50534 profileBookmarkMenuBridgeMap_.clear();
[email protected]449dd2f2009-05-27 13:04:00535}
536
[email protected]3b6aa8b62009-09-15 21:36:11537- (void)didEndMainMessageLoop {
scottmg34c5dd882016-02-03 05:21:54538 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile]));
539 if (!chrome::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11540 // As we're shutting down, we need to nuke the TabRestoreService, which
541 // will start the shutdown of the NavigationControllers and allow for
542 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
543 // and may end up crashing when some thread tries to use the IO thread (or
544 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35545 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11546 }
547}
548
[email protected]8cfbdbd2011-06-16 04:17:17549// If the window has a tab controller, make "close window" be cmd-shift-w,
550// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48551// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56552- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
553 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
554 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17555 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
556}
557
558// If the window has a tab controller, make "close tab" take over cmd-w,
559// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56560- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
561 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17562 [closeTabMenuItem_ setKeyEquivalent:@"w"];
563 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
564 } else {
565 [closeTabMenuItem_ setKeyEquivalent:@""];
566 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
567 }
568}
569
[email protected]9f5f79b62011-10-28 00:43:45570// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17571// Close Tab/Close Window accordingly.
andresantoso04f7bab2015-01-15 19:19:16572- (void)menuNeedsUpdate:(NSMenu*)menu {
573 DCHECK(menu == [closeTabMenuItem_ menu]);
andresantosoaf2fb7892015-03-24 21:40:20574
575 BOOL enableCloseTabShortcut = NO;
576 id target = [NSApp targetForAction:@selector(performClose:)];
577
578 // |target| is an instance of NSPopover or NSWindow.
579 // If a popover (likely the dictionary lookup popover), we want Cmd-W to
580 // close the popover so map it to "Close Window".
581 // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
582 if ([target isKindOfClass:[NSWindow class]]) {
583 NSWindow* window = target;
584 NSWindow* mainWindow = [NSApp mainWindow];
585 if (!window || ([window parentWindow] == mainWindow)) {
586 // If the target window is a child of the main window (e.g. a bubble), the
587 // main window should be the one that handles the close menu item action.
588 window = mainWindow;
589 }
andresantoso55fd2512015-04-01 21:07:04590 Browser* browser = chrome::FindBrowserWithWindow(window);
591 enableCloseTabShortcut = browser && browser->is_type_tabbed();
[email protected]9f5f79b62011-10-28 00:43:45592 }
593
[email protected]ebbe94b2012-01-18 20:11:56594 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
595 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17596}
597
andresantoso04f7bab2015-01-15 19:19:16598- (void)windowDidResignKey:(NSNotification*)notify {
599 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
600 // returns nil regardless of whether any suitable candidates for the key
601 // window remain. It seems that the new key window for the app is not set
602 // until after this notification is fired, so a check is performed after the
603 // run loop is allowed to spin.
604 [self performSelector:@selector(checkForAnyKeyWindows)
605 withObject:nil
606 afterDelay:0.0];
[email protected]8cfbdbd2011-06-16 04:17:17607}
608
andresantoso04f7bab2015-01-15 19:19:16609- (void)windowDidBecomeMain:(NSNotification*)notify {
andresantoso55fd2512015-04-01 21:07:04610 Browser* browser = chrome::FindBrowserWithWindow([notify object]);
611 if (browser)
612 [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
andresantoso04f7bab2015-01-15 19:19:16613}
614
615- (void)windowDidResignMain:(NSNotification*)notify {
616 if (chrome::GetTotalBrowserCount() == 0) {
[email protected]cae68b3a2011-11-21 23:29:49617 [self windowChangedToProfile:
618 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24619 }
620}
621
[email protected]d4c811e72013-10-29 21:57:55622- (void)activeSpaceDidChange:(NSNotification*)notify {
623 if (reopenTime_.is_null() ||
624 ![NSApp isActive] ||
625 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
626 kWorkspaceChangeTimeoutMs) {
627 return;
628 }
629
630 // The last applicationShouldHandleReopen:hasVisibleWindows: call
631 // happened during a space change. Now that the change has
632 // completed, raise browser windows.
633 reopenTime_ = base::TimeTicks();
634 std::set<NSWindow*> browserWindows;
scottmg8abbff832016-01-28 22:57:37635 for (auto* browser : *BrowserList::GetInstance())
[email protected]d4c811e72013-10-29 21:57:55636 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]d4c811e72013-10-29 21:57:55637 if (!browserWindows.empty()) {
[email protected]6c4b79602014-05-28 16:47:21638 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:55639 }
640}
641
jochenbf9420152015-01-13 14:12:57642// Called when shutting down or logging out.
643- (void)willPowerOff:(NSNotification*)notify {
644 // Don't attempt any shutdown here. Cocoa will shortly call
645 // -[BrowserCrApplication terminate:].
646 isPoweringOff_ = YES;
647}
648
[email protected]dd6ab1282010-07-20 01:07:32649- (void)checkForAnyKeyWindows {
650 if ([NSApp keyWindow])
651 return;
652
[email protected]ad50def52011-10-19 23:17:07653 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30654 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07655 content::NotificationService::AllSources(),
656 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00657}
658
[email protected]414fde592009-05-21 16:14:43659// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43660// Placed here for 2 reasons:
661// 1) Same spot as other Pref stuff
662// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43663- (void)setUpdateCheckInterval {
664#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49665 CFStringRef app = CFSTR("com.google.Keystone.Agent");
666 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43667 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
668 if (!plist) {
669 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50670 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43671 CFPreferencesSetAppValue(checkInterval, value, app);
672 CFPreferencesAppSynchronize(app);
673 }
674#endif
675}
676
[email protected]66791aff2014-04-29 09:45:38677- (void)openStartupUrls {
erikchen19ee3922014-10-31 19:14:22678 DCHECK(startupComplete_);
679 [self openUrlsReplacingNTP:startupUrls_];
680 startupUrls_.clear();
681}
682
683- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
684 if (urls.empty())
685 return;
686
[email protected]66791aff2014-04-29 09:45:38687 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
688 // NSApplication is created in MainMessageLoop, and then the shortcut urls
689 // are passed in via Apple events. At this point, the first browser is
690 // already loaded in PreMainMessageLoop. If we initialize NSApplication
691 // before PreMainMessageLoop to capture shortcut URL events, it may cause
692 // more problems because it relies on things created in PreMainMessageLoop
693 // and may break existing message loop design.
erikchen19ee3922014-10-31 19:14:22694
695 // If the browser hasn't started yet, just queue up the URLs.
696 if (!startupComplete_) {
697 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]66791aff2014-04-29 09:45:38698 return;
erikchen19ee3922014-10-31 19:14:22699 }
[email protected]66791aff2014-04-29 09:45:38700
701 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
702 // startup urls in new tabs, because the omnibox will stay focused if we
703 // load url in NTP tab.
704 Browser* browser = chrome::GetLastActiveBrowser();
705 int startupIndex = TabStripModel::kNoTab;
706 content::WebContents* startupContent = NULL;
707
708 if (browser && browser->tab_strip_model()->count() == 1) {
709 startupIndex = browser->tab_strip_model()->active_index();
710 startupContent = browser->tab_strip_model()->GetActiveWebContents();
711 }
712
erikchen19ee3922014-10-31 19:14:22713 [self openUrls:urls];
[email protected]66791aff2014-04-29 09:45:38714
715 if (startupIndex != TabStripModel::kNoTab &&
csharrison0b2013b2016-10-19 15:54:42716 startupContent->GetVisibleURL() == chrome::kChromeUINewTabURL) {
[email protected]66791aff2014-04-29 09:45:38717 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
718 TabStripModel::CLOSE_NONE);
719 }
720}
721
[email protected]136140c2009-05-19 13:58:25722// This is called after profiles have been loaded and preferences registered.
723// It is safe to access the default profile here.
724- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]7d1aaa62014-07-18 02:21:30725 MacStartupProfiler::GetInstance()->Profile(
726 MacStartupProfiler::DID_FINISH_LAUNCHING);
727 MacStartupProfiler::GetInstance()->RecordMetrics();
728
[email protected]c984d9f2010-07-20 20:52:20729 // Notify BrowserList to keep the application running so it doesn't go away
730 // when all the browser windows get closed.
dgn02377782016-03-12 00:58:38731 keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::APP_CONTROLLER,
732 KeepAliveRestartOption::DISABLED));
[email protected]136140c2009-05-19 13:58:25733
[email protected]414fde592009-05-21 16:14:43734 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53735
[email protected]edb2d032013-08-30 09:03:17736 // Start managing the menu for app windows. This needs to be done here because
737 // main menu item titles are not yet initialized in awakeFromNib.
[email protected]e7dc3992013-11-06 02:16:42738 [self initAppShimMenuController];
[email protected]edb2d032013-08-30 09:03:17739
[email protected]425f7a02014-04-29 01:51:44740 // If enabled, keep Chrome alive when apps are open instead of quitting all
741 // apps.
742 quitWithAppsController_ = new QuitWithAppsController();
743
andresantoso04f7bab2015-01-15 19:19:16744 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
745 [[closeTabMenuItem_ menu] setDelegate:self];
746
lwchkg9c183942016-03-13 06:29:54747 // Instantiate the ProfileAttributesStorage observer so that we can get
[email protected]1c62b2f2013-06-28 00:15:00748 // notified when a profile is deleted.
lwchkg9c183942016-03-13 06:29:54749 profileAttributesStorageObserver_.reset(new AppControllerProfileObserver(
[email protected]1c62b2f2013-06-28 00:15:00750 g_browser_process->profile_manager(), self));
751
[email protected]f2c20fa2009-12-01 17:42:02752 // Since Chrome is localized to more languages than the OS, tell Cocoa which
753 // menu is the Help so it can add the search item to it.
[email protected]73980132012-07-26 20:09:28754 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02755
[email protected]12dc3d42010-02-22 23:37:12756 // Record the path to the (browser) app bundle; this is used by the app mode
Gabriel Charette66d79ed22017-06-21 17:58:22757 // shim.
758 base::PostTaskWithTraits(FROM_HERE,
759 {base::MayBlock(), base::TaskPriority::BACKGROUND,
760 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
761 base::Bind(&RecordLastRunAppBundlePath));
[email protected]12dc3d42010-02-22 23:37:12762
[email protected]eef99c22010-08-17 05:55:16763 // Makes "Services" menu items available.
764 [self registerServicesMenuTypesTo:[notify object]];
765
[email protected]caadfca2010-01-22 21:51:21766 startupComplete_ = YES;
767
scottmg5c03fe022016-02-03 01:27:24768 Browser* browser = chrome::FindLastActive();
erikchen600f7962014-12-12 00:17:38769 content::WebContents* activeWebContents = nullptr;
770 if (browser)
771 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
772 [self updateHandoffManager:activeWebContents];
[email protected]66791aff2014-04-29 09:45:38773 [self openStartupUrls];
[email protected]aac169d2011-03-18 19:53:03774
[email protected]05454532013-01-22 21:09:08775 PrefService* localState = g_browser_process->local_state();
776 if (localState) {
777 localPrefRegistrar_.Init(localState);
778 localPrefRegistrar_.Add(
779 prefs::kAllowFileSelectionDialogs,
780 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
781 menuState_.get()));
782 }
erikchen600f7962014-12-12 00:17:38783
784 handoff_active_url_observer_bridge_.reset(
785 new HandoffActiveURLObserverBridge(self));
Robert Sesek99845182017-08-24 20:53:33786
787 // Disable fatal OOM to hack around an OS bug https://crbug.com/654695.
788 if (base::mac::IsOS10_12()) {
789 g_swizzle_imk_input_session = new base::mac::ScopedObjCClassSwizzler(
790 NSClassFromString(@"IMKInputSession"),
791 [OOMDisabledIMKInputSession class],
792 @selector(_coreAttributesFromRange:whichAttributes:completionHandler:));
793 }
[email protected]7c321082009-02-09 15:35:47794}
795
[email protected]73f5b362009-08-10 23:58:21796// Helper function for populating and displaying the in progress downloads at
797// exit alert panel.
798- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48799 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13800 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21801 NSString* waitTitle = nil;
802 NSString* exitTitle = nil;
803
804 // Set the dialog text based on whether or not there are multiple downloads.
jshinec68f032015-05-14 00:03:23805 // Dialog text: warning and explanation.
806 titleText = l10n_util::GetPluralNSStringF(
807 IDS_DOWNLOAD_REMOVE_CONFIRM_TITLE, downloadCount);
808 explanationText = l10n_util::GetPluralNSStringF(
809 IDS_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION, downloadCount);
[email protected]83a9f652012-04-25 21:03:48810 // Cancel download and exit button text.
jshinec68f032015-05-14 00:03:23811 exitTitle = l10n_util::GetPluralNSStringF(
812 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL, downloadCount);
[email protected]83a9f652012-04-25 21:03:48813
814 // Wait for download button text.
jshinec68f032015-05-14 00:03:23815 waitTitle = l10n_util::GetPluralNSStringF(
816 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL, downloadCount);
[email protected]73f5b362009-08-10 23:58:21817
818 // 'waitButton' is the default choice.
[email protected]361b47c2013-07-02 15:13:24819 int choice = NSRunAlertPanel(titleText, @"%@",
820 waitTitle, exitTitle, nil, explanationText);
[email protected]73f5b362009-08-10 23:58:21821 return choice == NSAlertDefaultReturn ? YES : NO;
822}
823
824// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41825// user to see if we should continue to exit (and thus cancel the downloads), or
826// if we should wait.
827- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21828 ProfileManager* profile_manager = g_browser_process->profile_manager();
829 if (!profile_manager)
830 return YES;
[email protected]09729a552009-08-03 23:21:41831
[email protected]844a1002011-04-19 11:37:21832 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
833 for (size_t i = 0; i < profiles.size(); ++i) {
peterccb33e82017-05-02 19:00:44834 DownloadCoreService* download_core_service =
835 DownloadCoreServiceFactory::GetForBrowserContext(profiles[i]);
[email protected]9bb54ee2011-10-12 17:43:35836 DownloadManager* download_manager =
peterccb33e82017-05-02 19:00:44837 (download_core_service->HasCreatedDownloadManager()
838 ? BrowserContext::GetDownloadManager(profiles[i])
839 : NULL);
[email protected]422a7d12013-10-21 12:10:42840 if (download_manager &&
841 download_manager->NonMaliciousInProgressCount() > 0) {
842 int downloadCount = download_manager->NonMaliciousInProgressCount();
[email protected]73f5b362009-08-10 23:58:21843 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
844 // Create a new browser window (if necessary) and navigate to the
845 // downloads page if the user chooses to wait.
scottmg34c5dd882016-02-03 05:21:54846 Browser* browser = chrome::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21847 if (!browser) {
erg7b01d692017-02-22 21:57:35848 browser = new Browser(Browser::CreateParams(profiles[i], true));
[email protected]73f5b362009-08-10 23:58:21849 browser->window()->Show();
850 }
851 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12852 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21853 return NO;
854 }
[email protected]09729a552009-08-03 23:21:41855
[email protected]73f5b362009-08-10 23:58:21856 // User wants to exit.
857 return YES;
[email protected]09729a552009-08-03 23:21:41858 }
[email protected]09729a552009-08-03 23:21:41859 }
860
[email protected]73f5b362009-08-10 23:58:21861 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41862 return YES;
863}
864
[email protected]fbc947b2009-06-19 13:28:24865// Called to determine if we should enable the "restore tab" menu item.
866// Checks with the TabRestoreService to see if there's anything there to
867// restore and returns YES if so.
868- (BOOL)canRestoreTab {
blundell74001adc2015-09-18 11:04:25869 sessions::TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35870 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24871 return service && !service->entries().empty();
872}
873
[email protected]1c62b2f2013-06-28 00:15:00874// Called from the AppControllerProfileObserver every time a profile is deleted.
875- (void)profileWasRemoved:(const base::FilePath&)profilePath {
[email protected]1c62b2f2013-06-28 00:15:00876 // If the lastProfile has been deleted, the profile manager has
877 // already loaded a new one, so the pointer needs to be updated;
878 // otherwise we will try to start up a browser window with a pointer
879 // to the old profile.
bauerb447f6432015-03-02 22:34:51880 // In a browser test, the application is not brought to the front, so
881 // |lastProfile_| might be null.
mlerman8ae56aa2015-04-24 13:56:27882 if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
883 // Force windowChangedToProfile: to set the lastProfile_ and also update the
884 // relevant menuBridge objects.
885 lastProfile_ = nullptr;
886 [self windowChangedToProfile:g_browser_process->profile_manager()->
887 GetLastUsedProfile()];
888 }
lgarron9e6dee22014-11-18 01:03:39889
avi82554752016-09-23 17:48:50890 profileBookmarkMenuBridgeMap_.erase(profilePath);
[email protected]1c62b2f2013-06-28 00:15:00891}
892
[email protected]05454532013-01-22 21:09:08893// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21894// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
895// sheets) will not count as blocking the browser. But things like open/save
896// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08897- (BOOL)keyWindowIsModal {
898 if ([NSApp modalWindow])
899 return YES;
900
[email protected]f2bc6e92012-10-14 02:08:38901 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]05454532013-01-22 21:09:08902 return browser &&
903 [[browser->window()->GetNativeWindow() attachedSheet]
904 isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06905}
906
[email protected]88d74942009-01-21 22:04:44907// Called to validate menu items when there are no key windows. All the
908// items we care about have been set with the |commandDispatch:| action and
909// a target of FirstResponder in IB. If it's not one of those, let it
910// continue up the responder chain to be handled elsewhere. We pull out the
911// tag as the cross-platform constant to differentiate and dispatch the
912// various commands.
913- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
914 SEL action = [item action];
915 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08916 if (action == @selector(commandDispatch:) ||
917 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44918 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08919 if (menuState_ && // NULL in tests.
920 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24921 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26922 // The File Menu commands are not automatically disabled by Cocoa when a
923 // dialog sheet obscures the browser window, so we disable several of
924 // them here. We don't need to include IDC_CLOSE_WINDOW, because
925 // app_controller is only activated when there are no key windows (see
926 // function comment).
[email protected]fbc947b2009-06-19 13:28:24927 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08928 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06929 break;
[email protected]f6c15fa2010-06-04 20:08:21930 // Browser-level items that open in new tabs should not open if there's
931 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06932 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06933 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21934 case IDC_SHOW_HISTORY:
935 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08936 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21937 break;
938 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21939 case IDC_TASK_MANAGER:
940 // Allow the user to open a new window if there's a window-modal
941 // dialog.
[email protected]05454532013-01-22 21:09:08942 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24943 break;
944 default:
[email protected]f6c15fa2010-06-04 20:08:21945 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08946 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24947 }
948 }
spqchan9d60fce2016-02-10 18:30:47949
950 // "Show as tab" should only appear when the current window is a popup.
951 // Since |validateUserInterfaceItem:| is called only when there are no
952 // key windows, we should just hide this.
953 // This is handled outside of the switch statement because we want to hide
954 // this regardless if the command is supported or not.
955 if (tag == IDC_SHOW_AS_TAB) {
956 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
957 [menuItem setHidden:YES];
958 }
[email protected]3b6aa8b62009-09-15 21:36:11959 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44960 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52961 } else if (action == @selector(showPreferences:)) {
962 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07963 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
964 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47965 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38966 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48967 } else if (action == @selector(toggleConfirmToQuit:)) {
968 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
969 enable = YES;
[email protected]3a90b452013-02-15 04:33:48970 } else if (action == @selector(executeApplication:)) {
971 enable = YES;
[email protected]88d74942009-01-21 22:04:44972 }
973 return enable;
974}
975
[email protected]88d74942009-01-21 22:04:44976- (void)commandDispatch:(id)sender {
[email protected]2a39d1a2014-04-10 05:46:24977 Profile* lastProfile = [self safeLastProfileForNewWindows];
[email protected]f0a51fb52009-03-05 12:46:38978
[email protected]947fc0d2010-01-14 22:33:05979 // Handle the case where we're dispatching a command from a sender that's in a
980 // browser window. This means that the command came from a background window
981 // and is getting here because the foreground window is not a browser window.
982 if ([sender respondsToSelector:@selector(window)]) {
983 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:04984 if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
[email protected]947fc0d2010-01-14 22:33:05985 [delegate commandDispatch:sender];
986 return;
987 }
988 }
989
[email protected]8d4bbdc2012-09-20 21:36:49990 // Ignore commands during session restore's browser creation. It uses a
gab2998ee72017-05-05 16:23:50991 // nested run loop and commands dispatched during this operation cause
[email protected]8d4bbdc2012-09-20 21:36:49992 // havoc.
993 if (SessionRestore::IsRestoring(lastProfile) &&
gab7af9dc02017-05-05 13:38:54994 base::RunLoop::IsNestedOnCurrentThread()) {
[email protected]8d4bbdc2012-09-20 21:36:49995 return;
gab7af9dc02017-05-05 13:38:54996 }
[email protected]8d4bbdc2012-09-20 21:36:49997
[email protected]88d74942009-01-21 22:04:44998 NSInteger tag = [sender tag];
[email protected]7108d912014-01-30 08:10:45999
1000 // If there are no browser windows, and we are trying to open a browser
mlerman7831f57d2015-05-25 11:40:151001 // for a locked profile or the system profile, we have to show the User
1002 // Manager instead as the locked profile needs authentication and the system
1003 // profile cannot have a browser.
1004 if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile()) {
mlermane6e040a2014-10-31 00:53:211005 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261006 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
[email protected]7108d912014-01-30 08:10:451007 return;
1008 }
1009
[email protected]88d74942009-01-21 22:04:441010 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:241011 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:111012 // Create a new tab in an existing browser window (which we activate) if
1013 // possible.
[email protected]a585a8db2011-06-20 18:58:351014 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:401015 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:111016 break;
1017 }
1018 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:441019 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:351020 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:111021 break;
[email protected]91a5b3e2009-10-30 19:32:221022 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:401023 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1024 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:441025 break;
[email protected]cddc5242009-12-07 18:54:331026 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:401027 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1028 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:331029 break;
[email protected]863ff662009-01-26 20:18:181030 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:481031 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:181032 break;
[email protected]fbc947b2009-06-19 13:28:241033 case IDC_RESTORE_TAB:
scottmgd161e6c2016-02-17 02:08:011034 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:241035 break;
[email protected]e19516d2009-04-28 17:15:191036 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:401037 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:191038 break;
[email protected]1fdff702009-10-22 00:36:181039 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:381040 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:351041 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121042 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231043 } else {
[email protected]1f0b50b2012-06-22 20:37:161044 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231045 }
[email protected]93e181762009-05-29 14:30:381046 break;
[email protected]1fdff702009-10-22 00:36:181047 }
[email protected]4aee5652009-11-19 18:59:211048 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:351049 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121050 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231051 } else {
[email protected]1f0b50b2012-06-22 20:37:161052 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231053 }
[email protected]4aee5652009-11-19 18:59:211054 break;
1055 }
[email protected]af7c25e2010-01-23 05:46:451056 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]a585a8db2011-06-20 18:58:351057 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121058 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:471059 } else {
[email protected]47e532b2010-04-23 17:46:401060 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:161061 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:471062 }
[email protected]af7c25e2010-01-23 05:46:451063 break;
[email protected]91a5b3e2009-10-30 19:32:221064 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:351065 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121066 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:111067 else
[email protected]1f0b50b2012-06-22 20:37:161068 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221069 break;
1070 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:351071 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121072 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:111073 else
[email protected]1f0b50b2012-06-22 20:37:161074 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221075 break;
[email protected]bb37e6ec2009-11-18 17:59:361076 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:351077 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:081078 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:111079 else
[email protected]1f0b50b2012-06-22 20:37:161080 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:361081 break;
[email protected]2ca35612012-06-12 03:49:481082 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:351083 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121084 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:111085 else
[email protected]1f0b50b2012-06-22 20:37:161086 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:181087 break;
[email protected]ceaaf1812010-01-20 22:13:091088 case IDC_TASK_MANAGER:
mlermane6e040a2014-10-31 00:53:211089 chrome::OpenTaskManager(NULL);
[email protected]ceaaf1812010-01-20 22:13:091090 break;
[email protected]4a42d272010-06-18 01:29:421091 case IDC_OPTIONS:
1092 [self showPreferences:sender];
1093 break;
[email protected]d630d7d52010-02-21 00:55:111094 }
[email protected]88d74942009-01-21 22:04:441095}
1096
[email protected]93b59fc2010-12-21 20:00:471097// Run a (background) application in a new tab.
1098- (void)executeApplication:(id)sender {
1099 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351100 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471101 DCHECK(profile);
1102 BackgroundApplicationListModel applications(profile);
1103 DCHECK(tag >= 0 &&
1104 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341105 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331106 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471107}
1108
[email protected]947fc0d2010-01-14 22:33:051109// Same as |-commandDispatch:|, but executes commands using a disposition
1110// determined by the key flags. This will get called in the case where the
1111// frontmost window is not a browser window, and the user has command-clicked
1112// a button in a background browser window whose action is
1113// |-commandDispatchUsingKeyModifiers:|
1114- (void)commandDispatchUsingKeyModifiers:(id)sender {
1115 DCHECK(sender);
1116 if ([sender respondsToSelector:@selector(window)]) {
1117 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041118 if ([delegate respondsToSelector:
1119 @selector(commandDispatchUsingKeyModifiers:)]) {
[email protected]947fc0d2010-01-14 22:33:051120 [delegate commandDispatchUsingKeyModifiers:sender];
1121 }
1122 }
1123}
1124
[email protected]2e29e2232013-07-26 10:40:591125// NSApplication delegate method called when someone clicks on the dock icon.
1126// To match standard mac behavior, we should open a new window if there are no
1127// browser windows.
[email protected]ff81e0a2009-04-13 14:58:541128- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581129 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541130 // If the browser is currently trying to quit, don't do anything and return NO
1131 // to prevent AppKit from doing anything.
1132 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1133 if (browser_shutdown::IsTryingToQuit())
1134 return NO;
1135
[email protected]2e29e2232013-07-26 10:40:591136 // Bring all browser windows to the front. Specifically, this brings them in
1137 // front of any app windows. FocusWindowSet will also unminimize the most
1138 // recently minimized window if no windows in the set are visible.
[email protected]a25920ee2013-09-05 19:38:491139 // If there are any, return here. Otherwise, the windows are panels or
1140 // notifications so we still need to open a new window.
[email protected]bf193bc52013-06-08 04:39:581141 if (hasVisibleWindows) {
[email protected]2e29e2232013-07-26 10:40:591142 std::set<NSWindow*> browserWindows;
scottmg8abbff832016-01-28 22:57:371143 for (auto* browser : *BrowserList::GetInstance()) {
mitchelljonese59a1612014-12-16 00:34:591144 // When focusing Chrome, don't focus any browser windows associated with
1145 // a currently running app shim, so ignore them.
1146 if (browser && browser->is_app()) {
mitchelljonesf00422082015-01-05 23:38:031147 extensions::ExtensionRegistry* registry =
1148 extensions::ExtensionRegistry::Get(browser->profile());
1149 const extensions::Extension* extension = registry->GetExtensionById(
1150 web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1151 extensions::ExtensionRegistry::ENABLED);
mitchelljonesb118a0c2015-01-07 02:51:341152 if (extension && extension->is_hosted_app())
mitchelljonese59a1612014-12-16 00:34:591153 continue;
mitchelljonese59a1612014-12-16 00:34:591154 }
[email protected]2e29e2232013-07-26 10:40:591155 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]0236be22012-01-11 01:05:351156 }
[email protected]a25920ee2013-09-05 19:38:491157 if (!browserWindows.empty()) {
[email protected]d4c811e72013-10-29 21:57:551158 NSWindow* keyWindow = [NSApp keyWindow];
1159 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1160 // The key window is not on the active space. We must be mid-animation
1161 // for a space transition triggered by the dock. Delay the call to
1162 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1163 // wrong space's windows get raised, resulting in an off-screen key
1164 // window. It does not work to |ui::FocusWindowSet| twice, once here
1165 // and once in |activeSpaceDidChange:|, as that appears to break when
1166 // the omnibox is focused.
1167 //
1168 // This check relies on OS X setting the key window to a window on the
1169 // target space before calling this method.
1170 //
1171 // See http://crbug.com/309656.
1172 reopenTime_ = base::TimeTicks::Now();
1173 } else {
[email protected]6c4b79602014-05-28 16:47:211174 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:551175 }
1176 // Return NO; we've done (or soon will do) the deminiaturize, so
1177 // AppKit shouldn't do anything.
[email protected]a25920ee2013-09-05 19:38:491178 return NO;
1179 }
[email protected]0236be22012-01-11 01:05:351180 }
[email protected]ff81e0a2009-04-13 14:58:541181
[email protected]0d1210d62010-09-07 17:31:381182 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481183 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381184 // allow session to be restored first time the user clicks on a Dock icon.
1185 // Normally, it'd just open a new empty page.
1186 {
[email protected]eddcf7502012-02-09 22:43:481187 static BOOL doneOnce = NO;
[email protected]70593e52014-05-15 08:30:231188 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1189 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1190 doneOnce = YES;
1191 if (attemptRestore) {
1192 SessionService* sessionService =
1193 SessionServiceFactory::GetForProfileForSessionRestore(
1194 [self lastProfile]);
1195 if (sessionService &&
1196 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1197 return NO;
[email protected]eddcf7502012-02-09 22:43:481198 }
[email protected]0d1210d62010-09-07 17:31:381199 }
[email protected]fc44f242012-02-14 16:54:391200
[email protected]ff81e0a2009-04-13 14:58:541201 // Otherwise open a new window.
[email protected]7108d912014-01-30 08:10:451202 // If the last profile was locked, we have to open the User Manager, as the
mlerman7831f57d2015-05-25 11:40:151203 // profile requires authentication. Similarly, because guest mode and system
1204 // profile are implemented as forced incognito, we can't open a new guest
1205 // browser either, so we have to show the User Manager as well.
[email protected]7108d912014-01-30 08:10:451206 Profile* lastProfile = [self lastProfile];
mlerman7831f57d2015-05-25 11:40:151207 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1208 lastProfile->IsSystemProfile()) {
mlermane6e040a2014-10-31 00:53:211209 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261210 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1211 } else {
[email protected]7108d912014-01-30 08:10:451212 CreateBrowser(lastProfile);
mlermane29d0032014-09-24 19:31:261213 }
[email protected]ff81e0a2009-04-13 14:58:541214
1215 // We've handled the reopen event, so return NO to tell AppKit not
1216 // to do anything.
1217 return NO;
1218}
1219
[email protected]88d74942009-01-21 22:04:441220- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521221 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241222 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441223 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181224 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191225 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381226 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241227 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221228 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331229 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451230 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221231 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1232 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361233 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481234 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211235 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]236ad3022013-09-04 03:27:431236#if defined(GOOGLE_CHROME_BUILD)
[email protected]1c41a932010-11-22 23:41:231237 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]236ad3022013-09-04 03:27:431238#endif
[email protected]ceaaf1812010-01-20 22:13:091239 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441240}
[email protected]1bcdb532009-01-16 17:47:571241
[email protected]961a6932011-07-19 19:52:461242// Conditionally adds the Profile menu to the main menu bar.
1243- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461244 NSMenu* mainMenu = [NSApp mainMenu];
1245 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401246
[email protected]de71ae992013-07-18 03:30:381247 if (!profiles::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401248 [mainMenu removeItem:profileMenu];
1249 return;
1250 }
1251
[email protected]6b2d30bc2011-10-11 18:16:391252 // The controller will unhide the menu if necessary.
1253 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461254
[email protected]6b2d30bc2011-10-11 18:16:391255 profileMenuController_.reset(
1256 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461257}
1258
[email protected]a99fce0e2011-03-21 20:58:481259// The Confirm to Quit preference is atypical in that the preference lives in
1260// the app menu right above the Quit menu item. This method will refresh the
1261// display of that item depending on the preference state.
1262- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1263 // Format the string so that the correct key equivalent is displayed.
1264 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1265 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1266 base::SysNSStringToUTF16(acceleratorString));
1267 [item setTitle:title];
1268
[email protected]b6366ffa2012-02-29 17:12:261269 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481270 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1271 [item setState:enabled ? NSOnState : NSOffState];
1272}
1273
[email protected]eef99c22010-08-17 05:55:161274- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411275 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1276 // handles requests from services.
1277 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1278 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161279}
1280
[email protected]a585a8db2011-06-20 18:58:351281- (Profile*)lastProfile {
andresantoso55fd2512015-04-01 21:07:041282 // Return the profile of the last-used Browser, if available.
[email protected]7fd5a462011-06-19 16:57:231283 if (lastProfile_)
1284 return lastProfile_;
1285
[email protected]fbb04552014-01-16 15:47:381286 // On first launch, use the logic that ChromeBrowserMain uses to determine
1287 // the initial profile.
1288 ProfileManager* profile_manager = g_browser_process->profile_manager();
1289 if (!profile_manager)
1290 return NULL;
[email protected]3f34599d2009-03-25 22:11:431291
avi3ef9ec9e2014-12-22 22:50:171292 return profile_manager->GetProfile(
1293 GetStartupProfilePath(profile_manager->user_data_dir(),
1294 *base::CommandLine::ForCurrentProcess()));
[email protected]3f34599d2009-03-25 22:11:431295}
1296
[email protected]2a39d1a2014-04-10 05:46:241297- (Profile*)safeLastProfileForNewWindows {
1298 Profile* profile = [self lastProfile];
1299
1300 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1301 if (profile->IsGuestSession())
1302 return profile->GetOffTheRecordProfile();
1303
1304 return profile;
1305}
1306
mlermane6e040a2014-10-31 00:53:211307// Returns true if a browser window may be opened for the last active profile.
1308- (bool)canOpenNewBrowser {
1309 Profile* profile = [self safeLastProfileForNewWindows];
1310
1311 const PrefService* prefs = g_browser_process->local_state();
1312 return !profile->IsGuestSession() ||
1313 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1314}
1315
[email protected]57750f822009-04-21 21:43:091316// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031317// StartupBrowserCreator here because on the other platforms, URLs to open come
1318// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1319// to bottleneck the openings through that for uniform handling.
[email protected]d630d7d52010-02-21 00:55:111320- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211321 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111322 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251323 return;
1324 }
[email protected]57750f822009-04-21 21:43:091325
Scott Violet1f106b582017-07-12 15:49:581326 Browser* browser = chrome::GetLastActiveBrowser();
1327 // if no browser window exists then create one with no tabs to be filled in
1328 if (!browser) {
1329 browser = new Browser(
1330 Browser::CreateParams([self safeLastProfileForNewWindows], true));
1331 browser->window()->Show();
eugenebng7afbc36e2017-06-15 13:38:471332 }
Scott Violet1f106b582017-07-12 15:49:581333
1334 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1335 chrome::startup::IsFirstRun first_run =
1336 first_run::IsChromeFirstRun() ? chrome::startup::IS_FIRST_RUN
1337 : chrome::startup::IS_NOT_FIRST_RUN;
1338 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1339 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091340}
1341
[email protected]57750f822009-04-21 21:43:091342- (void)getUrl:(NSAppleEventDescriptor*)event
1343 withReply:(NSAppleEventDescriptor*)reply {
1344 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1345 stringValue];
1346
1347 GURL gurl(base::SysNSStringToUTF8(urlStr));
1348 std::vector<GURL> gurlVector;
1349 gurlVector.push_back(gurl);
1350
erikchen19ee3922014-10-31 19:14:221351 [self openUrlsReplacingNTP:gurlVector];
[email protected]57750f822009-04-21 21:43:091352}
1353
[email protected]caadfca2010-01-22 21:51:211354- (void)application:(NSApplication*)sender
1355 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091356 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211357 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451358 GURL gurl =
[email protected]77d83542013-12-13 08:54:291359 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
[email protected]57750f822009-04-21 21:43:091360 gurlVector.push_back(gurl);
1361 }
[email protected]caadfca2010-01-22 21:51:211362 if (!gurlVector.empty())
erikchen19ee3922014-10-31 19:14:221363 [self openUrlsReplacingNTP:gurlVector];
[email protected]caadfca2010-01-22 21:51:211364 else
1365 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091366
[email protected]caadfca2010-01-22 21:51:211367 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091368}
[email protected]3f34599d2009-03-25 22:11:431369
[email protected]3111f08b2009-04-30 16:01:521370// Show the preferences window, or bring it to the front if it's already
1371// visible.
1372- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351373 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051374 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121375 chrome::ShowSettings(browser);
mlermane6e040a2014-10-31 00:53:211376 } else if ([self canOpenNewBrowser]) {
[email protected]445177652011-03-09 02:04:051377 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241378 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211379 } else {
1380 // No way to create a browser, default to the User Manager.
1381 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211382 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
[email protected]4a42d272010-06-18 01:29:421383 }
[email protected]d989f07c2009-11-14 00:35:461384}
1385
[email protected]bde3dda2009-05-20 22:13:071386- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561387 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121388 chrome::ShowAboutChrome(browser);
mlermane6e040a2014-10-31 00:53:211389 } else if ([self canOpenNewBrowser]) {
1390 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241391 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211392 } else {
1393 // No way to create a browser, default to the User Manager.
1394 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211395 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
[email protected]bde3dda2009-05-20 22:13:071396 }
[email protected]bde3dda2009-05-20 22:13:071397}
1398
[email protected]a99fce0e2011-03-21 20:58:481399- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261400 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481401 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1402 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1403}
1404
[email protected]3d4bd23f2009-10-06 03:58:381405// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471406- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381407 [NSApp activateIgnoringOtherApps:YES];
1408 [self commandDispatch:sender];
1409}
1410
[email protected]227fcee2010-06-11 19:19:371411- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441412 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351413 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471414
[email protected]646fadbf2012-09-08 01:49:011415 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1416 atOffset:0
1417 fromDock:YES];
1418 if (profilesAdded)
1419 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331420
[email protected]646fadbf2012-09-08 01:49:011421 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461422 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511423 [[NSMenuItem alloc] initWithTitle:titleStr
1424 action:@selector(commandFromDock:)
1425 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461426 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011427 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081428 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011429 [dockMenu addItem:item];
1430
[email protected]8d10a412013-08-09 19:18:001431 // |profile| can be NULL during unit tests.
treib6f9598012014-11-11 12:21:241432 if (!profile ||
1433 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1434 IncognitoModePrefs::DISABLED) {
[email protected]8d10a412013-08-09 19:18:001435 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1436 item.reset(
1437 [[NSMenuItem alloc] initWithTitle:titleStr
1438 action:@selector(commandFromDock:)
1439 keyEquivalent:@""]);
1440 [item setTarget:self];
1441 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1442 [item setEnabled:[self validateUserInterfaceItem:item]];
1443 [dockMenu addItem:item];
1444 }
[email protected]288bfcd32009-09-14 18:14:461445
[email protected]8c6b029d2011-01-21 22:39:511446 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1447 // tests which use the mock in place of the profile-initialized model.
1448
1449 // Avoid breaking unit tests which have no profile.
1450 if (profile) {
1451 BackgroundApplicationListModel applications(profile);
1452 if (applications.size()) {
1453 int position = 0;
1454 NSString* menuStr =
1455 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461456 base::scoped_nsobject<NSMenu> appMenu(
1457 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341458 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481459 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511460 cursor != applications.end();
1461 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501462 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511463 NSString* itemStr =
[email protected]670d3232013-12-24 17:58:581464 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461465 base::scoped_nsobject<NSMenuItem> appItem(
1466 [[NSMenuItem alloc] initWithTitle:itemStr
1467 action:@selector(executeApplication:)
1468 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511469 [appItem setTarget:self];
1470 [appItem setTag:position];
1471 [appMenu addItem:appItem];
1472 }
[email protected]8c6b029d2011-01-21 22:39:511473 }
1474 }
1475
[email protected]018a3962009-09-17 22:23:441476 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461477}
1478
[email protected]d630d7d52010-02-21 00:55:111479- (const std::vector<GURL>&)startupUrls {
1480 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211481}
1482
[email protected]7e4c69d02011-05-11 22:16:471483- (BookmarkMenuBridge*)bookmarkMenuBridge {
lgarron9e6dee22014-11-18 01:03:391484 return bookmarkMenuBridge_;
[email protected]7e4c69d02011-05-11 22:16:471485}
1486
mlerman8ae56aa2015-04-24 13:56:271487- (HistoryMenuBridge*)historyMenuBridge {
1488 return historyMenuBridge_.get();
1489}
1490
[email protected]33190c82012-04-10 17:04:441491- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1492 workAreaChangeObservers_.AddObserver(observer);
1493}
1494
1495- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1496 workAreaChangeObservers_.RemoveObserver(observer);
1497}
1498
[email protected]e7dc3992013-11-06 02:16:421499- (void)initAppShimMenuController {
[email protected]e4c63ec2014-01-14 15:50:541500 if (!appShimMenuController_)
[email protected]e7dc3992013-11-06 02:16:421501 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1502}
1503
nomsdd5b6a612014-09-23 15:20:161504- (void)windowChangedToProfile:(Profile*)profile {
1505 if (lastProfile_ == profile)
1506 return;
1507
lgarron9e6dee22014-11-18 01:03:391508 // Before tearing down the menu controller bridges, return the history menu to
1509 // its initial state.
1510 if (historyMenuBridge_)
nomsdd5b6a612014-09-23 15:20:161511 historyMenuBridge_->ResetMenu();
1512
dominicknb80838f2015-09-08 23:00:131513 // Rebuild the menus with the new profile. The bookmarks submenu is cached to
1514 // avoid slowdowns when switching between profiles with large numbers of
1515 // bookmarks. Before caching, store whether it is hidden, make the menu item
1516 // visible, and restore its original hidden state after resetting the submenu.
1517 // This works around an apparent AppKit bug where setting a *different* NSMenu
1518 // submenu on a *hidden* menu item forces the item to become visible.
1519 // See https://crbug.com/497813 for more details.
1520 NSMenuItem* bookmarkItem = [[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU];
1521 BOOL hidden = [bookmarkItem isHidden];
1522 [bookmarkItem setHidden:NO];
nomsdd5b6a612014-09-23 15:20:161523 lastProfile_ = profile;
1524
bauerb773470002015-02-20 12:20:201525 auto it = profileBookmarkMenuBridgeMap_.find(profile->GetPath());
lgarron9e6dee22014-11-18 01:03:391526 if (it == profileBookmarkMenuBridgeMap_.end()) {
dominicknb80838f2015-09-08 23:00:131527 base::scoped_nsobject<NSMenu> submenu([[bookmarkItem submenu] copy]);
bauerb773470002015-02-20 12:20:201528 bookmarkMenuBridge_ = new BookmarkMenuBridge(profile, submenu);
avi82554752016-09-23 17:48:501529 profileBookmarkMenuBridgeMap_[profile->GetPath()] =
1530 base::WrapUnique(bookmarkMenuBridge_);
lgarron9e6dee22014-11-18 01:03:391531 } else {
avi82554752016-09-23 17:48:501532 bookmarkMenuBridge_ = it->second.get();
lgarron9e6dee22014-11-18 01:03:391533 }
1534
nomsdd5b6a612014-09-23 15:20:161535 // No need to |BuildMenu| here. It is done lazily upon menu access.
dominicknb80838f2015-09-08 23:00:131536 [bookmarkItem setSubmenu:bookmarkMenuBridge_->BookmarkMenu()];
1537 [bookmarkItem setHidden:hidden];
nomsdd5b6a612014-09-23 15:20:161538
1539 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1540 historyMenuBridge_->BuildMenu();
1541
1542 chrome::BrowserCommandController::
1543 UpdateSharedCommandsForIncognitoAvailability(
1544 menuState_.get(), lastProfile_);
1545 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1546 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1547 profilePrefRegistrar_->Add(
1548 prefs::kIncognitoModeAvailability,
1549 base::Bind(&chrome::BrowserCommandController::
1550 UpdateSharedCommandsForIncognitoAvailability,
1551 menuState_.get(),
1552 lastProfile_));
1553}
1554
[email protected]ebbe94b2012-01-18 20:11:561555- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281556 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441557 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281558 withObject:nil
1559 afterDelay:0];
1560}
1561
[email protected]33190c82012-04-10 17:04:441562- (void)delayedScreenParametersUpdate {
ericwilligersd9d3ea12016-10-19 00:31:101563 for (auto& observer : workAreaChangeObservers_)
1564 observer.WorkAreaChanged();
[email protected]6a455072011-11-02 01:32:281565}
1566
[email protected]92747fe42014-08-18 23:25:261567- (BOOL)application:(NSApplication*)application
Peter Collingbournefc74af32017-07-10 21:00:181568 willContinueUserActivityWithType:(NSString*)userActivityType
Nico Weber23f11eae2017-07-13 23:39:411569 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261570 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1571}
1572
1573- (BOOL)application:(NSApplication*)application
1574 continueUserActivity:(NSUserActivity*)userActivity
Peter Collingbournefc74af32017-07-10 21:00:181575 restorationHandler:(void (^)(NSArray*))restorationHandler
Nico Weber23f11eae2017-07-13 23:39:411576 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261577 if (![userActivity.activityType
1578 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1579 return NO;
1580 }
1581
erikchen96e537d52014-10-28 23:43:171582 NSString* originString = base::mac::ObjCCast<NSString>(
1583 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1584 handoff::Origin origin = handoff::OriginFromString(originString);
1585 UMA_HISTOGRAM_ENUMERATION(
1586 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1587
jiangjc0c568c2014-12-04 19:02:121588 NSURL* url = userActivity.webpageURL;
[email protected]92747fe42014-08-18 23:25:261589 if (!url)
1590 return NO;
1591
1592 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1593 std::vector<GURL> gurlVector;
1594 gurlVector.push_back(gurl);
1595
erikchen19ee3922014-10-31 19:14:221596 [self openUrlsReplacingNTP:gurlVector];
[email protected]92747fe42014-08-18 23:25:261597 return YES;
1598}
1599
1600- (void)application:(NSApplication*)application
1601 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1602 error:(NSError*)error {
1603}
1604
erikchen600f7962014-12-12 00:17:381605#pragma mark - Handoff Manager
1606
1607- (BOOL)shouldUseHandoff {
sdy07171a42016-08-30 18:22:041608 return base::mac::IsAtLeastOS10_10();
erikchen600f7962014-12-12 00:17:381609}
1610
1611- (void)passURLToHandoffManager:(const GURL&)handoffURL {
Peter Collingbournefc74af32017-07-10 21:00:181612 if (@available(macOS 10.10, *)) {
1613 [handoffManager_ updateActiveURL:handoffURL];
1614 } else {
1615 // Only ends up being called in 10.10+, i.e. if shouldUseHandoff returns
1616 // true. Some tests override shouldUseHandoff to always return true, but
1617 // then they also override this function to do something else.
1618 NOTREACHED();
1619 }
erikchen600f7962014-12-12 00:17:381620}
1621
1622- (void)updateHandoffManager:(content::WebContents*)webContents {
1623 if (![self shouldUseHandoff])
1624 return;
1625
1626 if (!handoffManager_)
1627 handoffManager_.reset([[HandoffManager alloc] init]);
1628
1629 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1630 [self passURLToHandoffManager:handoffURL];
1631}
1632
1633- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1634 if (!webContents)
1635 return GURL();
1636
1637 Profile* profile =
1638 Profile::FromBrowserContext(webContents->GetBrowserContext());
1639 if (!profile)
1640 return GURL();
1641
1642 // Handoff is not allowed from an incognito profile. To err on the safe side,
1643 // also disallow Handoff from a guest profile.
1644 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1645 return GURL();
1646
1647 if (!webContents)
1648 return GURL();
1649
1650 return webContents->GetVisibleURL();
1651}
1652
1653#pragma mark - HandoffActiveURLObserverBridgeDelegate
1654
1655- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1656 [self updateHandoffManager:webContents];
1657}
1658
[email protected]d630d7d52010-02-21 00:55:111659@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191660
1661//---------------------------------------------------------------------------
1662
[email protected]216e9042009-10-29 17:05:231663namespace app_controller_mac {
1664
1665bool IsOpeningNewWindow() {
1666 return g_is_opening_new_window;
1667}
1668
1669} // namespace app_controller_mac