blob: 04fd504d4bde3555a5557fb6bda52a9e5c0be2dc [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
Ivan Sandrk9669d0e2017-12-15 23:50:209#include <memory>
10
Robert Sesek99845182017-08-24 20:53:3311#include "base/allocator/allocator_shim.h"
Scott Violet44165792018-02-22 02:08:0812#include "base/allocator/buildflags.h"
[email protected]d630d7d52010-02-21 00:55:1113#include "base/auto_reset.h"
[email protected]0b8caad2011-11-28 23:33:2714#include "base/bind.h"
[email protected]57750f822009-04-21 21:43:0915#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5216#include "base/files/file_path.h"
[email protected]151c4a62011-04-22 04:15:1317#include "base/mac/foundation_util.h"
[email protected]0378bf42011-01-01 18:20:1418#include "base/mac/mac_util.h"
Robert Sesek99845182017-08-24 20:53:3319#include "base/mac/scoped_objc_class_swizzler.h"
[email protected]2f301672014-06-07 00:58:5220#include "base/mac/sdk_forward_declarations.h"
avie4d7b6f2015-12-26 00:59:1821#include "base/macros.h"
asvitkineaa060312016-09-01 22:44:1322#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3723#include "base/metrics/user_metrics.h"
gab7af9dc02017-05-05 13:38:5424#include "base/run_loop.h"
[email protected]3ea1b182013-02-08 22:38:4125#include "base/strings/string_number_conversions.h"
[email protected]3268d7b72013-03-28 17:41:4326#include "base/strings/sys_string_conversions.h"
[email protected]135cb802013-06-09 16:44:2027#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3328#include "base/task/post_task.h"
Etienne Pierre-Doraya620e5e2018-12-06 19:02:1029#include "base/threading/scoped_blocking_call.h"
Nico Webereaa08412019-08-14 01:24:3730#include "build/branding_buildflags.h"
[email protected]1a3aba82010-11-08 23:52:5431#include "chrome/app/chrome_command_ids.h"
tapted63829f72014-09-24 23:50:5032#include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
Dominick Ng6ff51052018-07-06 05:30:2033#include "chrome/browser/apps/platform_apps/app_window_registry_util.h"
[email protected]a07676b22011-06-17 16:36:5334#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3335#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0736#include "chrome/browser/browser_process.h"
[email protected]fdf40f3e2013-07-11 23:55:4637#include "chrome/browser/chrome_notification_types.h"
Ivan Sandrk9669d0e2017-12-15 23:50:2038#include "chrome/browser/command_updater_impl.h"
peterccb33e82017-05-02 19:00:4439#include "chrome/browser/download/download_core_service.h"
40#include "chrome/browser/download/download_core_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3241#include "chrome/browser/extensions/extension_service.h"
[email protected]e4a377cf2011-10-05 02:51:4942#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2543#include "chrome/browser/lifetime/application_lifetime.h"
Avi Drissmand30927342018-05-22 15:04:2744#include "chrome/browser/lifetime/browser_shutdown.h"
[email protected]7d1aaa62014-07-18 02:21:3045#include "chrome/browser/mac/mac_startup_profiler.h"
Owen Min0b002e192018-07-10 15:04:1846#include "chrome/browser/policy/chrome_browser_policy_connector.h"
47#include "chrome/browser/policy/machine_level_user_cloud_policy_controller.h"
treib6f9598012014-11-11 12:21:2448#include "chrome/browser/prefs/incognito_mode_prefs.h"
lwchkg9c183942016-03-13 06:29:5449#include "chrome/browser/profiles/profile_attributes_entry.h"
50#include "chrome/browser/profiles/profile_attributes_storage.h"
[email protected]8ecad5e2010-12-02 21:18:3351#include "chrome/browser/profiles/profile_manager.h"
[email protected]de71ae992013-07-18 03:30:3852#include "chrome/browser/profiles/profiles_state.h"
[email protected]8d4bbdc2012-09-20 21:36:4953#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5054#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1555#include "chrome/browser/sessions/session_service_factory.h"
[email protected]92371eb2011-04-28 11:50:1556#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]3d27d272013-07-31 03:15:1657#include "chrome/browser/signin/signin_promo.h"
estade8c0780f2015-08-21 23:36:4158#include "chrome/browser/signin/signin_ui_util.h"
[email protected]40f047972009-11-25 03:54:4059#include "chrome/browser/sync/sync_ui_util.h"
[email protected]ae04f592010-11-18 20:41:3560#include "chrome/browser/ui/browser.h"
[email protected]05454532013-01-22 21:09:0861#include "chrome/browser/ui/browser_command_controller.h"
[email protected]a37d4b02012-06-25 21:56:1062#include "chrome/browser/ui/browser_commands.h"
[email protected]7108d912014-01-30 08:10:4563#include "chrome/browser/ui/browser_dialogs.h"
[email protected]d8748142012-05-16 21:13:4364#include "chrome/browser/ui/browser_finder.h"
scottmg8abbff832016-01-28 22:57:3765#include "chrome/browser/ui/browser_list.h"
[email protected]a13b76f2012-06-20 15:36:2966#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3567#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1268#include "chrome/browser/ui/chrome_pages.h"
[email protected]edb2d032013-08-30 09:03:1769#import "chrome/browser/ui/cocoa/apps/app_shim_menu_controller_mac.h"
[email protected]425f7a02014-04-29 01:51:4470#include "chrome/browser/ui/cocoa/apps/quit_with_apps_controller_mac.h"
[email protected]7d791652010-12-01 16:34:4971#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
Tom Anderson6a496032018-08-30 23:38:3772#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4973#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
erikchen600f7962014-12-12 00:17:3874#include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
[email protected]7d791652010-12-01 16:34:4975#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1376#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]ced445e92014-04-09 21:43:5977#import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
Leonard Grey2bdd08f2017-10-03 18:40:5278#import "chrome/browser/ui/cocoa/share_menu_controller.h"
Elly Fong-Jones0d121842019-08-12 22:03:4079#import "chrome/browser/ui/cocoa/tab_menu_bridge.h"
[email protected]ccfab592013-01-15 06:24:3280#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]4feb37d92012-07-01 20:22:1381#include "chrome/browser/ui/startup/startup_browser_creator.h"
82#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
andresantoso55fd2512015-04-01 21:07:0483#include "chrome/browser/ui/tabs/tab_strip_model.h"
mlermane29d0032014-09-24 19:31:2684#include "chrome/browser/ui/user_manager.h"
Alexey Baskakov2ce2ffc842018-08-06 02:57:1585#include "chrome/browser/web_applications/components/web_app_helpers.h"
Alexey Baskakovf302efe2018-07-28 02:02:3286#include "chrome/browser/web_applications/components/web_app_shortcut_mac.h"
[email protected]12dc3d42010-02-22 23:37:1287#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3888#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0889#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]ccfab592013-01-15 06:24:3290#include "chrome/common/extensions/extension_constants.h"
[email protected]6c583d32011-08-19 14:46:2291#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4892#include "chrome/common/pref_names.h"
[email protected]024617a2010-08-20 05:08:0593#include "chrome/common/url_constants.h"
[email protected]af39f002014-08-22 10:18:1894#include "chrome/grit/chromium_strings.h"
95#include "chrome/grit/generated_resources.h"
erikchen600f7962014-12-12 00:17:3896#include "components/handoff/handoff_manager.h"
erikchen332265b2014-11-14 19:59:5297#include "components/handoff/handoff_utility.h"
Michael Giuffrida2dbce0d12017-09-02 03:30:5998#include "components/keep_alive_registry/keep_alive_types.h"
99#include "components/keep_alive_registry/scoped_keep_alive.h"
brettwb1fc1b82016-02-02 00:19:08100#include "components/prefs/pref_service.h"
blundella08c5dd2015-09-18 06:14:16101#include "components/sessions/core/tab_restore_service.h"
[email protected]e582fdd2011-12-20 16:48:17102#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:07103#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:16104#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:20105#include "content/public/browser/plugin_service.h"
mitchelljonese59a1612014-12-16 00:34:59106#include "extensions/browser/extension_registry.h"
tapted574f09c2015-05-19 13:08:08107#include "extensions/browser/extension_system.h"
[email protected]d96cf752014-04-09 04:05:28108#include "net/base/filename_util.h"
[email protected]2e29e2232013-07-26 10:40:59109#include "ui/base/cocoa/focus_window_set.h"
[email protected]c051a1b2011-01-21 23:30:17110#include "ui/base/l10n/l10n_util.h"
111#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:44112
mitchelljonese59a1612014-12-16 00:34:59113using apps::AppShimHandler;
114using apps::ExtensionAppShimHandler;
[email protected]e6e30ac2014-01-13 21:24:39115using base::UserMetricsAction;
[email protected]b441a8492012-06-06 14:55:57116using content::BrowserContext;
[email protected]e582fdd2011-12-20 16:48:17117using content::DownloadManager;
[email protected]631bb742011-11-02 11:29:39118
[email protected]d630d7d52010-02-21 00:55:11119namespace {
120
[email protected]d4c811e72013-10-29 21:57:55121// How long we allow a workspace change notification to wait to be
122// associated with a dock activation. The animation lasts 250ms. See
123// applicationShouldHandleReopen:hasVisibleWindows:.
124static const int kWorkspaceChangeTimeoutMs = 500;
125
[email protected]a37d4b02012-06-25 21:56:10126// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03127// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
128// because otherwise the SessionService will try to restore sessions when we
129// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11130bool g_is_opening_new_window = false;
131
132// Activates a browser window having the given profile (the last one active) if
133// possible and returns a pointer to the activate |Browser| or NULL if this was
134// not possible. If the last active browser is minimized (in particular, if
135// there are only minimized windows), it will unminimize it.
136Browser* ActivateBrowser(Profile* profile) {
[email protected]5595ce6d2014-07-24 04:01:13137 Browser* browser = chrome::FindLastActiveWithProfile(
scottmg5c03fe022016-02-03 01:27:24138 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile);
[email protected]d630d7d52010-02-21 00:55:11139 if (browser)
140 browser->window()->Activate();
141 return browser;
142}
143
144// Creates an empty browser window with the given profile and returns a pointer
145// to the new |Browser|.
146Browser* CreateBrowser(Profile* profile) {
147 {
[email protected]997ec9f2012-11-21 04:44:14148 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
scottmg851949002016-02-09 20:09:44149 chrome::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11150 }
151
[email protected]f2bc6e92012-10-14 02:08:38152 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11153 CHECK(browser);
154 return browser;
155}
156
157// Activates a browser window having the given profile (the last one active) if
158// possible or creates an empty one if necessary. Returns a pointer to the
159// activated/new |Browser|.
160Browser* ActivateOrCreateBrowser(Profile* profile) {
161 if (Browser* browser = ActivateBrowser(profile))
162 return browser;
163 return CreateBrowser(profile);
164}
165
[email protected]151c4a62011-04-22 04:15:13166CFStringRef BaseBundleID_CFString() {
167 NSString* base_bundle_id =
168 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
169 return base::mac::NSToCFCast(base_bundle_id);
170}
171
[email protected]12dc3d42010-02-22 23:37:12172// Record the location of the application bundle (containing the main framework)
173// from which Chromium was loaded. This is used by app mode shims to find
174// Chromium.
175void RecordLastRunAppBundlePath() {
176 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
177 // real, user-visible app bundle directory. (The alternatives give either the
178 // framework's path or the initial app's path, which may be an app mode shim
179 // or a unit test.)
Etienne Bergeron436d42212019-02-26 17:15:12180 base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
181 base::BlockingType::MAY_BLOCK);
[email protected]bf0d26b2013-08-29 03:09:14182
Robert Sesek499376682019-05-16 23:25:48183 // Go up five levels from the versioned sub-directory of the framework, which
184 // is at C.app/Contents/Frameworks/C.framework/Versions/V.
185 base::FilePath app_bundle_path = chrome::GetFrameworkBundlePath()
186 .DirName()
187 .DirName()
188 .DirName()
189 .DirName()
190 .DirName();
[email protected]1c958682013-09-17 03:38:13191 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
192 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
[email protected]b6b72222012-02-11 02:04:13193 CFPreferencesSetAppValue(
194 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
[email protected]1c958682013-09-17 03:38:13195 app_bundle_path_cfstring, BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12196}
197
[email protected]7108d912014-01-30 08:10:45198bool IsProfileSignedOut(Profile* profile) {
lwchkg9c183942016-03-13 06:29:54199 ProfileAttributesEntry* entry;
200 bool has_entry =
201 g_browser_process->profile_manager()->GetProfileAttributesStorage().
202 GetProfileAttributesWithPath(profile->GetPath(), &entry);
203 return has_entry && entry->IsSigninRequired();
[email protected]7108d912014-01-30 08:10:45204}
205
erikchen600f7962014-12-12 00:17:38206} // namespace
[email protected]d630d7d52010-02-21 00:55:11207
erikchen600f7962014-12-12 00:17:38208@interface AppController () <HandoffActiveURLObserverBridgeDelegate>
[email protected]88d74942009-01-21 22:04:44209- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46210- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48211- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16212- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]57750f822009-04-21 21:43:09213- (void)getUrl:(NSAppleEventDescriptor*)event
214 withReply:(NSAppleEventDescriptor*)reply;
[email protected]d4c811e72013-10-29 21:57:55215- (void)activeSpaceDidChange:(NSNotification*)inNotification;
[email protected]dd6ab1282010-07-20 01:07:32216- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21217- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41218- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47219- (void)executeApplication:(id)sender;
[email protected]1c62b2f2013-06-28 00:15:00220- (void)profileWasRemoved:(const base::FilePath&)profilePath;
erikchen19ee3922014-10-31 19:14:22221
222// Opens a tab for each GURL in |urls|.
223- (void)openUrls:(const std::vector<GURL>&)urls;
224
225// This class cannot open urls until startup has finished. The urls that cannot
226// be opened are cached in |startupUrls_|. This method must be called exactly
227// once after startup has completed. It opens the urls in |startupUrls_|, and
228// clears |startupUrls_|.
229- (void)openStartupUrls;
230
231// Opens a tab for each GURL in |urls|. If there is exactly one tab open before
232// this method is called, and that tab is the NTP, then this method closes the
233// NTP after all the |urls| have been opened.
234- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
erikchen600f7962014-12-12 00:17:38235
erikchen600f7962014-12-12 00:17:38236// This method passes |handoffURL| to |handoffManager_|.
237- (void)passURLToHandoffManager:(const GURL&)handoffURL;
238
239// Lazily creates the Handoff Manager. Updates the state of the Handoff
240// Manager. This method is idempotent. This should be called:
241// - During initialization.
242// - When the current tab navigates to a new URL.
243// - When the active browser changes.
244// - When the active browser's active tab switches.
245// |webContents| should be the new, active WebContents.
246- (void)updateHandoffManager:(content::WebContents*)webContents;
247
248// Given |webContents|, extracts a GURL to be used for Handoff. This may return
249// the empty GURL.
250- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
Owen Min8c5d5382018-08-02 17:52:43251
252// Return false if Chrome startup is paused by dialog and AppController is
253// called without any initialized Profile.
254- (BOOL)isProfileReady;
[email protected]88d74942009-01-21 22:04:44255@end
[email protected]1bcdb532009-01-16 17:47:57256
lwchkg9c183942016-03-13 06:29:54257class AppControllerProfileObserver : public ProfileAttributesStorage::Observer {
[email protected]1c62b2f2013-06-28 00:15:00258 public:
259 AppControllerProfileObserver(
260 ProfileManager* profile_manager, AppController* app_controller)
261 : profile_manager_(profile_manager),
262 app_controller_(app_controller) {
263 DCHECK(profile_manager_);
264 DCHECK(app_controller_);
lwchkg9c183942016-03-13 06:29:54265 profile_manager_->GetProfileAttributesStorage().AddObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00266 }
267
Daniel Chenga542fca2014-10-21 09:51:29268 ~AppControllerProfileObserver() override {
[email protected]1c62b2f2013-06-28 00:15:00269 DCHECK(profile_manager_);
lwchkg9c183942016-03-13 06:29:54270 profile_manager_->GetProfileAttributesStorage().RemoveObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00271 }
272
273 private:
lwchkg9c183942016-03-13 06:29:54274 // ProfileAttributesStorage::Observer implementation:
[email protected]1c62b2f2013-06-28 00:15:00275
Daniel Chenga542fca2014-10-21 09:51:29276 void OnProfileAdded(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00277
Daniel Chenga542fca2014-10-21 09:51:29278 void OnProfileWasRemoved(const base::FilePath& profile_path,
279 const base::string16& profile_name) override {
[email protected]1c62b2f2013-06-28 00:15:00280 // When a profile is deleted we need to notify the AppController,
281 // so it can correctly update its pointer to the last used profile.
282 [app_controller_ profileWasRemoved:profile_path];
283 }
284
Daniel Chenga542fca2014-10-21 09:51:29285 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00286
Daniel Chenga542fca2014-10-21 09:51:29287 void OnProfileNameChanged(const base::FilePath& profile_path,
288 const base::string16& old_profile_name) override {}
[email protected]1c62b2f2013-06-28 00:15:00289
Daniel Chenga542fca2014-10-21 09:51:29290 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00291
292 ProfileManager* profile_manager_;
293
294 AppController* app_controller_; // Weak; owns us.
295
296 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
297};
298
Robert Sesek1eb85222017-08-24 23:17:09299#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33300// On macOS 10.12, the IME system attempts to allocate a 2^64 size buffer,
301// which would typically cause an OOM crash. To avoid this, the problematic
302// method is swizzled out and the make-OOM-fatal bit is disabled for the
303// duration of the original call. https://crbug.com/654695
304static base::mac::ScopedObjCClassSwizzler* g_swizzle_imk_input_session;
305
306@interface OOMDisabledIMKInputSession : NSObject
307@end
308
309@implementation OOMDisabledIMKInputSession
310
311- (void)_coreAttributesFromRange:(NSRange)range
312 whichAttributes:(long long)attributes
313 completionHandler:(void (^)(void))block {
314 // The allocator flag is per-process, so other threads may temporarily
315 // not have fatal OOM occur while this method executes, but it is better
316 // than crashing when using IME.
317 base::allocator::SetCallNewHandlerOnMallocFailure(false);
318 g_swizzle_imk_input_session->GetOriginalImplementation()(self, _cmd, range,
319 attributes, block);
320 base::allocator::SetCallNewHandlerOnMallocFailure(true);
321}
322
323@end
Robert Sesek1eb85222017-08-24 23:17:09324#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33325
[email protected]1bcdb532009-01-16 17:47:57326@implementation AppController
327
[email protected]caadfca2010-01-22 21:51:21328@synthesize startupComplete = startupComplete_;
329
andresantoso04f7bab2015-01-15 19:19:16330- (void)dealloc {
331 [[closeTabMenuItem_ menu] setDelegate:nil];
332 [super dealloc];
333}
334
[email protected]cd63ef62009-05-06 19:41:37335// This method is called very early in application startup (ie, before
336// the profile is loaded or any preferences have been registered). Defer any
337// user-data initialization until -applicationDidFinishLaunching:.
Robert Sesek124f80f92018-07-24 20:31:29338- (void)mainMenuCreated {
[email protected]7d1aaa62014-07-18 02:21:30339 MacStartupProfiler::GetInstance()->Profile(
340 MacStartupProfiler::AWAKE_FROM_NIB);
[email protected]136140c2009-05-19 13:58:25341 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09342 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
343 [em setEventHandler:self
344 andSelector:@selector(getUrl:withReply:)
345 forEventClass:kInternetEventClass
346 andEventID:kAEGetURL];
347 [em setEventHandler:self
348 andSelector:@selector(getUrl:withReply:)
349 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
350 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37351
[email protected]449dd2f2009-05-27 13:04:00352 NSNotificationCenter* notificationCenter =
353 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44354 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00355 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16356 selector:@selector(windowDidResignKey:)
[email protected]449dd2f2009-05-27 13:04:00357 name:NSWindowDidResignKeyNotification
358 object:nil];
359 [notificationCenter
360 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16361 selector:@selector(windowDidBecomeMain:)
[email protected]449dd2f2009-05-27 13:04:00362 name:NSWindowDidBecomeMainNotification
363 object:nil];
364 [notificationCenter
365 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16366 selector:@selector(windowDidResignMain:)
[email protected]449dd2f2009-05-27 13:04:00367 name:NSWindowDidResignMainNotification
368 object:nil];
369
[email protected]d4c811e72013-10-29 21:57:55370 // Register for space change notifications.
371 [[[NSWorkspace sharedWorkspace] notificationCenter]
372 addObserver:self
373 selector:@selector(activeSpaceDidChange:)
374 name:NSWorkspaceActiveSpaceDidChangeNotification
375 object:nil];
376
jochenbf9420152015-01-13 14:12:57377 [[[NSWorkspace sharedWorkspace] notificationCenter]
378 addObserver:self
379 selector:@selector(willPowerOff:)
380 name:NSWorkspaceWillPowerOffNotification
381 object:nil];
382
Robert Sesek705c3802018-10-24 20:58:42383 NSMenu* fileMenu = [[[NSApp mainMenu] itemWithTag:IDC_FILE_MENU] submenu];
384 closeTabMenuItem_ = [fileMenu itemWithTag:IDC_CLOSE_TAB];
385 DCHECK(closeTabMenuItem_);
386 closeWindowMenuItem_ = [fileMenu itemWithTag:IDC_CLOSE_WINDOW];
387 DCHECK(closeWindowMenuItem_);
388
[email protected]136140c2009-05-19 13:58:25389 // Set up the command updater for when there are no windows open
390 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46391
392 // Initialize the Profile menu.
393 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25394}
395
[email protected]71c0eb92012-01-03 17:57:30396- (void)unregisterEventHandlers {
397 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
398 [em removeEventHandlerForEventClass:kInternetEventClass
399 andEventID:kAEGetURL];
400 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
401 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30402 [em removeEventHandlerForEventClass:'WWW!'
403 andEventID:'OURL'];
404 [[NSNotificationCenter defaultCenter] removeObserver:self];
[email protected]d4c811e72013-10-29 21:57:55405 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[email protected]71c0eb92012-01-03 17:57:30406}
407
[email protected]7dc8c6b2010-04-09 17:02:50408// (NSApplicationDelegate protocol) This is the Apple-approved place to override
409// the default handlers.
410- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]7d1aaa62014-07-18 02:21:30411 MacStartupProfiler::GetInstance()->Profile(
412 MacStartupProfiler::WILL_FINISH_LAUNCHING);
sdy57883382016-09-12 16:00:37413
Erik Chen2d245df72017-07-15 03:16:06414 if (@available(macOS 10.12, *)) {
sdy57883382016-09-12 16:00:37415 NSWindow.allowsAutomaticWindowTabbing = NO;
416 }
spqchan210e2ed2017-07-27 23:17:40417
418 // If the OSX version supports this method, the system will automatically
419 // hide the item if there's no touch bar. However, for unsupported versions,
spqchan30556c32018-09-05 23:14:08420 // we'll have to manually remove the item from the menu.
spqchan210e2ed2017-07-27 23:17:40421 if (![NSApp
spqchan30556c32018-09-05 23:14:08422 respondsToSelector:@selector(toggleTouchBarCustomizationPalette:)]) {
spqchan210e2ed2017-07-27 23:17:40423 NSMenu* mainMenu = [NSApp mainMenu];
424 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
425 NSMenuItem* customizeItem = [viewMenu itemWithTag:IDC_CUSTOMIZE_TOUCH_BAR];
426 if (customizeItem)
427 [viewMenu removeItem:customizeItem];
428 }
Leonard Grey2bdd08f2017-10-03 18:40:52429
Leonard Grey34b5e622018-07-30 19:05:55430 [self initShareMenu];
[email protected]7dc8c6b2010-04-09 17:02:50431}
432
[email protected]8a5bd59042014-07-22 04:10:06433- (void)applicationWillHide:(NSNotification*)notification {
Owen Min8c5d5382018-08-02 17:52:43434 if (![self isProfileReady])
435 return;
Christopher Cameron027e4ad2018-09-21 16:52:54436 apps::ExtensionAppShimHandler::Get()->OnChromeWillHide();
[email protected]8a5bd59042014-07-22 04:10:06437}
438
[email protected]7dc8c6b2010-04-09 17:02:50439- (BOOL)tryToTerminateApplication:(NSApplication*)app {
jochenbf9420152015-01-13 14:12:57440 // Reset this now that we've received the call to terminate.
441 BOOL isPoweringOff = isPoweringOff_;
442 isPoweringOff_ = NO;
443
[email protected]3076fad2010-04-28 18:11:45444 // Check for in-process downloads, and prompt the user if they really want
445 // to quit (and thus cancel downloads). Only check if we're not already
446 // shutting down, else the user might be prompted multiple times if the
447 // download isn't stopped before terminate is called again.
448 if (!browser_shutdown::IsTryingToQuit() &&
449 ![self shouldQuitWithInProgressDownloads])
450 return NO;
451
[email protected]7dc8c6b2010-04-09 17:02:50452 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
453 // them in, but I'm not sure about UX; we'd also want to disable other things
454 // though.) http://crbug.com/40861
455
[email protected]70593e52014-05-15 08:30:23456 // Check for active apps. If quitting is prevented, only close browsers and
457 // sessions.
jochenbf9420152015-01-13 14:12:57458 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
459 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
avi3ef9ec9e2014-12-22 22:50:17460 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
mitchelljones3bc6ced2014-12-19 05:01:37461 switches::kHostedAppQuitNotification)) {
462 return NO;
463 }
464
[email protected]70593e52014-05-15 08:30:23465 content::NotificationService::current()->Notify(
466 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
467 content::NotificationService::AllSources(),
468 content::NotificationService::NoDetails());
469 // This will close all browser sessions.
470 chrome::CloseAllBrowsers();
jackhouae8e6e52015-05-29 06:36:46471
472 // At this point, the user has already chosen to cancel downloads. If we
473 // were to shut down as usual, the downloads would be cancelled in
peterccb33e82017-05-02 19:00:44474 // DownloadCoreService::Shutdown().
475 DownloadCoreService::CancelAllDownloads();
jackhouae8e6e52015-05-29 06:36:46476
[email protected]70593e52014-05-15 08:30:23477 return NO;
478 }
479
[email protected]0665ebe2013-02-13 09:53:19480 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50481
[email protected]0c95faf42013-10-28 06:27:20482 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20483 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56484 if (!browser_shutdown::IsTryingToQuit()) {
485 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30486 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56487 content::NotificationService::AllSources(),
488 content::NotificationService::NoDetails());
[email protected]0c95faf42013-10-28 06:27:20489 chrome::CloseAllBrowsersAndQuit();
[email protected]ef61b8c2012-01-20 10:54:56490 }
[email protected]7dc8c6b2010-04-09 17:02:50491
[email protected]c984d9f2010-07-20 20:52:20492 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50493}
494
495- (void)stopTryingToTerminateApplication:(NSApplication*)app {
496 if (browser_shutdown::IsTryingToQuit()) {
497 // Reset the "trying to quit" state, so that closing all browser windows
498 // will no longer lead to termination.
499 browser_shutdown::SetTryingToQuit(false);
500
501 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
502 // would have to reinstall them here. http://crbug.com/40861
503 }
[email protected]a9e8afc2009-08-11 22:03:17504}
505
Avi Drissmanf19bb472018-11-29 19:51:28506- (BOOL)runConfirmQuitPanel {
[email protected]90a4b9d2013-07-31 12:14:40507 // If there are no windows, quit immediately.
scottmg8abbff832016-01-28 22:57:37508 if (BrowserList::GetInstance()->empty() &&
jackhou261f7f32015-01-07 00:59:03509 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
Avi Drissmanf19bb472018-11-29 19:51:28510 return YES;
[email protected]90a4b9d2013-07-31 12:14:40511 }
512
[email protected]a99fce0e2011-03-21 20:58:48513 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26514 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23515 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
516 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
Avi Drissmanf19bb472018-11-29 19:51:28517 return YES;
[email protected]1eaddf32011-04-05 15:09:23518 }
[email protected]177aceb2010-11-03 16:17:41519
Avi Drissmanf19bb472018-11-29 19:51:28520 // Run only for keyboard-initiated quits.
521 if ([[NSApp currentEvent] type] != NSKeyDown)
[email protected]2020fd0b2010-12-10 01:16:50522 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41523
[email protected]5df54fb2011-03-07 18:15:26524 return [[ConfirmQuitPanelController sharedController]
Avi Drissmanf19bb472018-11-29 19:51:28525 runModalLoopForApplication:NSApp];
[email protected]177aceb2010-11-03 16:17:41526}
527
[email protected]449dd2f2009-05-27 13:04:00528// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50529- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50530 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19531 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11532
[email protected]c984d9f2010-07-20 20:52:20533 // Tell BrowserList not to keep the browser process alive. Once all the
534 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
dgn02377782016-03-12 00:58:38535 keep_alive_.reset();
[email protected]fbc947b2009-06-19 13:28:24536
[email protected]02a31dd2013-02-05 08:40:52537 // Reset all pref watching, as this object outlives the prefs system.
538 profilePrefRegistrar_.reset();
539 localPrefRegistrar_.RemoveAll();
540
[email protected]71c0eb92012-01-03 17:57:30541 [self unregisterEventHandlers];
[email protected]edb2d032013-08-30 09:03:17542
543 appShimMenuController_.reset();
lgarron9e6dee22014-11-18 01:03:39544
avi82554752016-09-23 17:48:50545 profileBookmarkMenuBridgeMap_.clear();
[email protected]449dd2f2009-05-27 13:04:00546}
547
[email protected]3b6aa8b62009-09-15 21:36:11548- (void)didEndMainMessageLoop {
scottmg34c5dd882016-02-03 05:21:54549 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile]));
550 if (!chrome::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11551 // As we're shutting down, we need to nuke the TabRestoreService, which
552 // will start the shutdown of the NavigationControllers and allow for
553 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
554 // and may end up crashing when some thread tries to use the IO thread (or
555 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35556 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11557 }
558}
559
[email protected]8cfbdbd2011-06-16 04:17:17560// If the window has a tab controller, make "close window" be cmd-shift-w,
561// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48562// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56563- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
564 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
565 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17566 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
567}
568
569// If the window has a tab controller, make "close tab" take over cmd-w,
570// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56571- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
572 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17573 [closeTabMenuItem_ setKeyEquivalent:@"w"];
574 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
575 } else {
576 [closeTabMenuItem_ setKeyEquivalent:@""];
577 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
578 }
579}
580
[email protected]9f5f79b62011-10-28 00:43:45581// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17582// Close Tab/Close Window accordingly.
andresantoso04f7bab2015-01-15 19:19:16583- (void)menuNeedsUpdate:(NSMenu*)menu {
584 DCHECK(menu == [closeTabMenuItem_ menu]);
erikchen22be2092018-06-12 15:54:00585 [self updateMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17586}
587
andresantoso04f7bab2015-01-15 19:19:16588- (void)windowDidResignKey:(NSNotification*)notify {
589 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
590 // returns nil regardless of whether any suitable candidates for the key
591 // window remain. It seems that the new key window for the app is not set
592 // until after this notification is fired, so a check is performed after the
593 // run loop is allowed to spin.
594 [self performSelector:@selector(checkForAnyKeyWindows)
595 withObject:nil
596 afterDelay:0.0];
[email protected]8cfbdbd2011-06-16 04:17:17597}
598
andresantoso04f7bab2015-01-15 19:19:16599- (void)windowDidBecomeMain:(NSNotification*)notify {
andresantoso55fd2512015-04-01 21:07:04600 Browser* browser = chrome::FindBrowserWithWindow([notify object]);
Elly Fong-Jones0d121842019-08-12 22:03:40601 if (!browser)
602 return;
603
Joel Hockey2687ab52019-08-14 23:59:46604 if (browser->is_type_normal()) {
Elly Fong-Jones0d121842019-08-12 22:03:40605 tabMenuBridge_ = std::make_unique<TabMenuBridge>(
606 browser->tab_strip_model(),
607 [[NSApp mainMenu] itemWithTag:IDC_TAB_MENU]);
608 tabMenuBridge_->BuildMenu();
609 } else {
610 tabMenuBridge_.reset();
611 }
612
613 [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
andresantoso04f7bab2015-01-15 19:19:16614}
615
616- (void)windowDidResignMain:(NSNotification*)notify {
Owen Min8c5d5382018-08-02 17:52:43617 if (chrome::GetTotalBrowserCount() == 0 && [self isProfileReady]) {
[email protected]cae68b3a2011-11-21 23:29:49618 [self windowChangedToProfile:
619 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24620 }
621}
622
[email protected]d4c811e72013-10-29 21:57:55623- (void)activeSpaceDidChange:(NSNotification*)notify {
624 if (reopenTime_.is_null() ||
625 ![NSApp isActive] ||
626 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
627 kWorkspaceChangeTimeoutMs) {
628 return;
629 }
630
631 // The last applicationShouldHandleReopen:hasVisibleWindows: call
632 // happened during a space change. Now that the change has
633 // completed, raise browser windows.
634 reopenTime_ = base::TimeTicks();
Christopher Cameron359c61e22018-10-18 08:06:20635 std::set<gfx::NativeWindow> browserWindows;
scottmg8abbff832016-01-28 22:57:37636 for (auto* browser : *BrowserList::GetInstance())
[email protected]d4c811e72013-10-29 21:57:55637 browserWindows.insert(browser->window()->GetNativeWindow());
Christopher Cameron359c61e22018-10-18 08:06:20638 if (!browserWindows.empty())
[email protected]6c4b79602014-05-28 16:47:21639 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:55640}
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 {
Nico Webereaa08412019-08-14 01:24:37664#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
[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.
Christian Dullweber820ee5f2018-04-26 13:24:31704 Profile* profile =
705 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
706 Browser* browser = chrome::FindLastActiveWithProfile(profile);
707
[email protected]66791aff2014-04-29 09:45:38708 int startupIndex = TabStripModel::kNoTab;
709 content::WebContents* startupContent = NULL;
710
711 if (browser && browser->tab_strip_model()->count() == 1) {
712 startupIndex = browser->tab_strip_model()->active_index();
713 startupContent = browser->tab_strip_model()->GetActiveWebContents();
714 }
715
erikchen19ee3922014-10-31 19:14:22716 [self openUrls:urls];
[email protected]66791aff2014-04-29 09:45:38717
kristiparka34b247a2018-03-09 19:05:34718 // In test environments where there is no network connection, the visible NTP
719 // URL may be chrome-search://local-ntp/local-ntp.html instead of
720 // chrome://newtab/. See local_ntp_test_utils::GetFinalNtpUrl for more
721 // details.
722 // This NTP check should be replaced once https://crbug.com/624410 is fixed.
[email protected]66791aff2014-04-29 09:45:38723 if (startupIndex != TabStripModel::kNoTab &&
kristiparka34b247a2018-03-09 19:05:34724 (startupContent->GetVisibleURL() == chrome::kChromeUINewTabURL ||
725 startupContent->GetVisibleURL() == chrome::kChromeSearchLocalNtpUrl)) {
[email protected]66791aff2014-04-29 09:45:38726 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
727 TabStripModel::CLOSE_NONE);
728 }
729}
730
[email protected]136140c2009-05-19 13:58:25731// This is called after profiles have been loaded and preferences registered.
732// It is safe to access the default profile here.
Owen Min3bcf8d152018-07-16 16:50:39733- (void)applicationDidFinishLaunching:(NSNotification*)notify {
734 if (g_browser_process->browser_policy_connector()
735 ->machine_level_user_cloud_policy_controller()
736 ->IsEnterpriseStartupDialogShowing()) {
737 // As Chrome is not ready when the Enterprise startup dialog is being shown.
738 // Store the notification as it will be reposted when the dialog is closed.
739 return;
740 }
741
[email protected]7d1aaa62014-07-18 02:21:30742 MacStartupProfiler::GetInstance()->Profile(
743 MacStartupProfiler::DID_FINISH_LAUNCHING);
744 MacStartupProfiler::GetInstance()->RecordMetrics();
745
[email protected]c984d9f2010-07-20 20:52:20746 // Notify BrowserList to keep the application running so it doesn't go away
747 // when all the browser windows get closed.
dgn02377782016-03-12 00:58:38748 keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::APP_CONTROLLER,
749 KeepAliveRestartOption::DISABLED));
[email protected]136140c2009-05-19 13:58:25750
[email protected]414fde592009-05-21 16:14:43751 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53752
[email protected]edb2d032013-08-30 09:03:17753 // Start managing the menu for app windows. This needs to be done here because
754 // main menu item titles are not yet initialized in awakeFromNib.
[email protected]e7dc3992013-11-06 02:16:42755 [self initAppShimMenuController];
[email protected]edb2d032013-08-30 09:03:17756
[email protected]425f7a02014-04-29 01:51:44757 // If enabled, keep Chrome alive when apps are open instead of quitting all
758 // apps.
759 quitWithAppsController_ = new QuitWithAppsController();
760
andresantoso04f7bab2015-01-15 19:19:16761 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
762 [[closeTabMenuItem_ menu] setDelegate:self];
763
lwchkg9c183942016-03-13 06:29:54764 // Instantiate the ProfileAttributesStorage observer so that we can get
[email protected]1c62b2f2013-06-28 00:15:00765 // notified when a profile is deleted.
lwchkg9c183942016-03-13 06:29:54766 profileAttributesStorageObserver_.reset(new AppControllerProfileObserver(
[email protected]1c62b2f2013-06-28 00:15:00767 g_browser_process->profile_manager(), self));
768
[email protected]12dc3d42010-02-22 23:37:12769 // Record the path to the (browser) app bundle; this is used by the app mode
Gabriel Charette66d79ed22017-06-21 17:58:22770 // shim.
Robert Sesek7f66190e2019-06-13 12:28:41771 if (base::mac::AmIBundled()) {
Sami Kyostila5e1306d2019-08-14 11:01:29772 base::PostTask(
773 FROM_HERE,
774 {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT,
775 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
776 base::BindOnce(&RecordLastRunAppBundlePath));
Robert Sesek7f66190e2019-06-13 12:28:41777 }
[email protected]12dc3d42010-02-22 23:37:12778
[email protected]eef99c22010-08-17 05:55:16779 // Makes "Services" menu items available.
780 [self registerServicesMenuTypesTo:[notify object]];
781
[email protected]caadfca2010-01-22 21:51:21782 startupComplete_ = YES;
783
scottmg5c03fe022016-02-03 01:27:24784 Browser* browser = chrome::FindLastActive();
erikchen600f7962014-12-12 00:17:38785 content::WebContents* activeWebContents = nullptr;
786 if (browser)
787 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
788 [self updateHandoffManager:activeWebContents];
[email protected]66791aff2014-04-29 09:45:38789 [self openStartupUrls];
[email protected]aac169d2011-03-18 19:53:03790
[email protected]05454532013-01-22 21:09:08791 PrefService* localState = g_browser_process->local_state();
792 if (localState) {
793 localPrefRegistrar_.Init(localState);
794 localPrefRegistrar_.Add(
795 prefs::kAllowFileSelectionDialogs,
796 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
797 menuState_.get()));
798 }
erikchen600f7962014-12-12 00:17:38799
800 handoff_active_url_observer_bridge_.reset(
801 new HandoffActiveURLObserverBridge(self));
Robert Sesek99845182017-08-24 20:53:33802
Robert Sesek1eb85222017-08-24 23:17:09803#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33804 // Disable fatal OOM to hack around an OS bug https://crbug.com/654695.
805 if (base::mac::IsOS10_12()) {
806 g_swizzle_imk_input_session = new base::mac::ScopedObjCClassSwizzler(
807 NSClassFromString(@"IMKInputSession"),
808 [OOMDisabledIMKInputSession class],
809 @selector(_coreAttributesFromRange:whichAttributes:completionHandler:));
810 }
Robert Sesek1eb85222017-08-24 23:17:09811#endif
[email protected]7c321082009-02-09 15:35:47812}
813
[email protected]73f5b362009-08-10 23:58:21814// Helper function for populating and displaying the in progress downloads at
815// exit alert panel.
816- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48817 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13818 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21819 NSString* waitTitle = nil;
820 NSString* exitTitle = nil;
821
822 // Set the dialog text based on whether or not there are multiple downloads.
jshinec68f032015-05-14 00:03:23823 // Dialog text: warning and explanation.
Bret Sepulveda331f10a2018-02-13 22:37:42824 titleText = l10n_util::GetPluralNSStringF(IDS_ABANDON_DOWNLOAD_DIALOG_TITLE,
825 downloadCount);
826 explanationText =
827 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_BROWSER_MESSAGE);
828 // "Cancel download and exit" button text.
829 exitTitle = l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_EXIT_BUTTON);
[email protected]83a9f652012-04-25 21:03:48830
Bret Sepulveda331f10a2018-02-13 22:37:42831 // "Wait for download" button text.
832 waitTitle =
833 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_CONTINUE_BUTTON);
[email protected]73f5b362009-08-10 23:58:21834
Elly Fong-Jonesbd6d39d2019-01-23 22:10:28835 base::scoped_nsobject<NSAlert> alert([[NSAlert alloc] init]);
836 [alert setMessageText:titleText];
837 [alert setInformativeText:explanationText];
838 [alert addButtonWithTitle:waitTitle];
839 [alert addButtonWithTitle:exitTitle];
840
[email protected]73f5b362009-08-10 23:58:21841 // 'waitButton' is the default choice.
Elly Fong-Jonesbd6d39d2019-01-23 22:10:28842 int choice = [alert runModal];
843 return choice == NSAlertFirstButtonReturn ? YES : NO;
[email protected]73f5b362009-08-10 23:58:21844}
845
846// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41847// user to see if we should continue to exit (and thus cancel the downloads), or
848// if we should wait.
849- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21850 ProfileManager* profile_manager = g_browser_process->profile_manager();
851 if (!profile_manager)
852 return YES;
[email protected]09729a552009-08-03 23:21:41853
[email protected]844a1002011-04-19 11:37:21854 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
Elly Fong-Jones08757f1e2018-01-31 16:24:44855
856 std::vector<Profile*> added_profiles;
857 for (Profile* p : profiles) {
858 if (p->HasOffTheRecordProfile())
859 added_profiles.push_back(p->GetOffTheRecordProfile());
860 }
861 profiles.insert(profiles.end(), added_profiles.begin(), added_profiles.end());
862
[email protected]844a1002011-04-19 11:37:21863 for (size_t i = 0; i < profiles.size(); ++i) {
peterccb33e82017-05-02 19:00:44864 DownloadCoreService* download_core_service =
865 DownloadCoreServiceFactory::GetForBrowserContext(profiles[i]);
[email protected]9bb54ee2011-10-12 17:43:35866 DownloadManager* download_manager =
peterccb33e82017-05-02 19:00:44867 (download_core_service->HasCreatedDownloadManager()
868 ? BrowserContext::GetDownloadManager(profiles[i])
869 : NULL);
[email protected]422a7d12013-10-21 12:10:42870 if (download_manager &&
871 download_manager->NonMaliciousInProgressCount() > 0) {
872 int downloadCount = download_manager->NonMaliciousInProgressCount();
[email protected]73f5b362009-08-10 23:58:21873 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
874 // Create a new browser window (if necessary) and navigate to the
875 // downloads page if the user chooses to wait.
scottmg34c5dd882016-02-03 05:21:54876 Browser* browser = chrome::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21877 if (!browser) {
erg7b01d692017-02-22 21:57:35878 browser = new Browser(Browser::CreateParams(profiles[i], true));
[email protected]73f5b362009-08-10 23:58:21879 browser->window()->Show();
880 }
881 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12882 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21883 return NO;
884 }
[email protected]09729a552009-08-03 23:21:41885
[email protected]73f5b362009-08-10 23:58:21886 // User wants to exit.
887 return YES;
[email protected]09729a552009-08-03 23:21:41888 }
[email protected]09729a552009-08-03 23:21:41889 }
890
[email protected]73f5b362009-08-10 23:58:21891 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41892 return YES;
893}
894
[email protected]fbc947b2009-06-19 13:28:24895// Called to determine if we should enable the "restore tab" menu item.
896// Checks with the TabRestoreService to see if there's anything there to
897// restore and returns YES if so.
898- (BOOL)canRestoreTab {
blundell74001adc2015-09-18 11:04:25899 sessions::TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35900 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24901 return service && !service->entries().empty();
902}
903
[email protected]1c62b2f2013-06-28 00:15:00904// Called from the AppControllerProfileObserver every time a profile is deleted.
905- (void)profileWasRemoved:(const base::FilePath&)profilePath {
[email protected]1c62b2f2013-06-28 00:15:00906 // If the lastProfile has been deleted, the profile manager has
907 // already loaded a new one, so the pointer needs to be updated;
908 // otherwise we will try to start up a browser window with a pointer
909 // to the old profile.
bauerb447f6432015-03-02 22:34:51910 // In a browser test, the application is not brought to the front, so
911 // |lastProfile_| might be null.
mlerman8ae56aa2015-04-24 13:56:27912 if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
913 // Force windowChangedToProfile: to set the lastProfile_ and also update the
914 // relevant menuBridge objects.
915 lastProfile_ = nullptr;
916 [self windowChangedToProfile:g_browser_process->profile_manager()->
917 GetLastUsedProfile()];
918 }
lgarron9e6dee22014-11-18 01:03:39919
avi82554752016-09-23 17:48:50920 profileBookmarkMenuBridgeMap_.erase(profilePath);
[email protected]1c62b2f2013-06-28 00:15:00921}
922
[email protected]05454532013-01-22 21:09:08923// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21924// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
925// sheets) will not count as blocking the browser. But things like open/save
926// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08927- (BOOL)keyWindowIsModal {
928 if ([NSApp modalWindow])
929 return YES;
930
[email protected]f2bc6e92012-10-14 02:08:38931 Browser* browser = chrome::GetLastActiveBrowser();
Christopher Cameron359c61e22018-10-18 08:06:20932 return browser && [[browser->window()->GetNativeWindow().GetNativeNSWindow()
933 attachedSheet] isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06934}
935
[email protected]88d74942009-01-21 22:04:44936// Called to validate menu items when there are no key windows. All the
937// items we care about have been set with the |commandDispatch:| action and
938// a target of FirstResponder in IB. If it's not one of those, let it
939// continue up the responder chain to be handled elsewhere. We pull out the
940// tag as the cross-platform constant to differentiate and dispatch the
941// various commands.
942- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
943 SEL action = [item action];
944 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08945 if (action == @selector(commandDispatch:) ||
946 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44947 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08948 if (menuState_ && // NULL in tests.
949 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24950 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26951 // The File Menu commands are not automatically disabled by Cocoa when a
952 // dialog sheet obscures the browser window, so we disable several of
953 // them here. We don't need to include IDC_CLOSE_WINDOW, because
954 // app_controller is only activated when there are no key windows (see
955 // function comment).
[email protected]fbc947b2009-06-19 13:28:24956 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08957 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06958 break;
[email protected]f6c15fa2010-06-04 20:08:21959 // Browser-level items that open in new tabs should not open if there's
960 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06961 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06962 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21963 case IDC_SHOW_HISTORY:
964 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08965 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21966 break;
967 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21968 case IDC_TASK_MANAGER:
969 // Allow the user to open a new window if there's a window-modal
970 // dialog.
[email protected]05454532013-01-22 21:09:08971 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24972 break;
973 default:
[email protected]f6c15fa2010-06-04 20:08:21974 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08975 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24976 }
977 }
spqchan9d60fce2016-02-10 18:30:47978
979 // "Show as tab" should only appear when the current window is a popup.
980 // Since |validateUserInterfaceItem:| is called only when there are no
981 // key windows, we should just hide this.
982 // This is handled outside of the switch statement because we want to hide
983 // this regardless if the command is supported or not.
984 if (tag == IDC_SHOW_AS_TAB) {
985 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
986 [menuItem setHidden:YES];
987 }
[email protected]3b6aa8b62009-09-15 21:36:11988 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44989 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52990 } else if (action == @selector(showPreferences:)) {
991 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07992 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
993 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47994 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38995 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48996 } else if (action == @selector(toggleConfirmToQuit:)) {
997 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
998 enable = YES;
[email protected]3a90b452013-02-15 04:33:48999 } else if (action == @selector(executeApplication:)) {
1000 enable = YES;
[email protected]88d74942009-01-21 22:04:441001 }
1002 return enable;
1003}
1004
[email protected]88d74942009-01-21 22:04:441005- (void)commandDispatch:(id)sender {
[email protected]2a39d1a2014-04-10 05:46:241006 Profile* lastProfile = [self safeLastProfileForNewWindows];
[email protected]f0a51fb52009-03-05 12:46:381007
[email protected]947fc0d2010-01-14 22:33:051008 // Handle the case where we're dispatching a command from a sender that's in a
1009 // browser window. This means that the command came from a background window
1010 // and is getting here because the foreground window is not a browser window.
1011 if ([sender respondsToSelector:@selector(window)]) {
1012 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041013 if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
[email protected]947fc0d2010-01-14 22:33:051014 [delegate commandDispatch:sender];
1015 return;
1016 }
1017 }
1018
[email protected]8d4bbdc2012-09-20 21:36:491019 // Ignore commands during session restore's browser creation. It uses a
gab2998ee72017-05-05 16:23:501020 // nested run loop and commands dispatched during this operation cause
[email protected]8d4bbdc2012-09-20 21:36:491021 // havoc.
Owen Min8c5d5382018-08-02 17:52:431022 if (lastProfile && SessionRestore::IsRestoring(lastProfile) &&
gab7af9dc02017-05-05 13:38:541023 base::RunLoop::IsNestedOnCurrentThread()) {
[email protected]8d4bbdc2012-09-20 21:36:491024 return;
gab7af9dc02017-05-05 13:38:541025 }
[email protected]8d4bbdc2012-09-20 21:36:491026
Trent Apted45d9ae22017-11-09 23:12:321027 // If not between -applicationDidFinishLaunching: and
1028 // -applicationWillTerminate:, ignore. This can happen when events are sitting
1029 // in the event queue while the browser is shutting down.
1030 if (!keep_alive_)
1031 return;
1032
[email protected]88d74942009-01-21 22:04:441033 NSInteger tag = [sender tag];
[email protected]7108d912014-01-30 08:10:451034
1035 // If there are no browser windows, and we are trying to open a browser
Owen Min027059d2018-03-13 22:17:361036 // for a locked profile or the system profile or the guest profile but
1037 // guest mode is disabled, we have to show the User Manager instead as the
1038 // locked profile needs authentication and the system profile cannot have a
1039 // browser.
1040 const PrefService* prefService = g_browser_process->local_state();
1041 if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile() ||
1042 (lastProfile->IsGuestSession() && prefService &&
1043 !prefService->GetBoolean(prefs::kBrowserGuestModeEnabled))) {
mlermane6e040a2014-10-31 00:53:211044 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261045 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
[email protected]7108d912014-01-30 08:10:451046 return;
1047 }
1048
[email protected]88d74942009-01-21 22:04:441049 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:241050 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:111051 // Create a new tab in an existing browser window (which we activate) if
1052 // possible.
[email protected]a585a8db2011-06-20 18:58:351053 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:401054 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:111055 break;
1056 }
Nico Weber331a98a82018-02-06 23:26:011057 FALLTHROUGH; // To create new window.
[email protected]88d74942009-01-21 22:04:441058 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:351059 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:111060 break;
[email protected]91a5b3e2009-10-30 19:32:221061 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:401062 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1063 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:441064 break;
[email protected]cddc5242009-12-07 18:54:331065 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:401066 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1067 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:331068 break;
[email protected]863ff662009-01-26 20:18:181069 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:481070 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:181071 break;
[email protected]fbc947b2009-06-19 13:28:241072 case IDC_RESTORE_TAB:
scottmgd161e6c2016-02-17 02:08:011073 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:241074 break;
[email protected]e19516d2009-04-28 17:15:191075 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:401076 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:191077 break;
[email protected]1fdff702009-10-22 00:36:181078 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:381079 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:351080 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121081 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231082 } else {
[email protected]1f0b50b2012-06-22 20:37:161083 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231084 }
[email protected]93e181762009-05-29 14:30:381085 break;
[email protected]1fdff702009-10-22 00:36:181086 }
[email protected]4aee5652009-11-19 18:59:211087 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:351088 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121089 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231090 } else {
[email protected]1f0b50b2012-06-22 20:37:161091 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231092 }
[email protected]4aee5652009-11-19 18:59:211093 break;
1094 }
[email protected]af7c25e2010-01-23 05:46:451095 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]a585a8db2011-06-20 18:58:351096 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121097 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:471098 } else {
[email protected]47e532b2010-04-23 17:46:401099 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:161100 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:471101 }
[email protected]af7c25e2010-01-23 05:46:451102 break;
[email protected]91a5b3e2009-10-30 19:32:221103 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:351104 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121105 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:111106 else
[email protected]1f0b50b2012-06-22 20:37:161107 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221108 break;
1109 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:351110 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121111 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:111112 else
[email protected]1f0b50b2012-06-22 20:37:161113 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221114 break;
[email protected]bb37e6ec2009-11-18 17:59:361115 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:351116 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:081117 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:111118 else
[email protected]1f0b50b2012-06-22 20:37:161119 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:361120 break;
[email protected]2ca35612012-06-12 03:49:481121 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:351122 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121123 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:111124 else
[email protected]1f0b50b2012-06-22 20:37:161125 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:181126 break;
[email protected]ceaaf1812010-01-20 22:13:091127 case IDC_TASK_MANAGER:
mlermane6e040a2014-10-31 00:53:211128 chrome::OpenTaskManager(NULL);
[email protected]ceaaf1812010-01-20 22:13:091129 break;
[email protected]4a42d272010-06-18 01:29:421130 case IDC_OPTIONS:
1131 [self showPreferences:sender];
1132 break;
[email protected]d630d7d52010-02-21 00:55:111133 }
[email protected]88d74942009-01-21 22:04:441134}
1135
[email protected]93b59fc2010-12-21 20:00:471136// Run a (background) application in a new tab.
1137- (void)executeApplication:(id)sender {
1138 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351139 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471140 DCHECK(profile);
1141 BackgroundApplicationListModel applications(profile);
1142 DCHECK(tag >= 0 &&
1143 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341144 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331145 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471146}
1147
[email protected]947fc0d2010-01-14 22:33:051148// Same as |-commandDispatch:|, but executes commands using a disposition
1149// determined by the key flags. This will get called in the case where the
1150// frontmost window is not a browser window, and the user has command-clicked
1151// a button in a background browser window whose action is
1152// |-commandDispatchUsingKeyModifiers:|
1153- (void)commandDispatchUsingKeyModifiers:(id)sender {
1154 DCHECK(sender);
1155 if ([sender respondsToSelector:@selector(window)]) {
1156 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041157 if ([delegate respondsToSelector:
1158 @selector(commandDispatchUsingKeyModifiers:)]) {
[email protected]947fc0d2010-01-14 22:33:051159 [delegate commandDispatchUsingKeyModifiers:sender];
1160 }
1161 }
1162}
1163
[email protected]2e29e2232013-07-26 10:40:591164// NSApplication delegate method called when someone clicks on the dock icon.
1165// To match standard mac behavior, we should open a new window if there are no
1166// browser windows.
[email protected]ff81e0a2009-04-13 14:58:541167- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581168 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541169 // If the browser is currently trying to quit, don't do anything and return NO
1170 // to prevent AppKit from doing anything.
1171 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1172 if (browser_shutdown::IsTryingToQuit())
1173 return NO;
1174
[email protected]2e29e2232013-07-26 10:40:591175 // Bring all browser windows to the front. Specifically, this brings them in
1176 // front of any app windows. FocusWindowSet will also unminimize the most
1177 // recently minimized window if no windows in the set are visible.
[email protected]a25920ee2013-09-05 19:38:491178 // If there are any, return here. Otherwise, the windows are panels or
1179 // notifications so we still need to open a new window.
[email protected]bf193bc52013-06-08 04:39:581180 if (hasVisibleWindows) {
Christopher Cameron359c61e22018-10-18 08:06:201181 std::set<gfx::NativeWindow> browserWindows;
scottmg8abbff832016-01-28 22:57:371182 for (auto* browser : *BrowserList::GetInstance()) {
mitchelljonese59a1612014-12-16 00:34:591183 // When focusing Chrome, don't focus any browser windows associated with
1184 // a currently running app shim, so ignore them.
Joel Hockey2687ab52019-08-14 23:59:461185 if (browser && browser->deprecated_is_app()) {
mitchelljonesf00422082015-01-05 23:38:031186 extensions::ExtensionRegistry* registry =
1187 extensions::ExtensionRegistry::Get(browser->profile());
1188 const extensions::Extension* extension = registry->GetExtensionById(
Alexey Baskakov2ce2ffc842018-08-06 02:57:151189 web_app::GetAppIdFromApplicationName(browser->app_name()),
mitchelljonesf00422082015-01-05 23:38:031190 extensions::ExtensionRegistry::ENABLED);
mitchelljonesb118a0c2015-01-07 02:51:341191 if (extension && extension->is_hosted_app())
mitchelljonese59a1612014-12-16 00:34:591192 continue;
mitchelljonese59a1612014-12-16 00:34:591193 }
[email protected]2e29e2232013-07-26 10:40:591194 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]0236be22012-01-11 01:05:351195 }
[email protected]a25920ee2013-09-05 19:38:491196 if (!browserWindows.empty()) {
[email protected]d4c811e72013-10-29 21:57:551197 NSWindow* keyWindow = [NSApp keyWindow];
1198 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1199 // The key window is not on the active space. We must be mid-animation
1200 // for a space transition triggered by the dock. Delay the call to
1201 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1202 // wrong space's windows get raised, resulting in an off-screen key
1203 // window. It does not work to |ui::FocusWindowSet| twice, once here
1204 // and once in |activeSpaceDidChange:|, as that appears to break when
1205 // the omnibox is focused.
1206 //
1207 // This check relies on OS X setting the key window to a window on the
1208 // target space before calling this method.
1209 //
1210 // See http://crbug.com/309656.
1211 reopenTime_ = base::TimeTicks::Now();
1212 } else {
[email protected]6c4b79602014-05-28 16:47:211213 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:551214 }
1215 // Return NO; we've done (or soon will do) the deminiaturize, so
1216 // AppKit shouldn't do anything.
[email protected]a25920ee2013-09-05 19:38:491217 return NO;
1218 }
[email protected]0236be22012-01-11 01:05:351219 }
[email protected]ff81e0a2009-04-13 14:58:541220
[email protected]0d1210d62010-09-07 17:31:381221 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481222 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381223 // allow session to be restored first time the user clicks on a Dock icon.
1224 // Normally, it'd just open a new empty page.
1225 {
[email protected]eddcf7502012-02-09 22:43:481226 static BOOL doneOnce = NO;
[email protected]70593e52014-05-15 08:30:231227 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1228 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1229 doneOnce = YES;
1230 if (attemptRestore) {
1231 SessionService* sessionService =
1232 SessionServiceFactory::GetForProfileForSessionRestore(
1233 [self lastProfile]);
1234 if (sessionService &&
Findit046795722018-10-03 11:44:481235 sessionService->RestoreIfNecessary(std::vector<GURL>()))
[email protected]70593e52014-05-15 08:30:231236 return NO;
[email protected]eddcf7502012-02-09 22:43:481237 }
[email protected]0d1210d62010-09-07 17:31:381238 }
[email protected]fc44f242012-02-14 16:54:391239
[email protected]ff81e0a2009-04-13 14:58:541240 // Otherwise open a new window.
[email protected]7108d912014-01-30 08:10:451241 // If the last profile was locked, we have to open the User Manager, as the
mlerman7831f57d2015-05-25 11:40:151242 // profile requires authentication. Similarly, because guest mode and system
1243 // profile are implemented as forced incognito, we can't open a new guest
1244 // browser either, so we have to show the User Manager as well.
[email protected]7108d912014-01-30 08:10:451245 Profile* lastProfile = [self lastProfile];
mlerman7831f57d2015-05-25 11:40:151246 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1247 lastProfile->IsSystemProfile()) {
mlermane6e040a2014-10-31 00:53:211248 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261249 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1250 } else {
[email protected]7108d912014-01-30 08:10:451251 CreateBrowser(lastProfile);
mlermane29d0032014-09-24 19:31:261252 }
[email protected]ff81e0a2009-04-13 14:58:541253
1254 // We've handled the reopen event, so return NO to tell AppKit not
1255 // to do anything.
1256 return NO;
1257}
1258
[email protected]88d74942009-01-21 22:04:441259- (void)initMenuState {
Ivan Sandrk9669d0e2017-12-15 23:50:201260 menuState_ = std::make_unique<CommandUpdaterImpl>(nullptr);
[email protected]fbc947b2009-06-19 13:28:241261 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441262 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181263 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191264 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381265 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241266 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221267 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331268 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451269 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221270 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1271 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361272 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481273 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211274 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
Nico Webereaa08412019-08-14 01:24:371275#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
[email protected]1c41a932010-11-22 23:41:231276 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]236ad3022013-09-04 03:27:431277#endif
[email protected]ceaaf1812010-01-20 22:13:091278 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441279}
[email protected]1bcdb532009-01-16 17:47:571280
[email protected]961a6932011-07-19 19:52:461281// Conditionally adds the Profile menu to the main menu bar.
1282- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461283 NSMenu* mainMenu = [NSApp mainMenu];
1284 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401285
[email protected]de71ae992013-07-18 03:30:381286 if (!profiles::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401287 [mainMenu removeItem:profileMenu];
1288 return;
1289 }
1290
[email protected]6b2d30bc2011-10-11 18:16:391291 // The controller will unhide the menu if necessary.
1292 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461293
[email protected]6b2d30bc2011-10-11 18:16:391294 profileMenuController_.reset(
1295 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461296}
1297
Leonard Grey2bdd08f2017-10-03 18:40:521298- (void)initShareMenu {
1299 shareMenuController_.reset([[ShareMenuController alloc] init]);
1300 NSMenu* mainMenu = [NSApp mainMenu];
1301 NSMenu* fileMenu = [[mainMenu itemWithTag:IDC_FILE_MENU] submenu];
1302 NSString* shareMenuTitle = l10n_util::GetNSString(IDS_SHARE_MAC);
Leonard Grey34b5e622018-07-30 19:05:551303 NSMenuItem* shareMenuItem = [fileMenu itemWithTitle:shareMenuTitle];
Leonard Grey2bdd08f2017-10-03 18:40:521304 base::scoped_nsobject<NSMenu> shareSubmenu(
1305 [[NSMenu alloc] initWithTitle:shareMenuTitle]);
1306 [shareSubmenu setDelegate:shareMenuController_];
1307 [shareMenuItem setSubmenu:shareSubmenu];
Leonard Grey2bdd08f2017-10-03 18:40:521308}
1309
[email protected]a99fce0e2011-03-21 20:58:481310// The Confirm to Quit preference is atypical in that the preference lives in
1311// the app menu right above the Quit menu item. This method will refresh the
1312// display of that item depending on the preference state.
1313- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1314 // Format the string so that the correct key equivalent is displayed.
1315 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1316 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1317 base::SysNSStringToUTF16(acceleratorString));
1318 [item setTitle:title];
1319
[email protected]b6366ffa2012-02-29 17:12:261320 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481321 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1322 [item setState:enabled ? NSOnState : NSOffState];
1323}
1324
[email protected]eef99c22010-08-17 05:55:161325- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411326 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1327 // handles requests from services.
Avi Drissmana0820222018-09-01 18:02:281328 NSArray* types = @[ base::mac::CFToNSCast(kUTTypeUTF8PlainText) ];
[email protected]09ea24c2010-08-23 19:05:411329 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161330}
1331
Owen Min8c5d5382018-08-02 17:52:431332// Return null if Chrome is not ready or there is no ProfileManager.
[email protected]a585a8db2011-06-20 18:58:351333- (Profile*)lastProfile {
andresantoso55fd2512015-04-01 21:07:041334 // Return the profile of the last-used Browser, if available.
[email protected]7fd5a462011-06-19 16:57:231335 if (lastProfile_)
1336 return lastProfile_;
1337
Owen Min8c5d5382018-08-02 17:52:431338 if (![self isProfileReady])
1339 return nullptr;
1340
[email protected]fbb04552014-01-16 15:47:381341 // On first launch, use the logic that ChromeBrowserMain uses to determine
1342 // the initial profile.
1343 ProfileManager* profile_manager = g_browser_process->profile_manager();
1344 if (!profile_manager)
Owen Min8c5d5382018-08-02 17:52:431345 return nullptr;
[email protected]3f34599d2009-03-25 22:11:431346
avi3ef9ec9e2014-12-22 22:50:171347 return profile_manager->GetProfile(
1348 GetStartupProfilePath(profile_manager->user_data_dir(),
1349 *base::CommandLine::ForCurrentProcess()));
[email protected]3f34599d2009-03-25 22:11:431350}
1351
[email protected]2a39d1a2014-04-10 05:46:241352- (Profile*)safeLastProfileForNewWindows {
1353 Profile* profile = [self lastProfile];
1354
Owen Min8c5d5382018-08-02 17:52:431355 if (!profile)
1356 return nullptr;
1357
[email protected]2a39d1a2014-04-10 05:46:241358 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1359 if (profile->IsGuestSession())
1360 return profile->GetOffTheRecordProfile();
1361
1362 return profile;
1363}
1364
mlermane6e040a2014-10-31 00:53:211365// Returns true if a browser window may be opened for the last active profile.
1366- (bool)canOpenNewBrowser {
1367 Profile* profile = [self safeLastProfileForNewWindows];
1368
1369 const PrefService* prefs = g_browser_process->local_state();
1370 return !profile->IsGuestSession() ||
1371 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1372}
1373
[email protected]57750f822009-04-21 21:43:091374// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031375// StartupBrowserCreator here because on the other platforms, URLs to open come
1376// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1377// to bottleneck the openings through that for uniform handling.
[email protected]d630d7d52010-02-21 00:55:111378- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211379 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111380 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251381 return;
1382 }
Christian Dullweber820ee5f2018-04-26 13:24:311383 // Pick the last used browser from a regular profile to open the urls.
1384 Profile* profile =
1385 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
1386 Browser* browser = chrome::FindLastActiveWithProfile(profile);
Scott Violet1f106b582017-07-12 15:49:581387 // if no browser window exists then create one with no tabs to be filled in
1388 if (!browser) {
1389 browser = new Browser(
1390 Browser::CreateParams([self safeLastProfileForNewWindows], true));
1391 browser->window()->Show();
eugenebng7afbc36e2017-06-15 13:38:471392 }
Scott Violet1f106b582017-07-12 15:49:581393
1394 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1395 chrome::startup::IsFirstRun first_run =
1396 first_run::IsChromeFirstRun() ? chrome::startup::IS_FIRST_RUN
1397 : chrome::startup::IS_NOT_FIRST_RUN;
1398 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1399 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091400}
1401
[email protected]57750f822009-04-21 21:43:091402- (void)getUrl:(NSAppleEventDescriptor*)event
1403 withReply:(NSAppleEventDescriptor*)reply {
1404 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1405 stringValue];
1406
1407 GURL gurl(base::SysNSStringToUTF8(urlStr));
1408 std::vector<GURL> gurlVector;
1409 gurlVector.push_back(gurl);
1410
erikchen19ee3922014-10-31 19:14:221411 [self openUrlsReplacingNTP:gurlVector];
[email protected]57750f822009-04-21 21:43:091412}
1413
[email protected]caadfca2010-01-22 21:51:211414- (void)application:(NSApplication*)sender
1415 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091416 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211417 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451418 GURL gurl =
[email protected]77d83542013-12-13 08:54:291419 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
[email protected]57750f822009-04-21 21:43:091420 gurlVector.push_back(gurl);
1421 }
[email protected]caadfca2010-01-22 21:51:211422 if (!gurlVector.empty())
erikchen19ee3922014-10-31 19:14:221423 [self openUrlsReplacingNTP:gurlVector];
[email protected]caadfca2010-01-22 21:51:211424 else
1425 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091426
[email protected]caadfca2010-01-22 21:51:211427 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091428}
[email protected]3f34599d2009-03-25 22:11:431429
[email protected]3111f08b2009-04-30 16:01:521430// Show the preferences window, or bring it to the front if it's already
1431// visible.
1432- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351433 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051434 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121435 chrome::ShowSettings(browser);
mlermane6e040a2014-10-31 00:53:211436 } else if ([self canOpenNewBrowser]) {
[email protected]445177652011-03-09 02:04:051437 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241438 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211439 } else {
1440 // No way to create a browser, default to the User Manager.
1441 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211442 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
[email protected]4a42d272010-06-18 01:29:421443 }
[email protected]d989f07c2009-11-14 00:35:461444}
1445
[email protected]bde3dda2009-05-20 22:13:071446- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561447 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121448 chrome::ShowAboutChrome(browser);
mlermane6e040a2014-10-31 00:53:211449 } else if ([self canOpenNewBrowser]) {
1450 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241451 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211452 } else {
1453 // No way to create a browser, default to the User Manager.
1454 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211455 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
[email protected]bde3dda2009-05-20 22:13:071456 }
[email protected]bde3dda2009-05-20 22:13:071457}
1458
[email protected]a99fce0e2011-03-21 20:58:481459- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261460 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481461 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1462 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1463}
1464
[email protected]3d4bd23f2009-10-06 03:58:381465// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471466- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381467 [NSApp activateIgnoringOtherApps:YES];
1468 [self commandDispatch:sender];
1469}
1470
[email protected]227fcee2010-06-11 19:19:371471- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441472 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351473 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471474
[email protected]646fadbf2012-09-08 01:49:011475 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1476 atOffset:0
1477 fromDock:YES];
1478 if (profilesAdded)
1479 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331480
[email protected]646fadbf2012-09-08 01:49:011481 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461482 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511483 [[NSMenuItem alloc] initWithTitle:titleStr
1484 action:@selector(commandFromDock:)
1485 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461486 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011487 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081488 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011489 [dockMenu addItem:item];
1490
[email protected]8d10a412013-08-09 19:18:001491 // |profile| can be NULL during unit tests.
treib6f9598012014-11-11 12:21:241492 if (!profile ||
1493 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1494 IncognitoModePrefs::DISABLED) {
[email protected]8d10a412013-08-09 19:18:001495 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1496 item.reset(
1497 [[NSMenuItem alloc] initWithTitle:titleStr
1498 action:@selector(commandFromDock:)
1499 keyEquivalent:@""]);
1500 [item setTarget:self];
1501 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1502 [item setEnabled:[self validateUserInterfaceItem:item]];
1503 [dockMenu addItem:item];
1504 }
[email protected]288bfcd32009-09-14 18:14:461505
[email protected]8c6b029d2011-01-21 22:39:511506 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1507 // tests which use the mock in place of the profile-initialized model.
1508
1509 // Avoid breaking unit tests which have no profile.
1510 if (profile) {
1511 BackgroundApplicationListModel applications(profile);
1512 if (applications.size()) {
1513 int position = 0;
1514 NSString* menuStr =
1515 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461516 base::scoped_nsobject<NSMenu> appMenu(
1517 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341518 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481519 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511520 cursor != applications.end();
1521 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501522 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511523 NSString* itemStr =
[email protected]670d3232013-12-24 17:58:581524 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461525 base::scoped_nsobject<NSMenuItem> appItem(
1526 [[NSMenuItem alloc] initWithTitle:itemStr
1527 action:@selector(executeApplication:)
1528 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511529 [appItem setTarget:self];
1530 [appItem setTag:position];
1531 [appMenu addItem:appItem];
1532 }
[email protected]8c6b029d2011-01-21 22:39:511533 }
1534 }
1535
[email protected]018a3962009-09-17 22:23:441536 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461537}
1538
[email protected]d630d7d52010-02-21 00:55:111539- (const std::vector<GURL>&)startupUrls {
1540 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211541}
1542
[email protected]7e4c69d02011-05-11 22:16:471543- (BookmarkMenuBridge*)bookmarkMenuBridge {
lgarron9e6dee22014-11-18 01:03:391544 return bookmarkMenuBridge_;
[email protected]7e4c69d02011-05-11 22:16:471545}
1546
mlerman8ae56aa2015-04-24 13:56:271547- (HistoryMenuBridge*)historyMenuBridge {
1548 return historyMenuBridge_.get();
1549}
1550
Elly Fong-Jones0d121842019-08-12 22:03:401551- (TabMenuBridge*)tabMenuBridge {
1552 return tabMenuBridge_.get();
1553}
1554
[email protected]e7dc3992013-11-06 02:16:421555- (void)initAppShimMenuController {
[email protected]e4c63ec2014-01-14 15:50:541556 if (!appShimMenuController_)
[email protected]e7dc3992013-11-06 02:16:421557 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1558}
1559
nomsdd5b6a612014-09-23 15:20:161560- (void)windowChangedToProfile:(Profile*)profile {
1561 if (lastProfile_ == profile)
1562 return;
1563
lgarron9e6dee22014-11-18 01:03:391564 // Before tearing down the menu controller bridges, return the history menu to
1565 // its initial state.
1566 if (historyMenuBridge_)
nomsdd5b6a612014-09-23 15:20:161567 historyMenuBridge_->ResetMenu();
1568
dominicknb80838f2015-09-08 23:00:131569 // Rebuild the menus with the new profile. The bookmarks submenu is cached to
1570 // avoid slowdowns when switching between profiles with large numbers of
1571 // bookmarks. Before caching, store whether it is hidden, make the menu item
1572 // visible, and restore its original hidden state after resetting the submenu.
1573 // This works around an apparent AppKit bug where setting a *different* NSMenu
1574 // submenu on a *hidden* menu item forces the item to become visible.
1575 // See https://crbug.com/497813 for more details.
1576 NSMenuItem* bookmarkItem = [[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU];
1577 BOOL hidden = [bookmarkItem isHidden];
1578 [bookmarkItem setHidden:NO];
nomsdd5b6a612014-09-23 15:20:161579 lastProfile_ = profile;
1580
Trent Aptedcf95689a2017-11-22 00:01:101581 auto& entry = profileBookmarkMenuBridgeMap_[profile->GetPath()];
1582 if (!entry) {
1583 // This creates a deep copy, but only the first 3 items in the root menu
1584 // are really wanted. This can probably be optimized, but lazy-loading of
1585 // the menu should reduce the impact in most flows.
dominicknb80838f2015-09-08 23:00:131586 base::scoped_nsobject<NSMenu> submenu([[bookmarkItem submenu] copy]);
Trent Aptedcf95689a2017-11-22 00:01:101587 [submenu setDelegate:nil]; // The delegate is also copied. Remove it.
1588
1589 entry = std::make_unique<BookmarkMenuBridge>(profile, submenu);
1590
1591 // Clear bookmarks from the old profile.
1592 entry->ClearBookmarkMenu();
lgarron9e6dee22014-11-18 01:03:391593 }
Trent Aptedcf95689a2017-11-22 00:01:101594 bookmarkMenuBridge_ = entry.get();
lgarron9e6dee22014-11-18 01:03:391595
nomsdd5b6a612014-09-23 15:20:161596 // No need to |BuildMenu| here. It is done lazily upon menu access.
dominicknb80838f2015-09-08 23:00:131597 [bookmarkItem setSubmenu:bookmarkMenuBridge_->BookmarkMenu()];
1598 [bookmarkItem setHidden:hidden];
nomsdd5b6a612014-09-23 15:20:161599
1600 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1601 historyMenuBridge_->BuildMenu();
1602
1603 chrome::BrowserCommandController::
1604 UpdateSharedCommandsForIncognitoAvailability(
1605 menuState_.get(), lastProfile_);
1606 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1607 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1608 profilePrefRegistrar_->Add(
1609 prefs::kIncognitoModeAvailability,
1610 base::Bind(&chrome::BrowserCommandController::
1611 UpdateSharedCommandsForIncognitoAvailability,
1612 menuState_.get(),
1613 lastProfile_));
1614}
1615
erikchen22be2092018-06-12 15:54:001616- (void)updateMenuItemKeyEquivalents {
1617 BOOL enableCloseTabShortcut = NO;
1618 id target = [NSApp targetForAction:@selector(performClose:)];
1619
1620 // |target| is an instance of NSPopover or NSWindow.
1621 // If a popover (likely the dictionary lookup popover), we want Cmd-W to
1622 // close the popover so map it to "Close Window".
1623 // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
1624 if ([target isKindOfClass:[NSWindow class]]) {
1625 NSWindow* window = target;
1626 NSWindow* mainWindow = [NSApp mainWindow];
1627 if (!window || ([window parentWindow] == mainWindow)) {
1628 // If the target window is a child of the main window (e.g. a bubble), the
1629 // main window should be the one that handles the close menu item action.
1630 window = mainWindow;
1631 }
1632 Browser* browser = chrome::FindBrowserWithWindow(window);
Joel Hockey2687ab52019-08-14 23:59:461633 enableCloseTabShortcut = browser && browser->is_type_normal();
erikchen22be2092018-06-12 15:54:001634 }
1635
1636 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
1637 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
1638}
1639
[email protected]92747fe42014-08-18 23:25:261640- (BOOL)application:(NSApplication*)application
Elly Fong-Jones397009ea2019-01-25 17:41:581641 willContinueUserActivityWithType:(NSString*)userActivityType {
[email protected]92747fe42014-08-18 23:25:261642 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1643}
1644
1645- (BOOL)application:(NSApplication*)application
1646 continueUserActivity:(NSUserActivity*)userActivity
Leonard Greybc00f8862018-09-26 17:24:221647#if !defined(MAC_OS_X_VERSION_10_14) || \
1648 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_14
Peter Collingbournefc74af32017-07-10 21:00:181649 restorationHandler:(void (^)(NSArray*))restorationHandler
Leonard Greybc00f8862018-09-26 17:24:221650#else
1651 restorationHandler:
1652 (void (^)(NSArray<id<NSUserActivityRestoring>>*))restorationHandler
1653#endif
Elly Fong-Jones397009ea2019-01-25 17:41:581654{
[email protected]92747fe42014-08-18 23:25:261655 if (![userActivity.activityType
1656 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1657 return NO;
1658 }
1659
erikchen96e537d52014-10-28 23:43:171660 NSString* originString = base::mac::ObjCCast<NSString>(
1661 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1662 handoff::Origin origin = handoff::OriginFromString(originString);
1663 UMA_HISTOGRAM_ENUMERATION(
1664 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1665
jiangjc0c568c2014-12-04 19:02:121666 NSURL* url = userActivity.webpageURL;
[email protected]92747fe42014-08-18 23:25:261667 if (!url)
1668 return NO;
1669
1670 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1671 std::vector<GURL> gurlVector;
1672 gurlVector.push_back(gurl);
1673
erikchen19ee3922014-10-31 19:14:221674 [self openUrlsReplacingNTP:gurlVector];
[email protected]92747fe42014-08-18 23:25:261675 return YES;
1676}
1677
1678- (void)application:(NSApplication*)application
1679 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1680 error:(NSError*)error {
1681}
1682
erikchen600f7962014-12-12 00:17:381683#pragma mark - Handoff Manager
1684
erikchen600f7962014-12-12 00:17:381685- (void)passURLToHandoffManager:(const GURL&)handoffURL {
Elly Fong-Jones397009ea2019-01-25 17:41:581686 [handoffManager_ updateActiveURL:handoffURL];
erikchen600f7962014-12-12 00:17:381687}
1688
1689- (void)updateHandoffManager:(content::WebContents*)webContents {
erikchen600f7962014-12-12 00:17:381690 if (!handoffManager_)
1691 handoffManager_.reset([[HandoffManager alloc] init]);
1692
1693 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1694 [self passURLToHandoffManager:handoffURL];
1695}
1696
1697- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1698 if (!webContents)
1699 return GURL();
1700
1701 Profile* profile =
1702 Profile::FromBrowserContext(webContents->GetBrowserContext());
1703 if (!profile)
1704 return GURL();
1705
1706 // Handoff is not allowed from an incognito profile. To err on the safe side,
1707 // also disallow Handoff from a guest profile.
Ramin Halavati7784def0d2019-05-20 09:20:461708 if (!profile->IsRegularProfile())
erikchen600f7962014-12-12 00:17:381709 return GURL();
1710
1711 if (!webContents)
1712 return GURL();
1713
1714 return webContents->GetVisibleURL();
1715}
1716
Owen Min8c5d5382018-08-02 17:52:431717- (BOOL)isProfileReady {
1718 return !g_browser_process->browser_policy_connector()
1719 ->machine_level_user_cloud_policy_controller()
1720 ->IsEnterpriseStartupDialogShowing();
1721}
1722
erikchen600f7962014-12-12 00:17:381723#pragma mark - HandoffActiveURLObserverBridgeDelegate
1724
1725- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1726 [self updateHandoffManager:webContents];
1727}
1728
[email protected]d630d7d52010-02-21 00:55:111729@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191730
1731//---------------------------------------------------------------------------
1732
Elly Fong-Jones68b85b82018-04-21 00:36:541733namespace {
1734
1735void UpdateProfileInUse(Profile* profile, Profile::CreateStatus status) {
1736 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1737 AppController* controller =
1738 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1739 [controller windowChangedToProfile:profile];
1740 }
1741}
1742
1743} // namespace
1744
[email protected]216e9042009-10-29 17:05:231745namespace app_controller_mac {
1746
1747bool IsOpeningNewWindow() {
1748 return g_is_opening_new_window;
1749}
1750
Elly Fong-Jones68b85b82018-04-21 00:36:541751void CreateGuestProfileIfNeeded() {
1752 g_browser_process->profile_manager()->CreateProfileAsync(
1753 ProfileManager::GetGuestProfilePath(),
Marc Treib92127162018-08-27 14:20:031754 base::BindRepeating(&UpdateProfileInUse), base::string16(),
Elly Fong-Jones68b85b82018-04-21 00:36:541755 std::string());
1756}
1757
Owen Min3bcf8d152018-07-16 16:50:391758void EnterpriseStartupDialogClosed() {
1759 AppController* controller =
1760 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1761 if (controller != nil) {
1762 NSNotification* notify = [NSNotification
1763 notificationWithName:NSApplicationDidFinishLaunchingNotification
1764 object:NSApp];
1765 [controller applicationDidFinishLaunching:notify];
1766 }
1767}
1768
[email protected]216e9042009-10-29 17:05:231769} // namespace app_controller_mac