blob: 1d4134ee0afd6476bb7b0e75f6ae070fca90d384 [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 Charette66d79ed22017-06-21 17:58:2228#include "base/task_scheduler/post_task.h"
29#include "base/threading/thread_restrictions.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"
[email protected]7d791652010-12-01 16:34:4972#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
erikchen600f7962014-12-12 00:17:3873#include "chrome/browser/ui/cocoa/handoff_active_url_observer_bridge.h"
[email protected]7d791652010-12-01 16:34:4974#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1375#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]ced445e92014-04-09 21:43:5976#import "chrome/browser/ui/cocoa/profiles/profile_menu_controller.h"
Leonard Grey2bdd08f2017-10-03 18:40:5277#import "chrome/browser/ui/cocoa/share_menu_controller.h"
Tom Andersonbddfeda52018-06-14 22:25:0678#import "chrome/browser/ui/confirm_quit.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 Baskakovf302efe2018-07-28 02:02:3284#include "chrome/browser/web_applications/components/web_app_shortcut_mac.h"
Alexey Baskakov2f8bf8162018-07-17 01:06:1185#include "chrome/browser/web_applications/extensions/web_app_extension_helpers.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.)
Francois Doray66bdfd82017-10-20 13:50:37182 base::AssertBlockingAllowed();
[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;
[email protected]88d74942009-01-21 22:04:44249@end
[email protected]1bcdb532009-01-16 17:47:57250
lwchkg9c183942016-03-13 06:29:54251class AppControllerProfileObserver : public ProfileAttributesStorage::Observer {
[email protected]1c62b2f2013-06-28 00:15:00252 public:
253 AppControllerProfileObserver(
254 ProfileManager* profile_manager, AppController* app_controller)
255 : profile_manager_(profile_manager),
256 app_controller_(app_controller) {
257 DCHECK(profile_manager_);
258 DCHECK(app_controller_);
lwchkg9c183942016-03-13 06:29:54259 profile_manager_->GetProfileAttributesStorage().AddObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00260 }
261
Daniel Chenga542fca2014-10-21 09:51:29262 ~AppControllerProfileObserver() override {
[email protected]1c62b2f2013-06-28 00:15:00263 DCHECK(profile_manager_);
lwchkg9c183942016-03-13 06:29:54264 profile_manager_->GetProfileAttributesStorage().RemoveObserver(this);
[email protected]1c62b2f2013-06-28 00:15:00265 }
266
267 private:
lwchkg9c183942016-03-13 06:29:54268 // ProfileAttributesStorage::Observer implementation:
[email protected]1c62b2f2013-06-28 00:15:00269
Daniel Chenga542fca2014-10-21 09:51:29270 void OnProfileAdded(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00271
Daniel Chenga542fca2014-10-21 09:51:29272 void OnProfileWasRemoved(const base::FilePath& profile_path,
273 const base::string16& profile_name) override {
[email protected]1c62b2f2013-06-28 00:15:00274 // When a profile is deleted we need to notify the AppController,
275 // so it can correctly update its pointer to the last used profile.
276 [app_controller_ profileWasRemoved:profile_path];
277 }
278
Daniel Chenga542fca2014-10-21 09:51:29279 void OnProfileWillBeRemoved(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00280
Daniel Chenga542fca2014-10-21 09:51:29281 void OnProfileNameChanged(const base::FilePath& profile_path,
282 const base::string16& old_profile_name) override {}
[email protected]1c62b2f2013-06-28 00:15:00283
Daniel Chenga542fca2014-10-21 09:51:29284 void OnProfileAvatarChanged(const base::FilePath& profile_path) override {}
[email protected]1c62b2f2013-06-28 00:15:00285
286 ProfileManager* profile_manager_;
287
288 AppController* app_controller_; // Weak; owns us.
289
290 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
291};
292
Robert Sesek1eb85222017-08-24 23:17:09293#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33294// On macOS 10.12, the IME system attempts to allocate a 2^64 size buffer,
295// which would typically cause an OOM crash. To avoid this, the problematic
296// method is swizzled out and the make-OOM-fatal bit is disabled for the
297// duration of the original call. https://crbug.com/654695
298static base::mac::ScopedObjCClassSwizzler* g_swizzle_imk_input_session;
299
300@interface OOMDisabledIMKInputSession : NSObject
301@end
302
303@implementation OOMDisabledIMKInputSession
304
305- (void)_coreAttributesFromRange:(NSRange)range
306 whichAttributes:(long long)attributes
307 completionHandler:(void (^)(void))block {
308 // The allocator flag is per-process, so other threads may temporarily
309 // not have fatal OOM occur while this method executes, but it is better
310 // than crashing when using IME.
311 base::allocator::SetCallNewHandlerOnMallocFailure(false);
312 g_swizzle_imk_input_session->GetOriginalImplementation()(self, _cmd, range,
313 attributes, block);
314 base::allocator::SetCallNewHandlerOnMallocFailure(true);
315}
316
317@end
Robert Sesek1eb85222017-08-24 23:17:09318#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33319
[email protected]1bcdb532009-01-16 17:47:57320@implementation AppController
321
[email protected]caadfca2010-01-22 21:51:21322@synthesize startupComplete = startupComplete_;
323
andresantoso04f7bab2015-01-15 19:19:16324- (void)dealloc {
325 [[closeTabMenuItem_ menu] setDelegate:nil];
326 [super dealloc];
327}
328
[email protected]cd63ef62009-05-06 19:41:37329// This method is called very early in application startup (ie, before
330// the profile is loaded or any preferences have been registered). Defer any
331// user-data initialization until -applicationDidFinishLaunching:.
Robert Sesek124f80f92018-07-24 20:31:29332- (void)mainMenuCreated {
[email protected]7d1aaa62014-07-18 02:21:30333 MacStartupProfiler::GetInstance()->Profile(
334 MacStartupProfiler::AWAKE_FROM_NIB);
[email protected]136140c2009-05-19 13:58:25335 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09336 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
337 [em setEventHandler:self
338 andSelector:@selector(getUrl:withReply:)
339 forEventClass:kInternetEventClass
340 andEventID:kAEGetURL];
341 [em setEventHandler:self
342 andSelector:@selector(getUrl:withReply:)
343 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
344 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37345
[email protected]449dd2f2009-05-27 13:04:00346 NSNotificationCenter* notificationCenter =
347 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44348 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00349 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16350 selector:@selector(windowDidResignKey:)
[email protected]449dd2f2009-05-27 13:04:00351 name:NSWindowDidResignKeyNotification
352 object:nil];
353 [notificationCenter
354 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16355 selector:@selector(windowDidBecomeMain:)
[email protected]449dd2f2009-05-27 13:04:00356 name:NSWindowDidBecomeMainNotification
357 object:nil];
358 [notificationCenter
359 addObserver:self
andresantoso04f7bab2015-01-15 19:19:16360 selector:@selector(windowDidResignMain:)
[email protected]449dd2f2009-05-27 13:04:00361 name:NSWindowDidResignMainNotification
362 object:nil];
363
[email protected]d4c811e72013-10-29 21:57:55364 // Register for space change notifications.
365 [[[NSWorkspace sharedWorkspace] notificationCenter]
366 addObserver:self
367 selector:@selector(activeSpaceDidChange:)
368 name:NSWorkspaceActiveSpaceDidChangeNotification
369 object:nil];
370
jochenbf9420152015-01-13 14:12:57371 [[[NSWorkspace sharedWorkspace] notificationCenter]
372 addObserver:self
373 selector:@selector(willPowerOff:)
374 name:NSWorkspaceWillPowerOffNotification
375 object:nil];
376
[email protected]136140c2009-05-19 13:58:25377 // Set up the command updater for when there are no windows open
378 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46379
380 // Initialize the Profile menu.
381 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25382}
383
[email protected]71c0eb92012-01-03 17:57:30384- (void)unregisterEventHandlers {
385 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
386 [em removeEventHandlerForEventClass:kInternetEventClass
387 andEventID:kAEGetURL];
388 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
389 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30390 [em removeEventHandlerForEventClass:'WWW!'
391 andEventID:'OURL'];
392 [[NSNotificationCenter defaultCenter] removeObserver:self];
[email protected]d4c811e72013-10-29 21:57:55393 [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[email protected]71c0eb92012-01-03 17:57:30394}
395
[email protected]7dc8c6b2010-04-09 17:02:50396// (NSApplicationDelegate protocol) This is the Apple-approved place to override
397// the default handlers.
398- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]7d1aaa62014-07-18 02:21:30399 MacStartupProfiler::GetInstance()->Profile(
400 MacStartupProfiler::WILL_FINISH_LAUNCHING);
sdy57883382016-09-12 16:00:37401
Erik Chen2d245df72017-07-15 03:16:06402 if (@available(macOS 10.12, *)) {
sdy57883382016-09-12 16:00:37403 NSWindow.allowsAutomaticWindowTabbing = NO;
404 }
spqchan210e2ed2017-07-27 23:17:40405
406 // If the OSX version supports this method, the system will automatically
407 // hide the item if there's no touch bar. However, for unsupported versions,
408 // we'll have to manually remove the item from the menu. The item also has
409 // to be removed if the feature is disabled.
410 if (![NSApp
411 respondsToSelector:@selector(toggleTouchBarCustomizationPalette:)] ||
412 !base::FeatureList::IsEnabled(features::kBrowserTouchBar)) {
413 NSMenu* mainMenu = [NSApp mainMenu];
414 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
415 NSMenuItem* customizeItem = [viewMenu itemWithTag:IDC_CUSTOMIZE_TOUCH_BAR];
416 if (customizeItem)
417 [viewMenu removeItem:customizeItem];
418 }
Leonard Grey2bdd08f2017-10-03 18:40:52419
420 // In |applicationWillFinishLaunching| because FeatureList isn't
421 // available at init time.
422 if (base::FeatureList::IsEnabled(features::kMacSystemShareMenu)) {
423 // Initialize the share menu.
424 [self initShareMenu];
425 }
spqchan2c5d541e2017-10-25 07:07:11426
427 // Remove "Enable Javascript in Apple Events" if the feature is disabled.
428 if (!base::FeatureList::IsEnabled(
429 features::kAppleScriptExecuteJavaScriptMenuItem)) {
430 NSMenu* mainMenu = [NSApp mainMenu];
431 NSMenu* viewMenu = [[mainMenu itemWithTag:IDC_VIEW_MENU] submenu];
432 NSMenu* devMenu = [[viewMenu itemWithTag:IDC_DEVELOPER_MENU] submenu];
433 NSMenuItem* javascriptAppleEventItem =
434 [devMenu itemWithTag:IDC_TOGGLE_JAVASCRIPT_APPLE_EVENTS];
435 if (javascriptAppleEventItem)
436 [devMenu removeItem:javascriptAppleEventItem];
437 }
[email protected]7dc8c6b2010-04-09 17:02:50438}
439
[email protected]8a5bd59042014-07-22 04:10:06440- (void)applicationWillHide:(NSNotification*)notification {
441 apps::ExtensionAppShimHandler::OnChromeWillHide();
442}
443
[email protected]7dc8c6b2010-04-09 17:02:50444- (BOOL)tryToTerminateApplication:(NSApplication*)app {
jochenbf9420152015-01-13 14:12:57445 // Reset this now that we've received the call to terminate.
446 BOOL isPoweringOff = isPoweringOff_;
447 isPoweringOff_ = NO;
448
[email protected]3076fad2010-04-28 18:11:45449 // Check for in-process downloads, and prompt the user if they really want
450 // to quit (and thus cancel downloads). Only check if we're not already
451 // shutting down, else the user might be prompted multiple times if the
452 // download isn't stopped before terminate is called again.
453 if (!browser_shutdown::IsTryingToQuit() &&
454 ![self shouldQuitWithInProgressDownloads])
455 return NO;
456
[email protected]7dc8c6b2010-04-09 17:02:50457 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
458 // them in, but I'm not sure about UX; we'd also want to disable other things
459 // though.) http://crbug.com/40861
460
[email protected]177aceb2010-11-03 16:17:41461 // Check if the user really wants to quit by employing the confirm-to-quit
462 // mechanism.
463 if (!browser_shutdown::IsTryingToQuit() &&
464 [self applicationShouldTerminate:app] != NSTerminateNow)
465 return NO;
466
[email protected]70593e52014-05-15 08:30:23467 // Check for active apps. If quitting is prevented, only close browsers and
468 // sessions.
jochenbf9420152015-01-13 14:12:57469 if (!browser_shutdown::IsTryingToQuit() && !isPoweringOff &&
470 quitWithAppsController_.get() && !quitWithAppsController_->ShouldQuit()) {
avi3ef9ec9e2014-12-22 22:50:17471 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
mitchelljones3bc6ced2014-12-19 05:01:37472 switches::kHostedAppQuitNotification)) {
473 return NO;
474 }
475
[email protected]70593e52014-05-15 08:30:23476 content::NotificationService::current()->Notify(
477 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
478 content::NotificationService::AllSources(),
479 content::NotificationService::NoDetails());
480 // This will close all browser sessions.
481 chrome::CloseAllBrowsers();
jackhouae8e6e52015-05-29 06:36:46482
483 // At this point, the user has already chosen to cancel downloads. If we
484 // were to shut down as usual, the downloads would be cancelled in
peterccb33e82017-05-02 19:00:44485 // DownloadCoreService::Shutdown().
486 DownloadCoreService::CancelAllDownloads();
jackhouae8e6e52015-05-29 06:36:46487
[email protected]70593e52014-05-15 08:30:23488 return NO;
489 }
490
[email protected]0665ebe2013-02-13 09:53:19491 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50492
[email protected]0c95faf42013-10-28 06:27:20493 // Initiate a shutdown (via chrome::CloseAllBrowsersAndQuit()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20494 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56495 if (!browser_shutdown::IsTryingToQuit()) {
496 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30497 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56498 content::NotificationService::AllSources(),
499 content::NotificationService::NoDetails());
[email protected]0c95faf42013-10-28 06:27:20500 chrome::CloseAllBrowsersAndQuit();
[email protected]ef61b8c2012-01-20 10:54:56501 }
[email protected]7dc8c6b2010-04-09 17:02:50502
[email protected]c984d9f2010-07-20 20:52:20503 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50504}
505
506- (void)stopTryingToTerminateApplication:(NSApplication*)app {
507 if (browser_shutdown::IsTryingToQuit()) {
508 // Reset the "trying to quit" state, so that closing all browser windows
509 // will no longer lead to termination.
510 browser_shutdown::SetTryingToQuit(false);
511
512 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
513 // would have to reinstall them here. http://crbug.com/40861
514 }
[email protected]a9e8afc2009-08-11 22:03:17515}
516
[email protected]177aceb2010-11-03 16:17:41517- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]90a4b9d2013-07-31 12:14:40518 // If there are no windows, quit immediately.
scottmg8abbff832016-01-28 22:57:37519 if (BrowserList::GetInstance()->empty() &&
jackhou261f7f32015-01-07 00:59:03520 !AppWindowRegistryUtil::IsAppWindowVisibleInAnyProfile(0)) {
[email protected]90a4b9d2013-07-31 12:14:40521 return NSTerminateNow;
522 }
523
[email protected]a99fce0e2011-03-21 20:58:48524 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26525 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23526 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
527 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41528 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23529 }
[email protected]177aceb2010-11-03 16:17:41530
531 // If the application is going to terminate as the result of a Cmd+Q
532 // invocation, use the special sauce to prevent accidental quitting.
533 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41534
[email protected]2020fd0b2010-12-10 01:16:50535 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26536 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50537 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41538
[email protected]5df54fb2011-03-07 18:15:26539 return [[ConfirmQuitPanelController sharedController]
540 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41541}
542
[email protected]449dd2f2009-05-27 13:04:00543// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50544- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50545 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19546 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11547
[email protected]c984d9f2010-07-20 20:52:20548 // Tell BrowserList not to keep the browser process alive. Once all the
549 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
dgn02377782016-03-12 00:58:38550 keep_alive_.reset();
[email protected]fbc947b2009-06-19 13:28:24551
[email protected]02a31dd2013-02-05 08:40:52552 // Reset all pref watching, as this object outlives the prefs system.
553 profilePrefRegistrar_.reset();
554 localPrefRegistrar_.RemoveAll();
555
[email protected]71c0eb92012-01-03 17:57:30556 [self unregisterEventHandlers];
[email protected]edb2d032013-08-30 09:03:17557
558 appShimMenuController_.reset();
lgarron9e6dee22014-11-18 01:03:39559
avi82554752016-09-23 17:48:50560 profileBookmarkMenuBridgeMap_.clear();
[email protected]449dd2f2009-05-27 13:04:00561}
562
[email protected]3b6aa8b62009-09-15 21:36:11563- (void)didEndMainMessageLoop {
scottmg34c5dd882016-02-03 05:21:54564 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile]));
565 if (!chrome::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11566 // As we're shutting down, we need to nuke the TabRestoreService, which
567 // will start the shutdown of the NavigationControllers and allow for
568 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
569 // and may end up crashing when some thread tries to use the IO thread (or
570 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35571 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11572 }
573}
574
[email protected]8cfbdbd2011-06-16 04:17:17575// If the window has a tab controller, make "close window" be cmd-shift-w,
576// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48577// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56578- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
579 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
580 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17581 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
582}
583
584// If the window has a tab controller, make "close tab" take over cmd-w,
585// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56586- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
587 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17588 [closeTabMenuItem_ setKeyEquivalent:@"w"];
589 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
590 } else {
591 [closeTabMenuItem_ setKeyEquivalent:@""];
592 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
593 }
594}
595
[email protected]9f5f79b62011-10-28 00:43:45596// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17597// Close Tab/Close Window accordingly.
andresantoso04f7bab2015-01-15 19:19:16598- (void)menuNeedsUpdate:(NSMenu*)menu {
599 DCHECK(menu == [closeTabMenuItem_ menu]);
erikchen22be2092018-06-12 15:54:00600 [self updateMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17601}
602
andresantoso04f7bab2015-01-15 19:19:16603- (void)windowDidResignKey:(NSNotification*)notify {
604 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
605 // returns nil regardless of whether any suitable candidates for the key
606 // window remain. It seems that the new key window for the app is not set
607 // until after this notification is fired, so a check is performed after the
608 // run loop is allowed to spin.
609 [self performSelector:@selector(checkForAnyKeyWindows)
610 withObject:nil
611 afterDelay:0.0];
[email protected]8cfbdbd2011-06-16 04:17:17612}
613
andresantoso04f7bab2015-01-15 19:19:16614- (void)windowDidBecomeMain:(NSNotification*)notify {
andresantoso55fd2512015-04-01 21:07:04615 Browser* browser = chrome::FindBrowserWithWindow([notify object]);
616 if (browser)
617 [self windowChangedToProfile:browser->profile()->GetOriginalProfile()];
andresantoso04f7bab2015-01-15 19:19:16618}
619
620- (void)windowDidResignMain:(NSNotification*)notify {
621 if (chrome::GetTotalBrowserCount() == 0) {
[email protected]cae68b3a2011-11-21 23:29:49622 [self windowChangedToProfile:
623 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24624 }
625}
626
[email protected]d4c811e72013-10-29 21:57:55627- (void)activeSpaceDidChange:(NSNotification*)notify {
628 if (reopenTime_.is_null() ||
629 ![NSApp isActive] ||
630 (base::TimeTicks::Now() - reopenTime_).InMilliseconds() >
631 kWorkspaceChangeTimeoutMs) {
632 return;
633 }
634
635 // The last applicationShouldHandleReopen:hasVisibleWindows: call
636 // happened during a space change. Now that the change has
637 // completed, raise browser windows.
638 reopenTime_ = base::TimeTicks();
639 std::set<NSWindow*> browserWindows;
scottmg8abbff832016-01-28 22:57:37640 for (auto* browser : *BrowserList::GetInstance())
[email protected]d4c811e72013-10-29 21:57:55641 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]d4c811e72013-10-29 21:57:55642 if (!browserWindows.empty()) {
[email protected]6c4b79602014-05-28 16:47:21643 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:55644 }
645}
646
jochenbf9420152015-01-13 14:12:57647// Called when shutting down or logging out.
648- (void)willPowerOff:(NSNotification*)notify {
649 // Don't attempt any shutdown here. Cocoa will shortly call
650 // -[BrowserCrApplication terminate:].
651 isPoweringOff_ = YES;
652}
653
[email protected]dd6ab1282010-07-20 01:07:32654- (void)checkForAnyKeyWindows {
655 if ([NSApp keyWindow])
656 return;
657
[email protected]ad50def52011-10-19 23:17:07658 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30659 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07660 content::NotificationService::AllSources(),
661 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00662}
663
[email protected]414fde592009-05-21 16:14:43664// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43665// Placed here for 2 reasons:
666// 1) Same spot as other Pref stuff
667// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43668- (void)setUpdateCheckInterval {
669#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49670 CFStringRef app = CFSTR("com.google.Keystone.Agent");
671 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43672 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
673 if (!plist) {
674 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50675 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43676 CFPreferencesSetAppValue(checkInterval, value, app);
677 CFPreferencesAppSynchronize(app);
678 }
679#endif
680}
681
[email protected]66791aff2014-04-29 09:45:38682- (void)openStartupUrls {
erikchen19ee3922014-10-31 19:14:22683 DCHECK(startupComplete_);
684 [self openUrlsReplacingNTP:startupUrls_];
685 startupUrls_.clear();
686}
687
688- (void)openUrlsReplacingNTP:(const std::vector<GURL>&)urls {
689 if (urls.empty())
690 return;
691
[email protected]66791aff2014-04-29 09:45:38692 // On Mac, the URLs are passed in via Cocoa, not command line. The Chrome
693 // NSApplication is created in MainMessageLoop, and then the shortcut urls
694 // are passed in via Apple events. At this point, the first browser is
695 // already loaded in PreMainMessageLoop. If we initialize NSApplication
696 // before PreMainMessageLoop to capture shortcut URL events, it may cause
697 // more problems because it relies on things created in PreMainMessageLoop
698 // and may break existing message loop design.
erikchen19ee3922014-10-31 19:14:22699
700 // If the browser hasn't started yet, just queue up the URLs.
701 if (!startupComplete_) {
702 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]66791aff2014-04-29 09:45:38703 return;
erikchen19ee3922014-10-31 19:14:22704 }
[email protected]66791aff2014-04-29 09:45:38705
706 // If there's only 1 tab and the tab is NTP, close this NTP tab and open all
707 // startup urls in new tabs, because the omnibox will stay focused if we
708 // load url in NTP tab.
Christian Dullweber820ee5f2018-04-26 13:24:31709 Profile* profile =
710 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
711 Browser* browser = chrome::FindLastActiveWithProfile(profile);
712
[email protected]66791aff2014-04-29 09:45:38713 int startupIndex = TabStripModel::kNoTab;
714 content::WebContents* startupContent = NULL;
715
716 if (browser && browser->tab_strip_model()->count() == 1) {
717 startupIndex = browser->tab_strip_model()->active_index();
718 startupContent = browser->tab_strip_model()->GetActiveWebContents();
719 }
720
erikchen19ee3922014-10-31 19:14:22721 [self openUrls:urls];
[email protected]66791aff2014-04-29 09:45:38722
kristiparka34b247a2018-03-09 19:05:34723 // In test environments where there is no network connection, the visible NTP
724 // URL may be chrome-search://local-ntp/local-ntp.html instead of
725 // chrome://newtab/. See local_ntp_test_utils::GetFinalNtpUrl for more
726 // details.
727 // This NTP check should be replaced once https://crbug.com/624410 is fixed.
[email protected]66791aff2014-04-29 09:45:38728 if (startupIndex != TabStripModel::kNoTab &&
kristiparka34b247a2018-03-09 19:05:34729 (startupContent->GetVisibleURL() == chrome::kChromeUINewTabURL ||
730 startupContent->GetVisibleURL() == chrome::kChromeSearchLocalNtpUrl)) {
[email protected]66791aff2014-04-29 09:45:38731 browser->tab_strip_model()->CloseWebContentsAt(startupIndex,
732 TabStripModel::CLOSE_NONE);
733 }
734}
735
[email protected]136140c2009-05-19 13:58:25736// This is called after profiles have been loaded and preferences registered.
737// It is safe to access the default profile here.
Owen Min3bcf8d152018-07-16 16:50:39738- (void)applicationDidFinishLaunching:(NSNotification*)notify {
739 if (g_browser_process->browser_policy_connector()
740 ->machine_level_user_cloud_policy_controller()
741 ->IsEnterpriseStartupDialogShowing()) {
742 // As Chrome is not ready when the Enterprise startup dialog is being shown.
743 // Store the notification as it will be reposted when the dialog is closed.
744 return;
745 }
746
[email protected]7d1aaa62014-07-18 02:21:30747 MacStartupProfiler::GetInstance()->Profile(
748 MacStartupProfiler::DID_FINISH_LAUNCHING);
749 MacStartupProfiler::GetInstance()->RecordMetrics();
750
[email protected]c984d9f2010-07-20 20:52:20751 // Notify BrowserList to keep the application running so it doesn't go away
752 // when all the browser windows get closed.
dgn02377782016-03-12 00:58:38753 keep_alive_.reset(new ScopedKeepAlive(KeepAliveOrigin::APP_CONTROLLER,
754 KeepAliveRestartOption::DISABLED));
[email protected]136140c2009-05-19 13:58:25755
[email protected]414fde592009-05-21 16:14:43756 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53757
[email protected]edb2d032013-08-30 09:03:17758 // Start managing the menu for app windows. This needs to be done here because
759 // main menu item titles are not yet initialized in awakeFromNib.
[email protected]e7dc3992013-11-06 02:16:42760 [self initAppShimMenuController];
[email protected]edb2d032013-08-30 09:03:17761
[email protected]425f7a02014-04-29 01:51:44762 // If enabled, keep Chrome alive when apps are open instead of quitting all
763 // apps.
764 quitWithAppsController_ = new QuitWithAppsController();
765
andresantoso04f7bab2015-01-15 19:19:16766 // Dynamically update shortcuts for "Close Window" and "Close Tab" menu items.
767 [[closeTabMenuItem_ menu] setDelegate:self];
768
lwchkg9c183942016-03-13 06:29:54769 // Instantiate the ProfileAttributesStorage observer so that we can get
[email protected]1c62b2f2013-06-28 00:15:00770 // notified when a profile is deleted.
lwchkg9c183942016-03-13 06:29:54771 profileAttributesStorageObserver_.reset(new AppControllerProfileObserver(
[email protected]1c62b2f2013-06-28 00:15:00772 g_browser_process->profile_manager(), self));
773
[email protected]12dc3d42010-02-22 23:37:12774 // Record the path to the (browser) app bundle; this is used by the app mode
Gabriel Charette66d79ed22017-06-21 17:58:22775 // shim.
776 base::PostTaskWithTraits(FROM_HERE,
Gabriel Charetteb10aeebc2018-07-26 20:15:00777 {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
Gabriel Charette66d79ed22017-06-21 17:58:22778 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
779 base::Bind(&RecordLastRunAppBundlePath));
[email protected]12dc3d42010-02-22 23:37:12780
[email protected]eef99c22010-08-17 05:55:16781 // Makes "Services" menu items available.
782 [self registerServicesMenuTypesTo:[notify object]];
783
[email protected]caadfca2010-01-22 21:51:21784 startupComplete_ = YES;
785
scottmg5c03fe022016-02-03 01:27:24786 Browser* browser = chrome::FindLastActive();
erikchen600f7962014-12-12 00:17:38787 content::WebContents* activeWebContents = nullptr;
788 if (browser)
789 activeWebContents = browser->tab_strip_model()->GetActiveWebContents();
790 [self updateHandoffManager:activeWebContents];
[email protected]66791aff2014-04-29 09:45:38791 [self openStartupUrls];
[email protected]aac169d2011-03-18 19:53:03792
[email protected]05454532013-01-22 21:09:08793 PrefService* localState = g_browser_process->local_state();
794 if (localState) {
795 localPrefRegistrar_.Init(localState);
796 localPrefRegistrar_.Add(
797 prefs::kAllowFileSelectionDialogs,
798 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
799 menuState_.get()));
800 }
erikchen600f7962014-12-12 00:17:38801
802 handoff_active_url_observer_bridge_.reset(
803 new HandoffActiveURLObserverBridge(self));
Robert Sesek99845182017-08-24 20:53:33804
Robert Sesek1eb85222017-08-24 23:17:09805#if BUILDFLAG(USE_ALLOCATOR_SHIM)
Robert Sesek99845182017-08-24 20:53:33806 // Disable fatal OOM to hack around an OS bug https://crbug.com/654695.
807 if (base::mac::IsOS10_12()) {
808 g_swizzle_imk_input_session = new base::mac::ScopedObjCClassSwizzler(
809 NSClassFromString(@"IMKInputSession"),
810 [OOMDisabledIMKInputSession class],
811 @selector(_coreAttributesFromRange:whichAttributes:completionHandler:));
812 }
Robert Sesek1eb85222017-08-24 23:17:09813#endif
[email protected]7c321082009-02-09 15:35:47814}
815
[email protected]73f5b362009-08-10 23:58:21816// Helper function for populating and displaying the in progress downloads at
817// exit alert panel.
818- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48819 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13820 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21821 NSString* waitTitle = nil;
822 NSString* exitTitle = nil;
823
824 // Set the dialog text based on whether or not there are multiple downloads.
jshinec68f032015-05-14 00:03:23825 // Dialog text: warning and explanation.
Bret Sepulveda331f10a2018-02-13 22:37:42826 titleText = l10n_util::GetPluralNSStringF(IDS_ABANDON_DOWNLOAD_DIALOG_TITLE,
827 downloadCount);
828 explanationText =
829 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_BROWSER_MESSAGE);
830 // "Cancel download and exit" button text.
831 exitTitle = l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_EXIT_BUTTON);
[email protected]83a9f652012-04-25 21:03:48832
Bret Sepulveda331f10a2018-02-13 22:37:42833 // "Wait for download" button text.
834 waitTitle =
835 l10n_util::GetNSString(IDS_ABANDON_DOWNLOAD_DIALOG_CONTINUE_BUTTON);
[email protected]73f5b362009-08-10 23:58:21836
837 // 'waitButton' is the default choice.
[email protected]361b47c2013-07-02 15:13:24838 int choice = NSRunAlertPanel(titleText, @"%@",
839 waitTitle, exitTitle, nil, explanationText);
[email protected]73f5b362009-08-10 23:58:21840 return choice == NSAlertDefaultReturn ? YES : NO;
841}
842
843// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41844// user to see if we should continue to exit (and thus cancel the downloads), or
845// if we should wait.
846- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21847 ProfileManager* profile_manager = g_browser_process->profile_manager();
848 if (!profile_manager)
849 return YES;
[email protected]09729a552009-08-03 23:21:41850
[email protected]844a1002011-04-19 11:37:21851 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
Elly Fong-Jones08757f1e2018-01-31 16:24:44852
853 std::vector<Profile*> added_profiles;
854 for (Profile* p : profiles) {
855 if (p->HasOffTheRecordProfile())
856 added_profiles.push_back(p->GetOffTheRecordProfile());
857 }
858 profiles.insert(profiles.end(), added_profiles.begin(), added_profiles.end());
859
[email protected]844a1002011-04-19 11:37:21860 for (size_t i = 0; i < profiles.size(); ++i) {
peterccb33e82017-05-02 19:00:44861 DownloadCoreService* download_core_service =
862 DownloadCoreServiceFactory::GetForBrowserContext(profiles[i]);
[email protected]9bb54ee2011-10-12 17:43:35863 DownloadManager* download_manager =
peterccb33e82017-05-02 19:00:44864 (download_core_service->HasCreatedDownloadManager()
865 ? BrowserContext::GetDownloadManager(profiles[i])
866 : NULL);
[email protected]422a7d12013-10-21 12:10:42867 if (download_manager &&
868 download_manager->NonMaliciousInProgressCount() > 0) {
869 int downloadCount = download_manager->NonMaliciousInProgressCount();
[email protected]73f5b362009-08-10 23:58:21870 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
871 // Create a new browser window (if necessary) and navigate to the
872 // downloads page if the user chooses to wait.
scottmg34c5dd882016-02-03 05:21:54873 Browser* browser = chrome::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21874 if (!browser) {
erg7b01d692017-02-22 21:57:35875 browser = new Browser(Browser::CreateParams(profiles[i], true));
[email protected]73f5b362009-08-10 23:58:21876 browser->window()->Show();
877 }
878 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12879 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21880 return NO;
881 }
[email protected]09729a552009-08-03 23:21:41882
[email protected]73f5b362009-08-10 23:58:21883 // User wants to exit.
884 return YES;
[email protected]09729a552009-08-03 23:21:41885 }
[email protected]09729a552009-08-03 23:21:41886 }
887
[email protected]73f5b362009-08-10 23:58:21888 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41889 return YES;
890}
891
[email protected]fbc947b2009-06-19 13:28:24892// Called to determine if we should enable the "restore tab" menu item.
893// Checks with the TabRestoreService to see if there's anything there to
894// restore and returns YES if so.
895- (BOOL)canRestoreTab {
blundell74001adc2015-09-18 11:04:25896 sessions::TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35897 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24898 return service && !service->entries().empty();
899}
900
[email protected]1c62b2f2013-06-28 00:15:00901// Called from the AppControllerProfileObserver every time a profile is deleted.
902- (void)profileWasRemoved:(const base::FilePath&)profilePath {
[email protected]1c62b2f2013-06-28 00:15:00903 // If the lastProfile has been deleted, the profile manager has
904 // already loaded a new one, so the pointer needs to be updated;
905 // otherwise we will try to start up a browser window with a pointer
906 // to the old profile.
bauerb447f6432015-03-02 22:34:51907 // In a browser test, the application is not brought to the front, so
908 // |lastProfile_| might be null.
mlerman8ae56aa2015-04-24 13:56:27909 if (!lastProfile_ || profilePath == lastProfile_->GetPath()) {
910 // Force windowChangedToProfile: to set the lastProfile_ and also update the
911 // relevant menuBridge objects.
912 lastProfile_ = nullptr;
913 [self windowChangedToProfile:g_browser_process->profile_manager()->
914 GetLastUsedProfile()];
915 }
lgarron9e6dee22014-11-18 01:03:39916
avi82554752016-09-23 17:48:50917 profileBookmarkMenuBridgeMap_.erase(profilePath);
[email protected]1c62b2f2013-06-28 00:15:00918}
919
[email protected]05454532013-01-22 21:09:08920// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21921// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
922// sheets) will not count as blocking the browser. But things like open/save
923// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08924- (BOOL)keyWindowIsModal {
925 if ([NSApp modalWindow])
926 return YES;
927
[email protected]f2bc6e92012-10-14 02:08:38928 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]05454532013-01-22 21:09:08929 return browser &&
930 [[browser->window()->GetNativeWindow() attachedSheet]
931 isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06932}
933
[email protected]88d74942009-01-21 22:04:44934// Called to validate menu items when there are no key windows. All the
935// items we care about have been set with the |commandDispatch:| action and
936// a target of FirstResponder in IB. If it's not one of those, let it
937// continue up the responder chain to be handled elsewhere. We pull out the
938// tag as the cross-platform constant to differentiate and dispatch the
939// various commands.
940- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
941 SEL action = [item action];
942 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08943 if (action == @selector(commandDispatch:) ||
944 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44945 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08946 if (menuState_ && // NULL in tests.
947 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24948 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26949 // The File Menu commands are not automatically disabled by Cocoa when a
950 // dialog sheet obscures the browser window, so we disable several of
951 // them here. We don't need to include IDC_CLOSE_WINDOW, because
952 // app_controller is only activated when there are no key windows (see
953 // function comment).
[email protected]fbc947b2009-06-19 13:28:24954 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08955 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06956 break;
[email protected]f6c15fa2010-06-04 20:08:21957 // Browser-level items that open in new tabs should not open if there's
958 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06959 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06960 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21961 case IDC_SHOW_HISTORY:
962 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08963 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21964 break;
965 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21966 case IDC_TASK_MANAGER:
967 // Allow the user to open a new window if there's a window-modal
968 // dialog.
[email protected]05454532013-01-22 21:09:08969 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24970 break;
971 default:
[email protected]f6c15fa2010-06-04 20:08:21972 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08973 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24974 }
975 }
spqchan9d60fce2016-02-10 18:30:47976
977 // "Show as tab" should only appear when the current window is a popup.
978 // Since |validateUserInterfaceItem:| is called only when there are no
979 // key windows, we should just hide this.
980 // This is handled outside of the switch statement because we want to hide
981 // this regardless if the command is supported or not.
982 if (tag == IDC_SHOW_AS_TAB) {
983 NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
984 [menuItem setHidden:YES];
985 }
[email protected]3b6aa8b62009-09-15 21:36:11986 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44987 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52988 } else if (action == @selector(showPreferences:)) {
989 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07990 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
991 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47992 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38993 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48994 } else if (action == @selector(toggleConfirmToQuit:)) {
995 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
996 enable = YES;
[email protected]3a90b452013-02-15 04:33:48997 } else if (action == @selector(executeApplication:)) {
998 enable = YES;
[email protected]88d74942009-01-21 22:04:44999 }
1000 return enable;
1001}
1002
[email protected]88d74942009-01-21 22:04:441003- (void)commandDispatch:(id)sender {
[email protected]2a39d1a2014-04-10 05:46:241004 Profile* lastProfile = [self safeLastProfileForNewWindows];
[email protected]f0a51fb52009-03-05 12:46:381005
[email protected]947fc0d2010-01-14 22:33:051006 // Handle the case where we're dispatching a command from a sender that's in a
1007 // browser window. This means that the command came from a background window
1008 // and is getting here because the foreground window is not a browser window.
1009 if ([sender respondsToSelector:@selector(window)]) {
1010 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041011 if ([delegate respondsToSelector:@selector(commandDispatch:)]) {
[email protected]947fc0d2010-01-14 22:33:051012 [delegate commandDispatch:sender];
1013 return;
1014 }
1015 }
1016
[email protected]8d4bbdc2012-09-20 21:36:491017 // Ignore commands during session restore's browser creation. It uses a
gab2998ee72017-05-05 16:23:501018 // nested run loop and commands dispatched during this operation cause
[email protected]8d4bbdc2012-09-20 21:36:491019 // havoc.
1020 if (SessionRestore::IsRestoring(lastProfile) &&
gab7af9dc02017-05-05 13:38:541021 base::RunLoop::IsNestedOnCurrentThread()) {
[email protected]8d4bbdc2012-09-20 21:36:491022 return;
gab7af9dc02017-05-05 13:38:541023 }
[email protected]8d4bbdc2012-09-20 21:36:491024
Trent Apted45d9ae22017-11-09 23:12:321025 // If not between -applicationDidFinishLaunching: and
1026 // -applicationWillTerminate:, ignore. This can happen when events are sitting
1027 // in the event queue while the browser is shutting down.
1028 if (!keep_alive_)
1029 return;
1030
[email protected]88d74942009-01-21 22:04:441031 NSInteger tag = [sender tag];
[email protected]7108d912014-01-30 08:10:451032
1033 // If there are no browser windows, and we are trying to open a browser
Owen Min027059d2018-03-13 22:17:361034 // for a locked profile or the system profile or the guest profile but
1035 // guest mode is disabled, we have to show the User Manager instead as the
1036 // locked profile needs authentication and the system profile cannot have a
1037 // browser.
1038 const PrefService* prefService = g_browser_process->local_state();
1039 if (IsProfileSignedOut(lastProfile) || lastProfile->IsSystemProfile() ||
1040 (lastProfile->IsGuestSession() && prefService &&
1041 !prefService->GetBoolean(prefs::kBrowserGuestModeEnabled))) {
mlermane6e040a2014-10-31 00:53:211042 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261043 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
[email protected]7108d912014-01-30 08:10:451044 return;
1045 }
1046
[email protected]88d74942009-01-21 22:04:441047 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:241048 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:111049 // Create a new tab in an existing browser window (which we activate) if
1050 // possible.
[email protected]a585a8db2011-06-20 18:58:351051 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:401052 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:111053 break;
1054 }
Nico Weber331a98a82018-02-06 23:26:011055 FALLTHROUGH; // To create new window.
[email protected]88d74942009-01-21 22:04:441056 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:351057 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:111058 break;
[email protected]91a5b3e2009-10-30 19:32:221059 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:401060 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1061 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:441062 break;
[email protected]cddc5242009-12-07 18:54:331063 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:401064 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
1065 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:331066 break;
[email protected]863ff662009-01-26 20:18:181067 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:481068 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:181069 break;
[email protected]fbc947b2009-06-19 13:28:241070 case IDC_RESTORE_TAB:
scottmgd161e6c2016-02-17 02:08:011071 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:241072 break;
[email protected]e19516d2009-04-28 17:15:191073 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:401074 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:191075 break;
[email protected]1fdff702009-10-22 00:36:181076 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:381077 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:351078 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121079 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231080 } else {
[email protected]1f0b50b2012-06-22 20:37:161081 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231082 }
[email protected]93e181762009-05-29 14:30:381083 break;
[email protected]1fdff702009-10-22 00:36:181084 }
[email protected]4aee5652009-11-19 18:59:211085 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:351086 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121087 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:231088 } else {
[email protected]1f0b50b2012-06-22 20:37:161089 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:231090 }
[email protected]4aee5652009-11-19 18:59:211091 break;
1092 }
[email protected]af7c25e2010-01-23 05:46:451093 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]a585a8db2011-06-20 18:58:351094 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:121095 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:471096 } else {
[email protected]47e532b2010-04-23 17:46:401097 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:161098 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:471099 }
[email protected]af7c25e2010-01-23 05:46:451100 break;
[email protected]91a5b3e2009-10-30 19:32:221101 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:351102 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121103 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:111104 else
[email protected]1f0b50b2012-06-22 20:37:161105 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221106 break;
1107 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:351108 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121109 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:111110 else
[email protected]1f0b50b2012-06-22 20:37:161111 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:221112 break;
[email protected]bb37e6ec2009-11-18 17:59:361113 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:351114 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:081115 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:111116 else
[email protected]1f0b50b2012-06-22 20:37:161117 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:361118 break;
[email protected]2ca35612012-06-12 03:49:481119 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:351120 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:121121 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:111122 else
[email protected]1f0b50b2012-06-22 20:37:161123 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:181124 break;
[email protected]ceaaf1812010-01-20 22:13:091125 case IDC_TASK_MANAGER:
mlermane6e040a2014-10-31 00:53:211126 chrome::OpenTaskManager(NULL);
[email protected]ceaaf1812010-01-20 22:13:091127 break;
[email protected]4a42d272010-06-18 01:29:421128 case IDC_OPTIONS:
1129 [self showPreferences:sender];
1130 break;
[email protected]d630d7d52010-02-21 00:55:111131 }
[email protected]88d74942009-01-21 22:04:441132}
1133
[email protected]93b59fc2010-12-21 20:00:471134// Run a (background) application in a new tab.
1135- (void)executeApplication:(id)sender {
1136 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351137 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471138 DCHECK(profile);
1139 BackgroundApplicationListModel applications(profile);
1140 DCHECK(tag >= 0 &&
1141 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341142 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331143 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471144}
1145
[email protected]947fc0d2010-01-14 22:33:051146// Same as |-commandDispatch:|, but executes commands using a disposition
1147// determined by the key flags. This will get called in the case where the
1148// frontmost window is not a browser window, and the user has command-clicked
1149// a button in a background browser window whose action is
1150// |-commandDispatchUsingKeyModifiers:|
1151- (void)commandDispatchUsingKeyModifiers:(id)sender {
1152 DCHECK(sender);
1153 if ([sender respondsToSelector:@selector(window)]) {
1154 id delegate = [[sender window] windowController];
andresantoso55fd2512015-04-01 21:07:041155 if ([delegate respondsToSelector:
1156 @selector(commandDispatchUsingKeyModifiers:)]) {
[email protected]947fc0d2010-01-14 22:33:051157 [delegate commandDispatchUsingKeyModifiers:sender];
1158 }
1159 }
1160}
1161
[email protected]2e29e2232013-07-26 10:40:591162// NSApplication delegate method called when someone clicks on the dock icon.
1163// To match standard mac behavior, we should open a new window if there are no
1164// browser windows.
[email protected]ff81e0a2009-04-13 14:58:541165- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581166 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541167 // If the browser is currently trying to quit, don't do anything and return NO
1168 // to prevent AppKit from doing anything.
1169 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1170 if (browser_shutdown::IsTryingToQuit())
1171 return NO;
1172
[email protected]2e29e2232013-07-26 10:40:591173 // Bring all browser windows to the front. Specifically, this brings them in
1174 // front of any app windows. FocusWindowSet will also unminimize the most
1175 // recently minimized window if no windows in the set are visible.
[email protected]a25920ee2013-09-05 19:38:491176 // If there are any, return here. Otherwise, the windows are panels or
1177 // notifications so we still need to open a new window.
[email protected]bf193bc52013-06-08 04:39:581178 if (hasVisibleWindows) {
[email protected]2e29e2232013-07-26 10:40:591179 std::set<NSWindow*> browserWindows;
scottmg8abbff832016-01-28 22:57:371180 for (auto* browser : *BrowserList::GetInstance()) {
mitchelljonese59a1612014-12-16 00:34:591181 // When focusing Chrome, don't focus any browser windows associated with
1182 // a currently running app shim, so ignore them.
1183 if (browser && browser->is_app()) {
mitchelljonesf00422082015-01-05 23:38:031184 extensions::ExtensionRegistry* registry =
1185 extensions::ExtensionRegistry::Get(browser->profile());
1186 const extensions::Extension* extension = registry->GetExtensionById(
1187 web_app::GetExtensionIdFromApplicationName(browser->app_name()),
1188 extensions::ExtensionRegistry::ENABLED);
mitchelljonesb118a0c2015-01-07 02:51:341189 if (extension && extension->is_hosted_app())
mitchelljonese59a1612014-12-16 00:34:591190 continue;
mitchelljonese59a1612014-12-16 00:34:591191 }
[email protected]2e29e2232013-07-26 10:40:591192 browserWindows.insert(browser->window()->GetNativeWindow());
[email protected]0236be22012-01-11 01:05:351193 }
[email protected]a25920ee2013-09-05 19:38:491194 if (!browserWindows.empty()) {
[email protected]d4c811e72013-10-29 21:57:551195 NSWindow* keyWindow = [NSApp keyWindow];
1196 if (keyWindow && ![keyWindow isOnActiveSpace]) {
1197 // The key window is not on the active space. We must be mid-animation
1198 // for a space transition triggered by the dock. Delay the call to
1199 // |ui::FocusWindowSet| until the transition completes. Otherwise, the
1200 // wrong space's windows get raised, resulting in an off-screen key
1201 // window. It does not work to |ui::FocusWindowSet| twice, once here
1202 // and once in |activeSpaceDidChange:|, as that appears to break when
1203 // the omnibox is focused.
1204 //
1205 // This check relies on OS X setting the key window to a window on the
1206 // target space before calling this method.
1207 //
1208 // See http://crbug.com/309656.
1209 reopenTime_ = base::TimeTicks::Now();
1210 } else {
[email protected]6c4b79602014-05-28 16:47:211211 ui::FocusWindowSetOnCurrentSpace(browserWindows);
[email protected]d4c811e72013-10-29 21:57:551212 }
1213 // Return NO; we've done (or soon will do) the deminiaturize, so
1214 // AppKit shouldn't do anything.
[email protected]a25920ee2013-09-05 19:38:491215 return NO;
1216 }
[email protected]0236be22012-01-11 01:05:351217 }
[email protected]ff81e0a2009-04-13 14:58:541218
[email protected]0d1210d62010-09-07 17:31:381219 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481220 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381221 // allow session to be restored first time the user clicks on a Dock icon.
1222 // Normally, it'd just open a new empty page.
1223 {
[email protected]eddcf7502012-02-09 22:43:481224 static BOOL doneOnce = NO;
[email protected]70593e52014-05-15 08:30:231225 BOOL attemptRestore = apps::AppShimHandler::ShouldRestoreSession() ||
1226 (!doneOnce && base::mac::WasLaunchedAsHiddenLoginItem());
1227 doneOnce = YES;
1228 if (attemptRestore) {
1229 SessionService* sessionService =
1230 SessionServiceFactory::GetForProfileForSessionRestore(
1231 [self lastProfile]);
1232 if (sessionService &&
1233 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1234 return NO;
[email protected]eddcf7502012-02-09 22:43:481235 }
[email protected]0d1210d62010-09-07 17:31:381236 }
[email protected]fc44f242012-02-14 16:54:391237
[email protected]ff81e0a2009-04-13 14:58:541238 // Otherwise open a new window.
[email protected]7108d912014-01-30 08:10:451239 // If the last profile was locked, we have to open the User Manager, as the
mlerman7831f57d2015-05-25 11:40:151240 // profile requires authentication. Similarly, because guest mode and system
1241 // profile are implemented as forced incognito, we can't open a new guest
1242 // browser either, so we have to show the User Manager as well.
[email protected]7108d912014-01-30 08:10:451243 Profile* lastProfile = [self lastProfile];
mlerman7831f57d2015-05-25 11:40:151244 if (lastProfile->IsGuestSession() || IsProfileSignedOut(lastProfile) ||
1245 lastProfile->IsSystemProfile()) {
mlermane6e040a2014-10-31 00:53:211246 UserManager::Show(base::FilePath(),
mlermane29d0032014-09-24 19:31:261247 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
1248 } else {
[email protected]7108d912014-01-30 08:10:451249 CreateBrowser(lastProfile);
mlermane29d0032014-09-24 19:31:261250 }
[email protected]ff81e0a2009-04-13 14:58:541251
1252 // We've handled the reopen event, so return NO to tell AppKit not
1253 // to do anything.
1254 return NO;
1255}
1256
[email protected]88d74942009-01-21 22:04:441257- (void)initMenuState {
Ivan Sandrk9669d0e2017-12-15 23:50:201258 menuState_ = std::make_unique<CommandUpdaterImpl>(nullptr);
[email protected]fbc947b2009-06-19 13:28:241259 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441260 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181261 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191262 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381263 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241264 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221265 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331266 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451267 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221268 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1269 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361270 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481271 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211272 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]236ad3022013-09-04 03:27:431273#if defined(GOOGLE_CHROME_BUILD)
[email protected]1c41a932010-11-22 23:41:231274 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]236ad3022013-09-04 03:27:431275#endif
[email protected]ceaaf1812010-01-20 22:13:091276 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441277}
[email protected]1bcdb532009-01-16 17:47:571278
[email protected]961a6932011-07-19 19:52:461279// Conditionally adds the Profile menu to the main menu bar.
1280- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461281 NSMenu* mainMenu = [NSApp mainMenu];
1282 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401283
[email protected]de71ae992013-07-18 03:30:381284 if (!profiles::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401285 [mainMenu removeItem:profileMenu];
1286 return;
1287 }
1288
[email protected]6b2d30bc2011-10-11 18:16:391289 // The controller will unhide the menu if necessary.
1290 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461291
[email protected]6b2d30bc2011-10-11 18:16:391292 profileMenuController_.reset(
1293 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461294}
1295
Leonard Grey2bdd08f2017-10-03 18:40:521296- (void)initShareMenu {
1297 shareMenuController_.reset([[ShareMenuController alloc] init]);
1298 NSMenu* mainMenu = [NSApp mainMenu];
1299 NSMenu* fileMenu = [[mainMenu itemWithTag:IDC_FILE_MENU] submenu];
1300 NSString* shareMenuTitle = l10n_util::GetNSString(IDS_SHARE_MAC);
1301 base::scoped_nsobject<NSMenuItem> shareMenuItem([[NSMenuItem alloc]
1302 initWithTitle:shareMenuTitle
1303 action:NULL
1304 keyEquivalent:@""]);
1305 base::scoped_nsobject<NSMenu> shareSubmenu(
1306 [[NSMenu alloc] initWithTitle:shareMenuTitle]);
1307 [shareSubmenu setDelegate:shareMenuController_];
1308 [shareMenuItem setSubmenu:shareSubmenu];
1309 // Replace "Email Page Location" with Share.
1310 // TODO(crbug.com/770804): Remove this code and update the XIB when
1311 // the share menu launches.
1312 NSInteger index = [fileMenu indexOfItemWithTag:IDC_EMAIL_PAGE_LOCATION];
1313 DCHECK(index != -1);
1314 [fileMenu removeItemAtIndex:index];
1315 [fileMenu insertItem:shareMenuItem atIndex:index];
1316}
1317
[email protected]a99fce0e2011-03-21 20:58:481318// The Confirm to Quit preference is atypical in that the preference lives in
1319// the app menu right above the Quit menu item. This method will refresh the
1320// display of that item depending on the preference state.
1321- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1322 // Format the string so that the correct key equivalent is displayed.
1323 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1324 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1325 base::SysNSStringToUTF16(acceleratorString));
1326 [item setTitle:title];
1327
[email protected]b6366ffa2012-02-29 17:12:261328 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481329 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1330 [item setState:enabled ? NSOnState : NSOffState];
1331}
1332
[email protected]eef99c22010-08-17 05:55:161333- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411334 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1335 // handles requests from services.
1336 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1337 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161338}
1339
[email protected]a585a8db2011-06-20 18:58:351340- (Profile*)lastProfile {
andresantoso55fd2512015-04-01 21:07:041341 // Return the profile of the last-used Browser, if available.
[email protected]7fd5a462011-06-19 16:57:231342 if (lastProfile_)
1343 return lastProfile_;
1344
[email protected]fbb04552014-01-16 15:47:381345 // On first launch, use the logic that ChromeBrowserMain uses to determine
1346 // the initial profile.
1347 ProfileManager* profile_manager = g_browser_process->profile_manager();
1348 if (!profile_manager)
1349 return NULL;
[email protected]3f34599d2009-03-25 22:11:431350
avi3ef9ec9e2014-12-22 22:50:171351 return profile_manager->GetProfile(
1352 GetStartupProfilePath(profile_manager->user_data_dir(),
1353 *base::CommandLine::ForCurrentProcess()));
[email protected]3f34599d2009-03-25 22:11:431354}
1355
[email protected]2a39d1a2014-04-10 05:46:241356- (Profile*)safeLastProfileForNewWindows {
1357 Profile* profile = [self lastProfile];
1358
1359 // Guest sessions must always be OffTheRecord. Use that when opening windows.
1360 if (profile->IsGuestSession())
1361 return profile->GetOffTheRecordProfile();
1362
1363 return profile;
1364}
1365
mlermane6e040a2014-10-31 00:53:211366// Returns true if a browser window may be opened for the last active profile.
1367- (bool)canOpenNewBrowser {
1368 Profile* profile = [self safeLastProfileForNewWindows];
1369
1370 const PrefService* prefs = g_browser_process->local_state();
1371 return !profile->IsGuestSession() ||
1372 prefs->GetBoolean(prefs::kBrowserGuestModeEnabled);
1373}
1374
[email protected]57750f822009-04-21 21:43:091375// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031376// StartupBrowserCreator here because on the other platforms, URLs to open come
1377// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1378// to bottleneck the openings through that for uniform handling.
[email protected]d630d7d52010-02-21 00:55:111379- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211380 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111381 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251382 return;
1383 }
Christian Dullweber820ee5f2018-04-26 13:24:311384 // Pick the last used browser from a regular profile to open the urls.
1385 Profile* profile =
1386 g_browser_process->profile_manager()->GetLastUsedProfileAllowedByPolicy();
1387 Browser* browser = chrome::FindLastActiveWithProfile(profile);
Scott Violet1f106b582017-07-12 15:49:581388 // if no browser window exists then create one with no tabs to be filled in
1389 if (!browser) {
1390 browser = new Browser(
1391 Browser::CreateParams([self safeLastProfileForNewWindows], true));
1392 browser->window()->Show();
eugenebng7afbc36e2017-06-15 13:38:471393 }
Scott Violet1f106b582017-07-12 15:49:581394
1395 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1396 chrome::startup::IsFirstRun first_run =
1397 first_run::IsChromeFirstRun() ? chrome::startup::IS_FIRST_RUN
1398 : chrome::startup::IS_NOT_FIRST_RUN;
1399 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1400 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091401}
1402
[email protected]57750f822009-04-21 21:43:091403- (void)getUrl:(NSAppleEventDescriptor*)event
1404 withReply:(NSAppleEventDescriptor*)reply {
1405 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1406 stringValue];
1407
1408 GURL gurl(base::SysNSStringToUTF8(urlStr));
1409 std::vector<GURL> gurlVector;
1410 gurlVector.push_back(gurl);
1411
erikchen19ee3922014-10-31 19:14:221412 [self openUrlsReplacingNTP:gurlVector];
[email protected]57750f822009-04-21 21:43:091413}
1414
[email protected]caadfca2010-01-22 21:51:211415- (void)application:(NSApplication*)sender
1416 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091417 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211418 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451419 GURL gurl =
[email protected]77d83542013-12-13 08:54:291420 net::FilePathToFileURL(base::FilePath([file fileSystemRepresentation]));
[email protected]57750f822009-04-21 21:43:091421 gurlVector.push_back(gurl);
1422 }
[email protected]caadfca2010-01-22 21:51:211423 if (!gurlVector.empty())
erikchen19ee3922014-10-31 19:14:221424 [self openUrlsReplacingNTP:gurlVector];
[email protected]caadfca2010-01-22 21:51:211425 else
1426 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091427
[email protected]caadfca2010-01-22 21:51:211428 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091429}
[email protected]3f34599d2009-03-25 22:11:431430
[email protected]3111f08b2009-04-30 16:01:521431// Show the preferences window, or bring it to the front if it's already
1432// visible.
1433- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351434 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051435 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121436 chrome::ShowSettings(browser);
mlermane6e040a2014-10-31 00:53:211437 } else if ([self canOpenNewBrowser]) {
[email protected]445177652011-03-09 02:04:051438 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241439 chrome::OpenOptionsWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211440 } else {
1441 // No way to create a browser, default to the User Manager.
1442 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211443 profiles::USER_MANAGER_SELECT_PROFILE_CHROME_SETTINGS);
[email protected]4a42d272010-06-18 01:29:421444 }
[email protected]d989f07c2009-11-14 00:35:461445}
1446
[email protected]bde3dda2009-05-20 22:13:071447- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561448 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121449 chrome::ShowAboutChrome(browser);
mlermane6e040a2014-10-31 00:53:211450 } else if ([self canOpenNewBrowser]) {
1451 // No browser window, so create one for the options tab.
[email protected]2a39d1a2014-04-10 05:46:241452 chrome::OpenAboutWindow([self safeLastProfileForNewWindows]);
mlermane6e040a2014-10-31 00:53:211453 } else {
1454 // No way to create a browser, default to the User Manager.
1455 UserManager::Show(base::FilePath(),
mlermane6e040a2014-10-31 00:53:211456 profiles::USER_MANAGER_SELECT_PROFILE_ABOUT_CHROME);
[email protected]bde3dda2009-05-20 22:13:071457 }
[email protected]bde3dda2009-05-20 22:13:071458}
1459
[email protected]a99fce0e2011-03-21 20:58:481460- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261461 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481462 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1463 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1464}
1465
[email protected]3d4bd23f2009-10-06 03:58:381466// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471467- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381468 [NSApp activateIgnoringOtherApps:YES];
1469 [self commandDispatch:sender];
1470}
1471
[email protected]227fcee2010-06-11 19:19:371472- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441473 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351474 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471475
[email protected]646fadbf2012-09-08 01:49:011476 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1477 atOffset:0
1478 fromDock:YES];
1479 if (profilesAdded)
1480 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331481
[email protected]646fadbf2012-09-08 01:49:011482 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461483 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511484 [[NSMenuItem alloc] initWithTitle:titleStr
1485 action:@selector(commandFromDock:)
1486 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461487 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011488 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081489 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011490 [dockMenu addItem:item];
1491
[email protected]8d10a412013-08-09 19:18:001492 // |profile| can be NULL during unit tests.
treib6f9598012014-11-11 12:21:241493 if (!profile ||
1494 IncognitoModePrefs::GetAvailability(profile->GetPrefs()) !=
1495 IncognitoModePrefs::DISABLED) {
[email protected]8d10a412013-08-09 19:18:001496 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1497 item.reset(
1498 [[NSMenuItem alloc] initWithTitle:titleStr
1499 action:@selector(commandFromDock:)
1500 keyEquivalent:@""]);
1501 [item setTarget:self];
1502 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
1503 [item setEnabled:[self validateUserInterfaceItem:item]];
1504 [dockMenu addItem:item];
1505 }
[email protected]288bfcd32009-09-14 18:14:461506
[email protected]8c6b029d2011-01-21 22:39:511507 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1508 // tests which use the mock in place of the profile-initialized model.
1509
1510 // Avoid breaking unit tests which have no profile.
1511 if (profile) {
1512 BackgroundApplicationListModel applications(profile);
1513 if (applications.size()) {
1514 int position = 0;
1515 NSString* menuStr =
1516 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461517 base::scoped_nsobject<NSMenu> appMenu(
1518 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341519 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481520 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511521 cursor != applications.end();
1522 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501523 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511524 NSString* itemStr =
[email protected]670d3232013-12-24 17:58:581525 base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461526 base::scoped_nsobject<NSMenuItem> appItem(
1527 [[NSMenuItem alloc] initWithTitle:itemStr
1528 action:@selector(executeApplication:)
1529 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511530 [appItem setTarget:self];
1531 [appItem setTag:position];
1532 [appMenu addItem:appItem];
1533 }
[email protected]8c6b029d2011-01-21 22:39:511534 }
1535 }
1536
[email protected]018a3962009-09-17 22:23:441537 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461538}
1539
[email protected]d630d7d52010-02-21 00:55:111540- (const std::vector<GURL>&)startupUrls {
1541 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211542}
1543
[email protected]7e4c69d02011-05-11 22:16:471544- (BookmarkMenuBridge*)bookmarkMenuBridge {
lgarron9e6dee22014-11-18 01:03:391545 return bookmarkMenuBridge_;
[email protected]7e4c69d02011-05-11 22:16:471546}
1547
mlerman8ae56aa2015-04-24 13:56:271548- (HistoryMenuBridge*)historyMenuBridge {
1549 return historyMenuBridge_.get();
1550}
1551
[email protected]e7dc3992013-11-06 02:16:421552- (void)initAppShimMenuController {
[email protected]e4c63ec2014-01-14 15:50:541553 if (!appShimMenuController_)
[email protected]e7dc3992013-11-06 02:16:421554 appShimMenuController_.reset([[AppShimMenuController alloc] init]);
1555}
1556
nomsdd5b6a612014-09-23 15:20:161557- (void)windowChangedToProfile:(Profile*)profile {
1558 if (lastProfile_ == profile)
1559 return;
1560
lgarron9e6dee22014-11-18 01:03:391561 // Before tearing down the menu controller bridges, return the history menu to
1562 // its initial state.
1563 if (historyMenuBridge_)
nomsdd5b6a612014-09-23 15:20:161564 historyMenuBridge_->ResetMenu();
1565
dominicknb80838f2015-09-08 23:00:131566 // Rebuild the menus with the new profile. The bookmarks submenu is cached to
1567 // avoid slowdowns when switching between profiles with large numbers of
1568 // bookmarks. Before caching, store whether it is hidden, make the menu item
1569 // visible, and restore its original hidden state after resetting the submenu.
1570 // This works around an apparent AppKit bug where setting a *different* NSMenu
1571 // submenu on a *hidden* menu item forces the item to become visible.
1572 // See https://crbug.com/497813 for more details.
1573 NSMenuItem* bookmarkItem = [[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU];
1574 BOOL hidden = [bookmarkItem isHidden];
1575 [bookmarkItem setHidden:NO];
nomsdd5b6a612014-09-23 15:20:161576 lastProfile_ = profile;
1577
Trent Aptedcf95689a2017-11-22 00:01:101578 auto& entry = profileBookmarkMenuBridgeMap_[profile->GetPath()];
1579 if (!entry) {
1580 // This creates a deep copy, but only the first 3 items in the root menu
1581 // are really wanted. This can probably be optimized, but lazy-loading of
1582 // the menu should reduce the impact in most flows.
dominicknb80838f2015-09-08 23:00:131583 base::scoped_nsobject<NSMenu> submenu([[bookmarkItem submenu] copy]);
Trent Aptedcf95689a2017-11-22 00:01:101584 [submenu setDelegate:nil]; // The delegate is also copied. Remove it.
1585
1586 entry = std::make_unique<BookmarkMenuBridge>(profile, submenu);
1587
1588 // Clear bookmarks from the old profile.
1589 entry->ClearBookmarkMenu();
lgarron9e6dee22014-11-18 01:03:391590 }
Trent Aptedcf95689a2017-11-22 00:01:101591 bookmarkMenuBridge_ = entry.get();
lgarron9e6dee22014-11-18 01:03:391592
nomsdd5b6a612014-09-23 15:20:161593 // No need to |BuildMenu| here. It is done lazily upon menu access.
dominicknb80838f2015-09-08 23:00:131594 [bookmarkItem setSubmenu:bookmarkMenuBridge_->BookmarkMenu()];
1595 [bookmarkItem setHidden:hidden];
nomsdd5b6a612014-09-23 15:20:161596
1597 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
1598 historyMenuBridge_->BuildMenu();
1599
1600 chrome::BrowserCommandController::
1601 UpdateSharedCommandsForIncognitoAvailability(
1602 menuState_.get(), lastProfile_);
1603 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
1604 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
1605 profilePrefRegistrar_->Add(
1606 prefs::kIncognitoModeAvailability,
1607 base::Bind(&chrome::BrowserCommandController::
1608 UpdateSharedCommandsForIncognitoAvailability,
1609 menuState_.get(),
1610 lastProfile_));
1611}
1612
erikchen22be2092018-06-12 15:54:001613- (void)updateMenuItemKeyEquivalents {
1614 BOOL enableCloseTabShortcut = NO;
1615 id target = [NSApp targetForAction:@selector(performClose:)];
1616
1617 // |target| is an instance of NSPopover or NSWindow.
1618 // If a popover (likely the dictionary lookup popover), we want Cmd-W to
1619 // close the popover so map it to "Close Window".
1620 // Otherwise, map Cmd-W to "Close Tab" if it's a browser window.
1621 if ([target isKindOfClass:[NSWindow class]]) {
1622 NSWindow* window = target;
1623 NSWindow* mainWindow = [NSApp mainWindow];
1624 if (!window || ([window parentWindow] == mainWindow)) {
1625 // If the target window is a child of the main window (e.g. a bubble), the
1626 // main window should be the one that handles the close menu item action.
1627 window = mainWindow;
1628 }
1629 Browser* browser = chrome::FindBrowserWithWindow(window);
1630 enableCloseTabShortcut = browser && browser->is_type_tabbed();
1631 }
1632
1633 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
1634 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
1635}
1636
[email protected]92747fe42014-08-18 23:25:261637- (BOOL)application:(NSApplication*)application
Peter Collingbournefc74af32017-07-10 21:00:181638 willContinueUserActivityWithType:(NSString*)userActivityType
Nico Weber23f11eae2017-07-13 23:39:411639 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261640 return [userActivityType isEqualToString:NSUserActivityTypeBrowsingWeb];
1641}
1642
1643- (BOOL)application:(NSApplication*)application
1644 continueUserActivity:(NSUserActivity*)userActivity
Peter Collingbournefc74af32017-07-10 21:00:181645 restorationHandler:(void (^)(NSArray*))restorationHandler
Nico Weber23f11eae2017-07-13 23:39:411646 API_AVAILABLE(macos(10.10)) {
[email protected]92747fe42014-08-18 23:25:261647 if (![userActivity.activityType
1648 isEqualToString:NSUserActivityTypeBrowsingWeb]) {
1649 return NO;
1650 }
1651
erikchen96e537d52014-10-28 23:43:171652 NSString* originString = base::mac::ObjCCast<NSString>(
1653 [userActivity.userInfo objectForKey:handoff::kOriginKey]);
1654 handoff::Origin origin = handoff::OriginFromString(originString);
1655 UMA_HISTOGRAM_ENUMERATION(
1656 "OSX.Handoff.Origin", origin, handoff::ORIGIN_COUNT);
1657
jiangjc0c568c2014-12-04 19:02:121658 NSURL* url = userActivity.webpageURL;
[email protected]92747fe42014-08-18 23:25:261659 if (!url)
1660 return NO;
1661
1662 GURL gurl(base::SysNSStringToUTF8([url absoluteString]));
1663 std::vector<GURL> gurlVector;
1664 gurlVector.push_back(gurl);
1665
erikchen19ee3922014-10-31 19:14:221666 [self openUrlsReplacingNTP:gurlVector];
[email protected]92747fe42014-08-18 23:25:261667 return YES;
1668}
1669
1670- (void)application:(NSApplication*)application
1671 didFailToContinueUserActivityWithType:(NSString*)userActivityType
1672 error:(NSError*)error {
1673}
1674
erikchen600f7962014-12-12 00:17:381675#pragma mark - Handoff Manager
1676
1677- (BOOL)shouldUseHandoff {
sdy07171a42016-08-30 18:22:041678 return base::mac::IsAtLeastOS10_10();
erikchen600f7962014-12-12 00:17:381679}
1680
1681- (void)passURLToHandoffManager:(const GURL&)handoffURL {
Peter Collingbournefc74af32017-07-10 21:00:181682 if (@available(macOS 10.10, *)) {
1683 [handoffManager_ updateActiveURL:handoffURL];
1684 } else {
1685 // Only ends up being called in 10.10+, i.e. if shouldUseHandoff returns
1686 // true. Some tests override shouldUseHandoff to always return true, but
1687 // then they also override this function to do something else.
1688 NOTREACHED();
1689 }
erikchen600f7962014-12-12 00:17:381690}
1691
1692- (void)updateHandoffManager:(content::WebContents*)webContents {
1693 if (![self shouldUseHandoff])
1694 return;
1695
1696 if (!handoffManager_)
1697 handoffManager_.reset([[HandoffManager alloc] init]);
1698
1699 GURL handoffURL = [self handoffURLFromWebContents:webContents];
1700 [self passURLToHandoffManager:handoffURL];
1701}
1702
1703- (GURL)handoffURLFromWebContents:(content::WebContents*)webContents {
1704 if (!webContents)
1705 return GURL();
1706
1707 Profile* profile =
1708 Profile::FromBrowserContext(webContents->GetBrowserContext());
1709 if (!profile)
1710 return GURL();
1711
1712 // Handoff is not allowed from an incognito profile. To err on the safe side,
1713 // also disallow Handoff from a guest profile.
1714 if (profile->GetProfileType() != Profile::REGULAR_PROFILE)
1715 return GURL();
1716
1717 if (!webContents)
1718 return GURL();
1719
1720 return webContents->GetVisibleURL();
1721}
1722
1723#pragma mark - HandoffActiveURLObserverBridgeDelegate
1724
1725- (void)handoffActiveURLChanged:(content::WebContents*)webContents {
1726 [self updateHandoffManager:webContents];
1727}
1728
[email protected]d630d7d52010-02-21 00:55:111729@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191730
1731//---------------------------------------------------------------------------
1732
Elly Fong-Jones68b85b82018-04-21 00:36:541733namespace {
1734
1735void UpdateProfileInUse(Profile* profile, Profile::CreateStatus status) {
1736 if (status == Profile::CREATE_STATUS_INITIALIZED) {
1737 AppController* controller =
1738 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1739 [controller windowChangedToProfile:profile];
1740 }
1741}
1742
1743} // namespace
1744
[email protected]216e9042009-10-29 17:05:231745namespace app_controller_mac {
1746
1747bool IsOpeningNewWindow() {
1748 return g_is_opening_new_window;
1749}
1750
Elly Fong-Jones68b85b82018-04-21 00:36:541751void CreateGuestProfileIfNeeded() {
1752 g_browser_process->profile_manager()->CreateProfileAsync(
1753 ProfileManager::GetGuestProfilePath(),
1754 base::BindRepeating(&UpdateProfileInUse), base::string16(), std::string(),
1755 std::string());
1756}
1757
Owen Min3bcf8d152018-07-16 16:50:391758void EnterpriseStartupDialogClosed() {
1759 AppController* controller =
1760 base::mac::ObjCCastStrict<AppController>([NSApp delegate]);
1761 if (controller != nil) {
1762 NSNotification* notify = [NSNotification
1763 notificationWithName:NSApplicationDidFinishLaunchingNotification
1764 object:NSApp];
1765 [controller applicationDidFinishLaunching:notify];
1766 }
1767}
1768
[email protected]216e9042009-10-29 17:05:231769} // namespace app_controller_mac