blob: e767e544eaa9be1b8905e4527b20aa2893b37fca [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"
[email protected]1a3aba82010-11-08 23:52:5430#include "chrome/app/chrome_command_ids.h"
tapted63829f72014-09-24 23:50:5031#include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
Dominick Ng6ff51052018-07-06 05:30:2032#include "chrome/browser/apps/platform_apps/app_window_registry_util.h"
[email protected]a07676b22011-06-17 16:36:5333#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3334#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0735#include "chrome/browser/browser_process.h"
[email protected]fdf40f3e2013-07-11 23:55:4636#include "chrome/browser/chrome_notification_types.h"
Ivan Sandrk9669d0e2017-12-15 23:50:2037#include "chrome/browser/command_updater_impl.h"
peterccb33e82017-05-02 19:00:4438#include "chrome/browser/download/download_core_service.h"
39#include "chrome/browser/download/download_core_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3240#include "chrome/browser/extensions/extension_service.h"
[email protected]e4a377cf2011-10-05 02:51:4941#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2542#include "chrome/browser/lifetime/application_lifetime.h"
Avi Drissmand30927342018-05-22 15:04:2743#include "chrome/browser/lifetime/browser_shutdown.h"
[email protected]7d1aaa62014-07-18 02:21:3044#include "chrome/browser/mac/mac_startup_profiler.h"
Owen Min0b002e192018-07-10 15:04:1845#include "chrome/browser/policy/chrome_browser_policy_connector.h"
46#include "chrome/browser/policy/machine_level_user_cloud_policy_controller.h"
treib6f9598012014-11-11 12:21:2447#include "chrome/browser/prefs/incognito_mode_prefs.h"
lwchkg9c183942016-03-13 06:29:5448#include "chrome/browser/profiles/profile_attributes_entry.h"
49#include "chrome/browser/profiles/profile_attributes_storage.h"
[email protected]8ecad5e2010-12-02 21:18:3350#include "chrome/browser/profiles/profile_manager.h"
[email protected]de71ae992013-07-18 03:30:3851#include "chrome/browser/profiles/profiles_state.h"
[email protected]8d4bbdc2012-09-20 21:36:4952#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5053#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1554#include "chrome/browser/sessions/session_service_factory.h"
[email protected]92371eb2011-04-28 11:50:1555#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]074311a2013-02-28 23:14:0956#include "chrome/browser/signin/signin_manager_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"
[email protected]ccfab592013-01-15 06:24:3279#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]4feb37d92012-07-01 20:22:1380#include "chrome/browser/ui/startup/startup_browser_creator.h"
81#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
andresantoso55fd2512015-04-01 21:07:0482#include "chrome/browser/ui/tabs/tab_strip_model.h"
mlermane29d0032014-09-24 19:31:2683#include "chrome/browser/ui/user_manager.h"
Alexey Baskakov2ce2ffc842018-08-06 02:57:1584#include "chrome/browser/web_applications/components/web_app_helpers.h"
Alexey Baskakovf302efe2018-07-28 02:02:3285#include "chrome/browser/web_applications/components/web_app_shortcut_mac.h"
spqchan210e2ed2017-07-27 23:17:4086#include "chrome/common/chrome_features.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"
maxbogue26f40222016-09-16 20:22:1896#include "components/browser_sync/profile_sync_service.h"
erikchen600f7962014-12-12 00:17:3897#include "components/handoff/handoff_manager.h"
erikchen332265b2014-11-14 19:59:5298#include "components/handoff/handoff_utility.h"
Michael Giuffrida2dbce0d12017-09-02 03:30:5999#include "components/keep_alive_registry/keep_alive_types.h"
100#include "components/keep_alive_registry/scoped_keep_alive.h"
brettwb1fc1b82016-02-02 00:19:08101#include "components/prefs/pref_service.h"
blundella08c5dd2015-09-18 06:14:16102#include "components/sessions/core/tab_restore_service.h"
[email protected]7fbd3b12014-04-01 11:19:16103#include "components/signin/core/browser/signin_manager.h"
[email protected]e582fdd2011-12-20 16:48:17104#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:07105#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:16106#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:20107#include "content/public/browser/plugin_service.h"
mitchelljonese59a1612014-12-16 00:34:59108#include "extensions/browser/extension_registry.h"
tapted574f09c2015-05-19 13:08:08109#include "extensions/browser/extension_system.h"
[email protected]d96cf752014-04-09 04:05:28110#include "net/base/filename_util.h"
[email protected]2e29e2232013-07-26 10:40:59111#include "ui/base/cocoa/focus_window_set.h"
[email protected]c051a1b2011-01-21 23:30:17112#include "ui/base/l10n/l10n_util.h"
113#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:44114
mitchelljonese59a1612014-12-16 00:34:59115using apps::AppShimHandler;
116using apps::ExtensionAppShimHandler;
[email protected]e6e30ac2014-01-13 21:24:39117using base::UserMetricsAction;
[email protected]b441a8492012-06-06 14:55:57118using content::BrowserContext;
[email protected]e582fdd2011-12-20 16:48:17119using content::DownloadManager;
[email protected]631bb742011-11-02 11:29:39120
[email protected]d630d7d52010-02-21 00:55:11121namespace {
122
[email protected]d4c811e72013-10-29 21:57:55123// How long we allow a workspace change notification to wait to be
124// associated with a dock activation. The animation lasts 250ms. See
125// applicationShouldHandleReopen:hasVisibleWindows:.
126static const int kWorkspaceChangeTimeoutMs = 500;
127
[email protected]a37d4b02012-06-25 21:56:10128// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03129// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
130// because otherwise the SessionService will try to restore sessions when we
131// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11132bool g_is_opening_new_window = false;
133
134// Activates a browser window having the given profile (the last one active) if
135// possible and returns a pointer to the activate |Browser| or NULL if this was
136// not possible. If the last active browser is minimized (in particular, if
137// there are only minimized windows), it will unminimize it.
138Browser* ActivateBrowser(Profile* profile) {
[email protected]5595ce6d2014-07-24 04:01:13139 Browser* browser = chrome::FindLastActiveWithProfile(
scottmg5c03fe022016-02-03 01:27:24140 profile->IsGuestSession() ? profile->GetOffTheRecordProfile() : profile);
[email protected]d630d7d52010-02-21 00:55:11141 if (browser)
142 browser->window()->Activate();
143 return browser;
144}
145
146// Creates an empty browser window with the given profile and returns a pointer
147// to the new |Browser|.
148Browser* CreateBrowser(Profile* profile) {
149 {
[email protected]997ec9f2012-11-21 04:44:14150 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
scottmg851949002016-02-09 20:09:44151 chrome::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11152 }
153
[email protected]f2bc6e92012-10-14 02:08:38154 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11155 CHECK(browser);
156 return browser;
157}
158
159// Activates a browser window having the given profile (the last one active) if
160// possible or creates an empty one if necessary. Returns a pointer to the
161// activated/new |Browser|.
162Browser* ActivateOrCreateBrowser(Profile* profile) {
163 if (Browser* browser = ActivateBrowser(profile))
164 return browser;
165 return CreateBrowser(profile);
166}
167
[email protected]151c4a62011-04-22 04:15:13168CFStringRef BaseBundleID_CFString() {
169 NSString* base_bundle_id =
170 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
171 return base::mac::NSToCFCast(base_bundle_id);
172}
173
[email protected]12dc3d42010-02-22 23:37:12174// Record the location of the application bundle (containing the main framework)
175// from which Chromium was loaded. This is used by app mode shims to find
176// Chromium.
177void RecordLastRunAppBundlePath() {
178 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
179 // real, user-visible app bundle directory. (The alternatives give either the
180 // framework's path or the initial app's path, which may be an app mode shim
181 // or a unit test.)
Etienne Pierre-Doraya620e5e2018-12-06 19:02:10182 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK);
[email protected]bf0d26b2013-08-29 03:09:14183
[email protected]1c958682013-09-17 03:38:13184 base::FilePath app_bundle_path =
[email protected]12dc3d42010-02-22 23:37:12185 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]1c958682013-09-17 03:38:13186 base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring(
187 base::SysUTF8ToCFStringRef(app_bundle_path.value()));
[email protected]b6b72222012-02-11 02:04:13188 CFPreferencesSetAppValue(
189 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
[email protected]1c958682013-09-17 03:38:13190 app_bundle_path_cfstring, BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12191}
192
[email protected]7108d912014-01-30 08:10:45193bool IsProfileSignedOut(Profile* profile) {
lwchkg9c183942016-03-13 06:29:54194 ProfileAttributesEntry* entry;
195 bool has_entry =
196 g_browser_process->profile_manager()->GetProfileAttributesStorage().
197 GetProfileAttributesWithPath(profile->GetPath(), &entry);
198 return has_entry && entry->IsSigninRequired();
[email protected]7108d912014-01-30 08:10:45199}
200
erikchen600f7962014-12-12 00:17:38201} // namespace
[email protected]d630d7d52010-02-21 00:55:11202
erikchen600f7962014-12-12 00:17:38203@interface AppController () <HandoffActiveURLObserverBridgeDelegate>
[email protected]88d74942009-01-21 22:04:44204- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46205- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48206- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16207- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]57750f822009-04-21 21:43:09208- (void)getUrl:(NSAppleEventDescriptor*)event
209 withReply:(NSAppleEventDescriptor*)reply;
[email protected]d4c811e72013-10-29 21:57:55210- (void)activeSpaceDidChange:(NSNotification*)inNotification;
[email protected]dd6ab1282010-07-20 01:07:32211- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21212- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41213- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47214- (void)executeApplication:(id)sender;
[email protected]1c62b2f2013-06-28 00:15:00215- (void)profileWasRemoved:(const base::FilePath&)profilePath;
erikchen19ee3922014-10-31 19:14:22216
217// Opens a tab for each GURL in |urls|.
218- (void)openUrls:(const std::vector<GURL>&)urls;
219
220// This class cannot open urls until startup has finished. The urls that cannot
221// be opened are cached in |startupUrls_|. This method must be called exactly
222// once after startup has completed. It opens the urls in |startupUrls_|, and
223// clears |startupUrls_|.
224- (void)openStartupUrls;
225
226// Opens a tab for each GURL in |urls|. If there is exactly one tab open before
227// this method is called, and that tab is the NTP, then this method closes the
228// NTP after all the |urls| have been opened.
229- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls;
erikchen600f7962014-12-12 00:17:38230
231// Whether instances of this class should use the Handoff feature.
232- (BOOL)shouldUseHandoff;
233
234// This method passes |handoffURL| to |handoffManager_|.
235- (void)passURLToHandoffManager:(const GURL&)handoffURL;
236
237// Lazily creates the Handoff Manager. Updates the state of the Handoff
238// Manager. This method is idempotent. This should be called:
239// - During initialization.
240// - When the current tab navigates to a new URL.
241// - When the active browser changes.
242// - When the active browser's active tab switches.
243// |webContents| should be the new, active WebContents.
244- (void)updateHandoffManager:(content::WebContents*)webContents;
245
246// Given |webContents|, extracts a GURL to be used for Handoff. This may return
247// the empty GURL.
248- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents;
Owen Min8c5d5382018-08-02 17:52:43249
250// Return false if Chrome startup is paused by dialog and AppController is
251// called without any initialized Profile.
252- (BOOL)isProfileReady;
[email protected]88d74942009-01-21 22:04:44253@end
[email protected]1bcdb532009-01-16 17:47:57254
lwchkg9c183942016-03-13 06:29:54255class AppControllerProfileObserver : public ProfileAttributesStorage::Observer {
[email protected]1c62b2f2013-06-28 00:15:00256 public:
257 AppControllerProfileObserver(
258 ProfileManager* profile_manager, AppController* app_controller)
259 : profile_manager_(profile_manager),
260 app_controller_(app_controller) {
261 DCHECK(profile_manager_);
262 DCHECK(app_controller_);
lwchkg9c183942016-03-13 06:29:54263 profile_manager_->GetProfileAttributesStorage().AddObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00264 }
265
Daniel Chenga542fca2014-10-21 09:51:29266 ~AppControllerProfileObserver() override {
[email protected]1c62b2f2013-06-28 00:15:00267 DCHECK(profile_manager_);
lwchkg9c183942016-03-13 06:29:54268 profile_manager_->GetProfileAttributesStorage().RemoveObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00269 }
270
271 private:
lwchkg9c183942016-03-13 06:29:54272 // ProfileAttributesStorage::Observer implementation:
[email protected]1c62b2f2013-06-28 00:15:00273
Daniel Chenga542fca2014-10-21 09:51:29274 void OnProfileAdded(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00275
Daniel Chenga542fca2014-10-21 09:51:29276 void OnProfileWasRemoved(const base::FilePath& profile_path,
277 const base::string16& profile_name) override {
[email protected]1c62b2f2013-06-28 00:15:00278 // When a profile is deleted we need to notify the AppController,
279 // so it can correctly update its pointer to the last used profile.
280 [app_controller_ profileWasRemoved:profile_path];
281 }
282
Daniel Chenga542fca2014-10-21 09:51:29283 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00284
Daniel Chenga542fca2014-10-21 09:51:29285 void OnProfileNameChanged(const base::FilePath& profile_path,
286 const base::string16& old_profile_name) override {}
[email protected]1c62b2f2013-06-28 00:15:00287
Daniel Chenga542fca2014-10-21 09:51:29288 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00289
290 ProfileManager* profile_manager_;
291
292 AppController* app_controller_; // Weak; owns us.
293
294 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
295};
296
Robert Sesek1eb85222017-08-24 23:17:09297#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33298// On macOS 10.12, the IME system attempts to allocate a 2^64 size buffer,
299// which would typically cause an OOM crash. To avoid this, the problematic
300// method is swizzled out and the make-OOM-fatal bit is disabled for the
301// duration of the original call. https://crbug.com/654695
302static base::mac::ScopedObjCClassSwizzler* g_swizzle_imk_input_session;
303
304@interface OOMDisabledIMKInputSession : NSObject
305@end
306
307@implementation OOMDisabledIMKInputSession
308
309- (void)_coreAttributesFromRange:(NSRange)range
310 whichAttributes:(long long)attributes
311 completionHandler:(void (^)(void))block {
312 // The allocator flag is per-process, so other threads may temporarily
313 // not have fatal OOM occur while this method executes, but it is better
314 // than crashing when using IME.
315 base::allocator::SetCallNewHandlerOnMallocFailure(false);
316 g_swizzle_imk_input_session->GetOriginalImplementation()(self, _cmd, range,
317 attributes, block);
318 base::allocator::SetCallNewHandlerOnMallocFailure(true);
319}
320
321@end
Robert Sesek1eb85222017-08-24 23:17:09322#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33323
[email protected]1bcdb532009-01-16 17:47:57324@implementation AppController
325
[email protected]caadfca2010-01-22 21:51:21326@synthesize startupComplete = startupComplete_;
327
andresantoso04f7bab2015-01-15 19:19:16328- (void)dealloc {
329 [[closeTabMenuItem_ menu] setDelegate:nil];
330 [super dealloc];
331}
332
[email protected]cd63ef62009-05-06 19:41:37333// This method is called very early in application startup (ie, before
334// the profile is loaded or any preferences have been registered). Defer any
335// user-data initialization until -applicationDidFinishLaunching:.
Robert Sesek124f80f92018-07-24 20:31:29336- (void)mainMenuCreated {
[email protected]7d1aaa62014-07-18 02:21:30337 MacStartupProfiler::GetInstance()->Profile(
338 MacStartupProfiler::AWAKE_FROM_NIB);
[email protected]136140c2009-05-19 13:58:25339 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09340 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
341 [em setEventHandler:self
342 andSelector:@selector(getUrl:withReply:)
343 forEventClass:kInternetEventClass
344 andEventID:kAEGetURL];
345 [em setEventHandler:self
346 andSelector:@selector(getUrl:withReply:)
347 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
348 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37349
[email protected]449dd2f2009-05-27 13:04:00350 NSNotificationCenter* notificationCenter =
351 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44352 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00353 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16354 selector:@selector(windowDidResignKey:)
[email protected]449dd2f2009-05-27 13:04:00355 name:NSWindowDidResignKeyNotification
356 object:nil];
357 [notificationCenter
358 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16359 selector:@selector(windowDidBecomeMain:)
[email protected]449dd2f2009-05-27 13:04:00360 name:NSWindowDidBecomeMainNotification
361 object:nil];
362 [notificationCenter
363 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16364 selector:@selector(windowDidResignMain:)
[email protected]449dd2f2009-05-27 13:04:00365 name:NSWindowDidResignMainNotification
366 object:nil];
367
[email protected]d4c811e72013-10-29 21:57:55368 // Register for space change notifications.
369 [[[NSWorkspace sharedWorkspace] notificationCenter]
370 addObserver:self
371 selector:@selector(activeSpaceDidChange:)
372 name:NSWorkspaceActiveSpaceDidChangeNotification
373 object:nil];
374
jochenbf9420152015-01-13 14:12:57375 [[[NSWorkspace sharedWorkspace] notificationCenter]
376 addObserver:self
377 selector:@selector(willPowerOff:)
378 name:NSWorkspaceWillPowerOffNotification
379 object:nil];
380
Robert Sesek705c3802018-10-24 20:58:42381 NSMenu* fileMenu = [[[NSApp mainMenu] itemWithTag:IDC_FILE_MENU] submenu];
382 closeTabMenuItem_ = [fileMenu itemWithTag:IDC_CLOSE_TAB];
383 DCHECK(closeTabMenuItem_);
384 closeWindowMenuItem_ = [fileMenu itemWithTag:IDC_CLOSE_WINDOW];
385 DCHECK(closeWindowMenuItem_);
386
[email protected]136140c2009-05-19 13:58:25387 // Set up the command updater for when there are no windows open
388 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46389
390 // Initialize the Profile menu.
391 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25392}
393
[email protected]71c0eb92012-01-03 17:57:30394- (void)unregisterEventHandlers {
395 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
396 [em removeEventHandlerForEventClass:kInternetEventClass
397 andEventID:kAEGetURL];
398 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
399 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30400 [em removeEventHandlerForEventClass:'WWW!'
401 andEventID:'OURL'];
402 [[NSNotificationCenter defaultCenter] removeObserver:self];
[email protected]d4c811e72013-10-29 21:57:55403 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[email protected]71c0eb92012-01-03 17:57:30404}
405
[email protected]7dc8c6b2010-04-09 17:02:50406// (NSApplicationDelegate protocol) This is the Apple-approved place to override
407// the default handlers.
408- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]7d1aaa62014-07-18 02:21:30409 MacStartupProfiler::GetInstance()->Profile(
410 MacStartupProfiler::WILL_FINISH_LAUNCHING);
sdy57883382016-09-12 16:00:37411
Erik Chen2d245df72017-07-15 03:16:06412 if (@available(macOS 10.12, *)) {
sdy57883382016-09-12 16:00:37413 NSWindow.allowsAutomaticWindowTabbing = NO;
414 }
spqchan210e2ed2017-07-27 23:17:40415
416 // If the OSX version supports this method, the system will automatically
417 // hide the item if there's no touch bar. However, for unsupported versions,
spqchan30556c32018-09-05 23:14:08418 // we'll have to manually remove the item from the menu.
spqchan210e2ed2017-07-27 23:17:40419 if (![NSApp
spqchan30556c32018-09-05 23:14:08420 respondsToSelector:@selector(toggleTouchBarCustomizationPalette:)]) {
spqchan210e2ed2017-07-27 23:17:40421 NSMenu* mainMenu = [NSApp mainMenu];
422 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
423 NSMenuItem* customizeItem = [viewMenu itemWithTag:IDC_CUSTOMIZE_TOUCH_BAR];
424 if (customizeItem)
425 [viewMenu removeItem:customizeItem];
426 }
Leonard Grey2bdd08f2017-10-03 18:40:52427
Leonard Grey34b5e622018-07-30 19:05:55428 [self initShareMenu];
spqchan2c5d541e2017-10-25 07:07:11429
430 // Remove "Enable Javascript in Apple Events" if the feature is disabled.
431 if (!base::FeatureList::IsEnabled(
432 features::kAppleScriptExecuteJavaScriptMenuItem)) {
433 NSMenu* mainMenu = [NSApp mainMenu];
434 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
435 NSMenu* devMenu = [[viewMenu itemWithTag:IDC_DEVELOPER_MENU] submenu];
436 NSMenuItem* javascriptAppleEventItem =
437 [devMenu itemWithTag:IDC_TOGGLE_JAVASCRIPT_APPLE_EVENTS];
438 if (javascriptAppleEventItem)
439 [devMenu removeItem:javascriptAppleEventItem];
440 }
[email protected]7dc8c6b2010-04-09 17:02:50441}
442
[email protected]8a5bd59042014-07-22 04:10:06443- (void)applicationWillHide:(NSNotification*)notification {
Owen Min8c5d5382018-08-02 17:52:43444 if (![self isProfileReady])
445 return;
Christopher Cameron027e4ad2018-09-21 16:52:54446 apps::ExtensionAppShimHandler::Get()->OnChromeWillHide();
[email protected]8a5bd59042014-07-22 04:10:06447}
448
[email protected]7dc8c6b2010-04-09 17:02:50449- (BOOL)tryToTerminateApplication:(NSApplication*)app {
jochenbf9420152015-01-13 14:12:57450 // Reset this now that we've received the call to terminate.
451 BOOL isPoweringOff = isPoweringOff_;
452 isPoweringOff_ = NO;
453
[email protected]3076fad2010-04-28 18:11:45454 // Check for in-process downloads, and prompt the user if they really want
455 // to quit (and thus cancel downloads). Only check if we're not already
456 // shutting down, else the user might be prompted multiple times if the
457 // download isn't stopped before terminate is called again.
458 if (!browser_shutdown::IsTryingToQuit() &&
459 ![self shouldQuitWithInProgressDownloads])
460 return NO;
461
[email protected]7dc8c6b2010-04-09 17:02:50462 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
463 // them in, but I'm not sure about UX; we'd also want to disable other things
464 // though.) http://crbug.com/40861
465
[email protected]70593e52014-05-15 08:30:23466 // Check for active apps. If quitting is prevented, only close browsers and
467 // sessions.
jochenbf9420152015-01-13 14:12:57468 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
469 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
avi3ef9ec9e2014-12-22 22:50:17470 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
mitchelljones3bc6ced2014-12-19 05:01:37471 switches::kHostedAppQuitNotification)) {
472 return NO;
473 }
474
[email protected]70593e52014-05-15 08:30:23475 content::NotificationService::current()->Notify(
476 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
477 content::NotificationService::AllSources(),
478 content::NotificationService::NoDetails());
479 // This will close all browser sessions.
480 chrome::CloseAllBrowsers();
jackhouae8e6e52015-05-29 06:36:46481
482 // At this point, the user has already chosen to cancel downloads. If we
483 // were to shut down as usual, the downloads would be cancelled in
peterccb33e82017-05-02 19:00:44484 // DownloadCoreService::Shutdown().
485 DownloadCoreService::CancelAllDownloads();
jackhouae8e6e52015-05-29 06:36:46486
[email protected]70593e52014-05-15 08:30:23487 return NO;
488 }
489
[email protected]0665ebe2013-02-13 09:53:19490 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50491
[email protected]0c95faf42013-10-28 06:27:20492 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20493 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56494 if (!browser_shutdown::IsTryingToQuit()) {
495 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30496 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56497 content::NotificationService::AllSources(),
498 content::NotificationService::NoDetails());
[email protected]0c95faf42013-10-28 06:27:20499 chrome::CloseAllBrowsersAndQuit();
[email protected]ef61b8c2012-01-20 10:54:56500 }
[email protected]7dc8c6b2010-04-09 17:02:50501
[email protected]c984d9f2010-07-20 20:52:20502 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50503}
504
505- (void)stopTryingToTerminateApplication:(NSApplication*)app {
506 if (browser_shutdown::IsTryingToQuit()) {
507 // Reset the "trying to quit" state, so that closing all browser windows
508 // will no longer lead to termination.
509 browser_shutdown::SetTryingToQuit(false);
510
511 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
512 // would have to reinstall them here. http://crbug.com/40861
513 }
[email protected]a9e8afc2009-08-11 22:03:17514}
515
Avi Drissmanf19bb472018-11-29 19:51:28516- (BOOL)runConfirmQuitPanel {
[email protected]90a4b9d2013-07-31 12:14:40517 // If there are no windows, quit immediately.
scottmg8abbff832016-01-28 22:57:37518 if (BrowserList::GetInstance()->empty() &&
jackhou261f7f32015-01-07 00:59:03519 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
Avi Drissmanf19bb472018-11-29 19:51:28520 return YES;
[email protected]90a4b9d2013-07-31 12:14:40521 }
522
[email protected]a99fce0e2011-03-21 20:58:48523 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26524 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23525 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
526 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
Avi Drissmanf19bb472018-11-29 19:51:28527 return YES;
[email protected]1eaddf32011-04-05 15:09:23528 }
[email protected]177aceb2010-11-03 16:17:41529
Avi Drissmanf19bb472018-11-29 19:51:28530 // Run only for keyboard-initiated quits.
531 if ([[NSApp currentEvent] type] != NSKeyDown)
[email protected]2020fd0b2010-12-10 01:16:50532 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41533
[email protected]5df54fb2011-03-07 18:15:26534 return [[ConfirmQuitPanelController sharedController]
Avi Drissmanf19bb472018-11-29 19:51:28535 runModalLoopForApplication:NSApp];
[email protected]177aceb2010-11-03 16:17:41536}
537
[email protected]449dd2f2009-05-27 13:04:00538// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50539- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50540 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19541 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11542
[email protected]c984d9f2010-07-20 20:52:20543 // Tell BrowserList not to keep the browser process alive. Once all the
544 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
dgn02377782016-03-12 00:58:38545 keep_alive_.reset();
[email protected]fbc947b2009-06-19 13:28:24546
[email protected]02a31dd2013-02-05 08:40:52547 // Reset all pref watching, as this object outlives the prefs system.
548 profilePrefRegistrar_.reset();
549 localPrefRegistrar_.RemoveAll();
550
[email protected]71c0eb92012-01-03 17:57:30551 [self unregisterEventHandlers];
[email protected]edb2d032013-08-30 09:03:17552
553 appShimMenuController_.reset();
lgarron9e6dee22014-11-18 01:03:39554
avi82554752016-09-23 17:48:50555 profileBookmarkMenuBridgeMap_.clear();
[email protected]449dd2f2009-05-27 13:04:00556}
557
[email protected]3b6aa8b62009-09-15 21:36:11558- (void)didEndMainMessageLoop {
scottmg34c5dd882016-02-03 05:21:54559 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile]));
560 if (!chrome::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11561 // As we're shutting down, we need to nuke the TabRestoreService, which
562 // will start the shutdown of the NavigationControllers and allow for
563 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
564 // and may end up crashing when some thread tries to use the IO thread (or
565 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35566 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11567 }
568}
569
[email protected]8cfbdbd2011-06-16 04:17:17570// If the window has a tab controller, make "close window" be cmd-shift-w,
571// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48572// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56573- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
574 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
575 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17576 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
577}
578
579// If the window has a tab controller, make "close tab" take over cmd-w,
580// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56581- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
582 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17583 [closeTabMenuItem_ setKeyEquivalent:@"w"];
584 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
585 } else {
586 [closeTabMenuItem_ setKeyEquivalent:@""];
587 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
588 }
589}
590
[email protected]9f5f79b62011-10-28 00:43:45591// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17592// Close Tab/Close Window accordingly.
andresantoso04f7bab2015-01-15 19:19:16593- (void)menuNeedsUpdate:(NSMenu*)menu {
594 DCHECK(menu == [closeTabMenuItem_ menu]);
erikchen22be2092018-06-12 15:54:00595 [self updateMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17596}
597
andresantoso04f7bab2015-01-15 19:19:16598- (void)windowDidResignKey:(NSNotification*)notify {
599 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
600 // returns nil regardless of whether any suitable candidates for the key
601 // window remain. It seems that the new key window for the app is not set
602 // until after this notification is fired, so a check is performed after the
603 // run loop is allowed to spin.
604 [self performSelector:@selector(checkForAnyKeyWindows)
605 withObject:nil
606 afterDelay:0.0];
[email protected]8cfbdbd2011-06-16 04:17:17607}
608
andresantoso04f7bab2015-01-15 19:19:16609- (void)windowDidBecomeMain:(NSNotification*)notify {
andresantoso55fd2512015-04-01 21:07:04610 Browser* browser = chrome::FindBrowserWithWindow([notify object]);
611 if (browser)
612 [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
andresantoso04f7bab2015-01-15 19:19:16613}
614
615- (void)windowDidResignMain:(NSNotification*)notify {
Owen Min8c5d5382018-08-02 17:52:43616 if (chrome::GetTotalBrowserCount() == 0 && [self isProfileReady]) {
[email protected]cae68b3a2011-11-21 23:29:49617 [self windowChangedToProfile:
618 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24619 }
620}
621
[email protected]d4c811e72013-10-29 21:57:55622- (void)activeSpaceDidChange:(NSNotification*)notify {
623 if (reopenTime_.is_null() ||
624 ![NSApp isActive] ||
625 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
626 kWorkspaceChangeTimeoutMs) {
627 return;
628 }
629
630 // The last applicationShouldHandleReopen:hasVisibleWindows: call
631 // happened during a space change. Now that the change has
632 // completed, raise browser windows.
633 reopenTime_ = base::TimeTicks();
Christopher Cameron359c61e22018-10-18 08:06:20634 std::set<gfx::NativeWindow> browserWindows;
scottmg8abbff832016-01-28 22:57:37635 for (auto* browser : *BrowserList::GetInstance())
[email protected]d4c811e72013-10-29 21:57:55636 browserWindows.insert(browser->window()->GetNativeWindow());
Christopher Cameron359c61e22018-10-18 08:06:20637 if (!browserWindows.empty())
[email protected]6c4b79602014-05-28 16:47:21638 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:55639}
640
jochenbf9420152015-01-13 14:12:57641// Called when shutting down or logging out.
642- (void)willPowerOff:(NSNotification*)notify {
643 // Don't attempt any shutdown here. Cocoa will shortly call
644 // -[BrowserCrApplication terminate:].
645 isPoweringOff_ = YES;
646}
647
[email protected]dd6ab1282010-07-20 01:07:32648- (void)checkForAnyKeyWindows {
649 if ([NSApp keyWindow])
650 return;
651
[email protected]ad50def52011-10-19 23:17:07652 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30653 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07654 content::NotificationService::AllSources(),
655 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00656}
657
[email protected]414fde592009-05-21 16:14:43658// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43659// Placed here for 2 reasons:
660// 1) Same spot as other Pref stuff
661// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43662- (void)setUpdateCheckInterval {
663#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49664 CFStringRef app = CFSTR("com.google.Keystone.Agent");
665 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43666 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
667 if (!plist) {
668 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50669 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43670 CFPreferencesSetAppValue(checkInterval, value, app);
671 CFPreferencesAppSynchronize(app);
672 }
673#endif
674}
675
[email protected]66791aff2014-04-29 09:45:38676- (void)openStartupUrls {
erikchen19ee3922014-10-31 19:14:22677 DCHECK(startupComplete_);
678 [self openUrlsReplacingNTP:startupUrls_];
679 startupUrls_.clear();
680}
681
682- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
683 if (urls.empty())
684 return;
685
[email protected]66791aff2014-04-29 09:45:38686 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
687 // NSApplication is created in MainMessageLoop, and then the shortcut urls
688 // are passed in via Apple events. At this point, the first browser is
689 // already loaded in PreMainMessageLoop. If we initialize NSApplication
690 // before PreMainMessageLoop to capture shortcut URL events, it may cause
691 // more problems because it relies on things created in PreMainMessageLoop
692 // and may break existing message loop design.
erikchen19ee3922014-10-31 19:14:22693
694 // If the browser hasn't started yet, just queue up the URLs.
695 if (!startupComplete_) {
696 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]66791aff2014-04-29 09:45:38697 return;
erikchen19ee3922014-10-31 19:14:22698 }
[email protected]66791aff2014-04-29 09:45:38699
700 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
701 // startup urls in new tabs, because the omnibox will stay focused if we
702 // load url in NTP tab.
Christian Dullweber820ee5f2018-04-26 13:24:31703 Profile* profile =
704 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
705 Browser* browser = chrome::FindLastActiveWithProfile(profile);
706
[email protected]66791aff2014-04-29 09:45:38707 int startupIndex = TabStripModel::kNoTab;
708 content::WebContents* startupContent = NULL;
709
710 if (browser && browser->tab_strip_model()->count() == 1) {
711 startupIndex = browser->tab_strip_model()->active_index();
712 startupContent = browser->tab_strip_model()->GetActiveWebContents();
713 }
714
erikchen19ee3922014-10-31 19:14:22715 [self openUrls:urls];
[email protected]66791aff2014-04-29 09:45:38716
kristiparka34b247a2018-03-09 19:05:34717 // In test environments where there is no network connection, the visible NTP
718 // URL may be chrome-search://local-ntp/local-ntp.html instead of
719 // chrome://newtab/. See local_ntp_test_utils::GetFinalNtpUrl for more
720 // details.
721 // This NTP check should be replaced once https://crbug.com/624410 is fixed.
[email protected]66791aff2014-04-29 09:45:38722 if (startupIndex != TabStripModel::kNoTab &&
kristiparka34b247a2018-03-09 19:05:34723 (startupContent->GetVisibleURL() == chrome::kChromeUINewTabURL ||
724 startupContent->GetVisibleURL() == chrome::kChromeSearchLocalNtpUrl)) {
[email protected]66791aff2014-04-29 09:45:38725 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
726 TabStripModel::CLOSE_NONE);
727 }
728}
729
[email protected]136140c2009-05-19 13:58:25730// This is called after profiles have been loaded and preferences registered.
731// It is safe to access the default profile here.
Owen Min3bcf8d152018-07-16 16:50:39732- (void)applicationDidFinishLaunching:(NSNotification*)notify {
733 if (g_browser_process->browser_policy_connector()
734 ->machine_level_user_cloud_policy_controller()
735 ->IsEnterpriseStartupDialogShowing()) {
736 // As Chrome is not ready when the Enterprise startup dialog is being shown.
737 // Store the notification as it will be reposted when the dialog is closed.
738 return;
739 }
740
[email protected]7d1aaa62014-07-18 02:21:30741 MacStartupProfiler::GetInstance()->Profile(
742 MacStartupProfiler::DID_FINISH_LAUNCHING);
743 MacStartupProfiler::GetInstance()->RecordMetrics();
744
[email protected]c984d9f2010-07-20 20:52:20745 // Notify BrowserList to keep the application running so it doesn't go away
746 // when all the browser windows get closed.
dgn02377782016-03-12 00:58:38747 keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::APP_CONTROLLER,
748 KeepAliveRestartOption::DISABLED));
[email protected]136140c2009-05-19 13:58:25749
[email protected]414fde592009-05-21 16:14:43750 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53751
[email protected]edb2d032013-08-30 09:03:17752 // Start managing the menu for app windows. This needs to be done here because
753 // main menu item titles are not yet initialized in awakeFromNib.
[email protected]e7dc3992013-11-06 02:16:42754 [self initAppShimMenuController];
[email protected]edb2d032013-08-30 09:03:17755
[email protected]425f7a02014-04-29 01:51:44756 // If enabled, keep Chrome alive when apps are open instead of quitting all
757 // apps.
758 quitWithAppsController_ = new QuitWithAppsController();
759
andresantoso04f7bab2015-01-15 19:19:16760 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
761 [[closeTabMenuItem_ menu] setDelegate:self];
762
lwchkg9c183942016-03-13 06:29:54763 // Instantiate the ProfileAttributesStorage observer so that we can get
[email protected]1c62b2f2013-06-28 00:15:00764 // notified when a profile is deleted.
lwchkg9c183942016-03-13 06:29:54765 profileAttributesStorageObserver_.reset(new AppControllerProfileObserver(
[email protected]1c62b2f2013-06-28 00:15:00766 g_browser_process->profile_manager(), self));
767
[email protected]12dc3d42010-02-22 23:37:12768 // Record the path to the (browser) app bundle; this is used by the app mode
Gabriel Charette66d79ed22017-06-21 17:58:22769 // shim.
770 base::PostTaskWithTraits(FROM_HERE,
Gabriel Charetteb10aeebc2018-07-26 20:15:00771 {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
Gabriel Charette66d79ed22017-06-21 17:58:22772 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
773 base::Bind(&RecordLastRunAppBundlePath));
[email protected]12dc3d42010-02-22 23:37:12774
[email protected]eef99c22010-08-17 05:55:16775 // Makes "Services" menu items available.
776 [self registerServicesMenuTypesTo:[notify object]];
777
[email protected]caadfca2010-01-22 21:51:21778 startupComplete_ = YES;
779
scottmg5c03fe022016-02-03 01:27:24780 Browser* browser = chrome::FindLastActive();
erikchen600f7962014-12-12 00:17:38781 content::WebContents* activeWebContents = nullptr;
782 if (browser)
783 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
784 [self updateHandoffManager:activeWebContents];
[email protected]66791aff2014-04-29 09:45:38785 [self openStartupUrls];
[email protected]aac169d2011-03-18 19:53:03786
[email protected]05454532013-01-22 21:09:08787 PrefService* localState = g_browser_process->local_state();
788 if (localState) {
789 localPrefRegistrar_.Init(localState);
790 localPrefRegistrar_.Add(
791 prefs::kAllowFileSelectionDialogs,
792 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
793 menuState_.get()));
794 }
erikchen600f7962014-12-12 00:17:38795
796 handoff_active_url_observer_bridge_.reset(
797 new HandoffActiveURLObserverBridge(self));
Robert Sesek99845182017-08-24 20:53:33798
Robert Sesek1eb85222017-08-24 23:17:09799#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33800 // Disable fatal OOM to hack around an OS bug https://crbug.com/654695.
801 if (base::mac::IsOS10_12()) {
802 g_swizzle_imk_input_session = new base::mac::ScopedObjCClassSwizzler(
803 NSClassFromString(@"IMKInputSession"),
804 [OOMDisabledIMKInputSession class],
805 @selector(_coreAttributesFromRange:whichAttributes:completionHandler:));
806 }
Robert Sesek1eb85222017-08-24 23:17:09807#endif
[email protected]7c321082009-02-09 15:35:47808}
809
[email protected]73f5b362009-08-10 23:58:21810// Helper function for populating and displaying the in progress downloads at
811// exit alert panel.
812- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48813 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13814 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21815 NSString* waitTitle = nil;
816 NSString* exitTitle = nil;
817
818 // Set the dialog text based on whether or not there are multiple downloads.
jshinec68f032015-05-14 00:03:23819 // Dialog text: warning and explanation.
Bret Sepulveda331f10a2018-02-13 22:37:42820 titleText = l10n_util::GetPluralNSStringF(IDS_ABANDON_DOWNLOAD_DIALOG_TITLE,
821 downloadCount);
822 explanationText =
823 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_BROWSER_MESSAGE);
824 // "Cancel download and exit" button text.
825 exitTitle = l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_EXIT_BUTTON);
[email protected]83a9f652012-04-25 21:03:48826
Bret Sepulveda331f10a2018-02-13 22:37:42827 // "Wait for download" button text.
828 waitTitle =
829 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_CONTINUE_BUTTON);
[email protected]73f5b362009-08-10 23:58:21830
831 // 'waitButton' is the default choice.
[email protected]361b47c2013-07-02 15:13:24832 int choice = NSRunAlertPanel(titleText, @"%@",
833 waitTitle, exitTitle, nil, explanationText);
[email protected]73f5b362009-08-10 23:58:21834 return choice == NSAlertDefaultReturn ? YES : NO;
835}
836
837// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41838// user to see if we should continue to exit (and thus cancel the downloads), or
839// if we should wait.
840- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21841 ProfileManager* profile_manager = g_browser_process->profile_manager();
842 if (!profile_manager)
843 return YES;
[email protected]09729a552009-08-03 23:21:41844
[email protected]844a1002011-04-19 11:37:21845 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
Elly Fong-Jones08757f1e2018-01-31 16:24:44846
847 std::vector<Profile*> added_profiles;
848 for (Profile* p : profiles) {
849 if (p->HasOffTheRecordProfile())
850 added_profiles.push_back(p->GetOffTheRecordProfile());
851 }
852 profiles.insert(profiles.end(), added_profiles.begin(), added_profiles.end());
853
[email protected]844a1002011-04-19 11:37:21854 for (size_t i = 0; i < profiles.size(); ++i) {
peterccb33e82017-05-02 19:00:44855 DownloadCoreService* download_core_service =
856 DownloadCoreServiceFactory::GetForBrowserContext(profiles[i]);
[email protected]9bb54ee2011-10-12 17:43:35857 DownloadManager* download_manager =
peterccb33e82017-05-02 19:00:44858 (download_core_service->HasCreatedDownloadManager()
859 ? BrowserContext::GetDownloadManager(profiles[i])
860 : NULL);
[email protected]422a7d12013-10-21 12:10:42861 if (download_manager &&
862 download_manager->NonMaliciousInProgressCount() > 0) {
863 int downloadCount = download_manager->NonMaliciousInProgressCount();
[email protected]73f5b362009-08-10 23:58:21864 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
865 // Create a new browser window (if necessary) and navigate to the
866 // downloads page if the user chooses to wait.
scottmg34c5dd882016-02-03 05:21:54867 Browser* browser = chrome::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21868 if (!browser) {
erg7b01d692017-02-22 21:57:35869 browser = new Browser(Browser::CreateParams(profiles[i], true));
[email protected]73f5b362009-08-10 23:58:21870 browser->window()->Show();
871 }
872 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12873 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21874 return NO;
875 }
[email protected]09729a552009-08-03 23:21:41876
[email protected]73f5b362009-08-10 23:58:21877 // User wants to exit.
878 return YES;
[email protected]09729a552009-08-03 23:21:41879 }
[email protected]09729a552009-08-03 23:21:41880 }
881
[email protected]73f5b362009-08-10 23:58:21882 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41883 return YES;
884}
885
[email protected]fbc947b2009-06-19 13:28:24886// Called to determine if we should enable the "restore tab" menu item.
887// Checks with the TabRestoreService to see if there's anything there to
888// restore and returns YES if so.
889- (BOOL)canRestoreTab {
blundell74001adc2015-09-18 11:04:25890 sessions::TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35891 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24892 return service && !service->entries().empty();
893}
894
[email protected]1c62b2f2013-06-28 00:15:00895// Called from the AppControllerProfileObserver every time a profile is deleted.
896- (void)profileWasRemoved:(const base::FilePath&)profilePath {
[email protected]1c62b2f2013-06-28 00:15:00897 // If the lastProfile has been deleted, the profile manager has
898 // already loaded a new one, so the pointer needs to be updated;
899 // otherwise we will try to start up a browser window with a pointer
900 // to the old profile.
bauerb447f6432015-03-02 22:34:51901 // In a browser test, the application is not brought to the front, so
902 // |lastProfile_| might be null.
mlerman8ae56aa2015-04-24 13:56:27903 if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
904 // Force windowChangedToProfile: to set the lastProfile_ and also update the
905 // relevant menuBridge objects.
906 lastProfile_ = nullptr;
907 [self windowChangedToProfile:g_browser_process->profile_manager()->
908 GetLastUsedProfile()];
909 }
lgarron9e6dee22014-11-18 01:03:39910
avi82554752016-09-23 17:48:50911 profileBookmarkMenuBridgeMap_.erase(profilePath);
[email protected]1c62b2f2013-06-28 00:15:00912}
913
[email protected]05454532013-01-22 21:09:08914// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21915// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
916// sheets) will not count as blocking the browser. But things like open/save
917// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08918- (BOOL)keyWindowIsModal {
919 if ([NSApp modalWindow])
920 return YES;
921
[email protected]f2bc6e92012-10-14 02:08:38922 Browser* browser = chrome::GetLastActiveBrowser();
Christopher Cameron359c61e22018-10-18 08:06:20923 return browser && [[browser->window()->GetNativeWindow().GetNativeNSWindow()
924 attachedSheet] isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06925}
926
[email protected]88d74942009-01-21 22:04:44927// Called to validate menu items when there are no key windows. All the
928// items we care about have been set with the |commandDispatch:| action and
929// a target of FirstResponder in IB. If it's not one of those, let it
930// continue up the responder chain to be handled elsewhere. We pull out the
931// tag as the cross-platform constant to differentiate and dispatch the
932// various commands.
933- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
934 SEL action = [item action];
935 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08936 if (action == @selector(commandDispatch:) ||
937 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44938 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08939 if (menuState_ && // NULL in tests.
940 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24941 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26942 // The File Menu commands are not automatically disabled by Cocoa when a
943 // dialog sheet obscures the browser window, so we disable several of
944 // them here. We don't need to include IDC_CLOSE_WINDOW, because
945 // app_controller is only activated when there are no key windows (see
946 // function comment).
[email protected]fbc947b2009-06-19 13:28:24947 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08948 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06949 break;
[email protected]f6c15fa2010-06-04 20:08:21950 // Browser-level items that open in new tabs should not open if there's
951 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06952 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06953 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21954 case IDC_SHOW_HISTORY:
955 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08956 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21957 break;
958 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21959 case IDC_TASK_MANAGER:
960 // Allow the user to open a new window if there's a window-modal
961 // dialog.
[email protected]05454532013-01-22 21:09:08962 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24963 break;
964 default:
[email protected]f6c15fa2010-06-04 20:08:21965 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08966 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24967 }
968 }
spqchan9d60fce2016-02-10 18:30:47969
970 // "Show as tab" should only appear when the current window is a popup.
971 // Since |validateUserInterfaceItem:| is called only when there are no
972 // key windows, we should just hide this.
973 // This is handled outside of the switch statement because we want to hide
974 // this regardless if the command is supported or not.
975 if (tag == IDC_SHOW_AS_TAB) {
976 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
977 [menuItem setHidden:YES];
978 }
[email protected]3b6aa8b62009-09-15 21:36:11979 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44980 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52981 } else if (action == @selector(showPreferences:)) {
982 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07983 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
984 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47985 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38986 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48987 } else if (action == @selector(toggleConfirmToQuit:)) {
988 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
989 enable = YES;
[email protected]3a90b452013-02-15 04:33:48990 } else if (action == @selector(executeApplication:)) {
991 enable = YES;
[email protected]88d74942009-01-21 22:04:44992 }
993 return enable;
994}
995
[email protected]88d74942009-01-21 22:04:44996- (void)commandDispatch:(id)sender {
[email protected]2a39d1a2014-04-10 05:46:24997 Profile* lastProfile = [self safeLastProfileForNewWindows];
[email protected]f0a51fb52009-03-05 12:46:38998
[email protected]947fc0d2010-01-14 22:33:05999 // Handle the case where we're dispatching a command from a sender that's in a
1000 // browser window. This means that the command came from a background window
1001 // and is getting here because the foreground window is not a browser window.
1002 if ([sender respondsToSelector:@selector(window)]) {
1003 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041004 if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
[email protected]947fc0d2010-01-14 22:33:051005 [delegate commandDispatch:sender];
1006 return;
1007 }
1008 }
1009
[email protected]8d4bbdc2012-09-20 21:36:491010 // Ignore commands during session restore's browser creation. It uses a
gab2998ee72017-05-05 16:23:501011 // nested run loop and commands dispatched during this operation cause
[email protected]8d4bbdc2012-09-20 21:36:491012 // havoc.
Owen Min8c5d5382018-08-02 17:52:431013 if (lastProfile && SessionRestore::IsRestoring(lastProfile) &&
gab7af9dc02017-05-05 13:38:541014 base::RunLoop::IsNestedOnCurrentThread()) {
[email protected]8d4bbdc2012-09-20 21:36:491015 return;
gab7af9dc02017-05-05 13:38:541016 }
[email protected]8d4bbdc2012-09-20 21:36:491017
Trent Apted45d9ae22017-11-09 23:12:321018 // If not between -applicationDidFinishLaunching: and
1019 // -applicationWillTerminate:, ignore. This can happen when events are sitting
1020 // in the event queue while the browser is shutting down.
1021 if (!keep_alive_)
1022 return;
1023
[email protected]88d74942009-01-21 22:04:441024 NSInteger tag = [sender tag];
[email protected]7108d912014-01-30 08:10:451025
1026 // If there are no browser windows, and we are trying to open a browser
Owen Min027059d2018-03-13 22:17:361027 // for a locked profile or the system profile or the guest profile but
1028 // guest mode is disabled, we have to show the User Manager instead as the
1029 // locked profile needs authentication and the system profile cannot have a
1030 // browser.
1031 const PrefService* prefService = g_browser_process->local_state();
1032 if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile() ||
1033 (lastProfile->IsGuestSession() && prefService &&
1034 !prefService->GetBoolean(prefs::kBrowserGuestModeEnabled))) {
mlermane6e040a2014-10-31 00:53:211035 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261036 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
[email protected]7108d912014-01-30 08:10:451037 return;
1038 }
1039
[email protected]88d74942009-01-21 22:04:441040 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:241041 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:111042 // Create a new tab in an existing browser window (which we activate) if
1043 // possible.
[email protected]a585a8db2011-06-20 18:58:351044 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:401045 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:111046 break;
1047 }
Nico Weber331a98a82018-02-06 23:26:011048 FALLTHROUGH; // To create new window.
[email protected]88d74942009-01-21 22:04:441049 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:351050 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:111051 break;
[email protected]91a5b3e2009-10-30 19:32:221052 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:401053 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1054 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:441055 break;
[email protected]cddc5242009-12-07 18:54:331056 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:401057 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1058 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:331059 break;
[email protected]863ff662009-01-26 20:18:181060 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:481061 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:181062 break;
[email protected]fbc947b2009-06-19 13:28:241063 case IDC_RESTORE_TAB:
scottmgd161e6c2016-02-17 02:08:011064 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:241065 break;
[email protected]e19516d2009-04-28 17:15:191066 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:401067 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:191068 break;
[email protected]1fdff702009-10-22 00:36:181069 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:381070 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:351071 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121072 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231073 } else {
[email protected]1f0b50b2012-06-22 20:37:161074 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231075 }
[email protected]93e181762009-05-29 14:30:381076 break;
[email protected]1fdff702009-10-22 00:36:181077 }
[email protected]4aee5652009-11-19 18:59:211078 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:351079 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121080 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231081 } else {
[email protected]1f0b50b2012-06-22 20:37:161082 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231083 }
[email protected]4aee5652009-11-19 18:59:211084 break;
1085 }
[email protected]af7c25e2010-01-23 05:46:451086 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]a585a8db2011-06-20 18:58:351087 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121088 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:471089 } else {
[email protected]47e532b2010-04-23 17:46:401090 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:161091 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:471092 }
[email protected]af7c25e2010-01-23 05:46:451093 break;
[email protected]91a5b3e2009-10-30 19:32:221094 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:351095 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121096 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:111097 else
[email protected]1f0b50b2012-06-22 20:37:161098 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221099 break;
1100 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:351101 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121102 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:111103 else
[email protected]1f0b50b2012-06-22 20:37:161104 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221105 break;
[email protected]bb37e6ec2009-11-18 17:59:361106 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:351107 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:081108 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:111109 else
[email protected]1f0b50b2012-06-22 20:37:161110 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:361111 break;
[email protected]2ca35612012-06-12 03:49:481112 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:351113 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121114 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:111115 else
[email protected]1f0b50b2012-06-22 20:37:161116 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:181117 break;
[email protected]ceaaf1812010-01-20 22:13:091118 case IDC_TASK_MANAGER:
mlermane6e040a2014-10-31 00:53:211119 chrome::OpenTaskManager(NULL);
[email protected]ceaaf1812010-01-20 22:13:091120 break;
[email protected]4a42d272010-06-18 01:29:421121 case IDC_OPTIONS:
1122 [self showPreferences:sender];
1123 break;
[email protected]d630d7d52010-02-21 00:55:111124 }
[email protected]88d74942009-01-21 22:04:441125}
1126
[email protected]93b59fc2010-12-21 20:00:471127// Run a (background) application in a new tab.
1128- (void)executeApplication:(id)sender {
1129 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351130 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471131 DCHECK(profile);
1132 BackgroundApplicationListModel applications(profile);
1133 DCHECK(tag >= 0 &&
1134 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341135 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331136 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471137}
1138
[email protected]947fc0d2010-01-14 22:33:051139// Same as |-commandDispatch:|, but executes commands using a disposition
1140// determined by the key flags. This will get called in the case where the
1141// frontmost window is not a browser window, and the user has command-clicked
1142// a button in a background browser window whose action is
1143// |-commandDispatchUsingKeyModifiers:|
1144- (void)commandDispatchUsingKeyModifiers:(id)sender {
1145 DCHECK(sender);
1146 if ([sender respondsToSelector:@selector(window)]) {
1147 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041148 if ([delegate respondsToSelector:
1149 @selector(commandDispatchUsingKeyModifiers:)]) {
[email protected]947fc0d2010-01-14 22:33:051150 [delegate commandDispatchUsingKeyModifiers:sender];
1151 }
1152 }
1153}
1154
[email protected]2e29e2232013-07-26 10:40:591155// NSApplication delegate method called when someone clicks on the dock icon.
1156// To match standard mac behavior, we should open a new window if there are no
1157// browser windows.
[email protected]ff81e0a2009-04-13 14:58:541158- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581159 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541160 // If the browser is currently trying to quit, don't do anything and return NO
1161 // to prevent AppKit from doing anything.
1162 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1163 if (browser_shutdown::IsTryingToQuit())
1164 return NO;
1165
[email protected]2e29e2232013-07-26 10:40:591166 // Bring all browser windows to the front. Specifically, this brings them in
1167 // front of any app windows. FocusWindowSet will also unminimize the most
1168 // recently minimized window if no windows in the set are visible.
[email protected]a25920ee2013-09-05 19:38:491169 // If there are any, return here. Otherwise, the windows are panels or
1170 // notifications so we still need to open a new window.
[email protected]bf193bc52013-06-08 04:39:581171 if (hasVisibleWindows) {
Christopher Cameron359c61e22018-10-18 08:06:201172 std::set<gfx::NativeWindow> browserWindows;
scottmg8abbff832016-01-28 22:57:371173 for (auto* browser : *BrowserList::GetInstance()) {
mitchelljonese59a1612014-12-16 00:34:591174 // When focusing Chrome, don't focus any browser windows associated with
1175 // a currently running app shim, so ignore them.
1176 if (browser && browser->is_app()) {
mitchelljonesf00422082015-01-05 23:38:031177 extensions::ExtensionRegistry* registry =
1178 extensions::ExtensionRegistry::Get(browser->profile());
1179 const extensions::Extension* extension = registry->GetExtensionById(
Alexey Baskakov2ce2ffc842018-08-06 02:57:151180 web_app::GetAppIdFromApplicationName(browser->app_name()),
mitchelljonesf00422082015-01-05 23:38:031181 extensions::ExtensionRegistry::ENABLED);
mitchelljonesb118a0c2015-01-07 02:51:341182 if (extension && extension->is_hosted_app())
mitchelljonese59a1612014-12-16 00:34:591183 continue;
mitchelljonese59a1612014-12-16 00:34:591184 }
[email protected]2e29e2232013-07-26 10:40:591185 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]0236be22012-01-11 01:05:351186 }
[email protected]a25920ee2013-09-05 19:38:491187 if (!browserWindows.empty()) {
[email protected]d4c811e72013-10-29 21:57:551188 NSWindow* keyWindow = [NSApp keyWindow];
1189 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1190 // The key window is not on the active space. We must be mid-animation
1191 // for a space transition triggered by the dock. Delay the call to
1192 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1193 // wrong space's windows get raised, resulting in an off-screen key
1194 // window. It does not work to |ui::FocusWindowSet| twice, once here
1195 // and once in |activeSpaceDidChange:|, as that appears to break when
1196 // the omnibox is focused.
1197 //
1198 // This check relies on OS X setting the key window to a window on the
1199 // target space before calling this method.
1200 //
1201 // See http://crbug.com/309656.
1202 reopenTime_ = base::TimeTicks::Now();
1203 } else {
[email protected]6c4b79602014-05-28 16:47:211204 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:551205 }
1206 // Return NO; we've done (or soon will do) the deminiaturize, so
1207 // AppKit shouldn't do anything.
[email protected]a25920ee2013-09-05 19:38:491208 return NO;
1209 }
[email protected]0236be22012-01-11 01:05:351210 }
[email protected]ff81e0a2009-04-13 14:58:541211
[email protected]0d1210d62010-09-07 17:31:381212 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481213 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381214 // allow session to be restored first time the user clicks on a Dock icon.
1215 // Normally, it'd just open a new empty page.
1216 {
[email protected]eddcf7502012-02-09 22:43:481217 static BOOL doneOnce = NO;
[email protected]70593e52014-05-15 08:30:231218 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1219 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1220 doneOnce = YES;
1221 if (attemptRestore) {
1222 SessionService* sessionService =
1223 SessionServiceFactory::GetForProfileForSessionRestore(
1224 [self lastProfile]);
1225 if (sessionService &&
Findit046795722018-10-03 11:44:481226 sessionService->RestoreIfNecessary(std::vector<GURL>()))
[email protected]70593e52014-05-15 08:30:231227 return NO;
[email protected]eddcf7502012-02-09 22:43:481228 }
[email protected]0d1210d62010-09-07 17:31:381229 }
[email protected]fc44f242012-02-14 16:54:391230
[email protected]ff81e0a2009-04-13 14:58:541231 // Otherwise open a new window.
[email protected]7108d912014-01-30 08:10:451232 // If the last profile was locked, we have to open the User Manager, as the
mlerman7831f57d2015-05-25 11:40:151233 // profile requires authentication. Similarly, because guest mode and system
1234 // profile are implemented as forced incognito, we can't open a new guest
1235 // browser either, so we have to show the User Manager as well.
[email protected]7108d912014-01-30 08:10:451236 Profile* lastProfile = [self lastProfile];
mlerman7831f57d2015-05-25 11:40:151237 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1238 lastProfile->IsSystemProfile()) {
mlermane6e040a2014-10-31 00:53:211239 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261240 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1241 } else {
[email protected]7108d912014-01-30 08:10:451242 CreateBrowser(lastProfile);
mlermane29d0032014-09-24 19:31:261243 }
[email protected]ff81e0a2009-04-13 14:58:541244
1245 // We've handled the reopen event, so return NO to tell AppKit not
1246 // to do anything.
1247 return NO;
1248}
1249
[email protected]88d74942009-01-21 22:04:441250- (void)initMenuState {
Ivan Sandrk9669d0e2017-12-15 23:50:201251 menuState_ = std::make_unique<CommandUpdaterImpl>(nullptr);
[email protected]fbc947b2009-06-19 13:28:241252 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441253 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181254 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191255 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381256 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241257 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221258 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331259 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451260 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221261 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1262 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361263 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481264 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211265 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]236ad3022013-09-04 03:27:431266#if defined(GOOGLE_CHROME_BUILD)
[email protected]1c41a932010-11-22 23:41:231267 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]236ad3022013-09-04 03:27:431268#endif
[email protected]ceaaf1812010-01-20 22:13:091269 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441270}
[email protected]1bcdb532009-01-16 17:47:571271
[email protected]961a6932011-07-19 19:52:461272// Conditionally adds the Profile menu to the main menu bar.
1273- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461274 NSMenu* mainMenu = [NSApp mainMenu];
1275 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401276
[email protected]de71ae992013-07-18 03:30:381277 if (!profiles::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401278 [mainMenu removeItem:profileMenu];
1279 return;
1280 }
1281
[email protected]6b2d30bc2011-10-11 18:16:391282 // The controller will unhide the menu if necessary.
1283 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461284
[email protected]6b2d30bc2011-10-11 18:16:391285 profileMenuController_.reset(
1286 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461287}
1288
Leonard Grey2bdd08f2017-10-03 18:40:521289- (void)initShareMenu {
1290 shareMenuController_.reset([[ShareMenuController alloc] init]);
1291 NSMenu* mainMenu = [NSApp mainMenu];
1292 NSMenu* fileMenu = [[mainMenu itemWithTag:IDC_FILE_MENU] submenu];
1293 NSString* shareMenuTitle = l10n_util::GetNSString(IDS_SHARE_MAC);
Leonard Grey34b5e622018-07-30 19:05:551294 NSMenuItem* shareMenuItem = [fileMenu itemWithTitle:shareMenuTitle];
Leonard Grey2bdd08f2017-10-03 18:40:521295 base::scoped_nsobject<NSMenu> shareSubmenu(
1296 [[NSMenu alloc] initWithTitle:shareMenuTitle]);
1297 [shareSubmenu setDelegate:shareMenuController_];
1298 [shareMenuItem setSubmenu:shareSubmenu];
Leonard Grey2bdd08f2017-10-03 18:40:521299}
1300
[email protected]a99fce0e2011-03-21 20:58:481301// The Confirm to Quit preference is atypical in that the preference lives in
1302// the app menu right above the Quit menu item. This method will refresh the
1303// display of that item depending on the preference state.
1304- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1305 // Format the string so that the correct key equivalent is displayed.
1306 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1307 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1308 base::SysNSStringToUTF16(acceleratorString));
1309 [item setTitle:title];
1310
[email protected]b6366ffa2012-02-29 17:12:261311 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481312 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1313 [item setState:enabled ? NSOnState : NSOffState];
1314}
1315
[email protected]eef99c22010-08-17 05:55:161316- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411317 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1318 // handles requests from services.
Avi Drissmana0820222018-09-01 18:02:281319 NSArray* types = @[ base::mac::CFToNSCast(kUTTypeUTF8PlainText) ];
[email protected]09ea24c2010-08-23 19:05:411320 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161321}
1322
Owen Min8c5d5382018-08-02 17:52:431323// Return null if Chrome is not ready or there is no ProfileManager.
[email protected]a585a8db2011-06-20 18:58:351324- (Profile*)lastProfile {
andresantoso55fd2512015-04-01 21:07:041325 // Return the profile of the last-used Browser, if available.
[email protected]7fd5a462011-06-19 16:57:231326 if (lastProfile_)
1327 return lastProfile_;
1328
Owen Min8c5d5382018-08-02 17:52:431329 if (![self isProfileReady])
1330 return nullptr;
1331
[email protected]fbb04552014-01-16 15:47:381332 // On first launch, use the logic that ChromeBrowserMain uses to determine
1333 // the initial profile.
1334 ProfileManager* profile_manager = g_browser_process->profile_manager();
1335 if (!profile_manager)
Owen Min8c5d5382018-08-02 17:52:431336 return nullptr;
[email protected]3f34599d2009-03-25 22:11:431337
avi3ef9ec9e2014-12-22 22:50:171338 return profile_manager->GetProfile(
1339 GetStartupProfilePath(profile_manager->user_data_dir(),
1340 *base::CommandLine::ForCurrentProcess()));
[email protected]3f34599d2009-03-25 22:11:431341}
1342
[email protected]2a39d1a2014-04-10 05:46:241343- (Profile*)safeLastProfileForNewWindows {
1344 Profile* profile = [self lastProfile];
1345
Owen Min8c5d5382018-08-02 17:52:431346 if (!profile)
1347 return nullptr;
1348
[email protected]2a39d1a2014-04-10 05:46:241349 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1350 if (profile->IsGuestSession())
1351 return profile->GetOffTheRecordProfile();
1352
1353 return profile;
1354}
1355
mlermane6e040a2014-10-31 00:53:211356// Returns true if a browser window may be opened for the last active profile.
1357- (bool)canOpenNewBrowser {
1358 Profile* profile = [self safeLastProfileForNewWindows];
1359
1360 const PrefService* prefs = g_browser_process->local_state();
1361 return !profile->IsGuestSession() ||
1362 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1363}
1364
[email protected]57750f822009-04-21 21:43:091365// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031366// StartupBrowserCreator here because on the other platforms, URLs to open come
1367// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1368// to bottleneck the openings through that for uniform handling.
[email protected]d630d7d52010-02-21 00:55:111369- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211370 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111371 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251372 return;
1373 }
Christian Dullweber820ee5f2018-04-26 13:24:311374 // Pick the last used browser from a regular profile to open the urls.
1375 Profile* profile =
1376 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
1377 Browser* browser = chrome::FindLastActiveWithProfile(profile);
Scott Violet1f106b582017-07-12 15:49:581378 // if no browser window exists then create one with no tabs to be filled in
1379 if (!browser) {
1380 browser = new Browser(
1381 Browser::CreateParams([self safeLastProfileForNewWindows], true));
1382 browser->window()->Show();
eugenebng7afbc36e2017-06-15 13:38:471383 }
Scott Violet1f106b582017-07-12 15:49:581384
1385 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1386 chrome::startup::IsFirstRun first_run =
1387 first_run::IsChromeFirstRun() ? chrome::startup::IS_FIRST_RUN
1388 : chrome::startup::IS_NOT_FIRST_RUN;
1389 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1390 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091391}
1392
[email protected]57750f822009-04-21 21:43:091393- (void)getUrl:(NSAppleEventDescriptor*)event
1394 withReply:(NSAppleEventDescriptor*)reply {
1395 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1396 stringValue];
1397
1398 GURL gurl(base::SysNSStringToUTF8(urlStr));
1399 std::vector<GURL> gurlVector;
1400 gurlVector.push_back(gurl);
1401
erikchen19ee3922014-10-31 19:14:221402 [self openUrlsReplacingNTP:gurlVector];
[email protected]57750f822009-04-21 21:43:091403}
1404
[email protected]caadfca2010-01-22 21:51:211405- (void)application:(NSApplication*)sender
1406 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091407 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211408 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451409 GURL gurl =
[email protected]77d83542013-12-13 08:54:291410 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
[email protected]57750f822009-04-21 21:43:091411 gurlVector.push_back(gurl);
1412 }
[email protected]caadfca2010-01-22 21:51:211413 if (!gurlVector.empty())
erikchen19ee3922014-10-31 19:14:221414 [self openUrlsReplacingNTP:gurlVector];
[email protected]caadfca2010-01-22 21:51:211415 else
1416 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091417
[email protected]caadfca2010-01-22 21:51:211418 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091419}
[email protected]3f34599d2009-03-25 22:11:431420
[email protected]3111f08b2009-04-30 16:01:521421// Show the preferences window, or bring it to the front if it's already
1422// visible.
1423- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351424 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051425 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121426 chrome::ShowSettings(browser);
mlermane6e040a2014-10-31 00:53:211427 } else if ([self canOpenNewBrowser]) {
[email protected]445177652011-03-09 02:04:051428 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241429 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211430 } else {
1431 // No way to create a browser, default to the User Manager.
1432 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211433 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
[email protected]4a42d272010-06-18 01:29:421434 }
[email protected]d989f07c2009-11-14 00:35:461435}
1436
[email protected]bde3dda2009-05-20 22:13:071437- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561438 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121439 chrome::ShowAboutChrome(browser);
mlermane6e040a2014-10-31 00:53:211440 } else if ([self canOpenNewBrowser]) {
1441 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241442 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211443 } else {
1444 // No way to create a browser, default to the User Manager.
1445 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211446 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
[email protected]bde3dda2009-05-20 22:13:071447 }
[email protected]bde3dda2009-05-20 22:13:071448}
1449
[email protected]a99fce0e2011-03-21 20:58:481450- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261451 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481452 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1453 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1454}
1455
[email protected]3d4bd23f2009-10-06 03:58:381456// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471457- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381458 [NSApp activateIgnoringOtherApps:YES];
1459 [self commandDispatch:sender];
1460}
1461
[email protected]227fcee2010-06-11 19:19:371462- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441463 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351464 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471465
[email protected]646fadbf2012-09-08 01:49:011466 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1467 atOffset:0
1468 fromDock:YES];
1469 if (profilesAdded)
1470 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331471
[email protected]646fadbf2012-09-08 01:49:011472 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461473 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511474 [[NSMenuItem alloc] initWithTitle:titleStr
1475 action:@selector(commandFromDock:)
1476 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461477 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011478 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081479 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011480 [dockMenu addItem:item];
1481
[email protected]8d10a412013-08-09 19:18:001482 // |profile| can be NULL during unit tests.
treib6f9598012014-11-11 12:21:241483 if (!profile ||
1484 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1485 IncognitoModePrefs::DISABLED) {
[email protected]8d10a412013-08-09 19:18:001486 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1487 item.reset(
1488 [[NSMenuItem alloc] initWithTitle:titleStr
1489 action:@selector(commandFromDock:)
1490 keyEquivalent:@""]);
1491 [item setTarget:self];
1492 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1493 [item setEnabled:[self validateUserInterfaceItem:item]];
1494 [dockMenu addItem:item];
1495 }
[email protected]288bfcd32009-09-14 18:14:461496
[email protected]8c6b029d2011-01-21 22:39:511497 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1498 // tests which use the mock in place of the profile-initialized model.
1499
1500 // Avoid breaking unit tests which have no profile.
1501 if (profile) {
1502 BackgroundApplicationListModel applications(profile);
1503 if (applications.size()) {
1504 int position = 0;
1505 NSString* menuStr =
1506 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461507 base::scoped_nsobject<NSMenu> appMenu(
1508 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341509 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481510 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511511 cursor != applications.end();
1512 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501513 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511514 NSString* itemStr =
[email protected]670d3232013-12-24 17:58:581515 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461516 base::scoped_nsobject<NSMenuItem> appItem(
1517 [[NSMenuItem alloc] initWithTitle:itemStr
1518 action:@selector(executeApplication:)
1519 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511520 [appItem setTarget:self];
1521 [appItem setTag:position];
1522 [appMenu addItem:appItem];
1523 }
[email protected]8c6b029d2011-01-21 22:39:511524 }
1525 }
1526
[email protected]018a3962009-09-17 22:23:441527 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461528}
1529
[email protected]d630d7d52010-02-21 00:55:111530- (const std::vector<GURL>&)startupUrls {
1531 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211532}
1533
[email protected]7e4c69d02011-05-11 22:16:471534- (BookmarkMenuBridge*)bookmarkMenuBridge {
lgarron9e6dee22014-11-18 01:03:391535 return bookmarkMenuBridge_;
[email protected]7e4c69d02011-05-11 22:16:471536}
1537
mlerman8ae56aa2015-04-24 13:56:271538- (HistoryMenuBridge*)historyMenuBridge {
1539 return historyMenuBridge_.get();
1540}
1541
[email protected]e7dc3992013-11-06 02:16:421542- (void)initAppShimMenuController {
[email protected]e4c63ec2014-01-14 15:50:541543 if (!appShimMenuController_)
[email protected]e7dc3992013-11-06 02:16:421544 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1545}
1546
nomsdd5b6a612014-09-23 15:20:161547- (void)windowChangedToProfile:(Profile*)profile {
1548 if (lastProfile_ == profile)
1549 return;
1550
lgarron9e6dee22014-11-18 01:03:391551 // Before tearing down the menu controller bridges, return the history menu to
1552 // its initial state.
1553 if (historyMenuBridge_)
nomsdd5b6a612014-09-23 15:20:161554 historyMenuBridge_->ResetMenu();
1555
dominicknb80838f2015-09-08 23:00:131556 // Rebuild the menus with the new profile. The bookmarks submenu is cached to
1557 // avoid slowdowns when switching between profiles with large numbers of
1558 // bookmarks. Before caching, store whether it is hidden, make the menu item
1559 // visible, and restore its original hidden state after resetting the submenu.
1560 // This works around an apparent AppKit bug where setting a *different* NSMenu
1561 // submenu on a *hidden* menu item forces the item to become visible.
1562 // See https://crbug.com/497813 for more details.
1563 NSMenuItem* bookmarkItem = [[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU];
1564 BOOL hidden = [bookmarkItem isHidden];
1565 [bookmarkItem setHidden:NO];
nomsdd5b6a612014-09-23 15:20:161566 lastProfile_ = profile;
1567
Trent Aptedcf95689a2017-11-22 00:01:101568 auto& entry = profileBookmarkMenuBridgeMap_[profile->GetPath()];
1569 if (!entry) {
1570 // This creates a deep copy, but only the first 3 items in the root menu
1571 // are really wanted. This can probably be optimized, but lazy-loading of
1572 // the menu should reduce the impact in most flows.
dominicknb80838f2015-09-08 23:00:131573 base::scoped_nsobject<NSMenu> submenu([[bookmarkItem submenu] copy]);
Trent Aptedcf95689a2017-11-22 00:01:101574 [submenu setDelegate:nil]; // The delegate is also copied. Remove it.
1575
1576 entry = std::make_unique<BookmarkMenuBridge>(profile, submenu);
1577
1578 // Clear bookmarks from the old profile.
1579 entry->ClearBookmarkMenu();
lgarron9e6dee22014-11-18 01:03:391580 }
Trent Aptedcf95689a2017-11-22 00:01:101581 bookmarkMenuBridge_ = entry.get();
lgarron9e6dee22014-11-18 01:03:391582
nomsdd5b6a612014-09-23 15:20:161583 // No need to |BuildMenu| here. It is done lazily upon menu access.
dominicknb80838f2015-09-08 23:00:131584 [bookmarkItem setSubmenu:bookmarkMenuBridge_->BookmarkMenu()];
1585 [bookmarkItem setHidden:hidden];
nomsdd5b6a612014-09-23 15:20:161586
1587 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1588 historyMenuBridge_->BuildMenu();
1589
1590 chrome::BrowserCommandController::
1591 UpdateSharedCommandsForIncognitoAvailability(
1592 menuState_.get(), lastProfile_);
1593 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1594 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1595 profilePrefRegistrar_->Add(
1596 prefs::kIncognitoModeAvailability,
1597 base::Bind(&chrome::BrowserCommandController::
1598 UpdateSharedCommandsForIncognitoAvailability,
1599 menuState_.get(),
1600 lastProfile_));
1601}
1602
erikchen22be2092018-06-12 15:54:001603- (void)updateMenuItemKeyEquivalents {
1604 BOOL enableCloseTabShortcut = NO;
1605 id target = [NSApp targetForAction:@selector(performClose:)];
1606
1607 // |target| is an instance of NSPopover or NSWindow.
1608 // If a popover (likely the dictionary lookup popover), we want Cmd-W to
1609 // close the popover so map it to "Close Window".
1610 // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
1611 if ([target isKindOfClass:[NSWindow class]]) {
1612 NSWindow* window = target;
1613 NSWindow* mainWindow = [NSApp mainWindow];
1614 if (!window || ([window parentWindow] == mainWindow)) {
1615 // If the target window is a child of the main window (e.g. a bubble), the
1616 // main window should be the one that handles the close menu item action.
1617 window = mainWindow;
1618 }
1619 Browser* browser = chrome::FindBrowserWithWindow(window);
1620 enableCloseTabShortcut = browser && browser->is_type_tabbed();
1621 }
1622
1623 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
1624 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
1625}
1626
[email protected]92747fe42014-08-18 23:25:261627- (BOOL)application:(NSApplication*)application
Peter Collingbournefc74af32017-07-10 21:00:181628 willContinueUserActivityWithType:(NSString*)userActivityType
Nico Weber23f11eae2017-07-13 23:39:411629 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261630 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1631}
1632
1633- (BOOL)application:(NSApplication*)application
1634 continueUserActivity:(NSUserActivity*)userActivity
Leonard Greybc00f8862018-09-26 17:24:221635#if !defined(MAC_OS_X_VERSION_10_14) || \
1636 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_14
Peter Collingbournefc74af32017-07-10 21:00:181637 restorationHandler:(void (^)(NSArray*))restorationHandler
Leonard Greybc00f8862018-09-26 17:24:221638#else
1639 restorationHandler:
1640 (void (^)(NSArray<id<NSUserActivityRestoring>>*))restorationHandler
1641#endif
Nico Weber23f11eae2017-07-13 23:39:411642 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261643 if (![userActivity.activityType
1644 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1645 return NO;
1646 }
1647
erikchen96e537d52014-10-28 23:43:171648 NSString* originString = base::mac::ObjCCast<NSString>(
1649 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1650 handoff::Origin origin = handoff::OriginFromString(originString);
1651 UMA_HISTOGRAM_ENUMERATION(
1652 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1653
jiangjc0c568c2014-12-04 19:02:121654 NSURL* url = userActivity.webpageURL;
[email protected]92747fe42014-08-18 23:25:261655 if (!url)
1656 return NO;
1657
1658 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1659 std::vector<GURL> gurlVector;
1660 gurlVector.push_back(gurl);
1661
erikchen19ee3922014-10-31 19:14:221662 [self openUrlsReplacingNTP:gurlVector];
[email protected]92747fe42014-08-18 23:25:261663 return YES;
1664}
1665
1666- (void)application:(NSApplication*)application
1667 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1668 error:(NSError*)error {
1669}
1670
erikchen600f7962014-12-12 00:17:381671#pragma mark - Handoff Manager
1672
1673- (BOOL)shouldUseHandoff {
sdy07171a42016-08-30 18:22:041674 return base::mac::IsAtLeastOS10_10();
erikchen600f7962014-12-12 00:17:381675}
1676
1677- (void)passURLToHandoffManager:(const GURL&)handoffURL {
Peter Collingbournefc74af32017-07-10 21:00:181678 if (@available(macOS 10.10, *)) {
1679 [handoffManager_ updateActiveURL:handoffURL];
1680 } else {
1681 // Only ends up being called in 10.10+, i.e. if shouldUseHandoff returns
1682 // true. Some tests override shouldUseHandoff to always return true, but
1683 // then they also override this function to do something else.
1684 NOTREACHED();
1685 }
erikchen600f7962014-12-12 00:17:381686}
1687
1688- (void)updateHandoffManager:(content::WebContents*)webContents {
1689 if (![self shouldUseHandoff])
1690 return;
1691
1692 if (!handoffManager_)
1693 handoffManager_.reset([[HandoffManager alloc] init]);
1694
1695 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1696 [self passURLToHandoffManager:handoffURL];
1697}
1698
1699- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1700 if (!webContents)
1701 return GURL();
1702
1703 Profile* profile =
1704 Profile::FromBrowserContext(webContents->GetBrowserContext());
1705 if (!profile)
1706 return GURL();
1707
1708 // Handoff is not allowed from an incognito profile. To err on the safe side,
1709 // also disallow Handoff from a guest profile.
1710 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1711 return GURL();
1712
1713 if (!webContents)
1714 return GURL();
1715
1716 return webContents->GetVisibleURL();
1717}
1718
Owen Min8c5d5382018-08-02 17:52:431719- (BOOL)isProfileReady {
1720 return !g_browser_process->browser_policy_connector()
1721 ->machine_level_user_cloud_policy_controller()
1722 ->IsEnterpriseStartupDialogShowing();
1723}
1724
erikchen600f7962014-12-12 00:17:381725#pragma mark - HandoffActiveURLObserverBridgeDelegate
1726
1727- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1728 [self updateHandoffManager:webContents];
1729}
1730
[email protected]d630d7d52010-02-21 00:55:111731@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191732
1733//---------------------------------------------------------------------------
1734
Elly Fong-Jones68b85b82018-04-21 00:36:541735namespace {
1736
1737void UpdateProfileInUse(Profile* profile, Profile::CreateStatus status) {
1738 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1739 AppController* controller =
1740 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1741 [controller windowChangedToProfile:profile];
1742 }
1743}
1744
1745} // namespace
1746
[email protected]216e9042009-10-29 17:05:231747namespace app_controller_mac {
1748
1749bool IsOpeningNewWindow() {
1750 return g_is_opening_new_window;
1751}
1752
Elly Fong-Jones68b85b82018-04-21 00:36:541753void CreateGuestProfileIfNeeded() {
1754 g_browser_process->profile_manager()->CreateProfileAsync(
1755 ProfileManager::GetGuestProfilePath(),
Marc Treib92127162018-08-27 14:20:031756 base::BindRepeating(&UpdateProfileInUse), base::string16(),
Elly Fong-Jones68b85b82018-04-21 00:36:541757 std::string());
1758}
1759
Owen Min3bcf8d152018-07-16 16:50:391760void EnterpriseStartupDialogClosed() {
1761 AppController* controller =
1762 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1763 if (controller != nil) {
1764 NSNotification* notify = [NSNotification
1765 notificationWithName:NSApplicationDidFinishLaunchingNotification
1766 object:NSApp];
1767 [controller applicationDidFinishLaunching:notify];
1768 }
1769}
1770
[email protected]216e9042009-10-29 17:05:231771} // namespace app_controller_mac