blob: 4aae313ffe21df569dc4fbb8ea3301bc7bc50127 [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]2c47bc12009-04-10 20:14:0023#include "chrome/browser/command_updater.h"
[email protected]9bb54ee2011-10-12 17:43:3524#include "chrome/browser/download/download_service.h"
25#include "chrome/browser/download/download_service_factory.h"
[email protected]ccfab592013-01-15 06:24:3226#include "chrome/browser/extensions/extension_service.h"
27#include "chrome/browser/extensions/extension_system.h"
[email protected]e4a377cf2011-10-05 02:51:4928#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2529#include "chrome/browser/lifetime/application_lifetime.h"
[email protected]a529af52011-08-15 20:56:1730#include "chrome/browser/printing/print_dialog_cloud.h"
[email protected]8ecad5e2010-12-02 21:18:3331#include "chrome/browser/profiles/profile_manager.h"
[email protected]a529af52011-08-15 20:56:1732#include "chrome/browser/service/service_process_control.h"
[email protected]8d4bbdc2012-09-20 21:36:4933#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5034#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1535#include "chrome/browser/sessions/session_service_factory.h"
[email protected]fbc947b2009-06-19 13:28:2436#include "chrome/browser/sessions/tab_restore_service.h"
[email protected]92371eb2011-04-28 11:50:1537#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]074311a2013-02-28 23:14:0938#include "chrome/browser/signin/signin_manager.h"
39#include "chrome/browser/signin/signin_manager_factory.h"
[email protected]f9bc9b92009-11-24 00:55:3540#include "chrome/browser/sync/profile_sync_service.h"
[email protected]40f047972009-11-25 03:54:4041#include "chrome/browser/sync/sync_ui_util.h"
[email protected]ae04f592010-11-18 20:41:3542#include "chrome/browser/ui/browser.h"
[email protected]05454532013-01-22 21:09:0843#include "chrome/browser/ui/browser_command_controller.h"
[email protected]a37d4b02012-06-25 21:56:1044#include "chrome/browser/ui/browser_commands.h"
[email protected]d8748142012-05-16 21:13:4345#include "chrome/browser/ui/browser_finder.h"
[email protected]b4207c42013-02-12 06:44:2046#include "chrome/browser/ui/browser_iterator.h"
[email protected]a13b76f2012-06-20 15:36:2947#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3548#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1249#include "chrome/browser/ui/chrome_pages.h"
[email protected]7d791652010-12-01 16:34:4950#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
51#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
52#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2653#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4954#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
55#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
56#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1357#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]961a6932011-07-19 19:52:4658#import "chrome/browser/ui/cocoa/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4759#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
60#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4961#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]ccfab592013-01-15 06:24:3262#include "chrome/browser/ui/extensions/application_launch.h"
[email protected]3b265312013-01-17 02:49:5563#include "chrome/browser/ui/host_desktop.h"
[email protected]4feb37d92012-07-01 20:22:1364#include "chrome/browser/ui/startup/startup_browser_creator.h"
65#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
[email protected]14fb7d32011-07-10 17:53:3266#include "chrome/common/chrome_notification_types.h"
[email protected]12dc3d42010-02-22 23:37:1267#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3868#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0869#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]ccfab592013-01-15 06:24:3270#include "chrome/common/extensions/extension_constants.h"
[email protected]6c583d32011-08-19 14:46:2271#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4872#include "chrome/common/pref_names.h"
[email protected]a529af52011-08-15 20:56:1773#include "chrome/common/service_messages.h"
[email protected]024617a2010-08-20 05:08:0574#include "chrome/common/url_constants.h"
[email protected]c38831a12011-10-28 12:44:4975#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1776#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0777#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1678#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:2079#include "content/public/browser/plugin_service.h"
[email protected]7f6f44c2011-12-14 13:23:3880#include "content/public/browser/user_metrics.h"
[email protected]9dcb59662009-09-23 01:15:5081#include "grit/chromium_strings.h"
[email protected]09729a552009-08-03 23:21:4182#include "grit/generated_resources.h"
[email protected]caadfca2010-01-22 21:51:2183#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1784#include "ui/base/l10n/l10n_util.h"
85#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:4486
[email protected]b441a8492012-06-06 14:55:5787using content::BrowserContext;
[email protected]631bb742011-11-02 11:29:3988using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:1789using content::DownloadManager;
[email protected]7f6f44c2011-12-14 13:23:3890using content::UserMetricsAction;
[email protected]631bb742011-11-02 11:29:3991
[email protected]d630d7d52010-02-21 00:55:1192namespace {
93
[email protected]ebbe94b2012-01-18 20:11:5694// Declare notification names from the 10.7 SDK.
95#if !defined(MAC_OS_X_VERSION_10_7) || \
96 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
97NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
98NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
99#endif
100
[email protected]a37d4b02012-06-25 21:56:10101// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03102// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
103// because otherwise the SessionService will try to restore sessions when we
104// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11105bool g_is_opening_new_window = false;
106
107// Activates a browser window having the given profile (the last one active) if
108// possible and returns a pointer to the activate |Browser| or NULL if this was
109// not possible. If the last active browser is minimized (in particular, if
110// there are only minimized windows), it will unminimize it.
111Browser* ActivateBrowser(Profile* profile) {
[email protected]694256072012-11-29 13:40:34112 Browser* browser = chrome::FindLastActiveWithProfile(profile,
113 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11114 if (browser)
115 browser->window()->Activate();
116 return browser;
117}
118
119// Creates an empty browser window with the given profile and returns a pointer
120// to the new |Browser|.
121Browser* CreateBrowser(Profile* profile) {
122 {
[email protected]997ec9f2012-11-21 04:44:14123 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]a8e3c532013-02-20 06:03:41124 chrome::NewEmptyWindow(profile, chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]d630d7d52010-02-21 00:55:11125 }
126
[email protected]f2bc6e92012-10-14 02:08:38127 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11128 CHECK(browser);
129 return browser;
130}
131
132// Activates a browser window having the given profile (the last one active) if
133// possible or creates an empty one if necessary. Returns a pointer to the
134// activated/new |Browser|.
135Browser* ActivateOrCreateBrowser(Profile* profile) {
136 if (Browser* browser = ActivateBrowser(profile))
137 return browser;
138 return CreateBrowser(profile);
139}
140
[email protected]151c4a62011-04-22 04:15:13141CFStringRef BaseBundleID_CFString() {
142 NSString* base_bundle_id =
143 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
144 return base::mac::NSToCFCast(base_bundle_id);
145}
146
[email protected]0b8caad2011-11-28 23:33:27147// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12148// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27149void PrefsSyncCallback() {
150 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
151 LOG(WARNING) << "Error recording application bundle path.";
152}
[email protected]12dc3d42010-02-22 23:37:12153
154// Record the location of the application bundle (containing the main framework)
155// from which Chromium was loaded. This is used by app mode shims to find
156// Chromium.
157void RecordLastRunAppBundlePath() {
158 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
159 // real, user-visible app bundle directory. (The alternatives give either the
160 // framework's path or the initial app's path, which may be an app mode shim
161 // or a unit test.)
[email protected]650b2d52013-02-10 03:41:45162 base::FilePath appBundlePath =
[email protected]12dc3d42010-02-22 23:37:12163 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]b6b72222012-02-11 02:04:13164 CFPreferencesSetAppValue(
165 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
166 base::SysUTF8ToCFStringRef(appBundlePath.value()),
167 BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12168
169 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]df32e89c2012-05-17 17:47:34170 BrowserThread::PostDelayedTask(
171 BrowserThread::FILE, FROM_HERE,
172 base::Bind(&PrefsSyncCallback),
173 base::TimeDelta::FromMilliseconds(1500));
[email protected]12dc3d42010-02-22 23:37:12174}
175
[email protected]d630d7d52010-02-21 00:55:11176} // anonymous namespace
177
[email protected]a99fce0e2011-03-21 20:58:48178@interface AppController (Private)
[email protected]88d74942009-01-21 22:04:44179- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46180- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48181- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16182- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]d630d7d52010-02-21 00:55:11183- (void)openUrls:(const std::vector<GURL>&)urls;
[email protected]57750f822009-04-21 21:43:09184- (void)getUrl:(NSAppleEventDescriptor*)event
185 withReply:(NSAppleEventDescriptor*)reply;
[email protected]a529af52011-08-15 20:56:17186- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
[email protected]449dd2f2009-05-27 13:04:00187- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]5c593702011-06-17 18:35:24188- (void)windowChangedToProfile:(Profile*)profile;
[email protected]dd6ab1282010-07-20 01:07:32189- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21190- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41191- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47192- (void)executeApplication:(id)sender;
[email protected]88d74942009-01-21 22:04:44193@end
[email protected]1bcdb532009-01-16 17:47:57194
195@implementation AppController
196
[email protected]caadfca2010-01-22 21:51:21197@synthesize startupComplete = startupComplete_;
198
[email protected]cd63ef62009-05-06 19:41:37199// This method is called very early in application startup (ie, before
200// the profile is loaded or any preferences have been registered). Defer any
201// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44202- (void)awakeFromNib {
[email protected]136140c2009-05-19 13:58:25203 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09204 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
205 [em setEventHandler:self
206 andSelector:@selector(getUrl:withReply:)
207 forEventClass:kInternetEventClass
208 andEventID:kAEGetURL];
209 [em setEventHandler:self
[email protected]a529af52011-08-15 20:56:17210 andSelector:@selector(submitCloudPrintJob:)
[email protected]13aec6c42011-10-27 21:22:08211 forEventClass:cloud_print::kAECloudPrintClass
212 andEventID:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:17213 [em setEventHandler:self
[email protected]57750f822009-04-21 21:43:09214 andSelector:@selector(getUrl:withReply:)
215 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
216 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37217
[email protected]449dd2f2009-05-27 13:04:00218 // Register for various window layering changes. We use these to update
219 // various UI elements (command-key equivalents, etc) when the frontmost
220 // window changes.
221 NSNotificationCenter* notificationCenter =
222 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44223 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00224 addObserver:self
225 selector:@selector(windowLayeringDidChange:)
226 name:NSWindowDidBecomeKeyNotification
227 object:nil];
228 [notificationCenter
229 addObserver:self
230 selector:@selector(windowLayeringDidChange:)
231 name:NSWindowDidResignKeyNotification
232 object:nil];
233 [notificationCenter
234 addObserver:self
235 selector:@selector(windowLayeringDidChange:)
236 name:NSWindowDidBecomeMainNotification
237 object:nil];
238 [notificationCenter
239 addObserver:self
240 selector:@selector(windowLayeringDidChange:)
241 name:NSWindowDidResignMainNotification
242 object:nil];
243
[email protected]ebbe94b2012-01-18 20:11:56244 if (base::mac::IsOSLionOrLater()) {
245 [notificationCenter
246 addObserver:self
247 selector:@selector(popoverDidShow:)
248 name:NSPopoverDidShowNotification
249 object:nil];
250 [notificationCenter
251 addObserver:self
252 selector:@selector(popoverDidClose:)
253 name:NSPopoverDidCloseNotification
254 object:nil];
255 }
256
[email protected]136140c2009-05-19 13:58:25257 // Set up the command updater for when there are no windows open
258 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46259
260 // Initialize the Profile menu.
261 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25262}
263
[email protected]71c0eb92012-01-03 17:57:30264- (void)unregisterEventHandlers {
265 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
266 [em removeEventHandlerForEventClass:kInternetEventClass
267 andEventID:kAEGetURL];
268 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
269 andEventID:cloud_print::kAECloudPrintClass];
[email protected]71c0eb92012-01-03 17:57:30270 [em removeEventHandlerForEventClass:'WWW!'
271 andEventID:'OURL'];
272 [[NSNotificationCenter defaultCenter] removeObserver:self];
273}
274
[email protected]7dc8c6b2010-04-09 17:02:50275// (NSApplicationDelegate protocol) This is the Apple-approved place to override
276// the default handlers.
277- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]58877932010-05-25 05:43:11278 // Nothing here right now.
[email protected]7dc8c6b2010-04-09 17:02:50279}
280
281- (BOOL)tryToTerminateApplication:(NSApplication*)app {
[email protected]3076fad2010-04-28 18:11:45282 // Check for in-process downloads, and prompt the user if they really want
283 // to quit (and thus cancel downloads). Only check if we're not already
284 // shutting down, else the user might be prompted multiple times if the
285 // download isn't stopped before terminate is called again.
286 if (!browser_shutdown::IsTryingToQuit() &&
287 ![self shouldQuitWithInProgressDownloads])
288 return NO;
289
[email protected]7dc8c6b2010-04-09 17:02:50290 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
291 // them in, but I'm not sure about UX; we'd also want to disable other things
292 // though.) http://crbug.com/40861
293
[email protected]177aceb2010-11-03 16:17:41294 // Check if the user really wants to quit by employing the confirm-to-quit
295 // mechanism.
296 if (!browser_shutdown::IsTryingToQuit() &&
297 [self applicationShouldTerminate:app] != NSTerminateNow)
298 return NO;
299
[email protected]0665ebe2013-02-13 09:53:19300 size_t num_browsers = chrome::GetTotalBrowserCount();
[email protected]7dc8c6b2010-04-09 17:02:50301
[email protected]0c98ab652013-02-18 00:39:37302 // Initiate a shutdown (via chrome::CloseAllBrowsers()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20303 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56304 if (!browser_shutdown::IsTryingToQuit()) {
305 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30306 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56307 content::NotificationService::AllSources(),
308 content::NotificationService::NoDetails());
[email protected]0c98ab652013-02-18 00:39:37309 chrome::CloseAllBrowsers();
[email protected]ef61b8c2012-01-20 10:54:56310 }
[email protected]7dc8c6b2010-04-09 17:02:50311
[email protected]c984d9f2010-07-20 20:52:20312 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50313}
314
315- (void)stopTryingToTerminateApplication:(NSApplication*)app {
316 if (browser_shutdown::IsTryingToQuit()) {
317 // Reset the "trying to quit" state, so that closing all browser windows
318 // will no longer lead to termination.
319 browser_shutdown::SetTryingToQuit(false);
320
321 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
322 // would have to reinstall them here. http://crbug.com/40861
323 }
[email protected]a9e8afc2009-08-11 22:03:17324}
325
[email protected]177aceb2010-11-03 16:17:41326- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]a99fce0e2011-03-21 20:58:48327 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26328 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23329 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
330 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41331 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23332 }
[email protected]177aceb2010-11-03 16:17:41333
334 // If the application is going to terminate as the result of a Cmd+Q
335 // invocation, use the special sauce to prevent accidental quitting.
336 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41337
[email protected]2020fd0b2010-12-10 01:16:50338 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26339 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50340 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41341
[email protected]5df54fb2011-03-07 18:15:26342 return [[ConfirmQuitPanelController sharedController]
343 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41344}
345
[email protected]449dd2f2009-05-27 13:04:00346// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50347- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50348 // There better be no browser windows left at this point.
[email protected]0665ebe2013-02-13 09:53:19349 CHECK_EQ(0u, chrome::GetTotalBrowserCount());
[email protected]3b6aa8b62009-09-15 21:36:11350
[email protected]c984d9f2010-07-20 20:52:20351 // Tell BrowserList not to keep the browser process alive. Once all the
352 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
[email protected]313fce12013-01-30 17:09:04353 chrome::EndKeepAlive();
[email protected]fbc947b2009-06-19 13:28:24354
[email protected]02a31dd2013-02-05 08:40:52355 // Reset all pref watching, as this object outlives the prefs system.
356 profilePrefRegistrar_.reset();
357 localPrefRegistrar_.RemoveAll();
358
[email protected]71c0eb92012-01-03 17:57:30359 [self unregisterEventHandlers];
[email protected]449dd2f2009-05-27 13:04:00360}
361
[email protected]3b6aa8b62009-09-15 21:36:11362- (void)didEndMainMessageLoop {
[email protected]c987a242013-02-28 01:17:41363 DCHECK_EQ(0u, chrome::GetBrowserCount([self lastProfile],
364 chrome::HOST_DESKTOP_TYPE_NATIVE));
365 if (!chrome::GetBrowserCount([self lastProfile],
366 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
[email protected]3b6aa8b62009-09-15 21:36:11367 // As we're shutting down, we need to nuke the TabRestoreService, which
368 // will start the shutdown of the NavigationControllers and allow for
369 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
370 // and may end up crashing when some thread tries to use the IO thread (or
371 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35372 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11373 }
374}
375
[email protected]8cfbdbd2011-06-16 04:17:17376// If the window has a tab controller, make "close window" be cmd-shift-w,
377// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48378// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56379- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
380 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
381 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17382 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
383}
384
385// If the window has a tab controller, make "close tab" take over cmd-w,
386// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56387- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
388 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17389 [closeTabMenuItem_ setKeyEquivalent:@"w"];
390 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
391 } else {
392 [closeTabMenuItem_ setKeyEquivalent:@""];
393 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
394 }
395}
396
397// Explicitly remove any command-key equivalents from the close tab/window
398// menus so that nothing can go haywire if we get a user action during pending
399// updates.
400- (void)clearCloseMenuItemKeyEquivalents {
401 [closeTabMenuItem_ setKeyEquivalent:@""];
402 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
403 [closeWindowMenuItem_ setKeyEquivalent:@""];
404 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
405}
406
[email protected]9f5f79b62011-10-28 00:43:45407// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17408// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45409- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17410 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17411
[email protected]9f5f79b62011-10-28 00:43:45412 NSWindow* window = [NSApp keyWindow];
413 NSWindow* mainWindow = [NSApp mainWindow];
414 if (!window || ([window parentWindow] == mainWindow)) {
415 // If the key window is a child of the main window (e.g. a bubble), the main
416 // window should be the one that handles the close menu item action.
417 // Also, there might be a small amount of time where there is no key window;
418 // in that case as well, just use our main browser window if there is one.
419 // You might think that we should just always use the main window, but the
420 // "About Chrome" window serves as a counterexample.
421 window = mainWindow;
422 }
423
424 BOOL hasTabs =
425 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56426 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
427 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
428 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17429}
430
431// Fix up the "close tab/close window" command-key equivalents. We do this
432// after a delay to ensure that window layer state has been set by the time
433// we do the enabling. This should only be called on the main thread, code that
434// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45435- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17436 DCHECK([NSThread isMainThread]);
437 if (!fileMenuUpdatePending_) {
438 // The OS prefers keypresses to timers, so it's possible that a cmd-w
439 // can sneak in before this timer fires. In order to prevent that from
440 // having any bad consequences, just clear the keys combos altogether. They
441 // will be reset when the timer eventually fires.
442 if ([NSThread isMainThread]) {
443 fileMenuUpdatePending_ = YES;
444 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45445 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
446 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17447 afterDelay:0];
448 } else {
449 // This shouldn't be happening, but if it does, force it to the main
450 // thread to avoid dropping the update. Don't mess with
451 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
452 // there could be a race between the selector finishing and setting the
453 // flag.
454 [self
[email protected]9f5f79b62011-10-28 00:43:45455 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
456 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17457 waitUntilDone:NO];
458 }
459 }
460}
461
[email protected]449dd2f2009-05-27 13:04:00462// Called when we get a notification about the window layering changing to
463// update the UI based on the new main window.
464- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45465 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17466
[email protected]dd6ab1282010-07-20 01:07:32467 if ([notify name] == NSWindowDidResignKeyNotification) {
468 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
469 // returns nil regardless of whether any suitable candidates for the key
470 // window remain. It seems that the new key window for the app is not set
471 // until after this notification is fired, so a check is performed after the
472 // run loop is allowed to spin.
473 [self performSelector:@selector(checkForAnyKeyWindows)
474 withObject:nil
475 afterDelay:0.0];
476 }
[email protected]5c593702011-06-17 18:35:24477
478 // If the window changed to a new BrowserWindowController, update the profile.
479 id windowController = [[notify object] windowController];
[email protected]dc251482012-01-03 18:55:21480 if ([notify name] == NSWindowDidBecomeMainNotification &&
481 [windowController isKindOfClass:[BrowserWindowController class]]) {
[email protected]5c593702011-06-17 18:35:24482 // If the profile is incognito, use the original profile.
483 Profile* newProfile = [windowController profile]->GetOriginalProfile();
484 [self windowChangedToProfile:newProfile];
[email protected]0665ebe2013-02-13 09:53:19485 } else if (chrome::GetTotalBrowserCount() == 0) {
[email protected]cae68b3a2011-11-21 23:29:49486 [self windowChangedToProfile:
487 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24488 }
489}
490
[email protected]ebbe94b2012-01-18 20:11:56491// Called on Lion and later when a popover (e.g. dictionary) is shown.
492- (void)popoverDidShow:(NSNotification*)notify {
493 hasPopover_ = YES;
494 [self fixCloseMenuItemKeyEquivalents];
495}
496
497// Called on Lion and later when a popover (e.g. dictionary) is closed.
498- (void)popoverDidClose:(NSNotification*)notify {
499 hasPopover_ = NO;
500 [self fixCloseMenuItemKeyEquivalents];
501}
502
[email protected]5c593702011-06-17 18:35:24503// Called when the user has changed browser windows, meaning the backing profile
504// may have changed. This can cause a rebuild of the user-data menus. This is a
505// no-op if the new profile is the same as the current one. This will always be
506// the original profile and never incognito.
507- (void)windowChangedToProfile:(Profile*)profile {
508 if (lastProfile_ == profile)
509 return;
510
511 // Before tearing down the menu controller bridges, return the Cocoa menus to
512 // their initial state.
513 if (bookmarkMenuBridge_.get())
514 bookmarkMenuBridge_->ResetMenu();
515 if (historyMenuBridge_.get())
516 historyMenuBridge_->ResetMenu();
517
518 // Rebuild the menus with the new profile.
519 lastProfile_ = profile;
520
[email protected]0c165cf2011-07-09 03:56:50521 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
522 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
[email protected]dc251482012-01-03 18:55:21523 // No need to |BuildMenu| here. It is done lazily upon menu access.
[email protected]5c593702011-06-17 18:35:24524
525 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
526 historyMenuBridge_->BuildMenu();
[email protected]05454532013-01-22 21:09:08527
528 chrome::BrowserCommandController::
529 UpdateSharedCommandsForIncognitoAvailability(
530 menuState_.get(), lastProfile_);
531 profilePrefRegistrar_.reset(new PrefChangeRegistrar());
532 profilePrefRegistrar_->Init(lastProfile_->GetPrefs());
533 profilePrefRegistrar_->Add(
534 prefs::kIncognitoModeAvailability,
535 base::Bind(&chrome::BrowserCommandController::
536 UpdateSharedCommandsForIncognitoAvailability,
537 menuState_.get(),
538 lastProfile_));
[email protected]dd6ab1282010-07-20 01:07:32539}
540
541- (void)checkForAnyKeyWindows {
542 if ([NSApp keyWindow])
543 return;
544
[email protected]ad50def52011-10-19 23:17:07545 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30546 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07547 content::NotificationService::AllSources(),
548 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00549}
550
[email protected]414fde592009-05-21 16:14:43551// If the auto-update interval is not set, make it 5 hours.
[email protected]414fde592009-05-21 16:14:43552// Placed here for 2 reasons:
553// 1) Same spot as other Pref stuff
554// 2) Try and be friendly by keeping this after app launch
[email protected]414fde592009-05-21 16:14:43555- (void)setUpdateCheckInterval {
556#if defined(GOOGLE_CHROME_BUILD)
[email protected]8be07172013-04-27 05:25:49557 CFStringRef app = CFSTR("com.google.Keystone.Agent");
558 CFStringRef checkInterval = CFSTR("checkInterval");
[email protected]414fde592009-05-21 16:14:43559 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
560 if (!plist) {
561 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50562 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43563 CFPreferencesSetAppValue(checkInterval, value, app);
564 CFPreferencesAppSynchronize(app);
565 }
566#endif
567}
568
[email protected]136140c2009-05-19 13:58:25569// This is called after profiles have been loaded and preferences registered.
570// It is safe to access the default profile here.
571- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]c984d9f2010-07-20 20:52:20572 // Notify BrowserList to keep the application running so it doesn't go away
573 // when all the browser windows get closed.
[email protected]313fce12013-01-30 17:09:04574 chrome::StartKeepAlive();
[email protected]136140c2009-05-19 13:58:25575
[email protected]414fde592009-05-21 16:14:43576 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53577
578 // Build up the encoding menu, the order of the items differs based on the
579 // current locale (see http://crbug.com/7647 for details).
580 // We need a valid g_browser_process to get the profile which is why we can't
581 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14582 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
583 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
584 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35585 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14586 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53587
[email protected]f2c20fa2009-12-01 17:42:02588 // Since Chrome is localized to more languages than the OS, tell Cocoa which
589 // menu is the Help so it can add the search item to it.
[email protected]73980132012-07-26 20:09:28590 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02591
[email protected]12dc3d42010-02-22 23:37:12592 // Record the path to the (browser) app bundle; this is used by the app mode
593 // shim.
594 RecordLastRunAppBundlePath();
595
[email protected]eef99c22010-08-17 05:55:16596 // Makes "Services" menu items available.
597 [self registerServicesMenuTypesTo:[notify object]];
598
[email protected]caadfca2010-01-22 21:51:21599 startupComplete_ = YES;
600
601 // TODO(viettrungluu): This is very temporary, since this should be done "in"
602 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
603 // (probably-empty) list of URLs from the command line.
[email protected]d630d7d52010-02-21 00:55:11604 if (startupUrls_.size()) {
605 [self openUrls:startupUrls_];
606 [self clearStartupUrls];
[email protected]caadfca2010-01-22 21:51:21607 }
[email protected]aac169d2011-03-18 19:53:03608
609 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
610 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
611 [tabposeMenuItem_ setHidden:YES];
612 }
[email protected]05454532013-01-22 21:09:08613
614 PrefService* localState = g_browser_process->local_state();
615 if (localState) {
616 localPrefRegistrar_.Init(localState);
617 localPrefRegistrar_.Add(
618 prefs::kAllowFileSelectionDialogs,
619 base::Bind(&chrome::BrowserCommandController::UpdateOpenFileState,
620 menuState_.get()));
621 }
[email protected]7c321082009-02-09 15:35:47622}
623
[email protected]a96ec6a2009-11-04 17:27:08624// This is called after profiles have been loaded and preferences registered.
625// It is safe to access the default profile here.
626- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]5904cb42012-09-24 15:05:20627 content::PluginService::GetInstance()->AppActivated();
[email protected]a96ec6a2009-11-04 17:27:08628}
629
[email protected]73f5b362009-08-10 23:58:21630// Helper function for populating and displaying the in progress downloads at
631// exit alert panel.
632- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48633 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13634 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21635 NSString* waitTitle = nil;
636 NSString* exitTitle = nil;
637
638 // Set the dialog text based on whether or not there are multiple downloads.
639 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13640 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48641 titleText = l10n_util::GetNSString(
642 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16643 explanationText = l10n_util::GetNSString(
644 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21645 } else {
[email protected]e8b5f7882009-09-14 20:59:13646 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48647 titleText = l10n_util::GetNSStringF(
648 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
[email protected]528c56d2010-07-30 19:28:44649 base::IntToString16(downloadCount));
[email protected]ab3b1c112012-01-13 22:04:16650 explanationText = l10n_util::GetNSString(
651 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21652 }
[email protected]83a9f652012-04-25 21:03:48653 // Cancel download and exit button text.
654 exitTitle = l10n_util::GetNSString(
655 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
656
657 // Wait for download button text.
658 waitTitle = l10n_util::GetNSString(
659 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21660
661 // 'waitButton' is the default choice.
[email protected]83a9f652012-04-25 21:03:48662 int choice = NSRunAlertPanel(titleText, explanationText,
[email protected]e8b5f7882009-09-14 20:59:13663 waitTitle, exitTitle, nil);
[email protected]73f5b362009-08-10 23:58:21664 return choice == NSAlertDefaultReturn ? YES : NO;
665}
666
667// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41668// user to see if we should continue to exit (and thus cancel the downloads), or
669// if we should wait.
670- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21671 ProfileManager* profile_manager = g_browser_process->profile_manager();
672 if (!profile_manager)
673 return YES;
[email protected]09729a552009-08-03 23:21:41674
[email protected]844a1002011-04-19 11:37:21675 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
676 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35677 DownloadService* download_service =
678 DownloadServiceFactory::GetForProfile(profiles[i]);
679 DownloadManager* download_manager =
680 (download_service->HasCreatedDownloadManager() ?
[email protected]b441a8492012-06-06 14:55:57681 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
[email protected]5656f8a2011-11-17 16:12:58682 if (download_manager && download_manager->InProgressCount() > 0) {
683 int downloadCount = download_manager->InProgressCount();
[email protected]73f5b362009-08-10 23:58:21684 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
685 // Create a new browser window (if necessary) and navigate to the
686 // downloads page if the user chooses to wait.
[email protected]3c6a0952012-12-17 11:56:09687 Browser* browser = chrome::FindBrowserWithProfile(
[email protected]323fd7122012-08-24 14:45:11688 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]73f5b362009-08-10 23:58:21689 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:21690 browser = new Browser(Browser::CreateParams(
691 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]73f5b362009-08-10 23:58:21692 browser->window()->Show();
693 }
694 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12695 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21696 return NO;
697 }
[email protected]09729a552009-08-03 23:21:41698
[email protected]73f5b362009-08-10 23:58:21699 // User wants to exit.
700 return YES;
[email protected]09729a552009-08-03 23:21:41701 }
[email protected]09729a552009-08-03 23:21:41702 }
703
[email protected]73f5b362009-08-10 23:58:21704 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41705 return YES;
706}
707
[email protected]fbc947b2009-06-19 13:28:24708// Called to determine if we should enable the "restore tab" menu item.
709// Checks with the TabRestoreService to see if there's anything there to
710// restore and returns YES if so.
711- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15712 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35713 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24714 return service && !service->entries().empty();
715}
716
[email protected]05454532013-01-22 21:09:08717// Returns true if there is a modal window (either window- or application-
[email protected]f6c15fa2010-06-04 20:08:21718// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
719// sheets) will not count as blocking the browser. But things like open/save
720// dialogs that are window modal will block the browser.
[email protected]05454532013-01-22 21:09:08721- (BOOL)keyWindowIsModal {
722 if ([NSApp modalWindow])
723 return YES;
724
[email protected]f2bc6e92012-10-14 02:08:38725 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]05454532013-01-22 21:09:08726 return browser &&
727 [[browser->window()->GetNativeWindow() attachedSheet]
728 isKindOfClass:[NSWindow class]];
[email protected]6a281332009-10-13 17:41:06729}
730
[email protected]88d74942009-01-21 22:04:44731// Called to validate menu items when there are no key windows. All the
732// items we care about have been set with the |commandDispatch:| action and
733// a target of FirstResponder in IB. If it's not one of those, let it
734// continue up the responder chain to be handled elsewhere. We pull out the
735// tag as the cross-platform constant to differentiate and dispatch the
736// various commands.
737- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
738 SEL action = [item action];
739 BOOL enable = NO;
[email protected]05454532013-01-22 21:09:08740 if (action == @selector(commandDispatch:) ||
741 action == @selector(commandFromDock:)) {
[email protected]88d74942009-01-21 22:04:44742 NSInteger tag = [item tag];
[email protected]05454532013-01-22 21:09:08743 if (menuState_ && // NULL in tests.
744 menuState_->SupportsCommand(tag)) {
[email protected]fbc947b2009-06-19 13:28:24745 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26746 // The File Menu commands are not automatically disabled by Cocoa when a
747 // dialog sheet obscures the browser window, so we disable several of
748 // them here. We don't need to include IDC_CLOSE_WINDOW, because
749 // app_controller is only activated when there are no key windows (see
750 // function comment).
[email protected]fbc947b2009-06-19 13:28:24751 case IDC_RESTORE_TAB:
[email protected]05454532013-01-22 21:09:08752 enable = ![self keyWindowIsModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06753 break;
[email protected]f6c15fa2010-06-04 20:08:21754 // Browser-level items that open in new tabs should not open if there's
755 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06756 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06757 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21758 case IDC_SHOW_HISTORY:
759 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]05454532013-01-22 21:09:08760 enable = ![self keyWindowIsModal];
[email protected]f6c15fa2010-06-04 20:08:21761 break;
762 // Browser-level items that open in new windows.
[email protected]f6c15fa2010-06-04 20:08:21763 case IDC_TASK_MANAGER:
764 // Allow the user to open a new window if there's a window-modal
765 // dialog.
[email protected]05454532013-01-22 21:09:08766 enable = ![self keyWindowIsModal];
[email protected]fbc947b2009-06-19 13:28:24767 break;
[email protected]65549182012-02-25 00:45:40768 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:35769 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:58770 // The profile may be NULL during shutdown -- see
771 // http://code.google.com/p/chromium/issues/detail?id=43048 .
772 //
773 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:35774 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:58775 // NULL.
[email protected]a585a8db2011-06-20 18:58:35776 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:58777 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:35778 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:58779 break;
780 }
[email protected]074311a2013-02-28 23:14:09781 SigninManager* signin = SigninManagerFactory::GetForProfile(
782 lastProfile->GetOriginalProfile());
783 enable = signin->IsSigninAllowed() &&
784 ![self keyWindowIsModal];
[email protected]6bf51192013-01-18 12:35:25785 [BrowserWindowController updateSigninItem:item
786 shouldShow:enable
787 currentProfile:lastProfile];
[email protected]f9bc9b92009-11-24 00:55:35788 break;
[email protected]446e16a2010-05-03 21:23:58789 }
[email protected]acaa37b2011-08-31 07:19:11790 case IDC_FEEDBACK:
791 enable = NO;
792 break;
[email protected]fbc947b2009-06-19 13:28:24793 default:
[email protected]f6c15fa2010-06-04 20:08:21794 enable = menuState_->IsCommandEnabled(tag) ?
[email protected]05454532013-01-22 21:09:08795 ![self keyWindowIsModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24796 }
797 }
[email protected]3b6aa8b62009-09-15 21:36:11798 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44799 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52800 } else if (action == @selector(showPreferences:)) {
801 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07802 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
803 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47804 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38805 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48806 } else if (action == @selector(toggleConfirmToQuit:)) {
807 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
808 enable = YES;
[email protected]3a90b452013-02-15 04:33:48809 } else if (action == @selector(executeApplication:)) {
810 enable = YES;
[email protected]88d74942009-01-21 22:04:44811 }
812 return enable;
813}
814
[email protected]947fc0d2010-01-14 22:33:05815// Called when the user picks a menu item when there are no key windows, or when
816// there is no foreground browser window. Calls through to the browser object to
817// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:11818// check, otherwise it should have been disabled in the UI in
819// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:44820- (void)commandDispatch:(id)sender {
[email protected]a585a8db2011-06-20 18:58:35821 Profile* lastProfile = [self lastProfile];
[email protected]f0a51fb52009-03-05 12:46:38822
[email protected]947fc0d2010-01-14 22:33:05823 // Handle the case where we're dispatching a command from a sender that's in a
824 // browser window. This means that the command came from a background window
825 // and is getting here because the foreground window is not a browser window.
826 if ([sender respondsToSelector:@selector(window)]) {
827 id delegate = [[sender window] windowController];
828 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
829 [delegate commandDispatch:sender];
830 return;
831 }
832 }
833
[email protected]8d4bbdc2012-09-20 21:36:49834 // Ignore commands during session restore's browser creation. It uses a
835 // nested message loop and commands dispatched during this operation cause
836 // havoc.
837 if (SessionRestore::IsRestoring(lastProfile) &&
[email protected]b3a25092013-05-28 22:08:16838 base::MessageLoop::current()->IsNested())
[email protected]8d4bbdc2012-09-20 21:36:49839 return;
840
[email protected]88d74942009-01-21 22:04:44841 NSInteger tag = [sender tag];
842 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:24843 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:11844 // Create a new tab in an existing browser window (which we activate) if
845 // possible.
[email protected]a585a8db2011-06-20 18:58:35846 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:40847 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:11848 break;
849 }
850 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:44851 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:35852 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:11853 break;
[email protected]91a5b3e2009-10-30 19:32:22854 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:40855 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
856 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:44857 break;
[email protected]cddc5242009-12-07 18:54:33858 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:40859 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
860 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:33861 break;
[email protected]863ff662009-01-26 20:18:18862 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:48863 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:18864 break;
[email protected]fbc947b2009-06-19 13:28:24865 case IDC_RESTORE_TAB:
[email protected]3b265312013-01-17 02:49:55866 // There is only the native desktop on Mac.
867 chrome::OpenWindowWithRestoredTabs(lastProfile,
868 chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]fbc947b2009-06-19 13:28:24869 break;
[email protected]e19516d2009-04-28 17:15:19870 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:40871 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:19872 break;
[email protected]1fdff702009-10-22 00:36:18873 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:38874 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:35875 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12876 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23877 } else {
[email protected]1f0b50b2012-06-22 20:37:16878 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23879 }
[email protected]93e181762009-05-29 14:30:38880 break;
[email protected]1fdff702009-10-22 00:36:18881 }
[email protected]4aee5652009-11-19 18:59:21882 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:35883 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12884 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23885 } else {
[email protected]1f0b50b2012-06-22 20:37:16886 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23887 }
[email protected]4aee5652009-11-19 18:59:21888 break;
889 }
[email protected]af7c25e2010-01-23 05:46:45890 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38891 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:35892 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12893 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:47894 } else {
[email protected]47e532b2010-04-23 17:46:40895 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:16896 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:47897 }
[email protected]af7c25e2010-01-23 05:46:45898 break;
[email protected]91a5b3e2009-10-30 19:32:22899 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:35900 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12901 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:11902 else
[email protected]1f0b50b2012-06-22 20:37:16903 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22904 break;
905 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:35906 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12907 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:11908 else
[email protected]1f0b50b2012-06-22 20:37:16909 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22910 break;
[email protected]bb37e6ec2009-11-18 17:59:36911 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:35912 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]bc9833c32013-02-28 04:05:08913 chrome::ShowExtensions(browser, std::string());
[email protected]d630d7d52010-02-21 00:55:11914 else
[email protected]1f0b50b2012-06-22 20:37:16915 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:36916 break;
[email protected]2ca35612012-06-12 03:49:48917 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:35918 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12919 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:11920 else
[email protected]1f0b50b2012-06-22 20:37:16921 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:18922 break;
[email protected]65549182012-02-25 00:45:40923 case IDC_SHOW_SYNC_SETUP:
924 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]08fafe42013-02-03 08:10:49925 chrome::ShowBrowserSignin(browser, SyncPromoUI::SOURCE_MENU);
[email protected]65549182012-02-25 00:45:40926 else
[email protected]1f0b50b2012-06-22 20:37:16927 chrome::OpenSyncSetupWindow(lastProfile, SyncPromoUI::SOURCE_MENU);
[email protected]f9bc9b92009-11-24 00:55:35928 break;
[email protected]ceaaf1812010-01-20 22:13:09929 case IDC_TASK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38930 content::RecordAction(UserMetricsAction("TaskManager"));
[email protected]adb6a84d2011-02-07 16:58:40931 TaskManagerMac::Show(false);
[email protected]ceaaf1812010-01-20 22:13:09932 break;
[email protected]4a42d272010-06-18 01:29:42933 case IDC_OPTIONS:
934 [self showPreferences:sender];
935 break;
[email protected]d630d7d52010-02-21 00:55:11936 }
[email protected]88d74942009-01-21 22:04:44937}
938
[email protected]93b59fc2010-12-21 20:00:47939// Run a (background) application in a new tab.
940- (void)executeApplication:(id)sender {
941 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:35942 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:47943 DCHECK(profile);
944 BackgroundApplicationListModel applications(profile);
945 DCHECK(tag >= 0 &&
946 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:34947 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:33948 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:47949}
950
[email protected]947fc0d2010-01-14 22:33:05951// Same as |-commandDispatch:|, but executes commands using a disposition
952// determined by the key flags. This will get called in the case where the
953// frontmost window is not a browser window, and the user has command-clicked
954// a button in a background browser window whose action is
955// |-commandDispatchUsingKeyModifiers:|
956- (void)commandDispatchUsingKeyModifiers:(id)sender {
957 DCHECK(sender);
958 if ([sender respondsToSelector:@selector(window)]) {
959 id delegate = [[sender window] windowController];
960 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
961 [delegate commandDispatchUsingKeyModifiers:sender];
962 }
963 }
964}
965
[email protected]ff81e0a2009-04-13 14:58:54966// NSApplication delegate method called when someone clicks on the
967// dock icon and there are no open windows. To match standard mac
968// behavior, we should open a new window.
969- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
[email protected]bf193bc52013-06-08 04:39:58970 hasVisibleWindows:(BOOL)hasVisibleWindows {
[email protected]70631402010-04-26 20:16:54971 // If the browser is currently trying to quit, don't do anything and return NO
972 // to prevent AppKit from doing anything.
973 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
974 if (browser_shutdown::IsTryingToQuit())
975 return NO;
976
[email protected]0236be22012-01-11 01:05:35977 // Don't do anything if there are visible tabbed or popup windows. This will
978 // cause AppKit to unminimize the most recently minimized window. If the
979 // visible windows are panels or notifications, we still need to open a new
980 // window.
[email protected]bf193bc52013-06-08 04:39:58981 if (hasVisibleWindows) {
[email protected]b4207c42013-02-12 06:44:20982 for (chrome::BrowserIterator iter; !iter.done(); iter.Next()) {
[email protected]0236be22012-01-11 01:05:35983 Browser* browser = *iter;
984 if (browser->is_type_tabbed() || browser->is_type_popup())
985 return YES;
986 }
987 }
[email protected]ff81e0a2009-04-13 14:58:54988
[email protected]0d1210d62010-09-07 17:31:38989 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:48990 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:38991 // allow session to be restored first time the user clicks on a Dock icon.
992 // Normally, it'd just open a new empty page.
993 {
[email protected]eddcf7502012-02-09 22:43:48994 static BOOL doneOnce = NO;
995 if (!doneOnce) {
996 doneOnce = YES;
997 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
998 SessionService* sessionService =
999 SessionServiceFactory::GetForProfile([self lastProfile]);
1000 if (sessionService &&
1001 sessionService->RestoreIfNecessary(std::vector<GURL>()))
1002 return NO;
[email protected]0d1210d62010-09-07 17:31:381003 }
[email protected]eddcf7502012-02-09 22:43:481004 }
[email protected]0d1210d62010-09-07 17:31:381005 }
[email protected]fc44f242012-02-14 16:54:391006
1007 // Platform apps don't use browser windows so don't do anything if there are
[email protected]bf193bc52013-06-08 04:39:581008 // visible windows, otherwise, launch the browser with the same command line
1009 // which should launch the app again.
[email protected]fc44f242012-02-14 16:54:391010 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
[email protected]bf193bc52013-06-08 04:39:581011 if (command_line.HasSwitch(switches::kAppId)) {
1012 if (hasVisibleWindows)
1013 return YES;
1014
1015 {
1016 base::AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
1017 int return_code;
1018 StartupBrowserCreator browser_creator;
1019 browser_creator.LaunchBrowser(
1020 command_line, [self lastProfile], base::FilePath(),
1021 chrome::startup::IS_NOT_PROCESS_STARTUP,
1022 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
1023 }
1024 return NO;
1025 }
[email protected]fc44f242012-02-14 16:54:391026
[email protected]ff81e0a2009-04-13 14:58:541027 // Otherwise open a new window.
[email protected]bf193bc52013-06-08 04:39:581028 CreateBrowser([self lastProfile]);
[email protected]ff81e0a2009-04-13 14:58:541029
1030 // We've handled the reopen event, so return NO to tell AppKit not
1031 // to do anything.
1032 return NO;
1033}
1034
[email protected]88d74942009-01-21 22:04:441035- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521036 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241037 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441038 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181039 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191040 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381041 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241042 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221043 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331044 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451045 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221046 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1047 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361048 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481049 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211050 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]1c41a932010-11-22 23:41:231051 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]65549182012-02-25 00:45:401052 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091053 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441054}
[email protected]1bcdb532009-01-16 17:47:571055
[email protected]961a6932011-07-19 19:52:461056// Conditionally adds the Profile menu to the main menu bar.
1057- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461058 NSMenu* mainMenu = [NSApp mainMenu];
1059 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401060
[email protected]beee7a92012-08-09 20:27:261061 if (!ProfileManager::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401062 [mainMenu removeItem:profileMenu];
1063 return;
1064 }
1065
[email protected]6b2d30bc2011-10-11 18:16:391066 // The controller will unhide the menu if necessary.
1067 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461068
[email protected]6b2d30bc2011-10-11 18:16:391069 profileMenuController_.reset(
1070 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461071}
1072
[email protected]a99fce0e2011-03-21 20:58:481073// The Confirm to Quit preference is atypical in that the preference lives in
1074// the app menu right above the Quit menu item. This method will refresh the
1075// display of that item depending on the preference state.
1076- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1077 // Format the string so that the correct key equivalent is displayed.
1078 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1079 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1080 base::SysNSStringToUTF16(acceleratorString));
1081 [item setTitle:title];
1082
[email protected]b6366ffa2012-02-29 17:12:261083 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481084 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1085 [item setState:enabled ? NSOnState : NSOffState];
1086}
1087
[email protected]eef99c22010-08-17 05:55:161088- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411089 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1090 // handles requests from services.
1091 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1092 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161093}
1094
[email protected]a585a8db2011-06-20 18:58:351095- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231096 // Return the profile of the last-used BrowserWindowController, if available.
1097 if (lastProfile_)
1098 return lastProfile_;
1099
[email protected]056f8792011-07-20 15:40:151100 // On first launch, no profile will be stored, so use last from Local State.
[email protected]3f34599d2009-03-25 22:11:431101 if (g_browser_process->profile_manager())
[email protected]056f8792011-07-20 15:40:151102 return g_browser_process->profile_manager()->GetLastUsedProfile();
[email protected]3f34599d2009-03-25 22:11:431103
[email protected]f6314002009-04-23 01:18:131104 return NULL;
[email protected]3f34599d2009-03-25 22:11:431105}
1106
[email protected]57750f822009-04-21 21:43:091107// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031108// StartupBrowserCreator here because on the other platforms, URLs to open come
1109// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1110// to bottleneck the openings through that for uniform handling.
[email protected]57750f822009-04-21 21:43:091111
[email protected]d630d7d52010-02-21 00:55:111112- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211113 // If the browser hasn't started yet, just queue up the URLs.
1114 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111115 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251116 return;
1117 }
[email protected]57750f822009-04-21 21:43:091118
[email protected]f2bc6e92012-10-14 02:08:381119 Browser* browser = chrome::GetLastActiveBrowser();
[email protected]0e863512009-05-28 19:45:071120 // if no browser window exists then create one with no tabs to be filled in
1121 if (!browser) {
[email protected]c125cdc2013-02-25 19:10:211122 browser = new Browser(Browser::CreateParams(
1123 [self lastProfile], chrome::HOST_DESKTOP_TYPE_NATIVE));
[email protected]ce560f82009-06-03 09:39:441124 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071125 }
1126
[email protected]947446b2010-10-21 03:36:311127 CommandLine dummy(CommandLine::NO_PROGRAM);
[email protected]4feb37d92012-07-01 20:22:131128 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1129 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
[email protected]650b2d52013-02-10 03:41:451130 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
[email protected]921071f852013-05-25 03:22:081131 launch.OpenURLsInBrowser(browser, false, urls, browser->host_desktop_type());
[email protected]57750f822009-04-21 21:43:091132}
1133
[email protected]57750f822009-04-21 21:43:091134- (void)getUrl:(NSAppleEventDescriptor*)event
1135 withReply:(NSAppleEventDescriptor*)reply {
1136 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1137 stringValue];
1138
1139 GURL gurl(base::SysNSStringToUTF8(urlStr));
1140 std::vector<GURL> gurlVector;
1141 gurlVector.push_back(gurl);
1142
[email protected]d630d7d52010-02-21 00:55:111143 [self openUrls:gurlVector];
[email protected]57750f822009-04-21 21:43:091144}
1145
[email protected]a529af52011-08-15 20:56:171146// Apple Event handler that receives print event from service
1147// process, gets the required data and launches Print dialog.
1148- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1149 // Pull parameter list out of Apple Event.
[email protected]ebbe94b2012-01-18 20:11:561150 NSAppleEventDescriptor* paramList =
[email protected]13aec6c42011-10-27 21:22:081151 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:171152
1153 if (paramList != nil) {
1154 // Pull required fields out of parameter list.
1155 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1156 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1157 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
[email protected]e8368e92011-08-20 04:05:561158 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
[email protected]a529af52011-08-15 20:56:171159 // Convert the title to UTF 16 as required.
1160 string16 title16 = base::SysNSStringToUTF16(printTitle);
[email protected]e8368e92011-08-20 04:05:561161 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
[email protected]a529af52011-08-15 20:56:171162 print_dialog_cloud::CreatePrintDialogForFile(
[email protected]b5b79d72012-05-24 19:42:281163 ProfileManager::GetDefaultProfile(), NULL,
[email protected]650b2d52013-02-10 03:41:451164 base::FilePath([inputPath UTF8String]), title16,
[email protected]b5b79d72012-05-24 19:42:281165 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
[email protected]a529af52011-08-15 20:56:171166 }
1167}
1168
[email protected]caadfca2010-01-22 21:51:211169- (void)application:(NSApplication*)sender
1170 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091171 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211172 for (NSString* file in filenames) {
[email protected]650b2d52013-02-10 03:41:451173 GURL gurl =
1174 net::FilePathToFileURL(base::FilePath(base::SysNSStringToUTF8(file)));
[email protected]57750f822009-04-21 21:43:091175 gurlVector.push_back(gurl);
1176 }
[email protected]caadfca2010-01-22 21:51:211177 if (!gurlVector.empty())
[email protected]d630d7d52010-02-21 00:55:111178 [self openUrls:gurlVector];
[email protected]caadfca2010-01-22 21:51:211179 else
1180 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091181
[email protected]caadfca2010-01-22 21:51:211182 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091183}
[email protected]3f34599d2009-03-25 22:11:431184
[email protected]3111f08b2009-04-30 16:01:521185// Show the preferences window, or bring it to the front if it's already
1186// visible.
1187- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351188 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051189 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121190 chrome::ShowSettings(browser);
[email protected]4a42d272010-06-18 01:29:421191 } else {
[email protected]445177652011-03-09 02:04:051192 // No browser window, so create one for the options tab.
[email protected]1f0b50b2012-06-22 20:37:161193 chrome::OpenOptionsWindow([self lastProfile]);
[email protected]4a42d272010-06-18 01:29:421194 }
[email protected]d989f07c2009-11-14 00:35:461195}
1196
[email protected]bde3dda2009-05-20 22:13:071197- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561198 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121199 chrome::ShowAboutChrome(browser);
[email protected]a9fbb0962012-03-21 23:25:131200 } else {
[email protected]a048ad22012-03-23 04:26:561201 // No browser window, so create one for the about tab.
[email protected]1f0b50b2012-06-22 20:37:161202 chrome::OpenAboutWindow([self lastProfile]);
[email protected]bde3dda2009-05-20 22:13:071203 }
[email protected]bde3dda2009-05-20 22:13:071204}
1205
[email protected]a99fce0e2011-03-21 20:58:481206- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261207 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481208 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1209 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1210}
1211
[email protected]3d4bd23f2009-10-06 03:58:381212// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471213- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381214 [NSApp activateIgnoringOtherApps:YES];
1215 [self commandDispatch:sender];
1216}
1217
[email protected]227fcee2010-06-11 19:19:371218- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441219 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351220 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471221
[email protected]646fadbf2012-09-08 01:49:011222 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1223 atOffset:0
1224 fromDock:YES];
1225 if (profilesAdded)
1226 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331227
[email protected]646fadbf2012-09-08 01:49:011228 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]8c6b029d2011-01-21 22:39:511229 scoped_nsobject<NSMenuItem> item(
1230 [[NSMenuItem alloc] initWithTitle:titleStr
1231 action:@selector(commandFromDock:)
1232 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461233 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011234 [item setTag:IDC_NEW_WINDOW];
[email protected]05454532013-01-22 21:09:081235 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]646fadbf2012-09-08 01:49:011236 [dockMenu addItem:item];
1237
1238 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1239 item.reset(
1240 [[NSMenuItem alloc] initWithTitle:titleStr
1241 action:@selector(commandFromDock:)
1242 keyEquivalent:@""]);
1243 [item setTarget:self];
[email protected]288bfcd32009-09-14 18:14:461244 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
[email protected]05454532013-01-22 21:09:081245 [item setEnabled:[self validateUserInterfaceItem:item]];
[email protected]018a3962009-09-17 22:23:441246 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461247
[email protected]8c6b029d2011-01-21 22:39:511248 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1249 // tests which use the mock in place of the profile-initialized model.
1250
1251 // Avoid breaking unit tests which have no profile.
1252 if (profile) {
1253 BackgroundApplicationListModel applications(profile);
1254 if (applications.size()) {
1255 int position = 0;
1256 NSString* menuStr =
1257 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1258 scoped_nsobject<NSMenu> appMenu([[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341259 for (extensions::ExtensionList::const_iterator cursor =
[email protected]3a90b452013-02-15 04:33:481260 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511261 cursor != applications.end();
1262 ++cursor, ++position) {
[email protected]2ce9c89752011-02-25 18:24:341263 DCHECK_EQ(applications.GetPosition(*cursor), position);
[email protected]8c6b029d2011-01-21 22:39:511264 NSString* itemStr =
1265 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
1266 scoped_nsobject<NSMenuItem> appItem([[NSMenuItem alloc]
1267 initWithTitle:itemStr
[email protected]3a90b452013-02-15 04:33:481268 action:@selector(executeApplication:)
[email protected]8c6b029d2011-01-21 22:39:511269 keyEquivalent:@""]);
1270 [appItem setTarget:self];
1271 [appItem setTag:position];
1272 [appMenu addItem:appItem];
1273 }
[email protected]3a90b452013-02-15 04:33:481274
[email protected]8c6b029d2011-01-21 22:39:511275 scoped_nsobject<NSMenuItem> appMenuItem([[NSMenuItem alloc]
1276 initWithTitle:menuStr
[email protected]3a90b452013-02-15 04:33:481277 action:@selector(executeApplication:)
[email protected]8c6b029d2011-01-21 22:39:511278 keyEquivalent:@""]);
1279 [appMenuItem setTarget:self];
[email protected]3a90b452013-02-15 04:33:481280 [appMenuItem setTag:IDC_VIEW_BACKGROUND_PAGES];
[email protected]8c6b029d2011-01-21 22:39:511281 [appMenuItem setSubmenu:appMenu];
1282 [dockMenu addItem:appMenuItem];
1283 }
1284 }
1285
[email protected]018a3962009-09-17 22:23:441286 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461287}
1288
[email protected]d630d7d52010-02-21 00:55:111289- (const std::vector<GURL>&)startupUrls {
1290 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211291}
1292
[email protected]d630d7d52010-02-21 00:55:111293- (void)clearStartupUrls {
1294 startupUrls_.clear();
[email protected]caadfca2010-01-22 21:51:211295}
1296
[email protected]7e4c69d02011-05-11 22:16:471297- (BookmarkMenuBridge*)bookmarkMenuBridge {
1298 return bookmarkMenuBridge_.get();
1299}
1300
[email protected]33190c82012-04-10 17:04:441301- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1302 workAreaChangeObservers_.AddObserver(observer);
1303}
1304
1305- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1306 workAreaChangeObservers_.RemoveObserver(observer);
1307}
1308
[email protected]ebbe94b2012-01-18 20:11:561309- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281310 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441311 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281312 withObject:nil
1313 afterDelay:0];
1314}
1315
[email protected]33190c82012-04-10 17:04:441316- (void)delayedScreenParametersUpdate {
1317 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1318 WorkAreaChanged());
[email protected]6a455072011-11-02 01:32:281319}
1320
[email protected]d630d7d52010-02-21 00:55:111321@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191322
1323//---------------------------------------------------------------------------
1324
[email protected]216e9042009-10-29 17:05:231325namespace app_controller_mac {
1326
1327bool IsOpeningNewWindow() {
1328 return g_is_opening_new_window;
1329}
1330
1331} // namespace app_controller_mac