blob: 703ae1648e4900d6be38f73505195ab0ec2a9d22 [file] [log] [blame]
[email protected]71c0eb92012-01-03 17:57:301// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]1bcdb532009-01-16 17:47:572// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]2c47bc12009-04-10 20:14:005#import "chrome/browser/app_controller_mac.h"
[email protected]1bcdb532009-01-16 17:47:576
[email protected]d630d7d52010-02-21 00:55:117#include "base/auto_reset.h"
[email protected]0b8caad2011-11-28 23:33:278#include "base/bind.h"
[email protected]57750f822009-04-21 21:43:099#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5210#include "base/files/file_path.h"
[email protected]151c4a62011-04-22 04:15:1311#include "base/mac/foundation_util.h"
[email protected]0378bf42011-01-01 18:20:1412#include "base/mac/mac_util.h"
[email protected]2c47bc12009-04-10 20:14:0013#include "base/message_loop.h"
[email protected]3853a4c2013-02-11 17:15:5714#include "base/prefs/pref_service.h"
[email protected]3ea1b182013-02-08 22:38:4115#include "base/strings/string_number_conversions.h"
[email protected]3268d7b72013-03-28 17:41:4316#include "base/strings/sys_string_conversions.h"
[email protected]135cb802013-06-09 16:44:2017#include "base/strings/utf_string_conversions.h"
[email protected]1a3aba82010-11-08 23:52:5418#include "chrome/app/chrome_command_ids.h"
[email protected]a07676b22011-06-17 16:36:5319#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3320#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0721#include "chrome/browser/browser_process.h"
[email protected]41741a962009-02-18 21:51:3922#include "chrome/browser/browser_shutdown.h"
[email protected]fdf40f3e2013-07-11 23:55:4623#include "chrome/browser/chrome_notification_types.h"
[email protected]2c47bc12009-04-10 20:14:0024#include "chrome/browser/command_updater.h"
[email protected]9bb54ee2011-10-12 17:43:3525#include "chrome/browser/download/download_service.h"
26#include "chrome/browser/download/download_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3227#include "chrome/browser/extensions/extension_service.h"
28#include "chrome/browser/extensions/extension_system.h"
[email protected]e4a377cf2011-10-05 02:51:4929#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2530#include "chrome/browser/lifetime/application_lifetime.h"
[email protected]a529af52011-08-15 20:56:1731#include "chrome/browser/printing/print_dialog_cloud.h"
[email protected]1c62b2f2013-06-28 00:15:0032#include "chrome/browser/profiles/profile_info_cache_observer.h"
[email protected]8ecad5e2010-12-02 21:18:3333#include "chrome/browser/profiles/profile_manager.h"
[email protected]a529af52011-08-15 20:56:1734#include "chrome/browser/service/service_process_control.h"
[email protected]8d4bbdc2012-09-20 21:36:4935#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5036#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1537#include "chrome/browser/sessions/session_service_factory.h"
[email protected]fbc947b2009-06-19 13:28:2438#include "chrome/browser/sessions/tab_restore_service.h"
[email protected]92371eb2011-04-28 11:50:1539#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]074311a2013-02-28 23:14:0940#include "chrome/browser/signin/signin_manager.h"
41#include "chrome/browser/signin/signin_manager_factory.h"
[email protected]f9bc9b92009-11-24 00:55:3542#include "chrome/browser/sync/profile_sync_service.h"
[email protected]40f047972009-11-25 03:54:4043#include "chrome/browser/sync/sync_ui_util.h"
[email protected]ae04f592010-11-18 20:41:3544#include "chrome/browser/ui/browser.h"
[email protected]05454532013-01-22 21:09:0845#include "chrome/browser/ui/browser_command_controller.h"
[email protected]a37d4b02012-06-25 21:56:1046#include "chrome/browser/ui/browser_commands.h"
[email protected]d8748142012-05-16 21:13:4347#include "chrome/browser/ui/browser_finder.h"
[email protected]b4207c42013-02-12 06:44:2048#include "chrome/browser/ui/browser_iterator.h"
[email protected]a13b76f2012-06-20 15:36:2949#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3550#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1251#include "chrome/browser/ui/chrome_pages.h"
[email protected]7d791652010-12-01 16:34:4952#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
53#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
54#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2655#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4956#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
57#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
58#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1359#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]961a6932011-07-19 19:52:4660#import "chrome/browser/ui/cocoa/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4761#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
62#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4963#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]ccfab592013-01-15 06:24:3264#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]3b265312013-01-17 02:49:5565#include "chrome/browser/ui/host_desktop.h"
[email protected]4feb37d92012-07-01 20:22:1366#include "chrome/browser/ui/startup/startup_browser_creator.h"
67#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
[email protected]12dc3d42010-02-22 23:37:1268#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3869#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0870#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]ccfab592013-01-15 06:24:3271#include "chrome/common/extensions/extension_constants.h"
[email protected]6c583d32011-08-19 14:46:2272#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4873#include "chrome/common/pref_names.h"
[email protected]a529af52011-08-15 20:56:1774#include "chrome/common/service_messages.h"
[email protected]024617a2010-08-20 05:08:0575#include "chrome/common/url_constants.h"
[email protected]c38831a12011-10-28 12:44:4976#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1777#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0778#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1679#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:2080#include "content/public/browser/plugin_service.h"
[email protected]7f6f44c2011-12-14 13:23:3881#include "content/public/browser/user_metrics.h"
[email protected]9dcb59662009-09-23 01:15:5082#include "grit/chromium_strings.h"
[email protected]09729a552009-08-03 23:21:4183#include "grit/generated_resources.h"
[email protected]caadfca2010-01-22 21:51:2184#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1785#include "ui/base/l10n/l10n_util.h"
86#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:4487
[email protected]b441a8492012-06-06 14:55:5788using content::BrowserContext;
[email protected]631bb742011-11-02 11:29:3989using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:1790using content::DownloadManager;
[email protected]7f6f44c2011-12-14 13:23:3891using content::UserMetricsAction;
[email protected]631bb742011-11-02 11:29:3992
[email protected]d630d7d52010-02-21 00:55:1193namespace {
94
[email protected]ebbe94b2012-01-18 20:11:5695// Declare notification names from the 10.7 SDK.
96#if !defined(MAC_OS_X_VERSION_10_7) || \
97 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
98NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
99NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
100#endif
101
[email protected]a37d4b02012-06-25 21:56:10102// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03103// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
104// because otherwise the SessionService will try to restore sessions when we
105// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11106bool g_is_opening_new_window = false;
107
108// Activates a browser window having the given profile (the last one active) if
109// possible and returns a pointer to the activate |Browser| or NULL if this was
110// not possible. If the last active browser is minimized (in particular, if
111// there are only minimized windows), it will unminimize it.
112Browser* ActivateBrowser(Profile* profile) {
[email protected]694256072012-11-29 13:40:34113 Browser* browser = chrome::FindLastActiveWithProfile(profile,
114 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11115 if (browser)
116 browser->window()->Activate();
117 return browser;
118}
119
120// Creates an empty browser window with the given profile and returns a pointer
121// to the new |Browser|.
122Browser* CreateBrowser(Profile* profile) {
123 {
[email protected]997ec9f2012-11-21 04:44:14124 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]a8e3c532013-02-20 06:03:41125 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11126 }
127
[email protected]f2bc6e92012-10-14 02:08:38128 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11129 CHECK(browser);
130 return browser;
131}
132
133// Activates a browser window having the given profile (the last one active) if
134// possible or creates an empty one if necessary. Returns a pointer to the
135// activated/new |Browser|.
136Browser* ActivateOrCreateBrowser(Profile* profile) {
137 if (Browser* browser = ActivateBrowser(profile))
138 return browser;
139 return CreateBrowser(profile);
140}
141
[email protected]151c4a62011-04-22 04:15:13142CFStringRef BaseBundleID_CFString() {
143 NSString* base_bundle_id =
144 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
145 return base::mac::NSToCFCast(base_bundle_id);
146}
147
[email protected]0b8caad2011-11-28 23:33:27148// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12149// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27150void PrefsSyncCallback() {
151 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
152 LOG(WARNING) << "Error recording application bundle path.";
153}
[email protected]12dc3d42010-02-22 23:37:12154
155// Record the location of the application bundle (containing the main framework)
156// from which Chromium was loaded. This is used by app mode shims to find
157// Chromium.
158void RecordLastRunAppBundlePath() {
159 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
160 // real, user-visible app bundle directory. (The alternatives give either the
161 // framework's path or the initial app's path, which may be an app mode shim
162 // or a unit test.)
[email protected]650b2d52013-02-10 03:41:45163 base::FilePath appBundlePath =
[email protected]12dc3d42010-02-22 23:37:12164 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]b6b72222012-02-11 02:04:13165 CFPreferencesSetAppValue(
166 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
167 base::SysUTF8ToCFStringRef(appBundlePath.value()),
168 BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12169
170 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]df32e89c2012-05-17 17:47:34171 BrowserThread::PostDelayedTask(
172 BrowserThread::FILE, FROM_HERE,
173 base::Bind(&PrefsSyncCallback),
174 base::TimeDelta::FromMilliseconds(1500));
[email protected]12dc3d42010-02-22 23:37:12175}
176
[email protected]d630d7d52010-02-21 00:55:11177} // anonymous namespace
178
[email protected]a99fce0e2011-03-21 20:58:48179@interface AppController (Private)
[email protected]88d74942009-01-21 22:04:44180- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46181- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48182- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16183- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]d630d7d52010-02-21 00:55:11184- (void)openUrls:(const std::vector<GURL>&)urls;
[email protected]57750f822009-04-21 21:43:09185- (void)getUrl:(NSAppleEventDescriptor*)event
186 withReply:(NSAppleEventDescriptor*)reply;
[email protected]a529af52011-08-15 20:56:17187- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
[email protected]449dd2f2009-05-27 13:04:00188- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]5c593702011-06-17 18:35:24189- (void)windowChangedToProfile:(Profile*)profile;
[email protected]dd6ab1282010-07-20 01:07:32190- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21191- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41192- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47193- (void)executeApplication:(id)sender;
[email protected]1c62b2f2013-06-28 00:15:00194- (void)profileWasRemoved:(const base::FilePath&)profilePath;
[email protected]88d74942009-01-21 22:04:44195@end
[email protected]1bcdb532009-01-16 17:47:57196
[email protected]1c62b2f2013-06-28 00:15:00197class AppControllerProfileObserver : public ProfileInfoCacheObserver {
198 public:
199 AppControllerProfileObserver(
200 ProfileManager* profile_manager, AppController* app_controller)
201 : profile_manager_(profile_manager),
202 app_controller_(app_controller) {
203 DCHECK(profile_manager_);
204 DCHECK(app_controller_);
205 profile_manager_->GetProfileInfoCache().AddObserver(this);
206 }
207
208 virtual ~AppControllerProfileObserver() {
209 DCHECK(profile_manager_);
210 profile_manager_->GetProfileInfoCache().RemoveObserver(this);
211 }
212
213 private:
214 // ProfileInfoCacheObserver implementation:
215
216 virtual void OnProfileAdded(const base::FilePath& profile_path) OVERRIDE {
217 }
218
219 virtual void OnProfileWasRemoved(const base::FilePath& profile_path,
220 const string16& profile_name) OVERRIDE {
221 // When a profile is deleted we need to notify the AppController,
222 // so it can correctly update its pointer to the last used profile.
223 [app_controller_ profileWasRemoved:profile_path];
224 }
225
226 virtual void OnProfileWillBeRemoved(
227 const base::FilePath& profile_path) OVERRIDE {
228 }
229
230 virtual void OnProfileNameChanged(const base::FilePath& profile_path,
231 const string16& old_profile_name) OVERRIDE {
232 }
233
234 virtual void OnProfileAvatarChanged(
235 const base::FilePath& profile_path) OVERRIDE {
236 }
237
238 ProfileManager* profile_manager_;
239
240 AppController* app_controller_; // Weak; owns us.
241
242 DISALLOW_COPY_AND_ASSIGN(AppControllerProfileObserver);
243};
244
[email protected]1bcdb532009-01-16 17:47:57245@implementation AppController
246
[email protected]caadfca2010-01-22 21:51:21247@synthesize startupComplete = startupComplete_;
248
[email protected]cd63ef62009-05-06 19:41:37249// This method is called very early in application startup (ie, before
250// the profile is loaded or any preferences have been registered). Defer any
251// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44252- (void)awakeFromNib {
[email protected]136140c2009-05-19 13:58:25253 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09254 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
255 [em setEventHandler:self
256 andSelector:@selector(getUrl:withReply:)
257 forEventClass:kInternetEventClass
258 andEventID:kAEGetURL];
259 [em setEventHandler:self
[email protected]a529af52011-08-15 20:56:17260 andSelector:@selector(submitCloudPrintJob:)
[email protected]13aec6c42011-10-27 21:22:08261 forEventClass:cloud_print::kAECloudPrintClass
262 andEventID:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:17263 [em setEventHandler:self
[email protected]57750f822009-04-21 21:43:09264 andSelector:@selector(getUrl:withReply:)
265 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
266 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37267
[email protected]449dd2f2009-05-27 13:04:00268 // Register for various window layering changes. We use these to update
269 // various UI elements (command-key equivalents, etc) when the frontmost
270 // window changes.
271 NSNotificationCenter* notificationCenter =
272 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44273 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00274 addObserver:self
275 selector:@selector(windowLayeringDidChange:)
276 name:NSWindowDidBecomeKeyNotification
277 object:nil];
278 [notificationCenter
279 addObserver:self
280 selector:@selector(windowLayeringDidChange:)
281 name:NSWindowDidResignKeyNotification
282 object:nil];
283 [notificationCenter
284 addObserver:self
285 selector:@selector(windowLayeringDidChange:)
286 name:NSWindowDidBecomeMainNotification
287 object:nil];
288 [notificationCenter
289 addObserver:self
290 selector:@selector(windowLayeringDidChange:)
291 name:NSWindowDidResignMainNotification
292 object:nil];
293
[email protected]ebbe94b2012-01-18 20:11:56294 if (base::mac::IsOSLionOrLater()) {
295 [notificationCenter
296 addObserver:self
297 selector:@selector(popoverDidShow:)
298 name:NSPopoverDidShowNotification
299 object:nil];
300 [notificationCenter
301 addObserver:self
302 selector:@selector(popoverDidClose:)
303 name:NSPopoverDidCloseNotification
304 object:nil];
305 }
306
[email protected]136140c2009-05-19 13:58:25307 // Set up the command updater for when there are no windows open
308 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46309
310 // Initialize the Profile menu.
311 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25312}
313
[email protected]71c0eb92012-01-03 17:57:30314- (void)unregisterEventHandlers {
315 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
316 [em removeEventHandlerForEventClass:kInternetEventClass
317 andEventID:kAEGetURL];
318 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
319 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30320 [em removeEventHandlerForEventClass:'WWW!'
321 andEventID:'OURL'];
322 [[NSNotificationCenter defaultCenter] removeObserver:self];
323}
324
[email protected]7dc8c6b2010-04-09 17:02:50325// (NSApplicationDelegate protocol) This is the Apple-approved place to override
326// the default handlers.
327- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]58877932010-05-25 05:43:11328 // Nothing here right now.
[email protected]7dc8c6b2010-04-09 17:02:50329}
330
331- (BOOL)tryToTerminateApplication:(NSApplication*)app {
[email protected]3076fad2010-04-28 18:11:45332 // Check for in-process downloads, and prompt the user if they really want
333 // to quit (and thus cancel downloads). Only check if we're not already
334 // shutting down, else the user might be prompted multiple times if the
335 // download isn't stopped before terminate is called again.
336 if (!browser_shutdown::IsTryingToQuit() &&
337 ![self shouldQuitWithInProgressDownloads])
338 return NO;
339
[email protected]7dc8c6b2010-04-09 17:02:50340 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
341 // them in, but I'm not sure about UX; we'd also want to disable other things
342 // though.) http://crbug.com/40861
343
[email protected]177aceb2010-11-03 16:17:41344 // Check if the user really wants to quit by employing the confirm-to-quit
345 // mechanism.
346 if (!browser_shutdown::IsTryingToQuit() &&
347 [self applicationShouldTerminate:app] != NSTerminateNow)
348 return NO;
349
[email protected]0665ebe2013-02-13 09:53:19350 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50351
[email protected]0c98ab652013-02-18 00:39:37352 // Initiate a shutdown (via chrome::CloseAllBrowsers()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20353 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56354 if (!browser_shutdown::IsTryingToQuit()) {
355 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30356 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56357 content::NotificationService::AllSources(),
358 content::NotificationService::NoDetails());
[email protected]0c98ab652013-02-18 00:39:37359 chrome::CloseAllBrowsers();
[email protected]ef61b8c2012-01-20 10:54:56360 }
[email protected]7dc8c6b2010-04-09 17:02:50361
[email protected]c984d9f2010-07-20 20:52:20362 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50363}
364
365- (void)stopTryingToTerminateApplication:(NSApplication*)app {
366 if (browser_shutdown::IsTryingToQuit()) {
367 // Reset the "trying to quit" state, so that closing all browser windows
368 // will no longer lead to termination.
369 browser_shutdown::SetTryingToQuit(false);
370
371 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
372 // would have to reinstall them here. http://crbug.com/40861
373 }
[email protected]a9e8afc2009-08-11 22:03:17374}
375
[email protected]177aceb2010-11-03 16:17:41376- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]a99fce0e2011-03-21 20:58:48377 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26378 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23379 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
380 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41381 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23382 }
[email protected]177aceb2010-11-03 16:17:41383
384 // If the application is going to terminate as the result of a Cmd+Q
385 // invocation, use the special sauce to prevent accidental quitting.
386 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41387
[email protected]2020fd0b2010-12-10 01:16:50388 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26389 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50390 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41391
[email protected]5df54fb2011-03-07 18:15:26392 return [[ConfirmQuitPanelController sharedController]
393 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41394}
395
[email protected]449dd2f2009-05-27 13:04:00396// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50397- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50398 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19399 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11400
[email protected]c984d9f2010-07-20 20:52:20401 // Tell BrowserList not to keep the browser process alive. Once all the
402 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
[email protected]313fce12013-01-30 17:09:04403 chrome::EndKeepAlive();
[email protected]fbc947b2009-06-19 13:28:24404
[email protected]02a31dd2013-02-05 08:40:52405 // Reset all pref watching, as this object outlives the prefs system.
406 profilePrefRegistrar_.reset();
407 localPrefRegistrar_.RemoveAll();
408
[email protected]71c0eb92012-01-03 17:57:30409 [self unregisterEventHandlers];
[email protected]449dd2f2009-05-27 13:04:00410}
411
[email protected]3b6aa8b62009-09-15 21:36:11412- (void)didEndMainMessageLoop {
[email protected]c987a242013-02-28 01:17:41413 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
414 chrome::HOST_DESKTOP_TYPE_NATIVE));
415 if (!chrome::GetBrowserCount([self lastProfile],
416 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
[email protected]3b6aa8b62009-09-15 21:36:11417 // As we're shutting down, we need to nuke the TabRestoreService, which
418 // will start the shutdown of the NavigationControllers and allow for
419 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
420 // and may end up crashing when some thread tries to use the IO thread (or
421 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35422 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11423 }
424}
425
[email protected]8cfbdbd2011-06-16 04:17:17426// If the window has a tab controller, make "close window" be cmd-shift-w,
427// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48428// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56429- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
430 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
431 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17432 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
433}
434
435// If the window has a tab controller, make "close tab" take over cmd-w,
436// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56437- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
438 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17439 [closeTabMenuItem_ setKeyEquivalent:@"w"];
440 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
441 } else {
442 [closeTabMenuItem_ setKeyEquivalent:@""];
443 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
444 }
445}
446
447// Explicitly remove any command-key equivalents from the close tab/window
448// menus so that nothing can go haywire if we get a user action during pending
449// updates.
450- (void)clearCloseMenuItemKeyEquivalents {
451 [closeTabMenuItem_ setKeyEquivalent:@""];
452 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
453 [closeWindowMenuItem_ setKeyEquivalent:@""];
454 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
455}
456
[email protected]9f5f79b62011-10-28 00:43:45457// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17458// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45459- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17460 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17461
[email protected]9f5f79b62011-10-28 00:43:45462 NSWindow* window = [NSApp keyWindow];
463 NSWindow* mainWindow = [NSApp mainWindow];
464 if (!window || ([window parentWindow] == mainWindow)) {
465 // If the key window is a child of the main window (e.g. a bubble), the main
466 // window should be the one that handles the close menu item action.
467 // Also, there might be a small amount of time where there is no key window;
468 // in that case as well, just use our main browser window if there is one.
469 // You might think that we should just always use the main window, but the
470 // "About Chrome" window serves as a counterexample.
471 window = mainWindow;
472 }
473
474 BOOL hasTabs =
475 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56476 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
477 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
478 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17479}
480
481// Fix up the "close tab/close window" command-key equivalents. We do this
482// after a delay to ensure that window layer state has been set by the time
483// we do the enabling. This should only be called on the main thread, code that
484// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45485- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17486 DCHECK([NSThread isMainThread]);
487 if (!fileMenuUpdatePending_) {
488 // The OS prefers keypresses to timers, so it's possible that a cmd-w
489 // can sneak in before this timer fires. In order to prevent that from
490 // having any bad consequences, just clear the keys combos altogether. They
491 // will be reset when the timer eventually fires.
492 if ([NSThread isMainThread]) {
493 fileMenuUpdatePending_ = YES;
494 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45495 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
496 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17497 afterDelay:0];
498 } else {
499 // This shouldn't be happening, but if it does, force it to the main
500 // thread to avoid dropping the update. Don't mess with
501 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
502 // there could be a race between the selector finishing and setting the
503 // flag.
504 [self
[email protected]9f5f79b62011-10-28 00:43:45505 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
506 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17507 waitUntilDone:NO];
508 }
509 }
510}
511
[email protected]449dd2f2009-05-27 13:04:00512// Called when we get a notification about the window layering changing to
513// update the UI based on the new main window.
514- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45515 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17516
[email protected]dd6ab1282010-07-20 01:07:32517 if ([notify name] == NSWindowDidResignKeyNotification) {
518 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
519 // returns nil regardless of whether any suitable candidates for the key
520 // window remain. It seems that the new key window for the app is not set
521 // until after this notification is fired, so a check is performed after the
522 // run loop is allowed to spin.
523 [self performSelector:@selector(checkForAnyKeyWindows)
524 withObject:nil
525 afterDelay:0.0];
526 }
[email protected]5c593702011-06-17 18:35:24527
528 // If the window changed to a new BrowserWindowController, update the profile.
529 id windowController = [[notify object] windowController];
[email protected]dc251482012-01-03 18:55:21530 if ([notify name] == NSWindowDidBecomeMainNotification &&
531 [windowController isKindOfClass:[BrowserWindowController class]]) {
[email protected]5c593702011-06-17 18:35:24532 // If the profile is incognito, use the original profile.
533 Profile* newProfile = [windowController profile]->GetOriginalProfile();
534 [self windowChangedToProfile:newProfile];
[email protected]0665ebe2013-02-13 09:53:19535 } else if (chrome::GetTotalBrowserCount() == 0) {
[email protected]cae68b3a2011-11-21 23:29:49536 [self windowChangedToProfile:
537 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24538 }
539}
540
[email protected]ebbe94b2012-01-18 20:11:56541// Called on Lion and later when a popover (e.g. dictionary) is shown.
542- (void)popoverDidShow:(NSNotification*)notify {
543 hasPopover_ = YES;
544 [self fixCloseMenuItemKeyEquivalents];
545}
546
547// Called on Lion and later when a popover (e.g. dictionary) is closed.
548- (void)popoverDidClose:(NSNotification*)notify {
549 hasPopover_ = NO;
550 [self fixCloseMenuItemKeyEquivalents];
551}
552
[email protected]5c593702011-06-17 18:35:24553// Called when the user has changed browser windows, meaning the backing profile
554// may have changed. This can cause a rebuild of the user-data menus. This is a
555// no-op if the new profile is the same as the current one. This will always be
556// the original profile and never incognito.
557- (void)windowChangedToProfile:(Profile*)profile {
558 if (lastProfile_ == profile)
559 return;
560
561 // Before tearing down the menu controller bridges, return the Cocoa menus to
562 // their initial state.
563 if (bookmarkMenuBridge_.get())
564 bookmarkMenuBridge_->ResetMenu();
565 if (historyMenuBridge_.get())
566 historyMenuBridge_->ResetMenu();
567
568 // Rebuild the menus with the new profile.
569 lastProfile_ = profile;
570
[email protected]0c165cf2011-07-09 03:56:50571 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
572 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
[email protected]dc251482012-01-03 18:55:21573 // No need to |BuildMenu| here. It is done lazily upon menu access.
[email protected]5c593702011-06-17 18:35:24574
575 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
576 historyMenuBridge_->BuildMenu();
[email protected]05454532013-01-22 21:09:08577
578 chrome::BrowserCommandController::
579 UpdateSharedCommandsForIncognitoAvailability(
580 menuState_.get(), lastProfile_);
581 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
582 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
583 profilePrefRegistrar_->Add(
584 prefs::kIncognitoModeAvailability,
585 base::Bind(&chrome::BrowserCommandController::
586 UpdateSharedCommandsForIncognitoAvailability,
587 menuState_.get(),
588 lastProfile_));
[email protected]dd6ab1282010-07-20 01:07:32589}
590
591- (void)checkForAnyKeyWindows {
592 if ([NSApp keyWindow])
593 return;
594
[email protected]ad50def52011-10-19 23:17:07595 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30596 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07597 content::NotificationService::AllSources(),
598 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00599}
600
[email protected]414fde592009-05-21 16:14:43601// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43602// Placed here for 2 reasons:
603// 1) Same spot as other Pref stuff
604// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43605- (void)setUpdateCheckInterval {
606#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49607 CFStringRef app = CFSTR("com.google.Keystone.Agent");
608 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43609 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
610 if (!plist) {
611 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50612 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43613 CFPreferencesSetAppValue(checkInterval, value, app);
614 CFPreferencesAppSynchronize(app);
615 }
616#endif
617}
618
[email protected]136140c2009-05-19 13:58:25619// This is called after profiles have been loaded and preferences registered.
620// It is safe to access the default profile here.
621- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]c984d9f2010-07-20 20:52:20622 // Notify BrowserList to keep the application running so it doesn't go away
623 // when all the browser windows get closed.
[email protected]313fce12013-01-30 17:09:04624 chrome::StartKeepAlive();
[email protected]136140c2009-05-19 13:58:25625
[email protected]414fde592009-05-21 16:14:43626 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53627
628 // Build up the encoding menu, the order of the items differs based on the
629 // current locale (see http://crbug.com/7647 for details).
630 // We need a valid g_browser_process to get the profile which is why we can't
631 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14632 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
633 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
634 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35635 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14636 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53637
[email protected]1c62b2f2013-06-28 00:15:00638 // Instantiate the ProfileInfoCache observer so that we can get
639 // notified when a profile is deleted.
640 profileInfoCacheObserver_.reset(new AppControllerProfileObserver(
641 g_browser_process->profile_manager(), self));
642
[email protected]f2c20fa2009-12-01 17:42:02643 // Since Chrome is localized to more languages than the OS, tell Cocoa which
644 // menu is the Help so it can add the search item to it.
[email protected]73980132012-07-26 20:09:28645 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02646
[email protected]12dc3d42010-02-22 23:37:12647 // Record the path to the (browser) app bundle; this is used by the app mode
648 // shim.
649 RecordLastRunAppBundlePath();
650
[email protected]eef99c22010-08-17 05:55:16651 // Makes "Services" menu items available.
652 [self registerServicesMenuTypesTo:[notify object]];
653
[email protected]caadfca2010-01-22 21:51:21654 startupComplete_ = YES;
655
656 // TODO(viettrungluu): This is very temporary, since this should be done "in"
657 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
658 // (probably-empty) list of URLs from the command line.
[email protected]d630d7d52010-02-21 00:55:11659 if (startupUrls_.size()) {
660 [self openUrls:startupUrls_];
661 [self clearStartupUrls];
[email protected]caadfca2010-01-22 21:51:21662 }
[email protected]aac169d2011-03-18 19:53:03663
664 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
665 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
666 [tabposeMenuItem_ setHidden:YES];
667 }
[email protected]05454532013-01-22 21:09:08668
669 PrefService* localState = g_browser_process->local_state();
670 if (localState) {
671 localPrefRegistrar_.Init(localState);
672 localPrefRegistrar_.Add(
673 prefs::kAllowFileSelectionDialogs,
674 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
675 menuState_.get()));
676 }
[email protected]7c321082009-02-09 15:35:47677}
678
[email protected]a96ec6a2009-11-04 17:27:08679// This is called after profiles have been loaded and preferences registered.
680// It is safe to access the default profile here.
681- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]5904cb42012-09-24 15:05:20682 content::PluginService::GetInstance()->AppActivated();
[email protected]a96ec6a2009-11-04 17:27:08683}
684
[email protected]73f5b362009-08-10 23:58:21685// Helper function for populating and displaying the in progress downloads at
686// exit alert panel.
687- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48688 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13689 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21690 NSString* waitTitle = nil;
691 NSString* exitTitle = nil;
692
693 // Set the dialog text based on whether or not there are multiple downloads.
694 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13695 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48696 titleText = l10n_util::GetNSString(
697 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16698 explanationText = l10n_util::GetNSString(
699 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21700 } else {
[email protected]e8b5f7882009-09-14 20:59:13701 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48702 titleText = l10n_util::GetNSStringF(
703 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
[email protected]528c56d2010-07-30 19:28:44704 base::IntToString16(downloadCount));
[email protected]ab3b1c112012-01-13 22:04:16705 explanationText = l10n_util::GetNSString(
706 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21707 }
[email protected]83a9f652012-04-25 21:03:48708 // Cancel download and exit button text.
709 exitTitle = l10n_util::GetNSString(
710 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
711
712 // Wait for download button text.
713 waitTitle = l10n_util::GetNSString(
714 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21715
716 // 'waitButton' is the default choice.
[email protected]361b47c2013-07-02 15:13:24717 int choice = NSRunAlertPanel(titleText, @"%@",
718 waitTitle, exitTitle, nil, explanationText);
[email protected]73f5b362009-08-10 23:58:21719 return choice == NSAlertDefaultReturn ? YES : NO;
720}
721
722// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41723// user to see if we should continue to exit (and thus cancel the downloads), or
724// if we should wait.
725- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21726 ProfileManager* profile_manager = g_browser_process->profile_manager();
727 if (!profile_manager)
728 return YES;
[email protected]09729a552009-08-03 23:21:41729
[email protected]844a1002011-04-19 11:37:21730 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
731 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35732 DownloadService* download_service =
733 DownloadServiceFactory::GetForProfile(profiles[i]);
734 DownloadManager* download_manager =
735 (download_service->HasCreatedDownloadManager() ?
[email protected]b441a8492012-06-06 14:55:57736 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
[email protected]5656f8a2011-11-17 16:12:58737 if (download_manager && download_manager->InProgressCount() > 0) {
738 int downloadCount = download_manager->InProgressCount();
[email protected]73f5b362009-08-10 23:58:21739 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
740 // Create a new browser window (if necessary) and navigate to the
741 // downloads page if the user chooses to wait.
[email protected]3c6a0952012-12-17 11:56:09742 Browser* browser = chrome::FindBrowserWithProfile(
[email protected]323fd7122012-08-24 14:45:11743 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]73f5b362009-08-10 23:58:21744 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:21745 browser = new Browser(Browser::CreateParams(
746 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]73f5b362009-08-10 23:58:21747 browser->window()->Show();
748 }
749 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12750 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21751 return NO;
752 }
[email protected]09729a552009-08-03 23:21:41753
[email protected]73f5b362009-08-10 23:58:21754 // User wants to exit.
755 return YES;
[email protected]09729a552009-08-03 23:21:41756 }
[email protected]09729a552009-08-03 23:21:41757 }
758
[email protected]73f5b362009-08-10 23:58:21759 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41760 return YES;
761}
762
[email protected]fbc947b2009-06-19 13:28:24763// Called to determine if we should enable the "restore tab" menu item.
764// Checks with the TabRestoreService to see if there's anything there to
765// restore and returns YES if so.
766- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15767 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35768 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24769 return service && !service->entries().empty();
770}
771
[email protected]1c62b2f2013-06-28 00:15:00772// Called from the AppControllerProfileObserver every time a profile is deleted.
773- (void)profileWasRemoved:(const base::FilePath&)profilePath {
774 Profile* lastProfile = [self lastProfile];
775
776 // If the lastProfile has been deleted, the profile manager has
777 // already loaded a new one, so the pointer needs to be updated;
778 // otherwise we will try to start up a browser window with a pointer
779 // to the old profile.
780 if (profilePath == lastProfile->GetPath())
781 lastProfile_ = g_browser_process->profile_manager()->GetLastUsedProfile();
782}
783
[email protected]05454532013-01-22 21:09:08784// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21785// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
786// sheets) will not count as blocking the browser. But things like open/save
787// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08788- (BOOL)keyWindowIsModal {
789 if ([NSApp modalWindow])
790 return YES;
791
[email protected]f2bc6e92012-10-14 02:08:38792 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]05454532013-01-22 21:09:08793 return browser &&
794 [[browser->window()->GetNativeWindow() attachedSheet]
795 isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06796}
797
[email protected]88d74942009-01-21 22:04:44798// Called to validate menu items when there are no key windows. All the
799// items we care about have been set with the |commandDispatch:| action and
800// a target of FirstResponder in IB. If it's not one of those, let it
801// continue up the responder chain to be handled elsewhere. We pull out the
802// tag as the cross-platform constant to differentiate and dispatch the
803// various commands.
804- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
805 SEL action = [item action];
806 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08807 if (action == @selector(commandDispatch:) ||
808 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44809 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08810 if (menuState_ && // NULL in tests.
811 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24812 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26813 // The File Menu commands are not automatically disabled by Cocoa when a
814 // dialog sheet obscures the browser window, so we disable several of
815 // them here. We don't need to include IDC_CLOSE_WINDOW, because
816 // app_controller is only activated when there are no key windows (see
817 // function comment).
[email protected]fbc947b2009-06-19 13:28:24818 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08819 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06820 break;
[email protected]f6c15fa2010-06-04 20:08:21821 // Browser-level items that open in new tabs should not open if there's
822 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06823 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06824 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21825 case IDC_SHOW_HISTORY:
826 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08827 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21828 break;
829 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21830 case IDC_TASK_MANAGER:
831 // Allow the user to open a new window if there's a window-modal
832 // dialog.
[email protected]05454532013-01-22 21:09:08833 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24834 break;
[email protected]65549182012-02-25 00:45:40835 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:35836 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:58837 // The profile may be NULL during shutdown -- see
838 // http://code.google.com/p/chromium/issues/detail?id=43048 .
839 //
840 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:35841 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:58842 // NULL.
[email protected]a585a8db2011-06-20 18:58:35843 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:58844 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:35845 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:58846 break;
847 }
[email protected]074311a2013-02-28 23:14:09848 SigninManager* signin = SigninManagerFactory::GetForProfile(
849 lastProfile->GetOriginalProfile());
850 enable = signin->IsSigninAllowed() &&
851 ![self keyWindowIsModal];
[email protected]6bf51192013-01-18 12:35:25852 [BrowserWindowController updateSigninItem:item
853 shouldShow:enable
854 currentProfile:lastProfile];
[email protected]f9bc9b92009-11-24 00:55:35855 break;
[email protected]446e16a2010-05-03 21:23:58856 }
[email protected]acaa37b2011-08-31 07:19:11857 case IDC_FEEDBACK:
858 enable = NO;
859 break;
[email protected]fbc947b2009-06-19 13:28:24860 default:
[email protected]f6c15fa2010-06-04 20:08:21861 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08862 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24863 }
864 }
[email protected]3b6aa8b62009-09-15 21:36:11865 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44866 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52867 } else if (action == @selector(showPreferences:)) {
868 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07869 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
870 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47871 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38872 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48873 } else if (action == @selector(toggleConfirmToQuit:)) {
874 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
875 enable = YES;
[email protected]3a90b452013-02-15 04:33:48876 } else if (action == @selector(executeApplication:)) {
877 enable = YES;
[email protected]88d74942009-01-21 22:04:44878 }
879 return enable;
880}
881
[email protected]947fc0d2010-01-14 22:33:05882// Called when the user picks a menu item when there are no key windows, or when
883// there is no foreground browser window. Calls through to the browser object to
884// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:11885// check, otherwise it should have been disabled in the UI in
886// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:44887- (void)commandDispatch:(id)sender {
[email protected]a585a8db2011-06-20 18:58:35888 Profile* lastProfile = [self lastProfile];
[email protected]f0a51fb52009-03-05 12:46:38889
[email protected]947fc0d2010-01-14 22:33:05890 // Handle the case where we're dispatching a command from a sender that's in a
891 // browser window. This means that the command came from a background window
892 // and is getting here because the foreground window is not a browser window.
893 if ([sender respondsToSelector:@selector(window)]) {
894 id delegate = [[sender window] windowController];
895 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
896 [delegate commandDispatch:sender];
897 return;
898 }
899 }
900
[email protected]8d4bbdc2012-09-20 21:36:49901 // Ignore commands during session restore's browser creation. It uses a
902 // nested message loop and commands dispatched during this operation cause
903 // havoc.
904 if (SessionRestore::IsRestoring(lastProfile) &&
[email protected]b3a25092013-05-28 22:08:16905 base::MessageLoop::current()->IsNested())
[email protected]8d4bbdc2012-09-20 21:36:49906 return;
907
[email protected]88d74942009-01-21 22:04:44908 NSInteger tag = [sender tag];
909 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:24910 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:11911 // Create a new tab in an existing browser window (which we activate) if
912 // possible.
[email protected]a585a8db2011-06-20 18:58:35913 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:40914 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:11915 break;
916 }
917 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:44918 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:35919 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:11920 break;
[email protected]91a5b3e2009-10-30 19:32:22921 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:40922 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
923 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:44924 break;
[email protected]cddc5242009-12-07 18:54:33925 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:40926 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
927 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:33928 break;
[email protected]863ff662009-01-26 20:18:18929 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:48930 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:18931 break;
[email protected]fbc947b2009-06-19 13:28:24932 case IDC_RESTORE_TAB:
[email protected]3b265312013-01-17 02:49:55933 // There is only the native desktop on Mac.
934 chrome::OpenWindowWithRestoredTabs(lastProfile,
935 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]fbc947b2009-06-19 13:28:24936 break;
[email protected]e19516d2009-04-28 17:15:19937 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:40938 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:19939 break;
[email protected]1fdff702009-10-22 00:36:18940 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:38941 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:35942 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12943 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23944 } else {
[email protected]1f0b50b2012-06-22 20:37:16945 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23946 }
[email protected]93e181762009-05-29 14:30:38947 break;
[email protected]1fdff702009-10-22 00:36:18948 }
[email protected]4aee5652009-11-19 18:59:21949 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:35950 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12951 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23952 } else {
[email protected]1f0b50b2012-06-22 20:37:16953 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23954 }
[email protected]4aee5652009-11-19 18:59:21955 break;
956 }
[email protected]af7c25e2010-01-23 05:46:45957 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38958 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:35959 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12960 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:47961 } else {
[email protected]47e532b2010-04-23 17:46:40962 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:16963 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:47964 }
[email protected]af7c25e2010-01-23 05:46:45965 break;
[email protected]91a5b3e2009-10-30 19:32:22966 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:35967 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12968 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:11969 else
[email protected]1f0b50b2012-06-22 20:37:16970 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22971 break;
972 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:35973 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12974 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:11975 else
[email protected]1f0b50b2012-06-22 20:37:16976 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22977 break;
[email protected]bb37e6ec2009-11-18 17:59:36978 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:35979 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:08980 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:11981 else
[email protected]1f0b50b2012-06-22 20:37:16982 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:36983 break;
[email protected]2ca35612012-06-12 03:49:48984 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:35985 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12986 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:11987 else
[email protected]1f0b50b2012-06-22 20:37:16988 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:18989 break;
[email protected]65549182012-02-25 00:45:40990 case IDC_SHOW_SYNC_SETUP:
991 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]08fafe42013-02-03 08:10:49992 chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_MENU);
[email protected]65549182012-02-25 00:45:40993 else
[email protected]1f0b50b2012-06-22 20:37:16994 chrome::OpenSyncSetupWindow(lastProfile, SyncPromoUI::SOURCE_MENU);
[email protected]f9bc9b92009-11-24 00:55:35995 break;
[email protected]ceaaf1812010-01-20 22:13:09996 case IDC_TASK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38997 content::RecordAction(UserMetricsAction("TaskManager"));
[email protected]29c262de2013-06-22 15:39:38998 TaskManagerMac::Show();
[email protected]ceaaf1812010-01-20 22:13:09999 break;
[email protected]4a42d272010-06-18 01:29:421000 case IDC_OPTIONS:
1001 [self showPreferences:sender];
1002 break;
[email protected]d630d7d52010-02-21 00:55:111003 }
[email protected]88d74942009-01-21 22:04:441004}
1005
[email protected]93b59fc2010-12-21 20:00:471006// Run a (background) application in a new tab.
1007- (void)executeApplication:(id)sender {
1008 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:351009 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471010 DCHECK(profile);
1011 BackgroundApplicationListModel applications(profile);
1012 DCHECK(tag >= 0 &&
1013 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:341014 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:331015 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:471016}
1017
[email protected]947fc0d2010-01-14 22:33:051018// Same as |-commandDispatch:|, but executes commands using a disposition
1019// determined by the key flags. This will get called in the case where the
1020// frontmost window is not a browser window, and the user has command-clicked
1021// a button in a background browser window whose action is
1022// |-commandDispatchUsingKeyModifiers:|
1023- (void)commandDispatchUsingKeyModifiers:(id)sender {
1024 DCHECK(sender);
1025 if ([sender respondsToSelector:@selector(window)]) {
1026 id delegate = [[sender window] windowController];
1027 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
1028 [delegate commandDispatchUsingKeyModifiers:sender];
1029 }
1030 }
1031}
1032
[email protected]ff81e0a2009-04-13 14:58:541033// NSApplication delegate method called when someone clicks on the
1034// dock icon and there are no open windows. To match standard mac
1035// behavior, we should open a new window.
1036- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:581037 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:541038 // If the browser is currently trying to quit, don't do anything and return NO
1039 // to prevent AppKit from doing anything.
1040 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
1041 if (browser_shutdown::IsTryingToQuit())
1042 return NO;
1043
[email protected]0236be22012-01-11 01:05:351044 // Don't do anything if there are visible tabbed or popup windows. This will
1045 // cause AppKit to unminimize the most recently minimized window. If the
1046 // visible windows are panels or notifications, we still need to open a new
1047 // window.
[email protected]bf193bc52013-06-08 04:39:581048 if (hasVisibleWindows) {
[email protected]b4207c42013-02-12 06:44:201049 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
[email protected]0236be22012-01-11 01:05:351050 Browser* browser = *iter;
1051 if (browser->is_type_tabbed() || browser->is_type_popup())
1052 return YES;
1053 }
1054 }
[email protected]ff81e0a2009-04-13 14:58:541055
[email protected]0d1210d62010-09-07 17:31:381056 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:481057 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:381058 // allow session to be restored first time the user clicks on a Dock icon.
1059 // Normally, it'd just open a new empty page.
1060 {
[email protected]eddcf7502012-02-09 22:43:481061 static BOOL doneOnce = NO;
1062 if (!doneOnce) {
1063 doneOnce = YES;
1064 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
1065 SessionService* sessionService =
1066 SessionServiceFactory::GetForProfile([self lastProfile]);
1067 if (sessionService &&
1068 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1069 return NO;
[email protected]0d1210d62010-09-07 17:31:381070 }
[email protected]eddcf7502012-02-09 22:43:481071 }
[email protected]0d1210d62010-09-07 17:31:381072 }
[email protected]fc44f242012-02-14 16:54:391073
1074 // Platform apps don't use browser windows so don't do anything if there are
[email protected]bf193bc52013-06-08 04:39:581075 // visible windows, otherwise, launch the browser with the same command line
1076 // which should launch the app again.
[email protected]fc44f242012-02-14 16:54:391077 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
[email protected]bf193bc52013-06-08 04:39:581078 if (command_line.HasSwitch(switches::kAppId)) {
1079 if (hasVisibleWindows)
1080 return YES;
1081
1082 {
1083 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1084 int return_code;
1085 StartupBrowserCreator browser_creator;
1086 browser_creator.LaunchBrowser(
1087 command_line, [self lastProfile], base::FilePath(),
1088 chrome::startup::IS_NOT_PROCESS_STARTUP,
1089 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
1090 }
1091 return NO;
1092 }
[email protected]fc44f242012-02-14 16:54:391093
[email protected]ff81e0a2009-04-13 14:58:541094 // Otherwise open a new window.
[email protected]bf193bc52013-06-08 04:39:581095 CreateBrowser([self lastProfile]);
[email protected]ff81e0a2009-04-13 14:58:541096
1097 // We've handled the reopen event, so return NO to tell AppKit not
1098 // to do anything.
1099 return NO;
1100}
1101
[email protected]88d74942009-01-21 22:04:441102- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521103 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241104 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441105 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181106 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191107 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381108 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241109 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221110 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331111 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451112 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221113 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1114 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361115 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481116 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211117 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]1c41a932010-11-22 23:41:231118 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]65549182012-02-25 00:45:401119 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091120 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441121}
[email protected]1bcdb532009-01-16 17:47:571122
[email protected]961a6932011-07-19 19:52:461123// Conditionally adds the Profile menu to the main menu bar.
1124- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461125 NSMenu* mainMenu = [NSApp mainMenu];
1126 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401127
[email protected]beee7a92012-08-09 20:27:261128 if (!ProfileManager::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401129 [mainMenu removeItem:profileMenu];
1130 return;
1131 }
1132
[email protected]6b2d30bc2011-10-11 18:16:391133 // The controller will unhide the menu if necessary.
1134 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461135
[email protected]6b2d30bc2011-10-11 18:16:391136 profileMenuController_.reset(
1137 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461138}
1139
[email protected]a99fce0e2011-03-21 20:58:481140// The Confirm to Quit preference is atypical in that the preference lives in
1141// the app menu right above the Quit menu item. This method will refresh the
1142// display of that item depending on the preference state.
1143- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1144 // Format the string so that the correct key equivalent is displayed.
1145 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1146 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1147 base::SysNSStringToUTF16(acceleratorString));
1148 [item setTitle:title];
1149
[email protected]b6366ffa2012-02-29 17:12:261150 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481151 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1152 [item setState:enabled ? NSOnState : NSOffState];
1153}
1154
[email protected]eef99c22010-08-17 05:55:161155- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411156 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1157 // handles requests from services.
1158 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1159 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161160}
1161
[email protected]a585a8db2011-06-20 18:58:351162- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231163 // Return the profile of the last-used BrowserWindowController, if available.
1164 if (lastProfile_)
1165 return lastProfile_;
1166
[email protected]056f8792011-07-20 15:40:151167 // On first launch, no profile will be stored, so use last from Local State.
[email protected]3f34599d2009-03-25 22:11:431168 if (g_browser_process->profile_manager())
[email protected]056f8792011-07-20 15:40:151169 return g_browser_process->profile_manager()->GetLastUsedProfile();
[email protected]3f34599d2009-03-25 22:11:431170
[email protected]f6314002009-04-23 01:18:131171 return NULL;
[email protected]3f34599d2009-03-25 22:11:431172}
1173
[email protected]57750f822009-04-21 21:43:091174// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031175// StartupBrowserCreator here because on the other platforms, URLs to open come
1176// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1177// to bottleneck the openings through that for uniform handling.
[email protected]57750f822009-04-21 21:43:091178
[email protected]d630d7d52010-02-21 00:55:111179- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211180 // If the browser hasn't started yet, just queue up the URLs.
1181 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111182 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251183 return;
1184 }
[email protected]57750f822009-04-21 21:43:091185
[email protected]f2bc6e92012-10-14 02:08:381186 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]0e863512009-05-28 19:45:071187 // if no browser window exists then create one with no tabs to be filled in
1188 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:211189 browser = new Browser(Browser::CreateParams(
1190 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]ce560f82009-06-03 09:39:441191 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071192 }
1193
[email protected]947446b2010-10-21 03:36:311194 CommandLine dummy(CommandLine::NO_PROGRAM);
[email protected]4feb37d92012-07-01 20:22:131195 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1196 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
[email protected]650b2d52013-02-10 03:41:451197 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
[email protected]921071f852013-05-25 03:22:081198 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
[email protected]57750f822009-04-21 21:43:091199}
1200
[email protected]57750f822009-04-21 21:43:091201- (void)getUrl:(NSAppleEventDescriptor*)event
1202 withReply:(NSAppleEventDescriptor*)reply {
1203 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1204 stringValue];
1205
1206 GURL gurl(base::SysNSStringToUTF8(urlStr));
1207 std::vector<GURL> gurlVector;
1208 gurlVector.push_back(gurl);
1209
[email protected]d630d7d52010-02-21 00:55:111210 [self openUrls:gurlVector];
[email protected]57750f822009-04-21 21:43:091211}
1212
[email protected]a529af52011-08-15 20:56:171213// Apple Event handler that receives print event from service
1214// process, gets the required data and launches Print dialog.
1215- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1216 // Pull parameter list out of Apple Event.
[email protected]ebbe94b2012-01-18 20:11:561217 NSAppleEventDescriptor* paramList =
[email protected]13aec6c42011-10-27 21:22:081218 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:171219
1220 if (paramList != nil) {
1221 // Pull required fields out of parameter list.
1222 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1223 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1224 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
[email protected]e8368e92011-08-20 04:05:561225 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
[email protected]a529af52011-08-15 20:56:171226 // Convert the title to UTF 16 as required.
1227 string16 title16 = base::SysNSStringToUTF16(printTitle);
[email protected]e8368e92011-08-20 04:05:561228 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
[email protected]a529af52011-08-15 20:56:171229 print_dialog_cloud::CreatePrintDialogForFile(
[email protected]b5b79d72012-05-24 19:42:281230 ProfileManager::GetDefaultProfile(), NULL,
[email protected]650b2d52013-02-10 03:41:451231 base::FilePath([inputPath UTF8String]), title16,
[email protected]b5b79d72012-05-24 19:42:281232 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
[email protected]a529af52011-08-15 20:56:171233 }
1234}
1235
[email protected]caadfca2010-01-22 21:51:211236- (void)application:(NSApplication*)sender
1237 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091238 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211239 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451240 GURL gurl =
1241 net::FilePathToFileURL(base::FilePath(base::SysNSStringToUTF8(file)));
[email protected]57750f822009-04-21 21:43:091242 gurlVector.push_back(gurl);
1243 }
[email protected]caadfca2010-01-22 21:51:211244 if (!gurlVector.empty())
[email protected]d630d7d52010-02-21 00:55:111245 [self openUrls:gurlVector];
[email protected]caadfca2010-01-22 21:51:211246 else
1247 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091248
[email protected]caadfca2010-01-22 21:51:211249 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091250}
[email protected]3f34599d2009-03-25 22:11:431251
[email protected]3111f08b2009-04-30 16:01:521252// Show the preferences window, or bring it to the front if it's already
1253// visible.
1254- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351255 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051256 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121257 chrome::ShowSettings(browser);
[email protected]4a42d272010-06-18 01:29:421258 } else {
[email protected]445177652011-03-09 02:04:051259 // No browser window, so create one for the options tab.
[email protected]1f0b50b2012-06-22 20:37:161260 chrome::OpenOptionsWindow([self lastProfile]);
[email protected]4a42d272010-06-18 01:29:421261 }
[email protected]d989f07c2009-11-14 00:35:461262}
1263
[email protected]bde3dda2009-05-20 22:13:071264- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561265 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121266 chrome::ShowAboutChrome(browser);
[email protected]a9fbb0962012-03-21 23:25:131267 } else {
[email protected]a048ad22012-03-23 04:26:561268 // No browser window, so create one for the about tab.
[email protected]1f0b50b2012-06-22 20:37:161269 chrome::OpenAboutWindow([self lastProfile]);
[email protected]bde3dda2009-05-20 22:13:071270 }
[email protected]bde3dda2009-05-20 22:13:071271}
1272
[email protected]a99fce0e2011-03-21 20:58:481273- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261274 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481275 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1276 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1277}
1278
[email protected]3d4bd23f2009-10-06 03:58:381279// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471280- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381281 [NSApp activateIgnoringOtherApps:YES];
1282 [self commandDispatch:sender];
1283}
1284
[email protected]227fcee2010-06-11 19:19:371285- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441286 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351287 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471288
[email protected]646fadbf2012-09-08 01:49:011289 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1290 atOffset:0
1291 fromDock:YES];
1292 if (profilesAdded)
1293 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331294
[email protected]646fadbf2012-09-08 01:49:011295 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]a8522032013-06-24 22:51:461296 base::scoped_nsobject<NSMenuItem> item(
[email protected]8c6b029d2011-01-21 22:39:511297 [[NSMenuItem alloc] initWithTitle:titleStr
1298 action:@selector(commandFromDock:)
1299 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461300 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011301 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081302 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011303 [dockMenu addItem:item];
1304
1305 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1306 item.reset(
1307 [[NSMenuItem alloc] initWithTitle:titleStr
1308 action:@selector(commandFromDock:)
1309 keyEquivalent:@""]);
1310 [item setTarget:self];
[email protected]288bfcd32009-09-14 18:14:461311 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
[email protected]05454532013-01-22 21:09:081312 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]018a3962009-09-17 22:23:441313 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461314
[email protected]8c6b029d2011-01-21 22:39:511315 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1316 // tests which use the mock in place of the profile-initialized model.
1317
1318 // Avoid breaking unit tests which have no profile.
1319 if (profile) {
1320 BackgroundApplicationListModel applications(profile);
1321 if (applications.size()) {
1322 int position = 0;
1323 NSString* menuStr =
1324 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
[email protected]a8522032013-06-24 22:51:461325 base::scoped_nsobject<NSMenu> appMenu(
1326 [[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341327 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481328 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511329 cursor != applications.end();
1330 ++cursor, ++position) {
[email protected]f15d9ebc2013-07-02 00:14:501331 DCHECK_EQ(applications.GetPosition(cursor->get()), position);
[email protected]8c6b029d2011-01-21 22:39:511332 NSString* itemStr =
1333 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
[email protected]a8522032013-06-24 22:51:461334 base::scoped_nsobject<NSMenuItem> appItem(
1335 [[NSMenuItem alloc] initWithTitle:itemStr
1336 action:@selector(executeApplication:)
1337 keyEquivalent:@""]);
[email protected]8c6b029d2011-01-21 22:39:511338 [appItem setTarget:self];
1339 [appItem setTag:position];
1340 [appMenu addItem:appItem];
1341 }
[email protected]8c6b029d2011-01-21 22:39:511342 }
1343 }
1344
[email protected]018a3962009-09-17 22:23:441345 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461346}
1347
[email protected]d630d7d52010-02-21 00:55:111348- (const std::vector<GURL>&)startupUrls {
1349 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211350}
1351
[email protected]d630d7d52010-02-21 00:55:111352- (void)clearStartupUrls {
1353 startupUrls_.clear();
[email protected]caadfca2010-01-22 21:51:211354}
1355
[email protected]7e4c69d02011-05-11 22:16:471356- (BookmarkMenuBridge*)bookmarkMenuBridge {
1357 return bookmarkMenuBridge_.get();
1358}
1359
[email protected]33190c82012-04-10 17:04:441360- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1361 workAreaChangeObservers_.AddObserver(observer);
1362}
1363
1364- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1365 workAreaChangeObservers_.RemoveObserver(observer);
1366}
1367
[email protected]ebbe94b2012-01-18 20:11:561368- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281369 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441370 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281371 withObject:nil
1372 afterDelay:0];
1373}
1374
[email protected]33190c82012-04-10 17:04:441375- (void)delayedScreenParametersUpdate {
1376 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1377 WorkAreaChanged());
[email protected]6a455072011-11-02 01:32:281378}
1379
[email protected]d630d7d52010-02-21 00:55:111380@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191381
1382//---------------------------------------------------------------------------
1383
[email protected]216e9042009-10-29 17:05:231384namespace app_controller_mac {
1385
1386bool IsOpeningNewWindow() {
1387 return g_is_opening_new_window;
1388}
1389
1390} // namespace app_controller_mac